diff --git a/.gitea/workflows/build-push-harbor.yml b/.gitea/workflows/build-push-harbor.yml new file mode 100644 index 0000000..9f73862 --- /dev/null +++ b/.gitea/workflows/build-push-harbor.yml @@ -0,0 +1,113 @@ +name: build-and-push-harbor + +on: + push: + branches: + - main + - master + - dev + - "feature/**" + workflow_dispatch: + +env: + IMAGE_NAME: st-1-example + +jobs: + docker-build-push: + runs-on: ubuntu-latest + outputs: + image_tag: ${{ steps.vars.outputs.short_sha }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set image tags + id: vars + run: | + echo "short_sha=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT" + echo "date_tag=$(date +%Y%m%d%H%M%S)" >> "$GITHUB_OUTPUT" + + - name: Login Harbor + env: + HARBOR_REGISTRY: ${{ secrets.HARBOR_REGISTRY }} + HARBOR_USERNAME: ${{ secrets.HARBOR_USERNAME }} + HARBOR_PASSWORD: ${{ secrets.HARBOR_PASSWORD }} + run: | + echo "$HARBOR_PASSWORD" | docker login "$HARBOR_REGISTRY" -u "$HARBOR_USERNAME" --password-stdin + + - name: Build image + env: + HARBOR_REGISTRY: ${{ secrets.HARBOR_REGISTRY }} + HARBOR_PROJECT: ${{ secrets.HARBOR_PROJECT }} + run: | + IMAGE="$HARBOR_REGISTRY/$HARBOR_PROJECT/$IMAGE_NAME" + docker build -f Dockerfile -t "$IMAGE:${{ steps.vars.outputs.short_sha }}" -t "$IMAGE:${{ steps.vars.outputs.date_tag }}" -t "$IMAGE:latest" . + + - name: Push image + env: + HARBOR_REGISTRY: ${{ secrets.HARBOR_REGISTRY }} + HARBOR_PROJECT: ${{ secrets.HARBOR_PROJECT }} + run: | + IMAGE="$HARBOR_REGISTRY/$HARBOR_PROJECT/$IMAGE_NAME" + docker push "$IMAGE:${{ steps.vars.outputs.short_sha }}" + docker push "$IMAGE:${{ steps.vars.outputs.date_tag }}" + docker push "$IMAGE:latest" + + deploy-server-docker: + runs-on: ubuntu-latest + needs: docker-build-push + if: github.ref_name == 'main' || github.ref_name == 'master' + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup SSH key + env: + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} + run: | + mkdir -p ~/.ssh + printf "%s" "$DEPLOY_SSH_KEY" > ~/.ssh/id_rsa + chmod 600 ~/.ssh/id_rsa + + - name: Add server host key + env: + DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }} + DEPLOY_PORT: ${{ secrets.DEPLOY_PORT }} + run: | + PORT="${DEPLOY_PORT:-22}" + ssh-keyscan -p "$PORT" "$DEPLOY_HOST" >> ~/.ssh/known_hosts + + - name: Upload compose file + env: + DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }} + DEPLOY_USER: ${{ secrets.DEPLOY_USER }} + DEPLOY_PORT: ${{ secrets.DEPLOY_PORT }} + DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }} + run: | + PORT="${DEPLOY_PORT:-22}" + TARGET_PATH="${DEPLOY_PATH:-/opt/st-1-example}" + ssh -p "$PORT" "$DEPLOY_USER@$DEPLOY_HOST" "mkdir -p $TARGET_PATH" + scp -P "$PORT" deploy/docker/docker-compose.yml "$DEPLOY_USER@$DEPLOY_HOST:$TARGET_PATH/docker-compose.yml" + + - name: Deploy on server + env: + DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }} + DEPLOY_USER: ${{ secrets.DEPLOY_USER }} + DEPLOY_PORT: ${{ secrets.DEPLOY_PORT }} + DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }} + HARBOR_REGISTRY: ${{ secrets.HARBOR_REGISTRY }} + HARBOR_PROJECT: ${{ secrets.HARBOR_PROJECT }} + HARBOR_USERNAME: ${{ secrets.HARBOR_USERNAME }} + HARBOR_PASSWORD: ${{ secrets.HARBOR_PASSWORD }} + run: | + PORT="${DEPLOY_PORT:-22}" + TARGET_PATH="${DEPLOY_PATH:-/opt/st-1-example}" + IMAGE_TAG="${{ needs.docker-build-push.outputs.image_tag }}" + ssh -p "$PORT" "$DEPLOY_USER@$DEPLOY_HOST" " + set -e; + cd $TARGET_PATH; + echo '$HARBOR_PASSWORD' | docker login '$HARBOR_REGISTRY' -u '$HARBOR_USERNAME' --password-stdin; + HARBOR_REGISTRY='$HARBOR_REGISTRY' HARBOR_PROJECT='$HARBOR_PROJECT' IMAGE_NAME='$IMAGE_NAME' IMAGE_TAG='$IMAGE_TAG' docker compose pull; + HARBOR_REGISTRY='$HARBOR_REGISTRY' HARBOR_PROJECT='$HARBOR_PROJECT' IMAGE_NAME='$IMAGE_NAME' IMAGE_TAG='$IMAGE_TAG' docker compose up -d; + docker image prune -f; + " diff --git a/app/community/api/community.go b/app/community/api/community.go new file mode 100644 index 0000000..bc6a5a1 --- /dev/null +++ b/app/community/api/community.go @@ -0,0 +1,34 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/community/api/internal/config" + "juwan-backend/app/community/api/internal/handler" + "juwan-backend/app/community/api/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/community-api.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/app/community/api/etc/community-api.yaml b/app/community/api/etc/community-api.yaml new file mode 100644 index 0000000..e23d7f1 --- /dev/null +++ b/app/community/api/etc/community-api.yaml @@ -0,0 +1,16 @@ +Name: community-api +Host: 0.0.0.0 +Port: 8888 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# k8s://juwan/:8080 + +CommunityRpcConf: + Target: k8s://juwan/community-rpc-svc.juwan:8080 + +UsercenterRpcConf: + Target: k8s://juwan/users-rpc-svc.juwan:8080 diff --git a/app/community/api/internal/config/config.go b/app/community/api/internal/config/config.go new file mode 100644 index 0000000..4cfad83 --- /dev/null +++ b/app/community/api/internal/config/config.go @@ -0,0 +1,15 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package config + +import ( + "github.com/zeromicro/go-zero/rest" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + rest.RestConf + CommunityRpcConf zrpc.RpcClientConf + UsercenterRpcConf zrpc.RpcClientConf +} diff --git a/app/community/api/internal/handler/community/createCommentHandler.go b/app/community/api/internal/handler/community/createCommentHandler.go new file mode 100644 index 0000000..40a34bb --- /dev/null +++ b/app/community/api/internal/handler/community/createCommentHandler.go @@ -0,0 +1,37 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" +) + +// 发表评论 +func CreateCommentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + types.PathId + types.CreateCommentReq + } + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + req.CreateCommentReq.PostId = req.PathId.Id + + l := community.NewCreateCommentLogic(r.Context(), svcCtx) + resp, err := l.CreateComment(&req.CreateCommentReq) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/createPostHandler.go b/app/community/api/internal/handler/community/createPostHandler.go new file mode 100644 index 0000000..a7192ba --- /dev/null +++ b/app/community/api/internal/handler/community/createPostHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 发布帖子 +func CreatePostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.CreatePostReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewCreatePostLogic(r.Context(), svcCtx) + resp, err := l.CreatePost(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/users/api/internal/handler/user/updateUserInfoHandler.go b/app/community/api/internal/handler/community/getPostHandler.go similarity index 51% rename from app/users/api/internal/handler/user/updateUserInfoHandler.go rename to app/community/api/internal/handler/community/getPostHandler.go index 1a1aad3..f8cba77 100644 --- a/app/users/api/internal/handler/user/updateUserInfoHandler.go +++ b/app/community/api/internal/handler/community/getPostHandler.go @@ -1,28 +1,28 @@ // Code scaffolded by goctl. Safe to edit. // goctl 1.9.2 -package user +package community import ( "net/http" "github.com/zeromicro/go-zero/rest/httpx" - "juwan-backend/app/users/api/internal/logic/user" - "juwan-backend/app/users/api/internal/svc" - "juwan-backend/app/users/api/internal/types" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" ) -// 修改用户信息 -func UpdateUserInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { +// 获取帖子详情 +func GetPostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.UpdateUserInfoReq + var req types.PathId if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return } - l := user.NewUpdateUserInfoLogic(r.Context(), svcCtx) - resp, err := l.UpdateUserInfo(&req) + l := community.NewGetPostLogic(r.Context(), svcCtx) + resp, err := l.GetPost(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) } else { diff --git a/app/community/api/internal/handler/community/likeCommentHandler.go b/app/community/api/internal/handler/community/likeCommentHandler.go new file mode 100644 index 0000000..7e384ee --- /dev/null +++ b/app/community/api/internal/handler/community/likeCommentHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 点赞评论 +func LikeCommentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewLikeCommentLogic(r.Context(), svcCtx) + resp, err := l.LikeComment(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/likePostHandler.go b/app/community/api/internal/handler/community/likePostHandler.go new file mode 100644 index 0000000..cc94fba --- /dev/null +++ b/app/community/api/internal/handler/community/likePostHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 点赞帖子 +func LikePostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewLikePostLogic(r.Context(), svcCtx) + resp, err := l.LikePost(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/listCommentsHandler.go b/app/community/api/internal/handler/community/listCommentsHandler.go new file mode 100644 index 0000000..152c60c --- /dev/null +++ b/app/community/api/internal/handler/community/listCommentsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 获取帖子评论 +func ListCommentsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.ListCommentsReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewListCommentsLogic(r.Context(), svcCtx) + resp, err := l.ListComments(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/listPostsHandler.go b/app/community/api/internal/handler/community/listPostsHandler.go new file mode 100644 index 0000000..a9ed71a --- /dev/null +++ b/app/community/api/internal/handler/community/listPostsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 获取帖子列表 +func ListPostsHandler(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 { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewListPostsLogic(r.Context(), svcCtx) + resp, err := l.ListPosts(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/listUserPostsHandler.go b/app/community/api/internal/handler/community/listUserPostsHandler.go new file mode 100644 index 0000000..ae779a6 --- /dev/null +++ b/app/community/api/internal/handler/community/listUserPostsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 获取用户帖子 +func ListUserPostsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.ListCommentsReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewListUserPostsLogic(r.Context(), svcCtx) + resp, err := l.ListUserPosts(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/pinPostHandler.go b/app/community/api/internal/handler/community/pinPostHandler.go new file mode 100644 index 0000000..d914b56 --- /dev/null +++ b/app/community/api/internal/handler/community/pinPostHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 置顶帖子 +func PinPostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewPinPostLogic(r.Context(), svcCtx) + resp, err := l.PinPost(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/unlikeCommentHandler.go b/app/community/api/internal/handler/community/unlikeCommentHandler.go new file mode 100644 index 0000000..fcbbdf4 --- /dev/null +++ b/app/community/api/internal/handler/community/unlikeCommentHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 取消点赞评论 +func UnlikeCommentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewUnlikeCommentLogic(r.Context(), svcCtx) + resp, err := l.UnlikeComment(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/unlikePostHandler.go b/app/community/api/internal/handler/community/unlikePostHandler.go new file mode 100644 index 0000000..1e4174d --- /dev/null +++ b/app/community/api/internal/handler/community/unlikePostHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 取消点赞帖子 +func UnlikePostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewUnlikePostLogic(r.Context(), svcCtx) + resp, err := l.UnlikePost(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/community/unpinPostHandler.go b/app/community/api/internal/handler/community/unpinPostHandler.go new file mode 100644 index 0000000..47c7c6f --- /dev/null +++ b/app/community/api/internal/handler/community/unpinPostHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/community/api/internal/logic/community" + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" +) + +// 取消置顶 +func UnpinPostHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := community.NewUnpinPostLogic(r.Context(), svcCtx) + resp, err := l.UnpinPost(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/community/api/internal/handler/routes.go b/app/community/api/internal/handler/routes.go new file mode 100644 index 0000000..ccbf8a0 --- /dev/null +++ b/app/community/api/internal/handler/routes.go @@ -0,0 +1,99 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 + +package handler + +import ( + "net/http" + + community "juwan-backend/app/community/api/internal/handler/community" + "juwan-backend/app/community/api/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + // 获取帖子列表 + Method: http.MethodGet, + Path: "/posts", + Handler: community.ListPostsHandler(serverCtx), + }, + { + // 获取帖子详情 + Method: http.MethodGet, + Path: "/posts/:id", + Handler: community.GetPostHandler(serverCtx), + }, + { + // 获取帖子评论 + Method: http.MethodGet, + Path: "/posts/:id/comments", + Handler: community.ListCommentsHandler(serverCtx), + }, + { + // 获取用户帖子 + Method: http.MethodGet, + Path: "/users/:id/posts", + Handler: community.ListUserPostsHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) + + server.AddRoutes( + []rest.Route{ + { + // 点赞评论 + Method: http.MethodPost, + Path: "/comments/:id/like", + Handler: community.LikeCommentHandler(serverCtx), + }, + { + // 取消点赞评论 + Method: http.MethodDelete, + Path: "/comments/:id/like", + Handler: community.UnlikeCommentHandler(serverCtx), + }, + { + // 发布帖子 + Method: http.MethodPost, + Path: "/posts", + Handler: community.CreatePostHandler(serverCtx), + }, + { + // 发表评论 + Method: http.MethodPost, + Path: "/posts/:id/comments", + Handler: community.CreateCommentHandler(serverCtx), + }, + { + // 点赞帖子 + Method: http.MethodPost, + Path: "/posts/:id/like", + Handler: community.LikePostHandler(serverCtx), + }, + { + // 取消点赞帖子 + Method: http.MethodDelete, + Path: "/posts/:id/like", + Handler: community.UnlikePostHandler(serverCtx), + }, + { + // 置顶帖子 + Method: http.MethodPost, + Path: "/posts/:id/pin", + Handler: community.PinPostHandler(serverCtx), + }, + { + // 取消置顶 + Method: http.MethodDelete, + Path: "/posts/:id/pin", + Handler: community.UnpinPostHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) +} diff --git a/app/community/api/internal/logic/community/createCommentLogic.go b/app/community/api/internal/logic/community/createCommentLogic.go new file mode 100644 index 0000000..e0800af --- /dev/null +++ b/app/community/api/internal/logic/community/createCommentLogic.go @@ -0,0 +1,57 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CreateCommentLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 发表评论 +func NewCreateCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCommentLogic { + return &CreateCommentLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CreateCommentLogic) CreateComment(req *types.CreateCommentReq) (resp *types.Comment, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + _, err = l.svcCtx.CommunityRpc.AddComments(l.ctx, &communitypb.AddCommentsReq{ + PostId: req.PostId, + AuthorId: uid, + Content: req.Content, + }) + if err != nil { + return nil, err + } + comments, err := l.svcCtx.CommunityRpc.SearchComments(l.ctx, &communitypb.SearchCommentsReq{ + Page: 0, + Limit: 1, + PostId: req.PostId, + AuthorId: uid, + }) + if err != nil || len(comments.GetComments()) == 0 { + return nil, err + } + out := mapComment(l.ctx, l.svcCtx, comments.GetComments()[len(comments.GetComments())-1], false) + return &out, nil + +} diff --git a/app/community/api/internal/logic/community/createPostLogic.go b/app/community/api/internal/logic/community/createPostLogic.go new file mode 100644 index 0000000..49b5773 --- /dev/null +++ b/app/community/api/internal/logic/community/createPostLogic.go @@ -0,0 +1,65 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + "strconv" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CreatePostLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 发布帖子 +func NewCreatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePostLogic { + return &CreatePostLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CreatePostLogic) CreatePost(req *types.CreatePostReq) (resp *types.Post, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + linkedOrderID := int64(0) + if req.LinkedOrderId != "" { + linkedOrderID, _ = strconv.ParseInt(req.LinkedOrderId, 10, 64) + } + _, err = l.svcCtx.CommunityRpc.AddPosts(l.ctx, &communitypb.AddPostsReq{ + AuthorId: uid, + AuthorRole: "consumer", + Title: req.Title, + Content: req.Content, + Images: req.Images, + Tags: req.Tags, + LinkedOrderId: linkedOrderID, + }) + if err != nil { + return nil, err + } + posts, err := l.svcCtx.CommunityRpc.SearchPosts(l.ctx, &communitypb.SearchPostsReq{ + Page: 0, + Limit: 1, + AuthorId: &uid, + }) + if err != nil || len(posts.GetPosts()) == 0 { + return nil, err + } + out := mapPost(l.ctx, l.svcCtx, posts.GetPosts()[0], false) + return &out, nil + +} diff --git a/app/community/api/internal/logic/community/getPostLogic.go b/app/community/api/internal/logic/community/getPostLogic.go new file mode 100644 index 0000000..f389ffb --- /dev/null +++ b/app/community/api/internal/logic/community/getPostLogic.go @@ -0,0 +1,45 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetPostLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取帖子详情 +func NewGetPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostLogic { + return &GetPostLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetPostLogic) GetPost(req *types.PathId) (resp *types.Post, err error) { + out, err := l.svcCtx.CommunityRpc.GetPostsById(l.ctx, &communitypb.GetPostsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + uid := currentUserIDOrZero(l.ctx) + liked := false + if uid > 0 { + likes, e := l.svcCtx.CommunityRpc.SearchPostLikes(l.ctx, &communitypb.SearchPostLikesReq{Page: 0, Limit: 1, PostId: &req.Id, UserId: &uid}) + liked = e == nil && len(likes.GetPostLikes()) > 0 + } + post := mapPost(l.ctx, l.svcCtx, out.GetPosts(), liked) + return &post, nil + +} diff --git a/app/community/api/internal/logic/community/helpers.go b/app/community/api/internal/logic/community/helpers.go new file mode 100644 index 0000000..91d7be4 --- /dev/null +++ b/app/community/api/internal/logic/community/helpers.go @@ -0,0 +1,69 @@ +package community + +import ( + "context" + "strconv" + "time" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + "juwan-backend/app/users/rpc/usercenter" + "juwan-backend/common/utils/contextj" +) + +func currentUserIDOrZero(ctx context.Context) int64 { + uid, err := contextj.UserIDFrom(ctx) + if err != nil { + return 0 + } + return uid +} + +func buildUserProfile(ctx context.Context, svcCtx *svc.ServiceContext, userID int64) types.UserProfile { + if userID <= 0 { + return types.UserProfile{} + } + resp, err := svcCtx.UserRpc.GetUsersById(ctx, &usercenter.GetUsersByIdReq{Id: userID}) + if err != nil || resp == nil || resp.Users == nil { + id := strconv.FormatInt(userID, 10) + return types.UserProfile{Id: id, Username: id, Nickname: "用户" + id, CreatedAt: time.Now().UTC().Format(time.RFC3339)} + } + u := resp.Users + return types.UserProfile{ + Id: strconv.FormatInt(u.GetId(), 10), + Username: u.GetUsername(), + Nickname: u.GetNickname(), + Avatar: u.GetAvatar(), + Role: u.GetCurrentRole(), + Phone: u.GetPhone(), + Bio: u.GetBio(), + CreatedAt: time.Unix(u.GetCreatedAt(), 0).UTC().Format(time.RFC3339), + } +} + +func mapPost(ctx context.Context, svcCtx *svc.ServiceContext, p *communitypb.Posts, liked bool) types.Post { + return types.Post{ + Id: p.GetId(), + Title: p.GetTitle(), + Content: p.GetContent(), + Images: append([]string(nil), p.GetImages()...), + Tags: append([]string(nil), p.GetTags()...), + LikeCount: p.GetLikeCount(), + CommentCount: p.GetCommentCount(), + Liked: liked, + Author: buildUserProfile(ctx, svcCtx, p.GetAuthorId()), + CreatedAt: time.Unix(p.GetCreatedAt(), 0).UTC().Format(time.RFC3339), + } +} + +func mapComment(ctx context.Context, svcCtx *svc.ServiceContext, c *communitypb.Comments, liked bool) types.Comment { + return types.Comment{ + Id: c.GetId(), + Content: c.GetContent(), + Author: buildUserProfile(ctx, svcCtx, c.GetAuthorId()), + LikeCount: c.GetLikeCount(), + Liked: liked, + CreatedAt: time.Unix(c.GetCreatedAt(), 0).UTC().Format(time.RFC3339), + } +} diff --git a/app/community/api/internal/logic/community/likeCommentLogic.go b/app/community/api/internal/logic/community/likeCommentLogic.go new file mode 100644 index 0000000..6fbb685 --- /dev/null +++ b/app/community/api/internal/logic/community/likeCommentLogic.go @@ -0,0 +1,43 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type LikeCommentLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 点赞评论 +func NewLikeCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LikeCommentLogic { + return &LikeCommentLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *LikeCommentLogic) LikeComment(req *types.PathId) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + _, err = l.svcCtx.CommunityRpc.AddCommentLikes(l.ctx, &communitypb.AddCommentLikesReq{CommentId: req.Id, UserId: uid}) + if err != nil { + return nil, err + } + return &types.EmptyResp{}, nil + +} diff --git a/app/community/api/internal/logic/community/likePostLogic.go b/app/community/api/internal/logic/community/likePostLogic.go new file mode 100644 index 0000000..daa71e9 --- /dev/null +++ b/app/community/api/internal/logic/community/likePostLogic.go @@ -0,0 +1,43 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type LikePostLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 点赞帖子 +func NewLikePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LikePostLogic { + return &LikePostLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *LikePostLogic) LikePost(req *types.PathId) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + _, err = l.svcCtx.CommunityRpc.AddPostLikes(l.ctx, &communitypb.AddPostLikesReq{PostId: req.Id, UserId: uid}) + if err != nil { + return nil, err + } + return &types.EmptyResp{}, nil + +} diff --git a/app/community/api/internal/logic/community/listCommentsLogic.go b/app/community/api/internal/logic/community/listCommentsLogic.go new file mode 100644 index 0000000..fcf02ab --- /dev/null +++ b/app/community/api/internal/logic/community/listCommentsLogic.go @@ -0,0 +1,55 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListCommentsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取帖子评论 +func NewListCommentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCommentsLogic { + return &ListCommentsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListCommentsLogic) ListComments(req *types.ListCommentsReq) (resp *types.CommentListResp, err error) { + if req.Limit <= 0 { + req.Limit = 20 + } + out, err := l.svcCtx.CommunityRpc.SearchComments(l.ctx, &communitypb.SearchCommentsReq{ + Page: req.Offset, + Limit: req.Limit, + PostId: req.Id, + }) + if err != nil { + return nil, err + } + uid := currentUserIDOrZero(l.ctx) + items := make([]types.Comment, 0, len(out.GetComments())) + for _, c := range out.GetComments() { + liked := false + if uid > 0 { + likes, e := l.svcCtx.CommunityRpc.SearchCommentLikes(l.ctx, &communitypb.SearchCommentLikesReq{Page: 0, Limit: 1, CommentId: c.Id, UserId: uid}) + liked = e == nil && len(likes.GetCommentLikes()) > 0 + } + items = append(items, mapComment(l.ctx, l.svcCtx, c, liked)) + } + return &types.CommentListResp{Items: items, Meta: types.PageMeta{Total: int64(len(items)), Offset: req.Offset, Limit: req.Limit}}, nil + +} diff --git a/app/community/api/internal/logic/community/listPostsLogic.go b/app/community/api/internal/logic/community/listPostsLogic.go new file mode 100644 index 0000000..d3f46fc --- /dev/null +++ b/app/community/api/internal/logic/community/listPostsLogic.go @@ -0,0 +1,56 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + "strings" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListPostsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取帖子列表 +func NewListPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListPostsLogic { + return &ListPostsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListPostsLogic) ListPosts(req *types.PostListReq) (resp *types.PostListResp, err error) { + if req.Limit <= 0 { + req.Limit = 20 + } + in := &communitypb.SearchPostsReq{Page: req.Offset, Limit: req.Limit} + if req.Tags != "" { + in.Tags = strings.Split(req.Tags, ",") + } + posts, err := l.svcCtx.CommunityRpc.SearchPosts(l.ctx, in) + if err != nil { + return nil, err + } + uid := currentUserIDOrZero(l.ctx) + items := make([]types.Post, 0, len(posts.GetPosts())) + for _, p := range posts.GetPosts() { + liked := false + if uid > 0 { + likes, e := l.svcCtx.CommunityRpc.SearchPostLikes(l.ctx, &communitypb.SearchPostLikesReq{Page: 0, Limit: 1, PostId: &p.Id, UserId: &uid}) + liked = e == nil && len(likes.GetPostLikes()) > 0 + } + items = append(items, mapPost(l.ctx, l.svcCtx, p, liked)) + } + return &types.PostListResp{Items: items, Meta: types.PageMeta{Total: int64(len(items)), Offset: req.Offset, Limit: req.Limit}}, nil + +} diff --git a/app/community/api/internal/logic/community/listUserPostsLogic.go b/app/community/api/internal/logic/community/listUserPostsLogic.go new file mode 100644 index 0000000..5b2ec8b --- /dev/null +++ b/app/community/api/internal/logic/community/listUserPostsLogic.go @@ -0,0 +1,52 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListUserPostsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取用户帖子 +func NewListUserPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUserPostsLogic { + return &ListUserPostsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListUserPostsLogic) ListUserPosts(req *types.ListCommentsReq) (resp *types.PostListResp, err error) { + if req.Limit <= 0 { + req.Limit = 20 + } + authorID := req.Id + out, err := l.svcCtx.CommunityRpc.SearchPosts(l.ctx, &communitypb.SearchPostsReq{Page: req.Offset, Limit: req.Limit, AuthorId: &authorID}) + if err != nil { + return nil, err + } + uid := currentUserIDOrZero(l.ctx) + items := make([]types.Post, 0, len(out.GetPosts())) + for _, p := range out.GetPosts() { + liked := false + if uid > 0 { + likes, e := l.svcCtx.CommunityRpc.SearchPostLikes(l.ctx, &communitypb.SearchPostLikesReq{Page: 0, Limit: 1, PostId: &p.Id, UserId: &uid}) + liked = e == nil && len(likes.GetPostLikes()) > 0 + } + items = append(items, mapPost(l.ctx, l.svcCtx, p, liked)) + } + return &types.PostListResp{Items: items, Meta: types.PageMeta{Total: int64(len(items)), Offset: req.Offset, Limit: req.Limit}}, nil + +} diff --git a/app/community/api/internal/logic/community/pinPostLogic.go b/app/community/api/internal/logic/community/pinPostLogic.go new file mode 100644 index 0000000..d0a4952 --- /dev/null +++ b/app/community/api/internal/logic/community/pinPostLogic.go @@ -0,0 +1,39 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type PinPostLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 置顶帖子 +func NewPinPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PinPostLogic { + return &PinPostLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *PinPostLogic) PinPost(req *types.PathId) (resp *types.EmptyResp, err error) { + t := true + _, err = l.svcCtx.CommunityRpc.UpdatePosts(l.ctx, &communitypb.UpdatePostsReq{Id: req.Id, Pinned: &t}) + if err != nil { + return nil, err + } + return &types.EmptyResp{}, nil + +} diff --git a/app/community/api/internal/logic/community/unlikeCommentLogic.go b/app/community/api/internal/logic/community/unlikeCommentLogic.go new file mode 100644 index 0000000..c410688 --- /dev/null +++ b/app/community/api/internal/logic/community/unlikeCommentLogic.go @@ -0,0 +1,43 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UnlikeCommentLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 取消点赞评论 +func NewUnlikeCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UnlikeCommentLogic { + return &UnlikeCommentLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *UnlikeCommentLogic) UnlikeComment(req *types.PathId) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + _, err = l.svcCtx.CommunityRpc.DelCommentLikes(l.ctx, &communitypb.DelCommentLikesReq{Id: req.Id, UserId: &uid}) + if err != nil { + return nil, err + } + return &types.EmptyResp{}, nil + +} diff --git a/app/community/api/internal/logic/community/unlikePostLogic.go b/app/community/api/internal/logic/community/unlikePostLogic.go new file mode 100644 index 0000000..0805265 --- /dev/null +++ b/app/community/api/internal/logic/community/unlikePostLogic.go @@ -0,0 +1,43 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UnlikePostLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 取消点赞帖子 +func NewUnlikePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UnlikePostLogic { + return &UnlikePostLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *UnlikePostLogic) UnlikePost(req *types.PathId) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + _, err = l.svcCtx.CommunityRpc.DelPostLikes(l.ctx, &communitypb.DelPostLikesReq{Id: req.Id, UserId: &uid}) + if err != nil { + return nil, err + } + return &types.EmptyResp{}, nil + +} diff --git a/app/community/api/internal/logic/community/unpinPostLogic.go b/app/community/api/internal/logic/community/unpinPostLogic.go new file mode 100644 index 0000000..26664d7 --- /dev/null +++ b/app/community/api/internal/logic/community/unpinPostLogic.go @@ -0,0 +1,39 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package community + +import ( + "context" + + "juwan-backend/app/community/api/internal/svc" + "juwan-backend/app/community/api/internal/types" + communitypb "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UnpinPostLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 取消置顶 +func NewUnpinPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UnpinPostLogic { + return &UnpinPostLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *UnpinPostLogic) UnpinPost(req *types.PathId) (resp *types.EmptyResp, err error) { + f := false + _, err = l.svcCtx.CommunityRpc.UpdatePosts(l.ctx, &communitypb.UpdatePostsReq{Id: req.Id, Pinned: &f}) + if err != nil { + return nil, err + } + return &types.EmptyResp{}, nil + +} diff --git a/app/community/api/internal/svc/serviceContext.go b/app/community/api/internal/svc/serviceContext.go new file mode 100644 index 0000000..3ebbac6 --- /dev/null +++ b/app/community/api/internal/svc/serviceContext.go @@ -0,0 +1,26 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package svc + +import ( + "juwan-backend/app/community/api/internal/config" + "juwan-backend/app/community/rpc/communityservice" + "juwan-backend/app/users/rpc/usercenter" + + "github.com/zeromicro/go-zero/zrpc" +) + +type ServiceContext struct { + Config config.Config + CommunityRpc communityservice.CommunityService + UserRpc usercenter.Usercenter +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + CommunityRpc: communityservice.NewCommunityService(zrpc.MustNewClient(c.CommunityRpcConf)), + UserRpc: usercenter.NewUsercenter(zrpc.MustNewClient(c.UsercenterRpcConf)), + } +} diff --git a/app/community/api/internal/types/types.go b/app/community/api/internal/types/types.go new file mode 100644 index 0000000..b7b9fbf --- /dev/null +++ b/app/community/api/internal/types/types.go @@ -0,0 +1,97 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 + +package types + +type Comment struct { + Id int64 `json:"id"` + Content string `json:"content"` + Author UserProfile `json:"author"` + LikeCount int64 `json:"likeCount"` + Liked bool `json:"liked"` + CreatedAt string `json:"createdAt"` +} + +type CommentListResp struct { + Items []Comment `json:"items"` + Meta PageMeta `json:"meta"` +} + +type CreateCommentReq struct { + PostId int64 `json:"-"` + Content string `json:"content"` +} + +type CreatePostReq struct { + Title string `json:"title"` + Content string `json:"content"` + Images []string `json:"images"` + Tags []string `json:"tags"` + LinkedOrderId string `json:"linkedOrderId,optional"` +} + +type EmptyResp struct { +} + +type ListCommentsReq struct { + PathId + PageReq +} + +type PageMeta struct { + Total int64 `json:"total"` + Offset int64 `json:"offset"` + Limit int64 `json:"limit"` +} + +type PageReq struct { + Offset int64 `form:"offset,default=0"` + Limit int64 `form:"limit,default=20"` +} + +type PathId struct { + Id int64 `path:"id"` +} + +type Post struct { + Id int64 `json:"id"` + Title string `json:"title"` + Content string `json:"content"` + Images []string `json:"images"` + Tags []string `json:"tags"` + LikeCount int64 `json:"likeCount"` + CommentCount int64 `json:"commentCount"` + Liked bool `json:"liked"` + Author UserProfile `json:"author"` + CreatedAt string `json:"createdAt"` +} + +type PostListReq struct { + PageReq + Tags string `form:"tags,optional"` + SortBy string `form:"sortBy,optional"` +} + +type PostListResp struct { + Items []Post `json:"items"` + Meta PageMeta `json:"meta"` +} + +type SimpleUser struct { + Id string `json:"id"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` +} + +type UserProfile struct { + Id string `json:"id"` + Username string `json:"username"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` + Role string `json:"role"` // consumer, player, owner, admin + VerifiedRoles []string `json:"verifiedRoles"` + VerificationStatus map[string]string `json:"verificationStatus"` + Phone string `json:"phone,optional"` + Bio string `json:"bio,optional"` + CreatedAt string `json:"createdAt"` +} diff --git a/app/community/rpc/communityservice/communityService.go b/app/community/rpc/communityservice/communityService.go new file mode 100644 index 0000000..91cae3c --- /dev/null +++ b/app/community/rpc/communityservice/communityService.go @@ -0,0 +1,202 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 +// Source: community.proto + +package communityservice + +import ( + "context" + + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + AddCommentLikesReq = pb.AddCommentLikesReq + AddCommentLikesResp = pb.AddCommentLikesResp + AddCommentsReq = pb.AddCommentsReq + AddCommentsResp = pb.AddCommentsResp + AddPostLikesReq = pb.AddPostLikesReq + AddPostLikesResp = pb.AddPostLikesResp + AddPostsReq = pb.AddPostsReq + AddPostsResp = pb.AddPostsResp + CommentLikes = pb.CommentLikes + Comments = pb.Comments + DelCommentLikesReq = pb.DelCommentLikesReq + DelCommentLikesResp = pb.DelCommentLikesResp + DelCommentsReq = pb.DelCommentsReq + DelCommentsResp = pb.DelCommentsResp + DelPostLikesReq = pb.DelPostLikesReq + DelPostLikesResp = pb.DelPostLikesResp + DelPostsReq = pb.DelPostsReq + DelPostsResp = pb.DelPostsResp + GetCommentLikesByIdReq = pb.GetCommentLikesByIdReq + GetCommentLikesByIdResp = pb.GetCommentLikesByIdResp + GetCommentsByIdReq = pb.GetCommentsByIdReq + GetCommentsByIdResp = pb.GetCommentsByIdResp + GetPostLikesByIdReq = pb.GetPostLikesByIdReq + GetPostLikesByIdResp = pb.GetPostLikesByIdResp + GetPostsByIdReq = pb.GetPostsByIdReq + GetPostsByIdResp = pb.GetPostsByIdResp + PostLikes = pb.PostLikes + Posts = pb.Posts + SearchCommentLikesReq = pb.SearchCommentLikesReq + SearchCommentLikesResp = pb.SearchCommentLikesResp + SearchCommentsReq = pb.SearchCommentsReq + SearchCommentsResp = pb.SearchCommentsResp + SearchPostLikesReq = pb.SearchPostLikesReq + SearchPostLikesResp = pb.SearchPostLikesResp + SearchPostsReq = pb.SearchPostsReq + SearchPostsResp = pb.SearchPostsResp + UpdateCommentLikesReq = pb.UpdateCommentLikesReq + UpdateCommentLikesResp = pb.UpdateCommentLikesResp + UpdateCommentsReq = pb.UpdateCommentsReq + UpdateCommentsResp = pb.UpdateCommentsResp + UpdatePostLikesReq = pb.UpdatePostLikesReq + UpdatePostLikesResp = pb.UpdatePostLikesResp + UpdatePostsReq = pb.UpdatePostsReq + UpdatePostsResp = pb.UpdatePostsResp + + CommunityService interface { + // -----------------------commentLikes----------------------- + AddCommentLikes(ctx context.Context, in *AddCommentLikesReq, opts ...grpc.CallOption) (*AddCommentLikesResp, error) + UpdateCommentLikes(ctx context.Context, in *UpdateCommentLikesReq, opts ...grpc.CallOption) (*UpdateCommentLikesResp, error) + DelCommentLikes(ctx context.Context, in *DelCommentLikesReq, opts ...grpc.CallOption) (*DelCommentLikesResp, error) + GetCommentLikesById(ctx context.Context, in *GetCommentLikesByIdReq, opts ...grpc.CallOption) (*GetCommentLikesByIdResp, error) + SearchCommentLikes(ctx context.Context, in *SearchCommentLikesReq, opts ...grpc.CallOption) (*SearchCommentLikesResp, error) + // -----------------------comments----------------------- + AddComments(ctx context.Context, in *AddCommentsReq, opts ...grpc.CallOption) (*AddCommentsResp, error) + UpdateComments(ctx context.Context, in *UpdateCommentsReq, opts ...grpc.CallOption) (*UpdateCommentsResp, error) + DelComments(ctx context.Context, in *DelCommentsReq, opts ...grpc.CallOption) (*DelCommentsResp, error) + GetCommentsById(ctx context.Context, in *GetCommentsByIdReq, opts ...grpc.CallOption) (*GetCommentsByIdResp, error) + SearchComments(ctx context.Context, in *SearchCommentsReq, opts ...grpc.CallOption) (*SearchCommentsResp, error) + // -----------------------postLikes----------------------- + AddPostLikes(ctx context.Context, in *AddPostLikesReq, opts ...grpc.CallOption) (*AddPostLikesResp, error) + UpdatePostLikes(ctx context.Context, in *UpdatePostLikesReq, opts ...grpc.CallOption) (*UpdatePostLikesResp, error) + DelPostLikes(ctx context.Context, in *DelPostLikesReq, opts ...grpc.CallOption) (*DelPostLikesResp, error) + GetPostLikesById(ctx context.Context, in *GetPostLikesByIdReq, opts ...grpc.CallOption) (*GetPostLikesByIdResp, error) + SearchPostLikes(ctx context.Context, in *SearchPostLikesReq, opts ...grpc.CallOption) (*SearchPostLikesResp, error) + // -----------------------posts----------------------- + AddPosts(ctx context.Context, in *AddPostsReq, opts ...grpc.CallOption) (*AddPostsResp, error) + UpdatePosts(ctx context.Context, in *UpdatePostsReq, opts ...grpc.CallOption) (*UpdatePostsResp, error) + DelPosts(ctx context.Context, in *DelPostsReq, opts ...grpc.CallOption) (*DelPostsResp, error) + GetPostsById(ctx context.Context, in *GetPostsByIdReq, opts ...grpc.CallOption) (*GetPostsByIdResp, error) + SearchPosts(ctx context.Context, in *SearchPostsReq, opts ...grpc.CallOption) (*SearchPostsResp, error) + } + + defaultCommunityService struct { + cli zrpc.Client + } +) + +func NewCommunityService(cli zrpc.Client) CommunityService { + return &defaultCommunityService{ + cli: cli, + } +} + +// -----------------------commentLikes----------------------- +func (m *defaultCommunityService) AddCommentLikes(ctx context.Context, in *AddCommentLikesReq, opts ...grpc.CallOption) (*AddCommentLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.AddCommentLikes(ctx, in, opts...) +} + +func (m *defaultCommunityService) UpdateCommentLikes(ctx context.Context, in *UpdateCommentLikesReq, opts ...grpc.CallOption) (*UpdateCommentLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.UpdateCommentLikes(ctx, in, opts...) +} + +func (m *defaultCommunityService) DelCommentLikes(ctx context.Context, in *DelCommentLikesReq, opts ...grpc.CallOption) (*DelCommentLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.DelCommentLikes(ctx, in, opts...) +} + +func (m *defaultCommunityService) GetCommentLikesById(ctx context.Context, in *GetCommentLikesByIdReq, opts ...grpc.CallOption) (*GetCommentLikesByIdResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.GetCommentLikesById(ctx, in, opts...) +} + +func (m *defaultCommunityService) SearchCommentLikes(ctx context.Context, in *SearchCommentLikesReq, opts ...grpc.CallOption) (*SearchCommentLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.SearchCommentLikes(ctx, in, opts...) +} + +// -----------------------comments----------------------- +func (m *defaultCommunityService) AddComments(ctx context.Context, in *AddCommentsReq, opts ...grpc.CallOption) (*AddCommentsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.AddComments(ctx, in, opts...) +} + +func (m *defaultCommunityService) UpdateComments(ctx context.Context, in *UpdateCommentsReq, opts ...grpc.CallOption) (*UpdateCommentsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.UpdateComments(ctx, in, opts...) +} + +func (m *defaultCommunityService) DelComments(ctx context.Context, in *DelCommentsReq, opts ...grpc.CallOption) (*DelCommentsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.DelComments(ctx, in, opts...) +} + +func (m *defaultCommunityService) GetCommentsById(ctx context.Context, in *GetCommentsByIdReq, opts ...grpc.CallOption) (*GetCommentsByIdResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.GetCommentsById(ctx, in, opts...) +} + +func (m *defaultCommunityService) SearchComments(ctx context.Context, in *SearchCommentsReq, opts ...grpc.CallOption) (*SearchCommentsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.SearchComments(ctx, in, opts...) +} + +// -----------------------postLikes----------------------- +func (m *defaultCommunityService) AddPostLikes(ctx context.Context, in *AddPostLikesReq, opts ...grpc.CallOption) (*AddPostLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.AddPostLikes(ctx, in, opts...) +} + +func (m *defaultCommunityService) UpdatePostLikes(ctx context.Context, in *UpdatePostLikesReq, opts ...grpc.CallOption) (*UpdatePostLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.UpdatePostLikes(ctx, in, opts...) +} + +func (m *defaultCommunityService) DelPostLikes(ctx context.Context, in *DelPostLikesReq, opts ...grpc.CallOption) (*DelPostLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.DelPostLikes(ctx, in, opts...) +} + +func (m *defaultCommunityService) GetPostLikesById(ctx context.Context, in *GetPostLikesByIdReq, opts ...grpc.CallOption) (*GetPostLikesByIdResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.GetPostLikesById(ctx, in, opts...) +} + +func (m *defaultCommunityService) SearchPostLikes(ctx context.Context, in *SearchPostLikesReq, opts ...grpc.CallOption) (*SearchPostLikesResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.SearchPostLikes(ctx, in, opts...) +} + +// -----------------------posts----------------------- +func (m *defaultCommunityService) AddPosts(ctx context.Context, in *AddPostsReq, opts ...grpc.CallOption) (*AddPostsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.AddPosts(ctx, in, opts...) +} + +func (m *defaultCommunityService) UpdatePosts(ctx context.Context, in *UpdatePostsReq, opts ...grpc.CallOption) (*UpdatePostsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.UpdatePosts(ctx, in, opts...) +} + +func (m *defaultCommunityService) DelPosts(ctx context.Context, in *DelPostsReq, opts ...grpc.CallOption) (*DelPostsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.DelPosts(ctx, in, opts...) +} + +func (m *defaultCommunityService) GetPostsById(ctx context.Context, in *GetPostsByIdReq, opts ...grpc.CallOption) (*GetPostsByIdResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.GetPostsById(ctx, in, opts...) +} + +func (m *defaultCommunityService) SearchPosts(ctx context.Context, in *SearchPostsReq, opts ...grpc.CallOption) (*SearchPostsResp, error) { + client := pb.NewCommunityServiceClient(m.cli.Conn()) + return client.SearchPosts(ctx, in, opts...) +} diff --git a/app/community/rpc/etc/pb.yaml b/app/community/rpc/etc/pb.yaml new file mode 100644 index 0000000..3763106 --- /dev/null +++ b/app/community/rpc/etc/pb.yaml @@ -0,0 +1,38 @@ +Name: pb.rpc +ListenOn: 0.0.0.0:8080 + + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# tcd: +# Hosts: +# - 127.0.0.1:2379 +# Key: pb.rpc + +# Target: k8s://juwan/.:8080 + + +SnowflakeRpcConf: + Target: k8s://juwan/snowflake-svc:8080 + + +DB: + Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + + +CacheConf: + - Host: "${REDIS_M_HOST}" + Type: node + Pass: "${REDIS_PASSWORD}" + User: "default" + - Host: "${REDIS_S_HOST}" + Type: node + Pass: "${REDIS_PASSWORD}" + User: "default" + +Log: + Level: info diff --git a/app/community/rpc/internal/config/config.go b/app/community/rpc/internal/config/config.go new file mode 100644 index 0000000..f4107e8 --- /dev/null +++ b/app/community/rpc/internal/config/config.go @@ -0,0 +1,17 @@ +package config + +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + zrpc.RpcServerConf + + SnowflakeRpcConf zrpc.RpcClientConf + DB struct { + Master string + Slaves string + } + CacheConf cache.CacheConf +} diff --git a/app/community/rpc/internal/logic/addCommentLikesLogic.go b/app/community/rpc/internal/logic/addCommentLikesLogic.go new file mode 100644 index 0000000..81e088d --- /dev/null +++ b/app/community/rpc/internal/logic/addCommentLikesLogic.go @@ -0,0 +1,55 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddCommentLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddCommentLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCommentLikesLogic { + return &AddCommentLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------commentLikes----------------------- +func (l *AddCommentLikesLogic) AddCommentLikes(in *pb.AddCommentLikesReq) (*pb.AddCommentLikesResp, error) { + if in.GetCommentId() <= 0 || in.GetUserId() <= 0 { + return nil, errors.New("commentId and userId are required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + comment, ok := store.Comments[in.GetCommentId()] + if !ok || comment.GetDeletedAt() > 0 { + return nil, errors.New("comment not found") + } + + key := commentLikeKey(in.GetCommentId(), in.GetUserId()) + if _, exists := store.CommentLikes[key]; exists { + return &pb.AddCommentLikesResp{}, nil + } + + store.CommentLikes[key] = &pb.CommentLikes{ + CommentId: in.GetCommentId(), + UserId: in.GetUserId(), + CreatedAt: nowUnix(in.GetCreatedAt()), + } + comment.LikeCount++ + + return &pb.AddCommentLikesResp{}, nil +} diff --git a/app/community/rpc/internal/logic/addCommentsLogic.go b/app/community/rpc/internal/logic/addCommentsLogic.go new file mode 100644 index 0000000..8283bbe --- /dev/null +++ b/app/community/rpc/internal/logic/addCommentsLogic.go @@ -0,0 +1,62 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddCommentsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddCommentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCommentsLogic { + return &AddCommentsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------comments----------------------- +func (l *AddCommentsLogic) AddComments(in *pb.AddCommentsReq) (*pb.AddCommentsResp, error) { + if in.GetPostId() <= 0 { + return nil, errors.New("postId is required") + } + if in.GetAuthorId() <= 0 { + return nil, errors.New("authorId is required") + } + if in.GetContent() == "" { + return nil, errors.New("content is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + post, ok := store.Posts[in.GetPostId()] + if !ok || post.GetDeletedAt() > 0 { + return nil, errors.New("post not found") + } + + now := nowUnix(in.GetCreatedAt()) + comment := &pb.Comments{ + Id: store.NextComment(), + PostId: in.GetPostId(), + AuthorId: in.GetAuthorId(), + Content: in.GetContent(), + LikeCount: 0, + CreatedAt: now, + } + store.Comments[comment.Id] = comment + post.CommentCount++ + post.UpdatedAt = now + + return &pb.AddCommentsResp{}, nil +} diff --git a/app/community/rpc/internal/logic/addPostLikesLogic.go b/app/community/rpc/internal/logic/addPostLikesLogic.go new file mode 100644 index 0000000..82a35ff --- /dev/null +++ b/app/community/rpc/internal/logic/addPostLikesLogic.go @@ -0,0 +1,56 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddPostLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddPostLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPostLikesLogic { + return &AddPostLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------postLikes----------------------- +func (l *AddPostLikesLogic) AddPostLikes(in *pb.AddPostLikesReq) (*pb.AddPostLikesResp, error) { + // todo: add your logic here and delete this line + if in.GetPostId() <= 0 || in.GetUserId() <= 0 { + return nil, errors.New("postId and userId are required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + post, ok := store.Posts[in.GetPostId()] + if !ok || post.GetDeletedAt() > 0 { + return nil, errors.New("post not found") + } + + key := postLikeKey(in.GetPostId(), in.GetUserId()) + if _, exists := store.PostLikes[key]; exists { + return &pb.AddPostLikesResp{}, nil + } + + store.PostLikes[key] = &pb.PostLikes{ + PostId: in.GetPostId(), + UserId: in.GetUserId(), + CreatedAt: nowUnix(in.GetCreatedAt()), + } + post.LikeCount++ + + return &pb.AddPostLikesResp{}, nil +} diff --git a/app/community/rpc/internal/logic/addPostsLogic.go b/app/community/rpc/internal/logic/addPostsLogic.go new file mode 100644 index 0000000..87f1742 --- /dev/null +++ b/app/community/rpc/internal/logic/addPostsLogic.go @@ -0,0 +1,67 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddPostsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPostsLogic { + return &AddPostsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------posts----------------------- +func (l *AddPostsLogic) AddPosts(in *pb.AddPostsReq) (*pb.AddPostsResp, error) { + if in.GetAuthorId() <= 0 { + return nil, errors.New("authorId is required") + } + if in.GetTitle() == "" { + return nil, errors.New("title is required") + } + if in.GetContent() == "" { + return nil, errors.New("content is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + now := nowUnix(in.GetCreatedAt()) + post := &pb.Posts{ + Id: store.NextPost(), + AuthorId: in.GetAuthorId(), + AuthorRole: in.GetAuthorRole(), + Title: in.GetTitle(), + Content: in.GetContent(), + Images: append([]string(nil), in.GetImages()...), + Tags: append([]string(nil), in.GetTags()...), + LinkedOrderId: in.GetLinkedOrderId(), + QuotedPostId: in.GetQuotedPostId(), + LikeCount: 0, + CommentCount: 0, + Pinned: in.GetPinned(), + SearchText: in.GetTitle() + " " + in.GetContent(), + CreatedAt: now, + UpdatedAt: now, + } + if post.AuthorRole == "" { + post.AuthorRole = "consumer" + } + store.Posts[post.Id] = post + + return &pb.AddPostsResp{}, nil +} diff --git a/app/community/rpc/internal/logic/delCommentLikesLogic.go b/app/community/rpc/internal/logic/delCommentLikesLogic.go new file mode 100644 index 0000000..1ecf61e --- /dev/null +++ b/app/community/rpc/internal/logic/delCommentLikesLogic.go @@ -0,0 +1,65 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelCommentLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelCommentLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelCommentLikesLogic { + return &DelCommentLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelCommentLikesLogic) DelCommentLikes(in *pb.DelCommentLikesReq) (*pb.DelCommentLikesResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + if in.UserId != nil && in.GetUserId() > 0 { + key := commentLikeKey(in.GetId(), in.GetUserId()) + if _, ok := store.CommentLikes[key]; ok { + delete(store.CommentLikes, key) + if comment, ok := store.Comments[in.GetId()]; ok && comment.LikeCount > 0 { + comment.LikeCount-- + } + } + return &pb.DelCommentLikesResp{}, nil + } + + removed := int64(0) + for key, like := range store.CommentLikes { + if like.GetCommentId() == in.GetId() { + delete(store.CommentLikes, key) + removed++ + } + } + if removed > 0 { + if comment, ok := store.Comments[in.GetId()]; ok { + if comment.LikeCount >= removed { + comment.LikeCount -= removed + } else { + comment.LikeCount = 0 + } + } + } + + return &pb.DelCommentLikesResp{}, nil +} diff --git a/app/community/rpc/internal/logic/delCommentsLogic.go b/app/community/rpc/internal/logic/delCommentsLogic.go new file mode 100644 index 0000000..297a15e --- /dev/null +++ b/app/community/rpc/internal/logic/delCommentsLogic.go @@ -0,0 +1,50 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelCommentsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelCommentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelCommentsLogic { + return &DelCommentsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelCommentsLogic) DelComments(in *pb.DelCommentsReq) (*pb.DelCommentsResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + comment, ok := store.Comments[in.GetId()] + if !ok { + return &pb.DelCommentsResp{}, nil + } + if comment.GetDeletedAt() == 0 { + now := nowUnix(0) + comment.DeletedAt = now + if post, ok := store.Posts[comment.GetPostId()]; ok && post.GetDeletedAt() == 0 && post.CommentCount > 0 { + post.CommentCount-- + post.UpdatedAt = now + } + } + + return &pb.DelCommentsResp{}, nil +} diff --git a/app/community/rpc/internal/logic/delPostLikesLogic.go b/app/community/rpc/internal/logic/delPostLikesLogic.go new file mode 100644 index 0000000..8b0e5ce --- /dev/null +++ b/app/community/rpc/internal/logic/delPostLikesLogic.go @@ -0,0 +1,65 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelPostLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelPostLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelPostLikesLogic { + return &DelPostLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelPostLikesLogic) DelPostLikes(in *pb.DelPostLikesReq) (*pb.DelPostLikesResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + if in.UserId != nil && in.GetUserId() > 0 { + key := postLikeKey(in.GetId(), in.GetUserId()) + if _, ok := store.PostLikes[key]; ok { + delete(store.PostLikes, key) + if post, ok := store.Posts[in.GetId()]; ok && post.LikeCount > 0 { + post.LikeCount-- + } + } + return &pb.DelPostLikesResp{}, nil + } + + removed := int64(0) + for key, like := range store.PostLikes { + if like.GetPostId() == in.GetId() { + delete(store.PostLikes, key) + removed++ + } + } + if removed > 0 { + if post, ok := store.Posts[in.GetId()]; ok { + if post.LikeCount >= removed { + post.LikeCount -= removed + } else { + post.LikeCount = 0 + } + } + } + + return &pb.DelPostLikesResp{}, nil +} diff --git a/app/community/rpc/internal/logic/delPostsLogic.go b/app/community/rpc/internal/logic/delPostsLogic.go new file mode 100644 index 0000000..15588c7 --- /dev/null +++ b/app/community/rpc/internal/logic/delPostsLogic.go @@ -0,0 +1,45 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelPostsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelPostsLogic { + return &DelPostsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelPostsLogic) DelPosts(in *pb.DelPostsReq) (*pb.DelPostsResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + post, ok := store.Posts[in.GetId()] + if !ok { + return &pb.DelPostsResp{}, nil + } + now := nowUnix(0) + post.DeletedAt = now + post.UpdatedAt = now + + return &pb.DelPostsResp{}, nil +} diff --git a/app/community/rpc/internal/logic/getCommentLikesByIdLogic.go b/app/community/rpc/internal/logic/getCommentLikesByIdLogic.go new file mode 100644 index 0000000..2366250 --- /dev/null +++ b/app/community/rpc/internal/logic/getCommentLikesByIdLogic.go @@ -0,0 +1,44 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetCommentLikesByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetCommentLikesByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCommentLikesByIdLogic { + return &GetCommentLikesByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetCommentLikesByIdLogic) GetCommentLikesById(in *pb.GetCommentLikesByIdReq) (*pb.GetCommentLikesByIdResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + for _, like := range store.CommentLikes { + if like.GetCommentId() == in.GetId() { + cp := *like + return &pb.GetCommentLikesByIdResp{CommentLikes: &cp}, nil + } + } + return nil, errors.New("comment like not found") + +} diff --git a/app/community/rpc/internal/logic/getCommentsByIdLogic.go b/app/community/rpc/internal/logic/getCommentsByIdLogic.go new file mode 100644 index 0000000..c840c1d --- /dev/null +++ b/app/community/rpc/internal/logic/getCommentsByIdLogic.go @@ -0,0 +1,43 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetCommentsByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetCommentsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCommentsByIdLogic { + return &GetCommentsByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetCommentsByIdLogic) GetCommentsById(in *pb.GetCommentsByIdReq) (*pb.GetCommentsByIdResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + comment, ok := store.Comments[in.GetId()] + if !ok || comment.GetDeletedAt() > 0 { + return nil, errors.New("comment not found") + } + out := *comment + + return &pb.GetCommentsByIdResp{Comments: &out}, nil +} diff --git a/app/community/rpc/internal/logic/getPostLikesByIdLogic.go b/app/community/rpc/internal/logic/getPostLikesByIdLogic.go new file mode 100644 index 0000000..a5cf988 --- /dev/null +++ b/app/community/rpc/internal/logic/getPostLikesByIdLogic.go @@ -0,0 +1,44 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetPostLikesByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetPostLikesByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostLikesByIdLogic { + return &GetPostLikesByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetPostLikesByIdLogic) GetPostLikesById(in *pb.GetPostLikesByIdReq) (*pb.GetPostLikesByIdResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + for _, like := range store.PostLikes { + if like.GetPostId() == in.GetId() { + cp := *like + return &pb.GetPostLikesByIdResp{PostLikes: &cp}, nil + } + } + return nil, errors.New("post like not found") + +} diff --git a/app/community/rpc/internal/logic/getPostsByIdLogic.go b/app/community/rpc/internal/logic/getPostsByIdLogic.go new file mode 100644 index 0000000..95a818a --- /dev/null +++ b/app/community/rpc/internal/logic/getPostsByIdLogic.go @@ -0,0 +1,46 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetPostsByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetPostsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostsByIdLogic { + return &GetPostsByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetPostsByIdLogic) GetPostsById(in *pb.GetPostsByIdReq) (*pb.GetPostsByIdResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + post, ok := store.Posts[in.GetId()] + if !ok || post.GetDeletedAt() > 0 { + return nil, errors.New("post not found") + } + + out := *post + out.Images = append([]string(nil), post.Images...) + out.Tags = append([]string(nil), post.Tags...) + + return &pb.GetPostsByIdResp{Posts: &out}, nil +} diff --git a/app/community/rpc/internal/logic/helpers.go b/app/community/rpc/internal/logic/helpers.go new file mode 100644 index 0000000..32dd62f --- /dev/null +++ b/app/community/rpc/internal/logic/helpers.go @@ -0,0 +1,45 @@ +package logic + +import ( + "sort" + "strconv" + "time" + + "juwan-backend/app/community/rpc/pb" +) + +func nowUnix(in int64) int64 { + if in > 0 { + return in + } + return time.Now().Unix() +} + +func postLikeKey(postID, userID int64) string { + return strconv.FormatInt(postID, 10) + ":" + strconv.FormatInt(userID, 10) +} + +func commentLikeKey(commentID, userID int64) string { + return strconv.FormatInt(commentID, 10) + ":" + strconv.FormatInt(userID, 10) +} + +func sortPostsDesc(posts []*pb.Posts) { + sort.Slice(posts, func(i, j int) bool { + if posts[i].Pinned != posts[j].Pinned { + return posts[i].Pinned + } + if posts[i].CreatedAt == posts[j].CreatedAt { + return posts[i].Id > posts[j].Id + } + return posts[i].CreatedAt > posts[j].CreatedAt + }) +} + +func sortCommentsAsc(comments []*pb.Comments) { + sort.Slice(comments, func(i, j int) bool { + if comments[i].CreatedAt == comments[j].CreatedAt { + return comments[i].Id < comments[j].Id + } + return comments[i].CreatedAt < comments[j].CreatedAt + }) +} diff --git a/app/community/rpc/internal/logic/searchCommentLikesLogic.go b/app/community/rpc/internal/logic/searchCommentLikesLogic.go new file mode 100644 index 0000000..8db9429 --- /dev/null +++ b/app/community/rpc/internal/logic/searchCommentLikesLogic.go @@ -0,0 +1,61 @@ +package logic + +import ( + "context" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchCommentLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchCommentLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchCommentLikesLogic { + return &SearchCommentLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchCommentLikesLogic) SearchCommentLikes(in *pb.SearchCommentLikesReq) (*pb.SearchCommentLikesResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + offset := in.GetPage() + if offset < 0 { + offset = 0 + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + filtered := make([]*pb.CommentLikes, 0, len(store.CommentLikes)) + for _, like := range store.CommentLikes { + if in.GetCommentId() > 0 && like.GetCommentId() != in.GetCommentId() { + continue + } + if in.GetUserId() > 0 && like.GetUserId() != in.GetUserId() { + continue + } + cp := *like + filtered = append(filtered, &cp) + } + + if offset >= int64(len(filtered)) { + return &pb.SearchCommentLikesResp{CommentLikes: []*pb.CommentLikes{}}, nil + } + end := offset + limit + if end > int64(len(filtered)) { + end = int64(len(filtered)) + } + + return &pb.SearchCommentLikesResp{CommentLikes: filtered[offset:end]}, nil +} diff --git a/app/community/rpc/internal/logic/searchCommentsLogic.go b/app/community/rpc/internal/logic/searchCommentsLogic.go new file mode 100644 index 0000000..a65a2c9 --- /dev/null +++ b/app/community/rpc/internal/logic/searchCommentsLogic.go @@ -0,0 +1,76 @@ +package logic + +import ( + "context" + "strings" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchCommentsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchCommentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchCommentsLogic { + return &SearchCommentsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchCommentsLogic) SearchComments(in *pb.SearchCommentsReq) (*pb.SearchCommentsResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + offset := in.GetPage() + if offset < 0 { + offset = 0 + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + filtered := make([]*pb.Comments, 0, len(store.Comments)) + for _, c := range store.Comments { + if c.GetDeletedAt() > 0 { + continue + } + if in.GetId() > 0 && c.GetId() != in.GetId() { + continue + } + if in.GetPostId() > 0 && c.GetPostId() != in.GetPostId() { + continue + } + if in.GetAuthorId() > 0 && c.GetAuthorId() != in.GetAuthorId() { + continue + } + if in.Content != nil && !strings.Contains(strings.ToLower(c.GetContent()), strings.ToLower(in.GetContent())) { + continue + } + if in.LikeCount != nil && c.GetLikeCount() != in.GetLikeCount() { + continue + } + cc := *c + filtered = append(filtered, &cc) + } + + sortCommentsAsc(filtered) + + if offset >= int64(len(filtered)) { + return &pb.SearchCommentsResp{Comments: []*pb.Comments{}}, nil + } + end := offset + limit + if end > int64(len(filtered)) { + end = int64(len(filtered)) + } + + return &pb.SearchCommentsResp{Comments: filtered[offset:end]}, nil +} diff --git a/app/community/rpc/internal/logic/searchPostLikesLogic.go b/app/community/rpc/internal/logic/searchPostLikesLogic.go new file mode 100644 index 0000000..00fc239 --- /dev/null +++ b/app/community/rpc/internal/logic/searchPostLikesLogic.go @@ -0,0 +1,61 @@ +package logic + +import ( + "context" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchPostLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchPostLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchPostLikesLogic { + return &SearchPostLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchPostLikesLogic) SearchPostLikes(in *pb.SearchPostLikesReq) (*pb.SearchPostLikesResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + offset := in.GetPage() + if offset < 0 { + offset = 0 + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + filtered := make([]*pb.PostLikes, 0, len(store.PostLikes)) + for _, like := range store.PostLikes { + if in.PostId != nil && like.GetPostId() != in.GetPostId() { + continue + } + if in.UserId != nil && like.GetUserId() != in.GetUserId() { + continue + } + cp := *like + filtered = append(filtered, &cp) + } + + if offset >= int64(len(filtered)) { + return &pb.SearchPostLikesResp{PostLikes: []*pb.PostLikes{}}, nil + } + end := offset + limit + if end > int64(len(filtered)) { + end = int64(len(filtered)) + } + + return &pb.SearchPostLikesResp{PostLikes: filtered[offset:end]}, nil +} diff --git a/app/community/rpc/internal/logic/searchPostsLogic.go b/app/community/rpc/internal/logic/searchPostsLogic.go new file mode 100644 index 0000000..56f69aa --- /dev/null +++ b/app/community/rpc/internal/logic/searchPostsLogic.go @@ -0,0 +1,96 @@ +package logic + +import ( + "context" + "strings" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchPostsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchPostsLogic { + return &SearchPostsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchPostsLogic) SearchPosts(in *pb.SearchPostsReq) (*pb.SearchPostsResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + offset := in.GetPage() + if offset < 0 { + offset = 0 + } + + store := l.svcCtx.Store + store.Mu.RLock() + defer store.Mu.RUnlock() + + filtered := make([]*pb.Posts, 0, len(store.Posts)) + for _, p := range store.Posts { + if p.GetDeletedAt() > 0 { + continue + } + if in.GetId() > 0 && p.GetId() != in.GetId() { + continue + } + if in.AuthorId != nil && p.GetAuthorId() != in.GetAuthorId() { + continue + } + if in.AuthorRole != nil && p.GetAuthorRole() != in.GetAuthorRole() { + continue + } + if in.Title != nil && !strings.Contains(strings.ToLower(p.GetTitle()), strings.ToLower(in.GetTitle())) { + continue + } + if in.Content != nil && !strings.Contains(strings.ToLower(p.GetContent()), strings.ToLower(in.GetContent())) { + continue + } + if len(in.GetTags()) > 0 { + match := false + for _, t := range in.GetTags() { + for _, pt := range p.GetTags() { + if t == pt { + match = true + break + } + } + if match { + break + } + } + if !match { + continue + } + } + + cp := *p + cp.Images = append([]string(nil), p.Images...) + cp.Tags = append([]string(nil), p.Tags...) + filtered = append(filtered, &cp) + } + + sortPostsDesc(filtered) + + if offset >= int64(len(filtered)) { + return &pb.SearchPostsResp{Posts: []*pb.Posts{}}, nil + } + end := offset + limit + if end > int64(len(filtered)) { + end = int64(len(filtered)) + } + + return &pb.SearchPostsResp{Posts: filtered[offset:end]}, nil +} diff --git a/app/community/rpc/internal/logic/updateCommentLikesLogic.go b/app/community/rpc/internal/logic/updateCommentLikesLogic.go new file mode 100644 index 0000000..30c8571 --- /dev/null +++ b/app/community/rpc/internal/logic/updateCommentLikesLogic.go @@ -0,0 +1,47 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateCommentLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateCommentLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateCommentLikesLogic { + return &UpdateCommentLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateCommentLikesLogic) UpdateCommentLikes(in *pb.UpdateCommentLikesReq) (*pb.UpdateCommentLikesResp, error) { + if in.GetCommentId() <= 0 || in.GetUserId() <= 0 { + return nil, errors.New("commentId and userId are required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + if _, ok := store.Comments[in.GetCommentId()]; !ok { + return nil, errors.New("comment not found") + } + key := commentLikeKey(in.GetCommentId(), in.GetUserId()) + store.CommentLikes[key] = &pb.CommentLikes{ + CommentId: in.GetCommentId(), + UserId: in.GetUserId(), + CreatedAt: nowUnix(in.GetCreatedAt()), + } + + return &pb.UpdateCommentLikesResp{}, nil +} diff --git a/app/community/rpc/internal/logic/updateCommentsLogic.go b/app/community/rpc/internal/logic/updateCommentsLogic.go new file mode 100644 index 0000000..a82fa5b --- /dev/null +++ b/app/community/rpc/internal/logic/updateCommentsLogic.go @@ -0,0 +1,61 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateCommentsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateCommentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateCommentsLogic { + return &UpdateCommentsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateCommentsLogic) UpdateComments(in *pb.UpdateCommentsReq) (*pb.UpdateCommentsResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + comment, ok := store.Comments[in.GetId()] + if !ok || comment.GetDeletedAt() > 0 { + return nil, errors.New("comment not found") + } + + if in.GetPostId() > 0 { + comment.PostId = in.GetPostId() + } + if in.GetAuthorId() > 0 { + comment.AuthorId = in.GetAuthorId() + } + if in.GetContent() != "" { + comment.Content = in.GetContent() + } + if in.GetLikeCount() > 0 { + comment.LikeCount = in.GetLikeCount() + } + if in.GetDeletedAt() > 0 { + comment.DeletedAt = in.GetDeletedAt() + } + if in.GetCreatedAt() > 0 { + comment.CreatedAt = in.GetCreatedAt() + } + + return &pb.UpdateCommentsResp{}, nil +} diff --git a/app/community/rpc/internal/logic/updatePostLikesLogic.go b/app/community/rpc/internal/logic/updatePostLikesLogic.go new file mode 100644 index 0000000..998d806 --- /dev/null +++ b/app/community/rpc/internal/logic/updatePostLikesLogic.go @@ -0,0 +1,49 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdatePostLikesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdatePostLikesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePostLikesLogic { + return &UpdatePostLikesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdatePostLikesLogic) UpdatePostLikes(in *pb.UpdatePostLikesReq) (*pb.UpdatePostLikesResp, error) { + if in.PostId == nil || in.UserId == nil { + return nil, errors.New("postId and userId are required") + } + postID := in.GetPostId() + userID := in.GetUserId() + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + if _, ok := store.Posts[postID]; !ok { + return nil, errors.New("post not found") + } + key := postLikeKey(postID, userID) + store.PostLikes[key] = &pb.PostLikes{ + PostId: postID, + UserId: userID, + CreatedAt: nowUnix(in.GetCreatedAt()), + } + + return &pb.UpdatePostLikesResp{}, nil +} diff --git a/app/community/rpc/internal/logic/updatePostsLogic.go b/app/community/rpc/internal/logic/updatePostsLogic.go new file mode 100644 index 0000000..2506670 --- /dev/null +++ b/app/community/rpc/internal/logic/updatePostsLogic.go @@ -0,0 +1,86 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdatePostsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdatePostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePostsLogic { + return &UpdatePostsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdatePostsLogic) UpdatePosts(in *pb.UpdatePostsReq) (*pb.UpdatePostsResp, error) { + if in.GetId() <= 0 { + return nil, errors.New("id is required") + } + + store := l.svcCtx.Store + store.Mu.Lock() + defer store.Mu.Unlock() + + post, ok := store.Posts[in.GetId()] + if !ok || post.GetDeletedAt() > 0 { + return nil, errors.New("post not found") + } + + if in.AuthorId != nil { + post.AuthorId = in.GetAuthorId() + } + if in.AuthorRole != nil { + post.AuthorRole = in.GetAuthorRole() + } + if in.Title != nil { + post.Title = in.GetTitle() + } + if in.Content != nil { + post.Content = in.GetContent() + } + if len(in.Images) > 0 { + post.Images = append([]string(nil), in.GetImages()...) + } + if len(in.Tags) > 0 { + post.Tags = append([]string(nil), in.GetTags()...) + } + if in.LinkedOrderId != nil { + post.LinkedOrderId = in.GetLinkedOrderId() + } + if in.QuotedPostId != nil { + post.QuotedPostId = in.GetQuotedPostId() + } + if in.LikeCount != nil { + post.LikeCount = in.GetLikeCount() + } + if in.CommentCount != nil { + post.CommentCount = in.GetCommentCount() + } + if in.Pinned != nil { + post.Pinned = in.GetPinned() + } + if in.SearchText != nil { + post.SearchText = in.GetSearchText() + } + if in.DeletedAt != nil { + post.DeletedAt = in.GetDeletedAt() + } + if in.CreatedAt != nil { + post.CreatedAt = in.GetCreatedAt() + } + post.UpdatedAt = nowUnix(in.GetUpdatedAt()) + + return &pb.UpdatePostsResp{}, nil +} diff --git a/app/community/rpc/internal/server/communityServiceServer.go b/app/community/rpc/internal/server/communityServiceServer.go new file mode 100644 index 0000000..8a94bb8 --- /dev/null +++ b/app/community/rpc/internal/server/communityServiceServer.go @@ -0,0 +1,128 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 +// Source: community.proto + +package server + +import ( + "context" + + "juwan-backend/app/community/rpc/internal/logic" + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" +) + +type CommunityServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedCommunityServiceServer +} + +func NewCommunityServiceServer(svcCtx *svc.ServiceContext) *CommunityServiceServer { + return &CommunityServiceServer{ + svcCtx: svcCtx, + } +} + +// -----------------------commentLikes----------------------- +func (s *CommunityServiceServer) AddCommentLikes(ctx context.Context, in *pb.AddCommentLikesReq) (*pb.AddCommentLikesResp, error) { + l := logic.NewAddCommentLikesLogic(ctx, s.svcCtx) + return l.AddCommentLikes(in) +} + +func (s *CommunityServiceServer) UpdateCommentLikes(ctx context.Context, in *pb.UpdateCommentLikesReq) (*pb.UpdateCommentLikesResp, error) { + l := logic.NewUpdateCommentLikesLogic(ctx, s.svcCtx) + return l.UpdateCommentLikes(in) +} + +func (s *CommunityServiceServer) DelCommentLikes(ctx context.Context, in *pb.DelCommentLikesReq) (*pb.DelCommentLikesResp, error) { + l := logic.NewDelCommentLikesLogic(ctx, s.svcCtx) + return l.DelCommentLikes(in) +} + +func (s *CommunityServiceServer) GetCommentLikesById(ctx context.Context, in *pb.GetCommentLikesByIdReq) (*pb.GetCommentLikesByIdResp, error) { + l := logic.NewGetCommentLikesByIdLogic(ctx, s.svcCtx) + return l.GetCommentLikesById(in) +} + +func (s *CommunityServiceServer) SearchCommentLikes(ctx context.Context, in *pb.SearchCommentLikesReq) (*pb.SearchCommentLikesResp, error) { + l := logic.NewSearchCommentLikesLogic(ctx, s.svcCtx) + return l.SearchCommentLikes(in) +} + +// -----------------------comments----------------------- +func (s *CommunityServiceServer) AddComments(ctx context.Context, in *pb.AddCommentsReq) (*pb.AddCommentsResp, error) { + l := logic.NewAddCommentsLogic(ctx, s.svcCtx) + return l.AddComments(in) +} + +func (s *CommunityServiceServer) UpdateComments(ctx context.Context, in *pb.UpdateCommentsReq) (*pb.UpdateCommentsResp, error) { + l := logic.NewUpdateCommentsLogic(ctx, s.svcCtx) + return l.UpdateComments(in) +} + +func (s *CommunityServiceServer) DelComments(ctx context.Context, in *pb.DelCommentsReq) (*pb.DelCommentsResp, error) { + l := logic.NewDelCommentsLogic(ctx, s.svcCtx) + return l.DelComments(in) +} + +func (s *CommunityServiceServer) GetCommentsById(ctx context.Context, in *pb.GetCommentsByIdReq) (*pb.GetCommentsByIdResp, error) { + l := logic.NewGetCommentsByIdLogic(ctx, s.svcCtx) + return l.GetCommentsById(in) +} + +func (s *CommunityServiceServer) SearchComments(ctx context.Context, in *pb.SearchCommentsReq) (*pb.SearchCommentsResp, error) { + l := logic.NewSearchCommentsLogic(ctx, s.svcCtx) + return l.SearchComments(in) +} + +// -----------------------postLikes----------------------- +func (s *CommunityServiceServer) AddPostLikes(ctx context.Context, in *pb.AddPostLikesReq) (*pb.AddPostLikesResp, error) { + l := logic.NewAddPostLikesLogic(ctx, s.svcCtx) + return l.AddPostLikes(in) +} + +func (s *CommunityServiceServer) UpdatePostLikes(ctx context.Context, in *pb.UpdatePostLikesReq) (*pb.UpdatePostLikesResp, error) { + l := logic.NewUpdatePostLikesLogic(ctx, s.svcCtx) + return l.UpdatePostLikes(in) +} + +func (s *CommunityServiceServer) DelPostLikes(ctx context.Context, in *pb.DelPostLikesReq) (*pb.DelPostLikesResp, error) { + l := logic.NewDelPostLikesLogic(ctx, s.svcCtx) + return l.DelPostLikes(in) +} + +func (s *CommunityServiceServer) GetPostLikesById(ctx context.Context, in *pb.GetPostLikesByIdReq) (*pb.GetPostLikesByIdResp, error) { + l := logic.NewGetPostLikesByIdLogic(ctx, s.svcCtx) + return l.GetPostLikesById(in) +} + +func (s *CommunityServiceServer) SearchPostLikes(ctx context.Context, in *pb.SearchPostLikesReq) (*pb.SearchPostLikesResp, error) { + l := logic.NewSearchPostLikesLogic(ctx, s.svcCtx) + return l.SearchPostLikes(in) +} + +// -----------------------posts----------------------- +func (s *CommunityServiceServer) AddPosts(ctx context.Context, in *pb.AddPostsReq) (*pb.AddPostsResp, error) { + l := logic.NewAddPostsLogic(ctx, s.svcCtx) + return l.AddPosts(in) +} + +func (s *CommunityServiceServer) UpdatePosts(ctx context.Context, in *pb.UpdatePostsReq) (*pb.UpdatePostsResp, error) { + l := logic.NewUpdatePostsLogic(ctx, s.svcCtx) + return l.UpdatePosts(in) +} + +func (s *CommunityServiceServer) DelPosts(ctx context.Context, in *pb.DelPostsReq) (*pb.DelPostsResp, error) { + l := logic.NewDelPostsLogic(ctx, s.svcCtx) + return l.DelPosts(in) +} + +func (s *CommunityServiceServer) GetPostsById(ctx context.Context, in *pb.GetPostsByIdReq) (*pb.GetPostsByIdResp, error) { + l := logic.NewGetPostsByIdLogic(ctx, s.svcCtx) + return l.GetPostsById(in) +} + +func (s *CommunityServiceServer) SearchPosts(ctx context.Context, in *pb.SearchPostsReq) (*pb.SearchPostsResp, error) { + l := logic.NewSearchPostsLogic(ctx, s.svcCtx) + return l.SearchPosts(in) +} diff --git a/app/community/rpc/internal/svc/serviceContext.go b/app/community/rpc/internal/svc/serviceContext.go new file mode 100644 index 0000000..33089dc --- /dev/null +++ b/app/community/rpc/internal/svc/serviceContext.go @@ -0,0 +1,15 @@ +package svc + +import "juwan-backend/app/community/rpc/internal/config" + +type ServiceContext struct { + Config config.Config + Store *CommunityStore +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + Store: NewCommunityStore(), + } +} diff --git a/app/community/rpc/internal/svc/store.go b/app/community/rpc/internal/svc/store.go new file mode 100644 index 0000000..56e545b --- /dev/null +++ b/app/community/rpc/internal/svc/store.go @@ -0,0 +1,40 @@ +package svc + +import ( + "sync" + + "juwan-backend/app/community/rpc/pb" +) + +type CommunityStore struct { + Mu sync.RWMutex + + nextPostID int64 + nextCommentID int64 + + Posts map[int64]*pb.Posts + Comments map[int64]*pb.Comments + PostLikes map[string]*pb.PostLikes + CommentLikes map[string]*pb.CommentLikes +} + +func NewCommunityStore() *CommunityStore { + return &CommunityStore{ + nextPostID: 1000, + nextCommentID: 1000, + Posts: make(map[int64]*pb.Posts), + Comments: make(map[int64]*pb.Comments), + PostLikes: make(map[string]*pb.PostLikes), + CommentLikes: make(map[string]*pb.CommentLikes), + } +} + +func (s *CommunityStore) NextPost() int64 { + s.nextPostID++ + return s.nextPostID +} + +func (s *CommunityStore) NextComment() int64 { + s.nextCommentID++ + return s.nextCommentID +} diff --git a/app/community/rpc/pb.go b/app/community/rpc/pb.go new file mode 100644 index 0000000..82c8fde --- /dev/null +++ b/app/community/rpc/pb.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/community/rpc/internal/config" + "juwan-backend/app/community/rpc/internal/server" + "juwan-backend/app/community/rpc/internal/svc" + "juwan-backend/app/community/rpc/pb" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/core/service" + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" + "google.golang.org/grpc/reflection" +) + +var configFile = flag.String("f", "etc/pb.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + ctx := svc.NewServiceContext(c) + + s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { + pb.RegisterCommunityServiceServer(grpcServer, server.NewCommunityServiceServer(ctx)) + + if c.Mode == service.DevMode || c.Mode == service.TestMode { + reflection.Register(grpcServer) + } + }) + defer s.Stop() + + fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) + s.Start() +} diff --git a/app/community/rpc/pb/community.pb.go b/app/community/rpc/pb/community.pb.go new file mode 100644 index 0000000..0f3fb88 --- /dev/null +++ b/app/community/rpc/pb/community.pb.go @@ -0,0 +1,3156 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v5.29.6 +// source: community.proto + +package pb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// --------------------------------commentLikes-------------------------------- +type CommentLikes struct { + state protoimpl.MessageState `protogen:"open.v1"` + CommentId int64 `protobuf:"varint,1,opt,name=commentId,proto3" json:"commentId,omitempty"` //commentId + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,3,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CommentLikes) Reset() { + *x = CommentLikes{} + mi := &file_community_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CommentLikes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CommentLikes) ProtoMessage() {} + +func (x *CommentLikes) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CommentLikes.ProtoReflect.Descriptor instead. +func (*CommentLikes) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{0} +} + +func (x *CommentLikes) GetCommentId() int64 { + if x != nil { + return x.CommentId + } + return 0 +} + +func (x *CommentLikes) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *CommentLikes) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddCommentLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + CommentId int64 `protobuf:"varint,1,opt,name=commentId,proto3" json:"commentId,omitempty"` //commentId + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,3,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddCommentLikesReq) Reset() { + *x = AddCommentLikesReq{} + mi := &file_community_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddCommentLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddCommentLikesReq) ProtoMessage() {} + +func (x *AddCommentLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddCommentLikesReq.ProtoReflect.Descriptor instead. +func (*AddCommentLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{1} +} + +func (x *AddCommentLikesReq) GetCommentId() int64 { + if x != nil { + return x.CommentId + } + return 0 +} + +func (x *AddCommentLikesReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *AddCommentLikesReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddCommentLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddCommentLikesResp) Reset() { + *x = AddCommentLikesResp{} + mi := &file_community_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddCommentLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddCommentLikesResp) ProtoMessage() {} + +func (x *AddCommentLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddCommentLikesResp.ProtoReflect.Descriptor instead. +func (*AddCommentLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{2} +} + +type UpdateCommentLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + CommentId int64 `protobuf:"varint,1,opt,name=commentId,proto3" json:"commentId,omitempty"` //commentId + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,3,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateCommentLikesReq) Reset() { + *x = UpdateCommentLikesReq{} + mi := &file_community_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateCommentLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateCommentLikesReq) ProtoMessage() {} + +func (x *UpdateCommentLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateCommentLikesReq.ProtoReflect.Descriptor instead. +func (*UpdateCommentLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{3} +} + +func (x *UpdateCommentLikesReq) GetCommentId() int64 { + if x != nil { + return x.CommentId + } + return 0 +} + +func (x *UpdateCommentLikesReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *UpdateCommentLikesReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type UpdateCommentLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateCommentLikesResp) Reset() { + *x = UpdateCommentLikesResp{} + mi := &file_community_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateCommentLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateCommentLikesResp) ProtoMessage() {} + +func (x *UpdateCommentLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateCommentLikesResp.ProtoReflect.Descriptor instead. +func (*UpdateCommentLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{4} +} + +type DelCommentLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + UserId *int64 `protobuf:"varint,2,opt,name=userId,proto3,oneof" json:"userId,omitempty"` //userId + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelCommentLikesReq) Reset() { + *x = DelCommentLikesReq{} + mi := &file_community_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelCommentLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelCommentLikesReq) ProtoMessage() {} + +func (x *DelCommentLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelCommentLikesReq.ProtoReflect.Descriptor instead. +func (*DelCommentLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{5} +} + +func (x *DelCommentLikesReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *DelCommentLikesReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +type DelCommentLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelCommentLikesResp) Reset() { + *x = DelCommentLikesResp{} + mi := &file_community_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelCommentLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelCommentLikesResp) ProtoMessage() {} + +func (x *DelCommentLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelCommentLikesResp.ProtoReflect.Descriptor instead. +func (*DelCommentLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{6} +} + +type GetCommentLikesByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCommentLikesByIdReq) Reset() { + *x = GetCommentLikesByIdReq{} + mi := &file_community_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCommentLikesByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCommentLikesByIdReq) ProtoMessage() {} + +func (x *GetCommentLikesByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCommentLikesByIdReq.ProtoReflect.Descriptor instead. +func (*GetCommentLikesByIdReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{7} +} + +func (x *GetCommentLikesByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetCommentLikesByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + CommentLikes *CommentLikes `protobuf:"bytes,1,opt,name=commentLikes,proto3" json:"commentLikes,omitempty"` //commentLikes + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCommentLikesByIdResp) Reset() { + *x = GetCommentLikesByIdResp{} + mi := &file_community_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCommentLikesByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCommentLikesByIdResp) ProtoMessage() {} + +func (x *GetCommentLikesByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCommentLikesByIdResp.ProtoReflect.Descriptor instead. +func (*GetCommentLikesByIdResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{8} +} + +func (x *GetCommentLikesByIdResp) GetCommentLikes() *CommentLikes { + if x != nil { + return x.CommentLikes + } + return nil +} + +type SearchCommentLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + CommentId int64 `protobuf:"varint,3,opt,name=commentId,proto3" json:"commentId,omitempty"` //commentId + UserId int64 `protobuf:"varint,4,opt,name=userId,proto3" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,5,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchCommentLikesReq) Reset() { + *x = SearchCommentLikesReq{} + mi := &file_community_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchCommentLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchCommentLikesReq) ProtoMessage() {} + +func (x *SearchCommentLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchCommentLikesReq.ProtoReflect.Descriptor instead. +func (*SearchCommentLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{9} +} + +func (x *SearchCommentLikesReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchCommentLikesReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchCommentLikesReq) GetCommentId() int64 { + if x != nil { + return x.CommentId + } + return 0 +} + +func (x *SearchCommentLikesReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *SearchCommentLikesReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type SearchCommentLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + CommentLikes []*CommentLikes `protobuf:"bytes,1,rep,name=commentLikes,proto3" json:"commentLikes,omitempty"` //commentLikes + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchCommentLikesResp) Reset() { + *x = SearchCommentLikesResp{} + mi := &file_community_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchCommentLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchCommentLikesResp) ProtoMessage() {} + +func (x *SearchCommentLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchCommentLikesResp.ProtoReflect.Descriptor instead. +func (*SearchCommentLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{10} +} + +func (x *SearchCommentLikesResp) GetCommentLikes() []*CommentLikes { + if x != nil { + return x.CommentLikes + } + return nil +} + +// --------------------------------comments-------------------------------- +type Comments struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + PostId int64 `protobuf:"varint,2,opt,name=postId,proto3" json:"postId,omitempty"` //postId + AuthorId int64 `protobuf:"varint,3,opt,name=authorId,proto3" json:"authorId,omitempty"` //authorId + Content string `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"` //content + LikeCount int64 `protobuf:"varint,5,opt,name=likeCount,proto3" json:"likeCount,omitempty"` //likeCount + CreatedAt int64 `protobuf:"varint,6,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + DeletedAt int64 `protobuf:"varint,7,opt,name=deletedAt,proto3" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Comments) Reset() { + *x = Comments{} + mi := &file_community_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Comments) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Comments) ProtoMessage() {} + +func (x *Comments) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Comments.ProtoReflect.Descriptor instead. +func (*Comments) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{11} +} + +func (x *Comments) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Comments) GetPostId() int64 { + if x != nil { + return x.PostId + } + return 0 +} + +func (x *Comments) GetAuthorId() int64 { + if x != nil { + return x.AuthorId + } + return 0 +} + +func (x *Comments) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *Comments) GetLikeCount() int64 { + if x != nil { + return x.LikeCount + } + return 0 +} + +func (x *Comments) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *Comments) GetDeletedAt() int64 { + if x != nil { + return x.DeletedAt + } + return 0 +} + +type AddCommentsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + PostId int64 `protobuf:"varint,1,opt,name=postId,proto3" json:"postId,omitempty"` //postId + AuthorId int64 `protobuf:"varint,2,opt,name=authorId,proto3" json:"authorId,omitempty"` //authorId + Content string `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"` //content + LikeCount int64 `protobuf:"varint,4,opt,name=likeCount,proto3" json:"likeCount,omitempty"` //likeCount + CreatedAt int64 `protobuf:"varint,5,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + DeletedAt int64 `protobuf:"varint,6,opt,name=deletedAt,proto3" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddCommentsReq) Reset() { + *x = AddCommentsReq{} + mi := &file_community_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddCommentsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddCommentsReq) ProtoMessage() {} + +func (x *AddCommentsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddCommentsReq.ProtoReflect.Descriptor instead. +func (*AddCommentsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{12} +} + +func (x *AddCommentsReq) GetPostId() int64 { + if x != nil { + return x.PostId + } + return 0 +} + +func (x *AddCommentsReq) GetAuthorId() int64 { + if x != nil { + return x.AuthorId + } + return 0 +} + +func (x *AddCommentsReq) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *AddCommentsReq) GetLikeCount() int64 { + if x != nil { + return x.LikeCount + } + return 0 +} + +func (x *AddCommentsReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *AddCommentsReq) GetDeletedAt() int64 { + if x != nil { + return x.DeletedAt + } + return 0 +} + +type AddCommentsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddCommentsResp) Reset() { + *x = AddCommentsResp{} + mi := &file_community_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddCommentsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddCommentsResp) ProtoMessage() {} + +func (x *AddCommentsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddCommentsResp.ProtoReflect.Descriptor instead. +func (*AddCommentsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{13} +} + +type UpdateCommentsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + PostId int64 `protobuf:"varint,2,opt,name=postId,proto3" json:"postId,omitempty"` //postId + AuthorId int64 `protobuf:"varint,3,opt,name=authorId,proto3" json:"authorId,omitempty"` //authorId + Content string `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"` //content + LikeCount int64 `protobuf:"varint,5,opt,name=likeCount,proto3" json:"likeCount,omitempty"` //likeCount + CreatedAt int64 `protobuf:"varint,6,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + DeletedAt int64 `protobuf:"varint,7,opt,name=deletedAt,proto3" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateCommentsReq) Reset() { + *x = UpdateCommentsReq{} + mi := &file_community_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateCommentsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateCommentsReq) ProtoMessage() {} + +func (x *UpdateCommentsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateCommentsReq.ProtoReflect.Descriptor instead. +func (*UpdateCommentsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{14} +} + +func (x *UpdateCommentsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateCommentsReq) GetPostId() int64 { + if x != nil { + return x.PostId + } + return 0 +} + +func (x *UpdateCommentsReq) GetAuthorId() int64 { + if x != nil { + return x.AuthorId + } + return 0 +} + +func (x *UpdateCommentsReq) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *UpdateCommentsReq) GetLikeCount() int64 { + if x != nil { + return x.LikeCount + } + return 0 +} + +func (x *UpdateCommentsReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *UpdateCommentsReq) GetDeletedAt() int64 { + if x != nil { + return x.DeletedAt + } + return 0 +} + +type UpdateCommentsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateCommentsResp) Reset() { + *x = UpdateCommentsResp{} + mi := &file_community_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateCommentsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateCommentsResp) ProtoMessage() {} + +func (x *UpdateCommentsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[15] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateCommentsResp.ProtoReflect.Descriptor instead. +func (*UpdateCommentsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{15} +} + +type DelCommentsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelCommentsReq) Reset() { + *x = DelCommentsReq{} + mi := &file_community_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelCommentsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelCommentsReq) ProtoMessage() {} + +func (x *DelCommentsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[16] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelCommentsReq.ProtoReflect.Descriptor instead. +func (*DelCommentsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{16} +} + +func (x *DelCommentsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelCommentsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelCommentsResp) Reset() { + *x = DelCommentsResp{} + mi := &file_community_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelCommentsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelCommentsResp) ProtoMessage() {} + +func (x *DelCommentsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelCommentsResp.ProtoReflect.Descriptor instead. +func (*DelCommentsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{17} +} + +type GetCommentsByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCommentsByIdReq) Reset() { + *x = GetCommentsByIdReq{} + mi := &file_community_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCommentsByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCommentsByIdReq) ProtoMessage() {} + +func (x *GetCommentsByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCommentsByIdReq.ProtoReflect.Descriptor instead. +func (*GetCommentsByIdReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{18} +} + +func (x *GetCommentsByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetCommentsByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Comments *Comments `protobuf:"bytes,1,opt,name=comments,proto3" json:"comments,omitempty"` //comments + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCommentsByIdResp) Reset() { + *x = GetCommentsByIdResp{} + mi := &file_community_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCommentsByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCommentsByIdResp) ProtoMessage() {} + +func (x *GetCommentsByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCommentsByIdResp.ProtoReflect.Descriptor instead. +func (*GetCommentsByIdResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{19} +} + +func (x *GetCommentsByIdResp) GetComments() *Comments { + if x != nil { + return x.Comments + } + return nil +} + +type SearchCommentsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + Id int64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` //id + PostId int64 `protobuf:"varint,4,opt,name=postId,proto3" json:"postId,omitempty"` //postId + AuthorId int64 `protobuf:"varint,5,opt,name=authorId,proto3" json:"authorId,omitempty"` //authorId + Content *string `protobuf:"bytes,6,opt,name=content,proto3,oneof" json:"content,omitempty"` //content + LikeCount *int64 `protobuf:"varint,7,opt,name=likeCount,proto3,oneof" json:"likeCount,omitempty"` //likeCount + CreatedAt int64 `protobuf:"varint,8,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + DeletedAt int64 `protobuf:"varint,9,opt,name=deletedAt,proto3" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchCommentsReq) Reset() { + *x = SearchCommentsReq{} + mi := &file_community_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchCommentsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchCommentsReq) ProtoMessage() {} + +func (x *SearchCommentsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[20] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchCommentsReq.ProtoReflect.Descriptor instead. +func (*SearchCommentsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{20} +} + +func (x *SearchCommentsReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchCommentsReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchCommentsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *SearchCommentsReq) GetPostId() int64 { + if x != nil { + return x.PostId + } + return 0 +} + +func (x *SearchCommentsReq) GetAuthorId() int64 { + if x != nil { + return x.AuthorId + } + return 0 +} + +func (x *SearchCommentsReq) GetContent() string { + if x != nil && x.Content != nil { + return *x.Content + } + return "" +} + +func (x *SearchCommentsReq) GetLikeCount() int64 { + if x != nil && x.LikeCount != nil { + return *x.LikeCount + } + return 0 +} + +func (x *SearchCommentsReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *SearchCommentsReq) GetDeletedAt() int64 { + if x != nil { + return x.DeletedAt + } + return 0 +} + +type SearchCommentsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Comments []*Comments `protobuf:"bytes,1,rep,name=comments,proto3" json:"comments,omitempty"` //comments + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchCommentsResp) Reset() { + *x = SearchCommentsResp{} + mi := &file_community_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchCommentsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchCommentsResp) ProtoMessage() {} + +func (x *SearchCommentsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[21] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchCommentsResp.ProtoReflect.Descriptor instead. +func (*SearchCommentsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{21} +} + +func (x *SearchCommentsResp) GetComments() []*Comments { + if x != nil { + return x.Comments + } + return nil +} + +// --------------------------------postLikes-------------------------------- +type PostLikes struct { + state protoimpl.MessageState `protogen:"open.v1"` + PostId int64 `protobuf:"varint,1,opt,name=postId,proto3" json:"postId,omitempty"` //postId + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,3,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PostLikes) Reset() { + *x = PostLikes{} + mi := &file_community_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PostLikes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PostLikes) ProtoMessage() {} + +func (x *PostLikes) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[22] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PostLikes.ProtoReflect.Descriptor instead. +func (*PostLikes) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{22} +} + +func (x *PostLikes) GetPostId() int64 { + if x != nil { + return x.PostId + } + return 0 +} + +func (x *PostLikes) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *PostLikes) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddPostLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + PostId int64 `protobuf:"varint,1,opt,name=postId,proto3" json:"postId,omitempty"` //postId + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,3,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddPostLikesReq) Reset() { + *x = AddPostLikesReq{} + mi := &file_community_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddPostLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddPostLikesReq) ProtoMessage() {} + +func (x *AddPostLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[23] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddPostLikesReq.ProtoReflect.Descriptor instead. +func (*AddPostLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{23} +} + +func (x *AddPostLikesReq) GetPostId() int64 { + if x != nil { + return x.PostId + } + return 0 +} + +func (x *AddPostLikesReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *AddPostLikesReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddPostLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddPostLikesResp) Reset() { + *x = AddPostLikesResp{} + mi := &file_community_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddPostLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddPostLikesResp) ProtoMessage() {} + +func (x *AddPostLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[24] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddPostLikesResp.ProtoReflect.Descriptor instead. +func (*AddPostLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{24} +} + +type UpdatePostLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + PostId *int64 `protobuf:"varint,1,opt,name=postId,proto3,oneof" json:"postId,omitempty"` //postId + UserId *int64 `protobuf:"varint,2,opt,name=userId,proto3,oneof" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,3,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdatePostLikesReq) Reset() { + *x = UpdatePostLikesReq{} + mi := &file_community_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdatePostLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdatePostLikesReq) ProtoMessage() {} + +func (x *UpdatePostLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[25] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdatePostLikesReq.ProtoReflect.Descriptor instead. +func (*UpdatePostLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{25} +} + +func (x *UpdatePostLikesReq) GetPostId() int64 { + if x != nil && x.PostId != nil { + return *x.PostId + } + return 0 +} + +func (x *UpdatePostLikesReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +func (x *UpdatePostLikesReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type UpdatePostLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdatePostLikesResp) Reset() { + *x = UpdatePostLikesResp{} + mi := &file_community_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdatePostLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdatePostLikesResp) ProtoMessage() {} + +func (x *UpdatePostLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[26] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdatePostLikesResp.ProtoReflect.Descriptor instead. +func (*UpdatePostLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{26} +} + +type DelPostLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + UserId *int64 `protobuf:"varint,2,opt,name=userId,proto3,oneof" json:"userId,omitempty"` //userId + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelPostLikesReq) Reset() { + *x = DelPostLikesReq{} + mi := &file_community_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelPostLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelPostLikesReq) ProtoMessage() {} + +func (x *DelPostLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[27] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelPostLikesReq.ProtoReflect.Descriptor instead. +func (*DelPostLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{27} +} + +func (x *DelPostLikesReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *DelPostLikesReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +type DelPostLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelPostLikesResp) Reset() { + *x = DelPostLikesResp{} + mi := &file_community_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelPostLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelPostLikesResp) ProtoMessage() {} + +func (x *DelPostLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[28] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelPostLikesResp.ProtoReflect.Descriptor instead. +func (*DelPostLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{28} +} + +type GetPostLikesByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPostLikesByIdReq) Reset() { + *x = GetPostLikesByIdReq{} + mi := &file_community_proto_msgTypes[29] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPostLikesByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPostLikesByIdReq) ProtoMessage() {} + +func (x *GetPostLikesByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[29] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPostLikesByIdReq.ProtoReflect.Descriptor instead. +func (*GetPostLikesByIdReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{29} +} + +func (x *GetPostLikesByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetPostLikesByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + PostLikes *PostLikes `protobuf:"bytes,1,opt,name=postLikes,proto3" json:"postLikes,omitempty"` //postLikes + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPostLikesByIdResp) Reset() { + *x = GetPostLikesByIdResp{} + mi := &file_community_proto_msgTypes[30] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPostLikesByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPostLikesByIdResp) ProtoMessage() {} + +func (x *GetPostLikesByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[30] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPostLikesByIdResp.ProtoReflect.Descriptor instead. +func (*GetPostLikesByIdResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{30} +} + +func (x *GetPostLikesByIdResp) GetPostLikes() *PostLikes { + if x != nil { + return x.PostLikes + } + return nil +} + +type SearchPostLikesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + PostId *int64 `protobuf:"varint,3,opt,name=postId,proto3,oneof" json:"postId,omitempty"` //postId + UserId *int64 `protobuf:"varint,4,opt,name=userId,proto3,oneof" json:"userId,omitempty"` //userId + CreatedAt int64 `protobuf:"varint,5,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchPostLikesReq) Reset() { + *x = SearchPostLikesReq{} + mi := &file_community_proto_msgTypes[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchPostLikesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchPostLikesReq) ProtoMessage() {} + +func (x *SearchPostLikesReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[31] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchPostLikesReq.ProtoReflect.Descriptor instead. +func (*SearchPostLikesReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{31} +} + +func (x *SearchPostLikesReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchPostLikesReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchPostLikesReq) GetPostId() int64 { + if x != nil && x.PostId != nil { + return *x.PostId + } + return 0 +} + +func (x *SearchPostLikesReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +func (x *SearchPostLikesReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type SearchPostLikesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + PostLikes []*PostLikes `protobuf:"bytes,1,rep,name=postLikes,proto3" json:"postLikes,omitempty"` //postLikes + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchPostLikesResp) Reset() { + *x = SearchPostLikesResp{} + mi := &file_community_proto_msgTypes[32] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchPostLikesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchPostLikesResp) ProtoMessage() {} + +func (x *SearchPostLikesResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[32] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchPostLikesResp.ProtoReflect.Descriptor instead. +func (*SearchPostLikesResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{32} +} + +func (x *SearchPostLikesResp) GetPostLikes() []*PostLikes { + if x != nil { + return x.PostLikes + } + return nil +} + +// --------------------------------posts-------------------------------- +type Posts struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + AuthorId int64 `protobuf:"varint,2,opt,name=authorId,proto3" json:"authorId,omitempty"` //authorId + AuthorRole string `protobuf:"bytes,3,opt,name=authorRole,proto3" json:"authorRole,omitempty"` //authorRole + Title string `protobuf:"bytes,4,opt,name=title,proto3" json:"title,omitempty"` //title + Content string `protobuf:"bytes,5,opt,name=content,proto3" json:"content,omitempty"` //content + Images []string `protobuf:"bytes,6,rep,name=images,proto3" json:"images,omitempty"` //images + Tags []string `protobuf:"bytes,7,rep,name=tags,proto3" json:"tags,omitempty"` //tags + LinkedOrderId int64 `protobuf:"varint,8,opt,name=linkedOrderId,proto3" json:"linkedOrderId,omitempty"` //linkedOrderId + QuotedPostId int64 `protobuf:"varint,9,opt,name=quotedPostId,proto3" json:"quotedPostId,omitempty"` //quotedPostId + LikeCount int64 `protobuf:"varint,10,opt,name=likeCount,proto3" json:"likeCount,omitempty"` //likeCount + CommentCount int64 `protobuf:"varint,11,opt,name=commentCount,proto3" json:"commentCount,omitempty"` //commentCount + Pinned bool `protobuf:"varint,12,opt,name=pinned,proto3" json:"pinned,omitempty"` //pinned + SearchText string `protobuf:"bytes,13,opt,name=searchText,proto3" json:"searchText,omitempty"` //searchText + CreatedAt int64 `protobuf:"varint,14,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + UpdatedAt int64 `protobuf:"varint,15,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt + DeletedAt int64 `protobuf:"varint,16,opt,name=deletedAt,proto3" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Posts) Reset() { + *x = Posts{} + mi := &file_community_proto_msgTypes[33] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Posts) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Posts) ProtoMessage() {} + +func (x *Posts) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[33] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Posts.ProtoReflect.Descriptor instead. +func (*Posts) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{33} +} + +func (x *Posts) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Posts) GetAuthorId() int64 { + if x != nil { + return x.AuthorId + } + return 0 +} + +func (x *Posts) GetAuthorRole() string { + if x != nil { + return x.AuthorRole + } + return "" +} + +func (x *Posts) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *Posts) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *Posts) GetImages() []string { + if x != nil { + return x.Images + } + return nil +} + +func (x *Posts) GetTags() []string { + if x != nil { + return x.Tags + } + return nil +} + +func (x *Posts) GetLinkedOrderId() int64 { + if x != nil { + return x.LinkedOrderId + } + return 0 +} + +func (x *Posts) GetQuotedPostId() int64 { + if x != nil { + return x.QuotedPostId + } + return 0 +} + +func (x *Posts) GetLikeCount() int64 { + if x != nil { + return x.LikeCount + } + return 0 +} + +func (x *Posts) GetCommentCount() int64 { + if x != nil { + return x.CommentCount + } + return 0 +} + +func (x *Posts) GetPinned() bool { + if x != nil { + return x.Pinned + } + return false +} + +func (x *Posts) GetSearchText() string { + if x != nil { + return x.SearchText + } + return "" +} + +func (x *Posts) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *Posts) GetUpdatedAt() int64 { + if x != nil { + return x.UpdatedAt + } + return 0 +} + +func (x *Posts) GetDeletedAt() int64 { + if x != nil { + return x.DeletedAt + } + return 0 +} + +type AddPostsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + AuthorId int64 `protobuf:"varint,1,opt,name=authorId,proto3" json:"authorId,omitempty"` //authorId + AuthorRole string `protobuf:"bytes,2,opt,name=authorRole,proto3" json:"authorRole,omitempty"` //authorRole + Title string `protobuf:"bytes,3,opt,name=title,proto3" json:"title,omitempty"` //title + Content string `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"` //content + Images []string `protobuf:"bytes,5,rep,name=images,proto3" json:"images,omitempty"` //images + Tags []string `protobuf:"bytes,6,rep,name=tags,proto3" json:"tags,omitempty"` //tags + LinkedOrderId int64 `protobuf:"varint,7,opt,name=linkedOrderId,proto3" json:"linkedOrderId,omitempty"` //linkedOrderId + QuotedPostId int64 `protobuf:"varint,8,opt,name=quotedPostId,proto3" json:"quotedPostId,omitempty"` //quotedPostId + LikeCount int64 `protobuf:"varint,9,opt,name=likeCount,proto3" json:"likeCount,omitempty"` //likeCount + CommentCount int64 `protobuf:"varint,10,opt,name=commentCount,proto3" json:"commentCount,omitempty"` //commentCount + Pinned bool `protobuf:"varint,11,opt,name=pinned,proto3" json:"pinned,omitempty"` //pinned + SearchText string `protobuf:"bytes,12,opt,name=searchText,proto3" json:"searchText,omitempty"` //searchText + CreatedAt int64 `protobuf:"varint,13,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + UpdatedAt int64 `protobuf:"varint,14,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt + DeletedAt int64 `protobuf:"varint,15,opt,name=deletedAt,proto3" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddPostsReq) Reset() { + *x = AddPostsReq{} + mi := &file_community_proto_msgTypes[34] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddPostsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddPostsReq) ProtoMessage() {} + +func (x *AddPostsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[34] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddPostsReq.ProtoReflect.Descriptor instead. +func (*AddPostsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{34} +} + +func (x *AddPostsReq) GetAuthorId() int64 { + if x != nil { + return x.AuthorId + } + return 0 +} + +func (x *AddPostsReq) GetAuthorRole() string { + if x != nil { + return x.AuthorRole + } + return "" +} + +func (x *AddPostsReq) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *AddPostsReq) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *AddPostsReq) GetImages() []string { + if x != nil { + return x.Images + } + return nil +} + +func (x *AddPostsReq) GetTags() []string { + if x != nil { + return x.Tags + } + return nil +} + +func (x *AddPostsReq) GetLinkedOrderId() int64 { + if x != nil { + return x.LinkedOrderId + } + return 0 +} + +func (x *AddPostsReq) GetQuotedPostId() int64 { + if x != nil { + return x.QuotedPostId + } + return 0 +} + +func (x *AddPostsReq) GetLikeCount() int64 { + if x != nil { + return x.LikeCount + } + return 0 +} + +func (x *AddPostsReq) GetCommentCount() int64 { + if x != nil { + return x.CommentCount + } + return 0 +} + +func (x *AddPostsReq) GetPinned() bool { + if x != nil { + return x.Pinned + } + return false +} + +func (x *AddPostsReq) GetSearchText() string { + if x != nil { + return x.SearchText + } + return "" +} + +func (x *AddPostsReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *AddPostsReq) GetUpdatedAt() int64 { + if x != nil { + return x.UpdatedAt + } + return 0 +} + +func (x *AddPostsReq) GetDeletedAt() int64 { + if x != nil { + return x.DeletedAt + } + return 0 +} + +type AddPostsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddPostsResp) Reset() { + *x = AddPostsResp{} + mi := &file_community_proto_msgTypes[35] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddPostsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddPostsResp) ProtoMessage() {} + +func (x *AddPostsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[35] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddPostsResp.ProtoReflect.Descriptor instead. +func (*AddPostsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{35} +} + +type UpdatePostsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + AuthorId *int64 `protobuf:"varint,2,opt,name=authorId,proto3,oneof" json:"authorId,omitempty"` //authorId + AuthorRole *string `protobuf:"bytes,3,opt,name=authorRole,proto3,oneof" json:"authorRole,omitempty"` //authorRole + Title *string `protobuf:"bytes,4,opt,name=title,proto3,oneof" json:"title,omitempty"` //title + Content *string `protobuf:"bytes,5,opt,name=content,proto3,oneof" json:"content,omitempty"` //content + Images []string `protobuf:"bytes,6,rep,name=images,proto3" json:"images,omitempty"` //images + Tags []string `protobuf:"bytes,7,rep,name=tags,proto3" json:"tags,omitempty"` //tags + LinkedOrderId *int64 `protobuf:"varint,8,opt,name=linkedOrderId,proto3,oneof" json:"linkedOrderId,omitempty"` //linkedOrderId + QuotedPostId *int64 `protobuf:"varint,9,opt,name=quotedPostId,proto3,oneof" json:"quotedPostId,omitempty"` //quotedPostId + LikeCount *int64 `protobuf:"varint,10,opt,name=likeCount,proto3,oneof" json:"likeCount,omitempty"` //likeCount + CommentCount *int64 `protobuf:"varint,11,opt,name=commentCount,proto3,oneof" json:"commentCount,omitempty"` //commentCount + Pinned *bool `protobuf:"varint,12,opt,name=pinned,proto3,oneof" json:"pinned,omitempty"` //pinned + SearchText *string `protobuf:"bytes,13,opt,name=searchText,proto3,oneof" json:"searchText,omitempty"` //searchText + CreatedAt *int64 `protobuf:"varint,14,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + UpdatedAt *int64 `protobuf:"varint,15,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt + DeletedAt *int64 `protobuf:"varint,16,opt,name=deletedAt,proto3,oneof" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdatePostsReq) Reset() { + *x = UpdatePostsReq{} + mi := &file_community_proto_msgTypes[36] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdatePostsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdatePostsReq) ProtoMessage() {} + +func (x *UpdatePostsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[36] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdatePostsReq.ProtoReflect.Descriptor instead. +func (*UpdatePostsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{36} +} + +func (x *UpdatePostsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdatePostsReq) GetAuthorId() int64 { + if x != nil && x.AuthorId != nil { + return *x.AuthorId + } + return 0 +} + +func (x *UpdatePostsReq) GetAuthorRole() string { + if x != nil && x.AuthorRole != nil { + return *x.AuthorRole + } + return "" +} + +func (x *UpdatePostsReq) GetTitle() string { + if x != nil && x.Title != nil { + return *x.Title + } + return "" +} + +func (x *UpdatePostsReq) GetContent() string { + if x != nil && x.Content != nil { + return *x.Content + } + return "" +} + +func (x *UpdatePostsReq) GetImages() []string { + if x != nil { + return x.Images + } + return nil +} + +func (x *UpdatePostsReq) GetTags() []string { + if x != nil { + return x.Tags + } + return nil +} + +func (x *UpdatePostsReq) GetLinkedOrderId() int64 { + if x != nil && x.LinkedOrderId != nil { + return *x.LinkedOrderId + } + return 0 +} + +func (x *UpdatePostsReq) GetQuotedPostId() int64 { + if x != nil && x.QuotedPostId != nil { + return *x.QuotedPostId + } + return 0 +} + +func (x *UpdatePostsReq) GetLikeCount() int64 { + if x != nil && x.LikeCount != nil { + return *x.LikeCount + } + return 0 +} + +func (x *UpdatePostsReq) GetCommentCount() int64 { + if x != nil && x.CommentCount != nil { + return *x.CommentCount + } + return 0 +} + +func (x *UpdatePostsReq) GetPinned() bool { + if x != nil && x.Pinned != nil { + return *x.Pinned + } + return false +} + +func (x *UpdatePostsReq) GetSearchText() string { + if x != nil && x.SearchText != nil { + return *x.SearchText + } + return "" +} + +func (x *UpdatePostsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *UpdatePostsReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +func (x *UpdatePostsReq) GetDeletedAt() int64 { + if x != nil && x.DeletedAt != nil { + return *x.DeletedAt + } + return 0 +} + +type UpdatePostsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdatePostsResp) Reset() { + *x = UpdatePostsResp{} + mi := &file_community_proto_msgTypes[37] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdatePostsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdatePostsResp) ProtoMessage() {} + +func (x *UpdatePostsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[37] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdatePostsResp.ProtoReflect.Descriptor instead. +func (*UpdatePostsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{37} +} + +type DelPostsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelPostsReq) Reset() { + *x = DelPostsReq{} + mi := &file_community_proto_msgTypes[38] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelPostsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelPostsReq) ProtoMessage() {} + +func (x *DelPostsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[38] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelPostsReq.ProtoReflect.Descriptor instead. +func (*DelPostsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{38} +} + +func (x *DelPostsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelPostsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelPostsResp) Reset() { + *x = DelPostsResp{} + mi := &file_community_proto_msgTypes[39] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelPostsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelPostsResp) ProtoMessage() {} + +func (x *DelPostsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[39] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelPostsResp.ProtoReflect.Descriptor instead. +func (*DelPostsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{39} +} + +type GetPostsByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPostsByIdReq) Reset() { + *x = GetPostsByIdReq{} + mi := &file_community_proto_msgTypes[40] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPostsByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPostsByIdReq) ProtoMessage() {} + +func (x *GetPostsByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[40] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPostsByIdReq.ProtoReflect.Descriptor instead. +func (*GetPostsByIdReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{40} +} + +func (x *GetPostsByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetPostsByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Posts *Posts `protobuf:"bytes,1,opt,name=posts,proto3" json:"posts,omitempty"` //posts + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPostsByIdResp) Reset() { + *x = GetPostsByIdResp{} + mi := &file_community_proto_msgTypes[41] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPostsByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPostsByIdResp) ProtoMessage() {} + +func (x *GetPostsByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[41] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPostsByIdResp.ProtoReflect.Descriptor instead. +func (*GetPostsByIdResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{41} +} + +func (x *GetPostsByIdResp) GetPosts() *Posts { + if x != nil { + return x.Posts + } + return nil +} + +type SearchPostsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + Id int64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` //id + AuthorId *int64 `protobuf:"varint,4,opt,name=authorId,proto3,oneof" json:"authorId,omitempty"` //authorId + AuthorRole *string `protobuf:"bytes,5,opt,name=authorRole,proto3,oneof" json:"authorRole,omitempty"` //authorRole + Title *string `protobuf:"bytes,6,opt,name=title,proto3,oneof" json:"title,omitempty"` //title + Content *string `protobuf:"bytes,7,opt,name=content,proto3,oneof" json:"content,omitempty"` //content + Images []string `protobuf:"bytes,8,rep,name=images,proto3" json:"images,omitempty"` //images + Tags []string `protobuf:"bytes,9,rep,name=tags,proto3" json:"tags,omitempty"` //tags + LinkedOrderId *int64 `protobuf:"varint,10,opt,name=linkedOrderId,proto3,oneof" json:"linkedOrderId,omitempty"` //linkedOrderId + QuotedPostId *int64 `protobuf:"varint,11,opt,name=quotedPostId,proto3,oneof" json:"quotedPostId,omitempty"` //quotedPostId + LikeCount *int64 `protobuf:"varint,12,opt,name=likeCount,proto3,oneof" json:"likeCount,omitempty"` //likeCount + CommentCount *int64 `protobuf:"varint,13,opt,name=commentCount,proto3,oneof" json:"commentCount,omitempty"` //commentCount + Pinned *bool `protobuf:"varint,14,opt,name=pinned,proto3,oneof" json:"pinned,omitempty"` //pinned + SearchText *string `protobuf:"bytes,15,opt,name=searchText,proto3,oneof" json:"searchText,omitempty"` //searchText + CreatedAt *int64 `protobuf:"varint,16,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + UpdatedAt *int64 `protobuf:"varint,17,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt + DeletedAt *int64 `protobuf:"varint,18,opt,name=deletedAt,proto3,oneof" json:"deletedAt,omitempty"` //deletedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchPostsReq) Reset() { + *x = SearchPostsReq{} + mi := &file_community_proto_msgTypes[42] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchPostsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchPostsReq) ProtoMessage() {} + +func (x *SearchPostsReq) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[42] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchPostsReq.ProtoReflect.Descriptor instead. +func (*SearchPostsReq) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{42} +} + +func (x *SearchPostsReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchPostsReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchPostsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *SearchPostsReq) GetAuthorId() int64 { + if x != nil && x.AuthorId != nil { + return *x.AuthorId + } + return 0 +} + +func (x *SearchPostsReq) GetAuthorRole() string { + if x != nil && x.AuthorRole != nil { + return *x.AuthorRole + } + return "" +} + +func (x *SearchPostsReq) GetTitle() string { + if x != nil && x.Title != nil { + return *x.Title + } + return "" +} + +func (x *SearchPostsReq) GetContent() string { + if x != nil && x.Content != nil { + return *x.Content + } + return "" +} + +func (x *SearchPostsReq) GetImages() []string { + if x != nil { + return x.Images + } + return nil +} + +func (x *SearchPostsReq) GetTags() []string { + if x != nil { + return x.Tags + } + return nil +} + +func (x *SearchPostsReq) GetLinkedOrderId() int64 { + if x != nil && x.LinkedOrderId != nil { + return *x.LinkedOrderId + } + return 0 +} + +func (x *SearchPostsReq) GetQuotedPostId() int64 { + if x != nil && x.QuotedPostId != nil { + return *x.QuotedPostId + } + return 0 +} + +func (x *SearchPostsReq) GetLikeCount() int64 { + if x != nil && x.LikeCount != nil { + return *x.LikeCount + } + return 0 +} + +func (x *SearchPostsReq) GetCommentCount() int64 { + if x != nil && x.CommentCount != nil { + return *x.CommentCount + } + return 0 +} + +func (x *SearchPostsReq) GetPinned() bool { + if x != nil && x.Pinned != nil { + return *x.Pinned + } + return false +} + +func (x *SearchPostsReq) GetSearchText() string { + if x != nil && x.SearchText != nil { + return *x.SearchText + } + return "" +} + +func (x *SearchPostsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *SearchPostsReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +func (x *SearchPostsReq) GetDeletedAt() int64 { + if x != nil && x.DeletedAt != nil { + return *x.DeletedAt + } + return 0 +} + +type SearchPostsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Posts []*Posts `protobuf:"bytes,1,rep,name=posts,proto3" json:"posts,omitempty"` //posts + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchPostsResp) Reset() { + *x = SearchPostsResp{} + mi := &file_community_proto_msgTypes[43] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchPostsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchPostsResp) ProtoMessage() {} + +func (x *SearchPostsResp) ProtoReflect() protoreflect.Message { + mi := &file_community_proto_msgTypes[43] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchPostsResp.ProtoReflect.Descriptor instead. +func (*SearchPostsResp) Descriptor() ([]byte, []int) { + return file_community_proto_rawDescGZIP(), []int{43} +} + +func (x *SearchPostsResp) GetPosts() []*Posts { + if x != nil { + return x.Posts + } + return nil +} + +var File_community_proto protoreflect.FileDescriptor + +const file_community_proto_rawDesc = "" + + "\n" + + "\x0fcommunity.proto\x12\x02pb\"b\n" + + "\fCommentLikes\x12\x1c\n" + + "\tcommentId\x18\x01 \x01(\x03R\tcommentId\x12\x16\n" + + "\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x1c\n" + + "\tcreatedAt\x18\x03 \x01(\x03R\tcreatedAt\"h\n" + + "\x12AddCommentLikesReq\x12\x1c\n" + + "\tcommentId\x18\x01 \x01(\x03R\tcommentId\x12\x16\n" + + "\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x1c\n" + + "\tcreatedAt\x18\x03 \x01(\x03R\tcreatedAt\"\x15\n" + + "\x13AddCommentLikesResp\"k\n" + + "\x15UpdateCommentLikesReq\x12\x1c\n" + + "\tcommentId\x18\x01 \x01(\x03R\tcommentId\x12\x16\n" + + "\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x1c\n" + + "\tcreatedAt\x18\x03 \x01(\x03R\tcreatedAt\"\x18\n" + + "\x16UpdateCommentLikesResp\"L\n" + + "\x12DelCommentLikesReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1b\n" + + "\x06userId\x18\x02 \x01(\x03H\x00R\x06userId\x88\x01\x01B\t\n" + + "\a_userId\"\x15\n" + + "\x13DelCommentLikesResp\"(\n" + + "\x16GetCommentLikesByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"O\n" + + "\x17GetCommentLikesByIdResp\x124\n" + + "\fcommentLikes\x18\x01 \x01(\v2\x10.pb.CommentLikesR\fcommentLikes\"\x95\x01\n" + + "\x15SearchCommentLikesReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x1c\n" + + "\tcommentId\x18\x03 \x01(\x03R\tcommentId\x12\x16\n" + + "\x06userId\x18\x04 \x01(\x03R\x06userId\x12\x1c\n" + + "\tcreatedAt\x18\x05 \x01(\x03R\tcreatedAt\"N\n" + + "\x16SearchCommentLikesResp\x124\n" + + "\fcommentLikes\x18\x01 \x03(\v2\x10.pb.CommentLikesR\fcommentLikes\"\xc2\x01\n" + + "\bComments\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x16\n" + + "\x06postId\x18\x02 \x01(\x03R\x06postId\x12\x1a\n" + + "\bauthorId\x18\x03 \x01(\x03R\bauthorId\x12\x18\n" + + "\acontent\x18\x04 \x01(\tR\acontent\x12\x1c\n" + + "\tlikeCount\x18\x05 \x01(\x03R\tlikeCount\x12\x1c\n" + + "\tcreatedAt\x18\x06 \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tdeletedAt\x18\a \x01(\x03R\tdeletedAt\"\xb8\x01\n" + + "\x0eAddCommentsReq\x12\x16\n" + + "\x06postId\x18\x01 \x01(\x03R\x06postId\x12\x1a\n" + + "\bauthorId\x18\x02 \x01(\x03R\bauthorId\x12\x18\n" + + "\acontent\x18\x03 \x01(\tR\acontent\x12\x1c\n" + + "\tlikeCount\x18\x04 \x01(\x03R\tlikeCount\x12\x1c\n" + + "\tcreatedAt\x18\x05 \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tdeletedAt\x18\x06 \x01(\x03R\tdeletedAt\"\x11\n" + + "\x0fAddCommentsResp\"\xcb\x01\n" + + "\x11UpdateCommentsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x16\n" + + "\x06postId\x18\x02 \x01(\x03R\x06postId\x12\x1a\n" + + "\bauthorId\x18\x03 \x01(\x03R\bauthorId\x12\x18\n" + + "\acontent\x18\x04 \x01(\tR\acontent\x12\x1c\n" + + "\tlikeCount\x18\x05 \x01(\x03R\tlikeCount\x12\x1c\n" + + "\tcreatedAt\x18\x06 \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tdeletedAt\x18\a \x01(\x03R\tdeletedAt\"\x14\n" + + "\x12UpdateCommentsResp\" \n" + + "\x0eDelCommentsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x11\n" + + "\x0fDelCommentsResp\"$\n" + + "\x12GetCommentsByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"?\n" + + "\x13GetCommentsByIdResp\x12(\n" + + "\bcomments\x18\x01 \x01(\v2\f.pb.CommentsR\bcomments\"\x99\x02\n" + + "\x11SearchCommentsReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x0e\n" + + "\x02id\x18\x03 \x01(\x03R\x02id\x12\x16\n" + + "\x06postId\x18\x04 \x01(\x03R\x06postId\x12\x1a\n" + + "\bauthorId\x18\x05 \x01(\x03R\bauthorId\x12\x1d\n" + + "\acontent\x18\x06 \x01(\tH\x00R\acontent\x88\x01\x01\x12!\n" + + "\tlikeCount\x18\a \x01(\x03H\x01R\tlikeCount\x88\x01\x01\x12\x1c\n" + + "\tcreatedAt\x18\b \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tdeletedAt\x18\t \x01(\x03R\tdeletedAtB\n" + + "\n" + + "\b_contentB\f\n" + + "\n" + + "_likeCount\">\n" + + "\x12SearchCommentsResp\x12(\n" + + "\bcomments\x18\x01 \x03(\v2\f.pb.CommentsR\bcomments\"Y\n" + + "\tPostLikes\x12\x16\n" + + "\x06postId\x18\x01 \x01(\x03R\x06postId\x12\x16\n" + + "\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x1c\n" + + "\tcreatedAt\x18\x03 \x01(\x03R\tcreatedAt\"_\n" + + "\x0fAddPostLikesReq\x12\x16\n" + + "\x06postId\x18\x01 \x01(\x03R\x06postId\x12\x16\n" + + "\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x1c\n" + + "\tcreatedAt\x18\x03 \x01(\x03R\tcreatedAt\"\x12\n" + + "\x10AddPostLikesResp\"\x82\x01\n" + + "\x12UpdatePostLikesReq\x12\x1b\n" + + "\x06postId\x18\x01 \x01(\x03H\x00R\x06postId\x88\x01\x01\x12\x1b\n" + + "\x06userId\x18\x02 \x01(\x03H\x01R\x06userId\x88\x01\x01\x12\x1c\n" + + "\tcreatedAt\x18\x03 \x01(\x03R\tcreatedAtB\t\n" + + "\a_postIdB\t\n" + + "\a_userId\"\x15\n" + + "\x13UpdatePostLikesResp\"I\n" + + "\x0fDelPostLikesReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1b\n" + + "\x06userId\x18\x02 \x01(\x03H\x00R\x06userId\x88\x01\x01B\t\n" + + "\a_userId\"\x12\n" + + "\x10DelPostLikesResp\"%\n" + + "\x13GetPostLikesByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"C\n" + + "\x14GetPostLikesByIdResp\x12+\n" + + "\tpostLikes\x18\x01 \x01(\v2\r.pb.PostLikesR\tpostLikes\"\xac\x01\n" + + "\x12SearchPostLikesReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x1b\n" + + "\x06postId\x18\x03 \x01(\x03H\x00R\x06postId\x88\x01\x01\x12\x1b\n" + + "\x06userId\x18\x04 \x01(\x03H\x01R\x06userId\x88\x01\x01\x12\x1c\n" + + "\tcreatedAt\x18\x05 \x01(\x03R\tcreatedAtB\t\n" + + "\a_postIdB\t\n" + + "\a_userId\"B\n" + + "\x13SearchPostLikesResp\x12+\n" + + "\tpostLikes\x18\x01 \x03(\v2\r.pb.PostLikesR\tpostLikes\"\xcd\x03\n" + + "\x05Posts\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1a\n" + + "\bauthorId\x18\x02 \x01(\x03R\bauthorId\x12\x1e\n" + + "\n" + + "authorRole\x18\x03 \x01(\tR\n" + + "authorRole\x12\x14\n" + + "\x05title\x18\x04 \x01(\tR\x05title\x12\x18\n" + + "\acontent\x18\x05 \x01(\tR\acontent\x12\x16\n" + + "\x06images\x18\x06 \x03(\tR\x06images\x12\x12\n" + + "\x04tags\x18\a \x03(\tR\x04tags\x12$\n" + + "\rlinkedOrderId\x18\b \x01(\x03R\rlinkedOrderId\x12\"\n" + + "\fquotedPostId\x18\t \x01(\x03R\fquotedPostId\x12\x1c\n" + + "\tlikeCount\x18\n" + + " \x01(\x03R\tlikeCount\x12\"\n" + + "\fcommentCount\x18\v \x01(\x03R\fcommentCount\x12\x16\n" + + "\x06pinned\x18\f \x01(\bR\x06pinned\x12\x1e\n" + + "\n" + + "searchText\x18\r \x01(\tR\n" + + "searchText\x12\x1c\n" + + "\tcreatedAt\x18\x0e \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tupdatedAt\x18\x0f \x01(\x03R\tupdatedAt\x12\x1c\n" + + "\tdeletedAt\x18\x10 \x01(\x03R\tdeletedAt\"\xc3\x03\n" + + "\vAddPostsReq\x12\x1a\n" + + "\bauthorId\x18\x01 \x01(\x03R\bauthorId\x12\x1e\n" + + "\n" + + "authorRole\x18\x02 \x01(\tR\n" + + "authorRole\x12\x14\n" + + "\x05title\x18\x03 \x01(\tR\x05title\x12\x18\n" + + "\acontent\x18\x04 \x01(\tR\acontent\x12\x16\n" + + "\x06images\x18\x05 \x03(\tR\x06images\x12\x12\n" + + "\x04tags\x18\x06 \x03(\tR\x04tags\x12$\n" + + "\rlinkedOrderId\x18\a \x01(\x03R\rlinkedOrderId\x12\"\n" + + "\fquotedPostId\x18\b \x01(\x03R\fquotedPostId\x12\x1c\n" + + "\tlikeCount\x18\t \x01(\x03R\tlikeCount\x12\"\n" + + "\fcommentCount\x18\n" + + " \x01(\x03R\fcommentCount\x12\x16\n" + + "\x06pinned\x18\v \x01(\bR\x06pinned\x12\x1e\n" + + "\n" + + "searchText\x18\f \x01(\tR\n" + + "searchText\x12\x1c\n" + + "\tcreatedAt\x18\r \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tupdatedAt\x18\x0e \x01(\x03R\tupdatedAt\x12\x1c\n" + + "\tdeletedAt\x18\x0f \x01(\x03R\tdeletedAt\"\x0e\n" + + "\fAddPostsResp\"\xcf\x05\n" + + "\x0eUpdatePostsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1f\n" + + "\bauthorId\x18\x02 \x01(\x03H\x00R\bauthorId\x88\x01\x01\x12#\n" + + "\n" + + "authorRole\x18\x03 \x01(\tH\x01R\n" + + "authorRole\x88\x01\x01\x12\x19\n" + + "\x05title\x18\x04 \x01(\tH\x02R\x05title\x88\x01\x01\x12\x1d\n" + + "\acontent\x18\x05 \x01(\tH\x03R\acontent\x88\x01\x01\x12\x16\n" + + "\x06images\x18\x06 \x03(\tR\x06images\x12\x12\n" + + "\x04tags\x18\a \x03(\tR\x04tags\x12)\n" + + "\rlinkedOrderId\x18\b \x01(\x03H\x04R\rlinkedOrderId\x88\x01\x01\x12'\n" + + "\fquotedPostId\x18\t \x01(\x03H\x05R\fquotedPostId\x88\x01\x01\x12!\n" + + "\tlikeCount\x18\n" + + " \x01(\x03H\x06R\tlikeCount\x88\x01\x01\x12'\n" + + "\fcommentCount\x18\v \x01(\x03H\aR\fcommentCount\x88\x01\x01\x12\x1b\n" + + "\x06pinned\x18\f \x01(\bH\bR\x06pinned\x88\x01\x01\x12#\n" + + "\n" + + "searchText\x18\r \x01(\tH\tR\n" + + "searchText\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\x0e \x01(\x03H\n" + + "R\tcreatedAt\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\x0f \x01(\x03H\vR\tupdatedAt\x88\x01\x01\x12!\n" + + "\tdeletedAt\x18\x10 \x01(\x03H\fR\tdeletedAt\x88\x01\x01B\v\n" + + "\t_authorIdB\r\n" + + "\v_authorRoleB\b\n" + + "\x06_titleB\n" + + "\n" + + "\b_contentB\x10\n" + + "\x0e_linkedOrderIdB\x0f\n" + + "\r_quotedPostIdB\f\n" + + "\n" + + "_likeCountB\x0f\n" + + "\r_commentCountB\t\n" + + "\a_pinnedB\r\n" + + "\v_searchTextB\f\n" + + "\n" + + "_createdAtB\f\n" + + "\n" + + "_updatedAtB\f\n" + + "\n" + + "_deletedAt\"\x11\n" + + "\x0fUpdatePostsResp\"\x1d\n" + + "\vDelPostsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x0e\n" + + "\fDelPostsResp\"!\n" + + "\x0fGetPostsByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"3\n" + + "\x10GetPostsByIdResp\x12\x1f\n" + + "\x05posts\x18\x01 \x01(\v2\t.pb.PostsR\x05posts\"\xf9\x05\n" + + "\x0eSearchPostsReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x0e\n" + + "\x02id\x18\x03 \x01(\x03R\x02id\x12\x1f\n" + + "\bauthorId\x18\x04 \x01(\x03H\x00R\bauthorId\x88\x01\x01\x12#\n" + + "\n" + + "authorRole\x18\x05 \x01(\tH\x01R\n" + + "authorRole\x88\x01\x01\x12\x19\n" + + "\x05title\x18\x06 \x01(\tH\x02R\x05title\x88\x01\x01\x12\x1d\n" + + "\acontent\x18\a \x01(\tH\x03R\acontent\x88\x01\x01\x12\x16\n" + + "\x06images\x18\b \x03(\tR\x06images\x12\x12\n" + + "\x04tags\x18\t \x03(\tR\x04tags\x12)\n" + + "\rlinkedOrderId\x18\n" + + " \x01(\x03H\x04R\rlinkedOrderId\x88\x01\x01\x12'\n" + + "\fquotedPostId\x18\v \x01(\x03H\x05R\fquotedPostId\x88\x01\x01\x12!\n" + + "\tlikeCount\x18\f \x01(\x03H\x06R\tlikeCount\x88\x01\x01\x12'\n" + + "\fcommentCount\x18\r \x01(\x03H\aR\fcommentCount\x88\x01\x01\x12\x1b\n" + + "\x06pinned\x18\x0e \x01(\bH\bR\x06pinned\x88\x01\x01\x12#\n" + + "\n" + + "searchText\x18\x0f \x01(\tH\tR\n" + + "searchText\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\x10 \x01(\x03H\n" + + "R\tcreatedAt\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\x11 \x01(\x03H\vR\tupdatedAt\x88\x01\x01\x12!\n" + + "\tdeletedAt\x18\x12 \x01(\x03H\fR\tdeletedAt\x88\x01\x01B\v\n" + + "\t_authorIdB\r\n" + + "\v_authorRoleB\b\n" + + "\x06_titleB\n" + + "\n" + + "\b_contentB\x10\n" + + "\x0e_linkedOrderIdB\x0f\n" + + "\r_quotedPostIdB\f\n" + + "\n" + + "_likeCountB\x0f\n" + + "\r_commentCountB\t\n" + + "\a_pinnedB\r\n" + + "\v_searchTextB\f\n" + + "\n" + + "_createdAtB\f\n" + + "\n" + + "_updatedAtB\f\n" + + "\n" + + "_deletedAt\"2\n" + + "\x0fSearchPostsResp\x12\x1f\n" + + "\x05posts\x18\x01 \x03(\v2\t.pb.PostsR\x05posts2\x88\n" + + "\n" + + "\x10communityService\x12B\n" + + "\x0fAddCommentLikes\x12\x16.pb.AddCommentLikesReq\x1a\x17.pb.AddCommentLikesResp\x12K\n" + + "\x12UpdateCommentLikes\x12\x19.pb.UpdateCommentLikesReq\x1a\x1a.pb.UpdateCommentLikesResp\x12B\n" + + "\x0fDelCommentLikes\x12\x16.pb.DelCommentLikesReq\x1a\x17.pb.DelCommentLikesResp\x12N\n" + + "\x13GetCommentLikesById\x12\x1a.pb.GetCommentLikesByIdReq\x1a\x1b.pb.GetCommentLikesByIdResp\x12K\n" + + "\x12SearchCommentLikes\x12\x19.pb.SearchCommentLikesReq\x1a\x1a.pb.SearchCommentLikesResp\x126\n" + + "\vAddComments\x12\x12.pb.AddCommentsReq\x1a\x13.pb.AddCommentsResp\x12?\n" + + "\x0eUpdateComments\x12\x15.pb.UpdateCommentsReq\x1a\x16.pb.UpdateCommentsResp\x126\n" + + "\vDelComments\x12\x12.pb.DelCommentsReq\x1a\x13.pb.DelCommentsResp\x12B\n" + + "\x0fGetCommentsById\x12\x16.pb.GetCommentsByIdReq\x1a\x17.pb.GetCommentsByIdResp\x12?\n" + + "\x0eSearchComments\x12\x15.pb.SearchCommentsReq\x1a\x16.pb.SearchCommentsResp\x129\n" + + "\fAddPostLikes\x12\x13.pb.AddPostLikesReq\x1a\x14.pb.AddPostLikesResp\x12B\n" + + "\x0fUpdatePostLikes\x12\x16.pb.UpdatePostLikesReq\x1a\x17.pb.UpdatePostLikesResp\x129\n" + + "\fDelPostLikes\x12\x13.pb.DelPostLikesReq\x1a\x14.pb.DelPostLikesResp\x12E\n" + + "\x10GetPostLikesById\x12\x17.pb.GetPostLikesByIdReq\x1a\x18.pb.GetPostLikesByIdResp\x12B\n" + + "\x0fSearchPostLikes\x12\x16.pb.SearchPostLikesReq\x1a\x17.pb.SearchPostLikesResp\x12-\n" + + "\bAddPosts\x12\x0f.pb.AddPostsReq\x1a\x10.pb.AddPostsResp\x126\n" + + "\vUpdatePosts\x12\x12.pb.UpdatePostsReq\x1a\x13.pb.UpdatePostsResp\x12-\n" + + "\bDelPosts\x12\x0f.pb.DelPostsReq\x1a\x10.pb.DelPostsResp\x129\n" + + "\fGetPostsById\x12\x13.pb.GetPostsByIdReq\x1a\x14.pb.GetPostsByIdResp\x126\n" + + "\vSearchPosts\x12\x12.pb.SearchPostsReq\x1a\x13.pb.SearchPostsRespB\x06Z\x04./pbb\x06proto3" + +var ( + file_community_proto_rawDescOnce sync.Once + file_community_proto_rawDescData []byte +) + +func file_community_proto_rawDescGZIP() []byte { + file_community_proto_rawDescOnce.Do(func() { + file_community_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_community_proto_rawDesc), len(file_community_proto_rawDesc))) + }) + return file_community_proto_rawDescData +} + +var file_community_proto_msgTypes = make([]protoimpl.MessageInfo, 44) +var file_community_proto_goTypes = []any{ + (*CommentLikes)(nil), // 0: pb.CommentLikes + (*AddCommentLikesReq)(nil), // 1: pb.AddCommentLikesReq + (*AddCommentLikesResp)(nil), // 2: pb.AddCommentLikesResp + (*UpdateCommentLikesReq)(nil), // 3: pb.UpdateCommentLikesReq + (*UpdateCommentLikesResp)(nil), // 4: pb.UpdateCommentLikesResp + (*DelCommentLikesReq)(nil), // 5: pb.DelCommentLikesReq + (*DelCommentLikesResp)(nil), // 6: pb.DelCommentLikesResp + (*GetCommentLikesByIdReq)(nil), // 7: pb.GetCommentLikesByIdReq + (*GetCommentLikesByIdResp)(nil), // 8: pb.GetCommentLikesByIdResp + (*SearchCommentLikesReq)(nil), // 9: pb.SearchCommentLikesReq + (*SearchCommentLikesResp)(nil), // 10: pb.SearchCommentLikesResp + (*Comments)(nil), // 11: pb.Comments + (*AddCommentsReq)(nil), // 12: pb.AddCommentsReq + (*AddCommentsResp)(nil), // 13: pb.AddCommentsResp + (*UpdateCommentsReq)(nil), // 14: pb.UpdateCommentsReq + (*UpdateCommentsResp)(nil), // 15: pb.UpdateCommentsResp + (*DelCommentsReq)(nil), // 16: pb.DelCommentsReq + (*DelCommentsResp)(nil), // 17: pb.DelCommentsResp + (*GetCommentsByIdReq)(nil), // 18: pb.GetCommentsByIdReq + (*GetCommentsByIdResp)(nil), // 19: pb.GetCommentsByIdResp + (*SearchCommentsReq)(nil), // 20: pb.SearchCommentsReq + (*SearchCommentsResp)(nil), // 21: pb.SearchCommentsResp + (*PostLikes)(nil), // 22: pb.PostLikes + (*AddPostLikesReq)(nil), // 23: pb.AddPostLikesReq + (*AddPostLikesResp)(nil), // 24: pb.AddPostLikesResp + (*UpdatePostLikesReq)(nil), // 25: pb.UpdatePostLikesReq + (*UpdatePostLikesResp)(nil), // 26: pb.UpdatePostLikesResp + (*DelPostLikesReq)(nil), // 27: pb.DelPostLikesReq + (*DelPostLikesResp)(nil), // 28: pb.DelPostLikesResp + (*GetPostLikesByIdReq)(nil), // 29: pb.GetPostLikesByIdReq + (*GetPostLikesByIdResp)(nil), // 30: pb.GetPostLikesByIdResp + (*SearchPostLikesReq)(nil), // 31: pb.SearchPostLikesReq + (*SearchPostLikesResp)(nil), // 32: pb.SearchPostLikesResp + (*Posts)(nil), // 33: pb.Posts + (*AddPostsReq)(nil), // 34: pb.AddPostsReq + (*AddPostsResp)(nil), // 35: pb.AddPostsResp + (*UpdatePostsReq)(nil), // 36: pb.UpdatePostsReq + (*UpdatePostsResp)(nil), // 37: pb.UpdatePostsResp + (*DelPostsReq)(nil), // 38: pb.DelPostsReq + (*DelPostsResp)(nil), // 39: pb.DelPostsResp + (*GetPostsByIdReq)(nil), // 40: pb.GetPostsByIdReq + (*GetPostsByIdResp)(nil), // 41: pb.GetPostsByIdResp + (*SearchPostsReq)(nil), // 42: pb.SearchPostsReq + (*SearchPostsResp)(nil), // 43: pb.SearchPostsResp +} +var file_community_proto_depIdxs = []int32{ + 0, // 0: pb.GetCommentLikesByIdResp.commentLikes:type_name -> pb.CommentLikes + 0, // 1: pb.SearchCommentLikesResp.commentLikes:type_name -> pb.CommentLikes + 11, // 2: pb.GetCommentsByIdResp.comments:type_name -> pb.Comments + 11, // 3: pb.SearchCommentsResp.comments:type_name -> pb.Comments + 22, // 4: pb.GetPostLikesByIdResp.postLikes:type_name -> pb.PostLikes + 22, // 5: pb.SearchPostLikesResp.postLikes:type_name -> pb.PostLikes + 33, // 6: pb.GetPostsByIdResp.posts:type_name -> pb.Posts + 33, // 7: pb.SearchPostsResp.posts:type_name -> pb.Posts + 1, // 8: pb.communityService.AddCommentLikes:input_type -> pb.AddCommentLikesReq + 3, // 9: pb.communityService.UpdateCommentLikes:input_type -> pb.UpdateCommentLikesReq + 5, // 10: pb.communityService.DelCommentLikes:input_type -> pb.DelCommentLikesReq + 7, // 11: pb.communityService.GetCommentLikesById:input_type -> pb.GetCommentLikesByIdReq + 9, // 12: pb.communityService.SearchCommentLikes:input_type -> pb.SearchCommentLikesReq + 12, // 13: pb.communityService.AddComments:input_type -> pb.AddCommentsReq + 14, // 14: pb.communityService.UpdateComments:input_type -> pb.UpdateCommentsReq + 16, // 15: pb.communityService.DelComments:input_type -> pb.DelCommentsReq + 18, // 16: pb.communityService.GetCommentsById:input_type -> pb.GetCommentsByIdReq + 20, // 17: pb.communityService.SearchComments:input_type -> pb.SearchCommentsReq + 23, // 18: pb.communityService.AddPostLikes:input_type -> pb.AddPostLikesReq + 25, // 19: pb.communityService.UpdatePostLikes:input_type -> pb.UpdatePostLikesReq + 27, // 20: pb.communityService.DelPostLikes:input_type -> pb.DelPostLikesReq + 29, // 21: pb.communityService.GetPostLikesById:input_type -> pb.GetPostLikesByIdReq + 31, // 22: pb.communityService.SearchPostLikes:input_type -> pb.SearchPostLikesReq + 34, // 23: pb.communityService.AddPosts:input_type -> pb.AddPostsReq + 36, // 24: pb.communityService.UpdatePosts:input_type -> pb.UpdatePostsReq + 38, // 25: pb.communityService.DelPosts:input_type -> pb.DelPostsReq + 40, // 26: pb.communityService.GetPostsById:input_type -> pb.GetPostsByIdReq + 42, // 27: pb.communityService.SearchPosts:input_type -> pb.SearchPostsReq + 2, // 28: pb.communityService.AddCommentLikes:output_type -> pb.AddCommentLikesResp + 4, // 29: pb.communityService.UpdateCommentLikes:output_type -> pb.UpdateCommentLikesResp + 6, // 30: pb.communityService.DelCommentLikes:output_type -> pb.DelCommentLikesResp + 8, // 31: pb.communityService.GetCommentLikesById:output_type -> pb.GetCommentLikesByIdResp + 10, // 32: pb.communityService.SearchCommentLikes:output_type -> pb.SearchCommentLikesResp + 13, // 33: pb.communityService.AddComments:output_type -> pb.AddCommentsResp + 15, // 34: pb.communityService.UpdateComments:output_type -> pb.UpdateCommentsResp + 17, // 35: pb.communityService.DelComments:output_type -> pb.DelCommentsResp + 19, // 36: pb.communityService.GetCommentsById:output_type -> pb.GetCommentsByIdResp + 21, // 37: pb.communityService.SearchComments:output_type -> pb.SearchCommentsResp + 24, // 38: pb.communityService.AddPostLikes:output_type -> pb.AddPostLikesResp + 26, // 39: pb.communityService.UpdatePostLikes:output_type -> pb.UpdatePostLikesResp + 28, // 40: pb.communityService.DelPostLikes:output_type -> pb.DelPostLikesResp + 30, // 41: pb.communityService.GetPostLikesById:output_type -> pb.GetPostLikesByIdResp + 32, // 42: pb.communityService.SearchPostLikes:output_type -> pb.SearchPostLikesResp + 35, // 43: pb.communityService.AddPosts:output_type -> pb.AddPostsResp + 37, // 44: pb.communityService.UpdatePosts:output_type -> pb.UpdatePostsResp + 39, // 45: pb.communityService.DelPosts:output_type -> pb.DelPostsResp + 41, // 46: pb.communityService.GetPostsById:output_type -> pb.GetPostsByIdResp + 43, // 47: pb.communityService.SearchPosts:output_type -> pb.SearchPostsResp + 28, // [28:48] is the sub-list for method output_type + 8, // [8:28] is the sub-list for method input_type + 8, // [8:8] is the sub-list for extension type_name + 8, // [8:8] is the sub-list for extension extendee + 0, // [0:8] is the sub-list for field type_name +} + +func init() { file_community_proto_init() } +func file_community_proto_init() { + if File_community_proto != nil { + return + } + file_community_proto_msgTypes[5].OneofWrappers = []any{} + file_community_proto_msgTypes[20].OneofWrappers = []any{} + file_community_proto_msgTypes[25].OneofWrappers = []any{} + file_community_proto_msgTypes[27].OneofWrappers = []any{} + file_community_proto_msgTypes[31].OneofWrappers = []any{} + file_community_proto_msgTypes[36].OneofWrappers = []any{} + file_community_proto_msgTypes[42].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_community_proto_rawDesc), len(file_community_proto_rawDesc)), + NumEnums: 0, + NumMessages: 44, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_community_proto_goTypes, + DependencyIndexes: file_community_proto_depIdxs, + MessageInfos: file_community_proto_msgTypes, + }.Build() + File_community_proto = out.File + file_community_proto_goTypes = nil + file_community_proto_depIdxs = nil +} diff --git a/app/community/rpc/pb/community_grpc.pb.go b/app/community/rpc/pb/community_grpc.pb.go new file mode 100644 index 0000000..a9eae8e --- /dev/null +++ b/app/community/rpc/pb/community_grpc.pb.go @@ -0,0 +1,851 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v5.29.6 +// source: community.proto + +package pb + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + CommunityService_AddCommentLikes_FullMethodName = "/pb.communityService/AddCommentLikes" + CommunityService_UpdateCommentLikes_FullMethodName = "/pb.communityService/UpdateCommentLikes" + CommunityService_DelCommentLikes_FullMethodName = "/pb.communityService/DelCommentLikes" + CommunityService_GetCommentLikesById_FullMethodName = "/pb.communityService/GetCommentLikesById" + CommunityService_SearchCommentLikes_FullMethodName = "/pb.communityService/SearchCommentLikes" + CommunityService_AddComments_FullMethodName = "/pb.communityService/AddComments" + CommunityService_UpdateComments_FullMethodName = "/pb.communityService/UpdateComments" + CommunityService_DelComments_FullMethodName = "/pb.communityService/DelComments" + CommunityService_GetCommentsById_FullMethodName = "/pb.communityService/GetCommentsById" + CommunityService_SearchComments_FullMethodName = "/pb.communityService/SearchComments" + CommunityService_AddPostLikes_FullMethodName = "/pb.communityService/AddPostLikes" + CommunityService_UpdatePostLikes_FullMethodName = "/pb.communityService/UpdatePostLikes" + CommunityService_DelPostLikes_FullMethodName = "/pb.communityService/DelPostLikes" + CommunityService_GetPostLikesById_FullMethodName = "/pb.communityService/GetPostLikesById" + CommunityService_SearchPostLikes_FullMethodName = "/pb.communityService/SearchPostLikes" + CommunityService_AddPosts_FullMethodName = "/pb.communityService/AddPosts" + CommunityService_UpdatePosts_FullMethodName = "/pb.communityService/UpdatePosts" + CommunityService_DelPosts_FullMethodName = "/pb.communityService/DelPosts" + CommunityService_GetPostsById_FullMethodName = "/pb.communityService/GetPostsById" + CommunityService_SearchPosts_FullMethodName = "/pb.communityService/SearchPosts" +) + +// CommunityServiceClient is the client API for CommunityService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type CommunityServiceClient interface { + // -----------------------commentLikes----------------------- + AddCommentLikes(ctx context.Context, in *AddCommentLikesReq, opts ...grpc.CallOption) (*AddCommentLikesResp, error) + UpdateCommentLikes(ctx context.Context, in *UpdateCommentLikesReq, opts ...grpc.CallOption) (*UpdateCommentLikesResp, error) + DelCommentLikes(ctx context.Context, in *DelCommentLikesReq, opts ...grpc.CallOption) (*DelCommentLikesResp, error) + GetCommentLikesById(ctx context.Context, in *GetCommentLikesByIdReq, opts ...grpc.CallOption) (*GetCommentLikesByIdResp, error) + SearchCommentLikes(ctx context.Context, in *SearchCommentLikesReq, opts ...grpc.CallOption) (*SearchCommentLikesResp, error) + // -----------------------comments----------------------- + AddComments(ctx context.Context, in *AddCommentsReq, opts ...grpc.CallOption) (*AddCommentsResp, error) + UpdateComments(ctx context.Context, in *UpdateCommentsReq, opts ...grpc.CallOption) (*UpdateCommentsResp, error) + DelComments(ctx context.Context, in *DelCommentsReq, opts ...grpc.CallOption) (*DelCommentsResp, error) + GetCommentsById(ctx context.Context, in *GetCommentsByIdReq, opts ...grpc.CallOption) (*GetCommentsByIdResp, error) + SearchComments(ctx context.Context, in *SearchCommentsReq, opts ...grpc.CallOption) (*SearchCommentsResp, error) + // -----------------------postLikes----------------------- + AddPostLikes(ctx context.Context, in *AddPostLikesReq, opts ...grpc.CallOption) (*AddPostLikesResp, error) + UpdatePostLikes(ctx context.Context, in *UpdatePostLikesReq, opts ...grpc.CallOption) (*UpdatePostLikesResp, error) + DelPostLikes(ctx context.Context, in *DelPostLikesReq, opts ...grpc.CallOption) (*DelPostLikesResp, error) + GetPostLikesById(ctx context.Context, in *GetPostLikesByIdReq, opts ...grpc.CallOption) (*GetPostLikesByIdResp, error) + SearchPostLikes(ctx context.Context, in *SearchPostLikesReq, opts ...grpc.CallOption) (*SearchPostLikesResp, error) + // -----------------------posts----------------------- + AddPosts(ctx context.Context, in *AddPostsReq, opts ...grpc.CallOption) (*AddPostsResp, error) + UpdatePosts(ctx context.Context, in *UpdatePostsReq, opts ...grpc.CallOption) (*UpdatePostsResp, error) + DelPosts(ctx context.Context, in *DelPostsReq, opts ...grpc.CallOption) (*DelPostsResp, error) + GetPostsById(ctx context.Context, in *GetPostsByIdReq, opts ...grpc.CallOption) (*GetPostsByIdResp, error) + SearchPosts(ctx context.Context, in *SearchPostsReq, opts ...grpc.CallOption) (*SearchPostsResp, error) +} + +type communityServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewCommunityServiceClient(cc grpc.ClientConnInterface) CommunityServiceClient { + return &communityServiceClient{cc} +} + +func (c *communityServiceClient) AddCommentLikes(ctx context.Context, in *AddCommentLikesReq, opts ...grpc.CallOption) (*AddCommentLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddCommentLikesResp) + err := c.cc.Invoke(ctx, CommunityService_AddCommentLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) UpdateCommentLikes(ctx context.Context, in *UpdateCommentLikesReq, opts ...grpc.CallOption) (*UpdateCommentLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateCommentLikesResp) + err := c.cc.Invoke(ctx, CommunityService_UpdateCommentLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) DelCommentLikes(ctx context.Context, in *DelCommentLikesReq, opts ...grpc.CallOption) (*DelCommentLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelCommentLikesResp) + err := c.cc.Invoke(ctx, CommunityService_DelCommentLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) GetCommentLikesById(ctx context.Context, in *GetCommentLikesByIdReq, opts ...grpc.CallOption) (*GetCommentLikesByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetCommentLikesByIdResp) + err := c.cc.Invoke(ctx, CommunityService_GetCommentLikesById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) SearchCommentLikes(ctx context.Context, in *SearchCommentLikesReq, opts ...grpc.CallOption) (*SearchCommentLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchCommentLikesResp) + err := c.cc.Invoke(ctx, CommunityService_SearchCommentLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) AddComments(ctx context.Context, in *AddCommentsReq, opts ...grpc.CallOption) (*AddCommentsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddCommentsResp) + err := c.cc.Invoke(ctx, CommunityService_AddComments_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) UpdateComments(ctx context.Context, in *UpdateCommentsReq, opts ...grpc.CallOption) (*UpdateCommentsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateCommentsResp) + err := c.cc.Invoke(ctx, CommunityService_UpdateComments_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) DelComments(ctx context.Context, in *DelCommentsReq, opts ...grpc.CallOption) (*DelCommentsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelCommentsResp) + err := c.cc.Invoke(ctx, CommunityService_DelComments_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) GetCommentsById(ctx context.Context, in *GetCommentsByIdReq, opts ...grpc.CallOption) (*GetCommentsByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetCommentsByIdResp) + err := c.cc.Invoke(ctx, CommunityService_GetCommentsById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) SearchComments(ctx context.Context, in *SearchCommentsReq, opts ...grpc.CallOption) (*SearchCommentsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchCommentsResp) + err := c.cc.Invoke(ctx, CommunityService_SearchComments_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) AddPostLikes(ctx context.Context, in *AddPostLikesReq, opts ...grpc.CallOption) (*AddPostLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddPostLikesResp) + err := c.cc.Invoke(ctx, CommunityService_AddPostLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) UpdatePostLikes(ctx context.Context, in *UpdatePostLikesReq, opts ...grpc.CallOption) (*UpdatePostLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdatePostLikesResp) + err := c.cc.Invoke(ctx, CommunityService_UpdatePostLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) DelPostLikes(ctx context.Context, in *DelPostLikesReq, opts ...grpc.CallOption) (*DelPostLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelPostLikesResp) + err := c.cc.Invoke(ctx, CommunityService_DelPostLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) GetPostLikesById(ctx context.Context, in *GetPostLikesByIdReq, opts ...grpc.CallOption) (*GetPostLikesByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetPostLikesByIdResp) + err := c.cc.Invoke(ctx, CommunityService_GetPostLikesById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) SearchPostLikes(ctx context.Context, in *SearchPostLikesReq, opts ...grpc.CallOption) (*SearchPostLikesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchPostLikesResp) + err := c.cc.Invoke(ctx, CommunityService_SearchPostLikes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) AddPosts(ctx context.Context, in *AddPostsReq, opts ...grpc.CallOption) (*AddPostsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddPostsResp) + err := c.cc.Invoke(ctx, CommunityService_AddPosts_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) UpdatePosts(ctx context.Context, in *UpdatePostsReq, opts ...grpc.CallOption) (*UpdatePostsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdatePostsResp) + err := c.cc.Invoke(ctx, CommunityService_UpdatePosts_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) DelPosts(ctx context.Context, in *DelPostsReq, opts ...grpc.CallOption) (*DelPostsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelPostsResp) + err := c.cc.Invoke(ctx, CommunityService_DelPosts_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) GetPostsById(ctx context.Context, in *GetPostsByIdReq, opts ...grpc.CallOption) (*GetPostsByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetPostsByIdResp) + err := c.cc.Invoke(ctx, CommunityService_GetPostsById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *communityServiceClient) SearchPosts(ctx context.Context, in *SearchPostsReq, opts ...grpc.CallOption) (*SearchPostsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchPostsResp) + err := c.cc.Invoke(ctx, CommunityService_SearchPosts_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// CommunityServiceServer is the server API for CommunityService service. +// All implementations must embed UnimplementedCommunityServiceServer +// for forward compatibility. +type CommunityServiceServer interface { + // -----------------------commentLikes----------------------- + AddCommentLikes(context.Context, *AddCommentLikesReq) (*AddCommentLikesResp, error) + UpdateCommentLikes(context.Context, *UpdateCommentLikesReq) (*UpdateCommentLikesResp, error) + DelCommentLikes(context.Context, *DelCommentLikesReq) (*DelCommentLikesResp, error) + GetCommentLikesById(context.Context, *GetCommentLikesByIdReq) (*GetCommentLikesByIdResp, error) + SearchCommentLikes(context.Context, *SearchCommentLikesReq) (*SearchCommentLikesResp, error) + // -----------------------comments----------------------- + AddComments(context.Context, *AddCommentsReq) (*AddCommentsResp, error) + UpdateComments(context.Context, *UpdateCommentsReq) (*UpdateCommentsResp, error) + DelComments(context.Context, *DelCommentsReq) (*DelCommentsResp, error) + GetCommentsById(context.Context, *GetCommentsByIdReq) (*GetCommentsByIdResp, error) + SearchComments(context.Context, *SearchCommentsReq) (*SearchCommentsResp, error) + // -----------------------postLikes----------------------- + AddPostLikes(context.Context, *AddPostLikesReq) (*AddPostLikesResp, error) + UpdatePostLikes(context.Context, *UpdatePostLikesReq) (*UpdatePostLikesResp, error) + DelPostLikes(context.Context, *DelPostLikesReq) (*DelPostLikesResp, error) + GetPostLikesById(context.Context, *GetPostLikesByIdReq) (*GetPostLikesByIdResp, error) + SearchPostLikes(context.Context, *SearchPostLikesReq) (*SearchPostLikesResp, error) + // -----------------------posts----------------------- + AddPosts(context.Context, *AddPostsReq) (*AddPostsResp, error) + UpdatePosts(context.Context, *UpdatePostsReq) (*UpdatePostsResp, error) + DelPosts(context.Context, *DelPostsReq) (*DelPostsResp, error) + GetPostsById(context.Context, *GetPostsByIdReq) (*GetPostsByIdResp, error) + SearchPosts(context.Context, *SearchPostsReq) (*SearchPostsResp, error) + mustEmbedUnimplementedCommunityServiceServer() +} + +// UnimplementedCommunityServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedCommunityServiceServer struct{} + +func (UnimplementedCommunityServiceServer) AddCommentLikes(context.Context, *AddCommentLikesReq) (*AddCommentLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddCommentLikes not implemented") +} +func (UnimplementedCommunityServiceServer) UpdateCommentLikes(context.Context, *UpdateCommentLikesReq) (*UpdateCommentLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateCommentLikes not implemented") +} +func (UnimplementedCommunityServiceServer) DelCommentLikes(context.Context, *DelCommentLikesReq) (*DelCommentLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelCommentLikes not implemented") +} +func (UnimplementedCommunityServiceServer) GetCommentLikesById(context.Context, *GetCommentLikesByIdReq) (*GetCommentLikesByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetCommentLikesById not implemented") +} +func (UnimplementedCommunityServiceServer) SearchCommentLikes(context.Context, *SearchCommentLikesReq) (*SearchCommentLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchCommentLikes not implemented") +} +func (UnimplementedCommunityServiceServer) AddComments(context.Context, *AddCommentsReq) (*AddCommentsResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddComments not implemented") +} +func (UnimplementedCommunityServiceServer) UpdateComments(context.Context, *UpdateCommentsReq) (*UpdateCommentsResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateComments not implemented") +} +func (UnimplementedCommunityServiceServer) DelComments(context.Context, *DelCommentsReq) (*DelCommentsResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelComments not implemented") +} +func (UnimplementedCommunityServiceServer) GetCommentsById(context.Context, *GetCommentsByIdReq) (*GetCommentsByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetCommentsById not implemented") +} +func (UnimplementedCommunityServiceServer) SearchComments(context.Context, *SearchCommentsReq) (*SearchCommentsResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchComments not implemented") +} +func (UnimplementedCommunityServiceServer) AddPostLikes(context.Context, *AddPostLikesReq) (*AddPostLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddPostLikes not implemented") +} +func (UnimplementedCommunityServiceServer) UpdatePostLikes(context.Context, *UpdatePostLikesReq) (*UpdatePostLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdatePostLikes not implemented") +} +func (UnimplementedCommunityServiceServer) DelPostLikes(context.Context, *DelPostLikesReq) (*DelPostLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelPostLikes not implemented") +} +func (UnimplementedCommunityServiceServer) GetPostLikesById(context.Context, *GetPostLikesByIdReq) (*GetPostLikesByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetPostLikesById not implemented") +} +func (UnimplementedCommunityServiceServer) SearchPostLikes(context.Context, *SearchPostLikesReq) (*SearchPostLikesResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchPostLikes not implemented") +} +func (UnimplementedCommunityServiceServer) AddPosts(context.Context, *AddPostsReq) (*AddPostsResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddPosts not implemented") +} +func (UnimplementedCommunityServiceServer) UpdatePosts(context.Context, *UpdatePostsReq) (*UpdatePostsResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdatePosts not implemented") +} +func (UnimplementedCommunityServiceServer) DelPosts(context.Context, *DelPostsReq) (*DelPostsResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelPosts not implemented") +} +func (UnimplementedCommunityServiceServer) GetPostsById(context.Context, *GetPostsByIdReq) (*GetPostsByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetPostsById not implemented") +} +func (UnimplementedCommunityServiceServer) SearchPosts(context.Context, *SearchPostsReq) (*SearchPostsResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchPosts not implemented") +} +func (UnimplementedCommunityServiceServer) mustEmbedUnimplementedCommunityServiceServer() {} +func (UnimplementedCommunityServiceServer) testEmbeddedByValue() {} + +// UnsafeCommunityServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to CommunityServiceServer will +// result in compilation errors. +type UnsafeCommunityServiceServer interface { + mustEmbedUnimplementedCommunityServiceServer() +} + +func RegisterCommunityServiceServer(s grpc.ServiceRegistrar, srv CommunityServiceServer) { + // If the following call panics, it indicates UnimplementedCommunityServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&CommunityService_ServiceDesc, srv) +} + +func _CommunityService_AddCommentLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddCommentLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).AddCommentLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_AddCommentLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).AddCommentLikes(ctx, req.(*AddCommentLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_UpdateCommentLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateCommentLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).UpdateCommentLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_UpdateCommentLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).UpdateCommentLikes(ctx, req.(*UpdateCommentLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_DelCommentLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelCommentLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).DelCommentLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_DelCommentLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).DelCommentLikes(ctx, req.(*DelCommentLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_GetCommentLikesById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetCommentLikesByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).GetCommentLikesById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_GetCommentLikesById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).GetCommentLikesById(ctx, req.(*GetCommentLikesByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_SearchCommentLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchCommentLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).SearchCommentLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_SearchCommentLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).SearchCommentLikes(ctx, req.(*SearchCommentLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_AddComments_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddCommentsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).AddComments(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_AddComments_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).AddComments(ctx, req.(*AddCommentsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_UpdateComments_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateCommentsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).UpdateComments(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_UpdateComments_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).UpdateComments(ctx, req.(*UpdateCommentsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_DelComments_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelCommentsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).DelComments(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_DelComments_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).DelComments(ctx, req.(*DelCommentsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_GetCommentsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetCommentsByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).GetCommentsById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_GetCommentsById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).GetCommentsById(ctx, req.(*GetCommentsByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_SearchComments_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchCommentsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).SearchComments(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_SearchComments_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).SearchComments(ctx, req.(*SearchCommentsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_AddPostLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddPostLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).AddPostLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_AddPostLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).AddPostLikes(ctx, req.(*AddPostLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_UpdatePostLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdatePostLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).UpdatePostLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_UpdatePostLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).UpdatePostLikes(ctx, req.(*UpdatePostLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_DelPostLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelPostLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).DelPostLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_DelPostLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).DelPostLikes(ctx, req.(*DelPostLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_GetPostLikesById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetPostLikesByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).GetPostLikesById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_GetPostLikesById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).GetPostLikesById(ctx, req.(*GetPostLikesByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_SearchPostLikes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchPostLikesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).SearchPostLikes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_SearchPostLikes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).SearchPostLikes(ctx, req.(*SearchPostLikesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_AddPosts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddPostsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).AddPosts(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_AddPosts_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).AddPosts(ctx, req.(*AddPostsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_UpdatePosts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdatePostsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).UpdatePosts(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_UpdatePosts_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).UpdatePosts(ctx, req.(*UpdatePostsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_DelPosts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelPostsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).DelPosts(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_DelPosts_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).DelPosts(ctx, req.(*DelPostsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_GetPostsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetPostsByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).GetPostsById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_GetPostsById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).GetPostsById(ctx, req.(*GetPostsByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _CommunityService_SearchPosts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchPostsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CommunityServiceServer).SearchPosts(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: CommunityService_SearchPosts_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CommunityServiceServer).SearchPosts(ctx, req.(*SearchPostsReq)) + } + return interceptor(ctx, in, info, handler) +} + +// CommunityService_ServiceDesc is the grpc.ServiceDesc for CommunityService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var CommunityService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.communityService", + HandlerType: (*CommunityServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "AddCommentLikes", + Handler: _CommunityService_AddCommentLikes_Handler, + }, + { + MethodName: "UpdateCommentLikes", + Handler: _CommunityService_UpdateCommentLikes_Handler, + }, + { + MethodName: "DelCommentLikes", + Handler: _CommunityService_DelCommentLikes_Handler, + }, + { + MethodName: "GetCommentLikesById", + Handler: _CommunityService_GetCommentLikesById_Handler, + }, + { + MethodName: "SearchCommentLikes", + Handler: _CommunityService_SearchCommentLikes_Handler, + }, + { + MethodName: "AddComments", + Handler: _CommunityService_AddComments_Handler, + }, + { + MethodName: "UpdateComments", + Handler: _CommunityService_UpdateComments_Handler, + }, + { + MethodName: "DelComments", + Handler: _CommunityService_DelComments_Handler, + }, + { + MethodName: "GetCommentsById", + Handler: _CommunityService_GetCommentsById_Handler, + }, + { + MethodName: "SearchComments", + Handler: _CommunityService_SearchComments_Handler, + }, + { + MethodName: "AddPostLikes", + Handler: _CommunityService_AddPostLikes_Handler, + }, + { + MethodName: "UpdatePostLikes", + Handler: _CommunityService_UpdatePostLikes_Handler, + }, + { + MethodName: "DelPostLikes", + Handler: _CommunityService_DelPostLikes_Handler, + }, + { + MethodName: "GetPostLikesById", + Handler: _CommunityService_GetPostLikesById_Handler, + }, + { + MethodName: "SearchPostLikes", + Handler: _CommunityService_SearchPostLikes_Handler, + }, + { + MethodName: "AddPosts", + Handler: _CommunityService_AddPosts_Handler, + }, + { + MethodName: "UpdatePosts", + Handler: _CommunityService_UpdatePosts_Handler, + }, + { + MethodName: "DelPosts", + Handler: _CommunityService_DelPosts_Handler, + }, + { + MethodName: "GetPostsById", + Handler: _CommunityService_GetPostsById_Handler, + }, + { + MethodName: "SearchPosts", + Handler: _CommunityService_SearchPosts_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "community.proto", +} diff --git a/app/email/mq/internal/logic/send_verification_code_logic.go b/app/email/mq/internal/logic/send_verification_code_logic.go index 1d8007f..e3f0417 100644 --- a/app/email/mq/internal/logic/send_verification_code_logic.go +++ b/app/email/mq/internal/logic/send_verification_code_logic.go @@ -57,7 +57,7 @@ func (l *SendVerificationCodeMq) Consume(ctx context.Context, key, value string) } subject := "Your verification code" - body := fmt.Sprintf("Your verification code is %s. It is valid for %d seconds. Scene: %s. RequestId: %s", code, expireIn, scene, payload.RequestID) + body := fmt.Sprintf("你的验证码是 %s. 该验证码有效时间 %d 秒. 用途: %s. 单号: %s", code, expireIn, scene, payload.RequestID) // logx.Info("Send email to address: %s, subject: %s", emailAddr, subject) err := l.svcCxt.MailSender.Send(ctx, mailer.Message{ diff --git a/app/game/api/internal/handler/game/getGameHandler.go b/app/game/api/internal/handler/game/getGameHandler.go index cdee532..be1aff6 100644 --- a/app/game/api/internal/handler/game/getGameHandler.go +++ b/app/game/api/internal/handler/game/getGameHandler.go @@ -4,27 +4,29 @@ package game import ( + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/game/api/internal/logic/game" "juwan-backend/app/game/api/internal/svc" "juwan-backend/app/game/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取游戏详情 func GetGameHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.GetGameReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return } l := game.NewGetGameLogic(r.Context(), svcCtx) - resp := l.GetGame(&req) + resp, err := l.GetGame(&req) if err != nil { - httpx.ErrorCtx(r.Context(), w, err) + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(400, err)) } else { httpx.OkJsonCtx(r.Context(), w, resp) } diff --git a/app/game/api/internal/logic/game/getGameLogic.go b/app/game/api/internal/logic/game/getGameLogic.go index a87cacf..12ee472 100644 --- a/app/game/api/internal/logic/game/getGameLogic.go +++ b/app/game/api/internal/logic/game/getGameLogic.go @@ -27,16 +27,16 @@ func NewGetGameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetGameLo } } -func (l *GetGameLogic) GetGame(req *types.GetGameReq) (resp *types.Game) { +func (l *GetGameLogic) GetGame(req *types.GetGameReq) (resp *types.Game, err error) { // todo: add your logic here and delete this line game, err := l.svcCtx.GameRpc.GetGamesById(l.ctx, &pb.GetGamesByIdReq{Id: req.Id}) if err != nil { - return nil + return nil, err } return &types.Game{ Id: game.Games.Id, Name: game.Games.Name, Icon: game.Games.Icon, Category: game.Games.Category, - } + }, nil } diff --git a/app/game/api/internal/logic/game/listGamesLogic.go b/app/game/api/internal/logic/game/listGamesLogic.go index 1791d22..56aff4f 100644 --- a/app/game/api/internal/logic/game/listGamesLogic.go +++ b/app/game/api/internal/logic/game/listGamesLogic.go @@ -5,6 +5,7 @@ package game import ( "context" + "juwan-backend/app/game/rpc/pb" "juwan-backend/app/game/api/internal/svc" "juwan-backend/app/game/api/internal/types" @@ -29,6 +30,30 @@ func NewListGamesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListGam func (l *ListGamesLogic) ListGames(req *types.PageReq) (resp *types.GameListResp, err error) { // todo: add your logic here and delete this line + all, err := l.svcCtx.GameRpc.SearchGames(l.ctx, &pb.SearchGamesReq{ + Page: req.Offset, + Limit: req.Limit, + }) + if err != nil { + return nil, err + } + + list := make([]types.Game, 0, len(all.Games)) + for _, v := range all.Games { + list = append(list, types.Game{ + Id: v.Id, + Name: v.Name, + Icon: v.Icon, + Category: v.Category, + }) + } + return &types.GameListResp{ + Items: list, + Meta: types.PageMeta{ + Total: 0, + Offset: req.Offset + 1, + Limit: 20, + }, + }, nil - return } diff --git a/app/game/api/internal/svc/serviceContext.go b/app/game/api/internal/svc/serviceContext.go index 33e5cbf..b26550c 100644 --- a/app/game/api/internal/svc/serviceContext.go +++ b/app/game/api/internal/svc/serviceContext.go @@ -5,19 +5,19 @@ package svc import ( "juwan-backend/app/game/api/internal/config" - "juwan-backend/app/game/rpc/gamepublic" + "juwan-backend/app/game/rpc/gameservice" "github.com/zeromicro/go-zero/zrpc" ) type ServiceContext struct { Config config.Config - GameRpc gamepublic.GamePublic + GameRpc gameservice.GameService } func NewServiceContext(c config.Config) *ServiceContext { return &ServiceContext{ Config: c, - GameRpc: gamepublic.NewGamePublic(zrpc.MustNewClient(c.GameRpcConf)), + GameRpc: gameservice.NewGameService(zrpc.MustNewClient(c.GameRpcConf)), } } diff --git a/app/game/rpc/etc/pb.yaml b/app/game/rpc/etc/pb.yaml index 4e156f8..1b9b37e 100644 --- a/app/game/rpc/etc/pb.yaml +++ b/app/game/rpc/etc/pb.yaml @@ -1,29 +1,19 @@ Name: pb.rpc ListenOn: 0.0.0.0:8080 - Prometheus: Host: 0.0.0.0 Port: 4001 Path: /metrics -# tcd: -# Hosts: -# - 127.0.0.1:2379 -# Key: pb.rpc - -# Target: k8s://juwan/.:8080 - - -#DB: -# Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@game-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" -# Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@game-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" - DB: Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" - Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" +SnowflakeRpcConf: + Target: k8s://juwan/snowflake-svc:8080 + CacheConf: - Host: "${REDIS_M_HOST}" Type: node diff --git a/app/game/rpc/gamepublic/gamePublic.go b/app/game/rpc/gamepublic/gamePublic.go deleted file mode 100644 index 7a07687..0000000 --- a/app/game/rpc/gamepublic/gamePublic.go +++ /dev/null @@ -1,288 +0,0 @@ -// Code generated by goctl. DO NOT EDIT. -// goctl 1.9.2 -// Source: game.proto - -package gamepublic - -import ( - "context" - - "juwan-backend/app/game/rpc/pb" - - "github.com/zeromicro/go-zero/zrpc" - "google.golang.org/grpc" -) - -type ( - AddGamesReq = pb.AddGamesReq - AddGamesResp = pb.AddGamesResp - AddPlayerServicesReq = pb.AddPlayerServicesReq - AddPlayerServicesResp = pb.AddPlayerServicesResp - AddPlayersReq = pb.AddPlayersReq - AddPlayersResp = pb.AddPlayersResp - AddShopInvitationsReq = pb.AddShopInvitationsReq - AddShopInvitationsResp = pb.AddShopInvitationsResp - AddShopPlayersReq = pb.AddShopPlayersReq - AddShopPlayersResp = pb.AddShopPlayersResp - AddShopsReq = pb.AddShopsReq - AddShopsResp = pb.AddShopsResp - DelGamesReq = pb.DelGamesReq - DelGamesResp = pb.DelGamesResp - DelPlayerServicesReq = pb.DelPlayerServicesReq - DelPlayerServicesResp = pb.DelPlayerServicesResp - DelPlayersReq = pb.DelPlayersReq - DelPlayersResp = pb.DelPlayersResp - DelShopInvitationsReq = pb.DelShopInvitationsReq - DelShopInvitationsResp = pb.DelShopInvitationsResp - DelShopPlayersReq = pb.DelShopPlayersReq - DelShopPlayersResp = pb.DelShopPlayersResp - DelShopsReq = pb.DelShopsReq - DelShopsResp = pb.DelShopsResp - Games = pb.Games - GetGamesByIdReq = pb.GetGamesByIdReq - GetGamesByIdResp = pb.GetGamesByIdResp - GetPlayerServicesByIdReq = pb.GetPlayerServicesByIdReq - GetPlayerServicesByIdResp = pb.GetPlayerServicesByIdResp - GetPlayersByIdReq = pb.GetPlayersByIdReq - GetPlayersByIdResp = pb.GetPlayersByIdResp - GetShopInvitationsByIdReq = pb.GetShopInvitationsByIdReq - GetShopInvitationsByIdResp = pb.GetShopInvitationsByIdResp - GetShopPlayersByIdReq = pb.GetShopPlayersByIdReq - GetShopPlayersByIdResp = pb.GetShopPlayersByIdResp - GetShopsByIdReq = pb.GetShopsByIdReq - GetShopsByIdResp = pb.GetShopsByIdResp - PlayerServices = pb.PlayerServices - Players = pb.Players - SearchGamesReq = pb.SearchGamesReq - SearchGamesResp = pb.SearchGamesResp - SearchPlayerServicesReq = pb.SearchPlayerServicesReq - SearchPlayerServicesResp = pb.SearchPlayerServicesResp - SearchPlayersReq = pb.SearchPlayersReq - SearchPlayersResp = pb.SearchPlayersResp - SearchShopInvitationsReq = pb.SearchShopInvitationsReq - SearchShopInvitationsResp = pb.SearchShopInvitationsResp - SearchShopPlayersReq = pb.SearchShopPlayersReq - SearchShopPlayersResp = pb.SearchShopPlayersResp - SearchShopsReq = pb.SearchShopsReq - SearchShopsResp = pb.SearchShopsResp - ShopInvitations = pb.ShopInvitations - ShopPlayers = pb.ShopPlayers - Shops = pb.Shops - UpdateGamesReq = pb.UpdateGamesReq - UpdateGamesResp = pb.UpdateGamesResp - UpdatePlayerServicesReq = pb.UpdatePlayerServicesReq - UpdatePlayerServicesResp = pb.UpdatePlayerServicesResp - UpdatePlayersReq = pb.UpdatePlayersReq - UpdatePlayersResp = pb.UpdatePlayersResp - UpdateShopInvitationsReq = pb.UpdateShopInvitationsReq - UpdateShopInvitationsResp = pb.UpdateShopInvitationsResp - UpdateShopPlayersReq = pb.UpdateShopPlayersReq - UpdateShopPlayersResp = pb.UpdateShopPlayersResp - UpdateShopsReq = pb.UpdateShopsReq - UpdateShopsResp = pb.UpdateShopsResp - - GamePublic interface { - // -----------------------games----------------------- - AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) - UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) - DelGames(ctx context.Context, in *DelGamesReq, opts ...grpc.CallOption) (*DelGamesResp, error) - GetGamesById(ctx context.Context, in *GetGamesByIdReq, opts ...grpc.CallOption) (*GetGamesByIdResp, error) - SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) - // -----------------------playerServices----------------------- - AddPlayerServices(ctx context.Context, in *AddPlayerServicesReq, opts ...grpc.CallOption) (*AddPlayerServicesResp, error) - UpdatePlayerServices(ctx context.Context, in *UpdatePlayerServicesReq, opts ...grpc.CallOption) (*UpdatePlayerServicesResp, error) - DelPlayerServices(ctx context.Context, in *DelPlayerServicesReq, opts ...grpc.CallOption) (*DelPlayerServicesResp, error) - GetPlayerServicesById(ctx context.Context, in *GetPlayerServicesByIdReq, opts ...grpc.CallOption) (*GetPlayerServicesByIdResp, error) - SearchPlayerServices(ctx context.Context, in *SearchPlayerServicesReq, opts ...grpc.CallOption) (*SearchPlayerServicesResp, error) - // -----------------------players----------------------- - AddPlayers(ctx context.Context, in *AddPlayersReq, opts ...grpc.CallOption) (*AddPlayersResp, error) - UpdatePlayers(ctx context.Context, in *UpdatePlayersReq, opts ...grpc.CallOption) (*UpdatePlayersResp, error) - DelPlayers(ctx context.Context, in *DelPlayersReq, opts ...grpc.CallOption) (*DelPlayersResp, error) - GetPlayersById(ctx context.Context, in *GetPlayersByIdReq, opts ...grpc.CallOption) (*GetPlayersByIdResp, error) - SearchPlayers(ctx context.Context, in *SearchPlayersReq, opts ...grpc.CallOption) (*SearchPlayersResp, error) - // -----------------------shopInvitations----------------------- - AddShopInvitations(ctx context.Context, in *AddShopInvitationsReq, opts ...grpc.CallOption) (*AddShopInvitationsResp, error) - UpdateShopInvitations(ctx context.Context, in *UpdateShopInvitationsReq, opts ...grpc.CallOption) (*UpdateShopInvitationsResp, error) - DelShopInvitations(ctx context.Context, in *DelShopInvitationsReq, opts ...grpc.CallOption) (*DelShopInvitationsResp, error) - GetShopInvitationsById(ctx context.Context, in *GetShopInvitationsByIdReq, opts ...grpc.CallOption) (*GetShopInvitationsByIdResp, error) - SearchShopInvitations(ctx context.Context, in *SearchShopInvitationsReq, opts ...grpc.CallOption) (*SearchShopInvitationsResp, error) - // -----------------------shopPlayers----------------------- - AddShopPlayers(ctx context.Context, in *AddShopPlayersReq, opts ...grpc.CallOption) (*AddShopPlayersResp, error) - UpdateShopPlayers(ctx context.Context, in *UpdateShopPlayersReq, opts ...grpc.CallOption) (*UpdateShopPlayersResp, error) - DelShopPlayers(ctx context.Context, in *DelShopPlayersReq, opts ...grpc.CallOption) (*DelShopPlayersResp, error) - GetShopPlayersById(ctx context.Context, in *GetShopPlayersByIdReq, opts ...grpc.CallOption) (*GetShopPlayersByIdResp, error) - SearchShopPlayers(ctx context.Context, in *SearchShopPlayersReq, opts ...grpc.CallOption) (*SearchShopPlayersResp, error) - // -----------------------shops----------------------- - AddShops(ctx context.Context, in *AddShopsReq, opts ...grpc.CallOption) (*AddShopsResp, error) - UpdateShops(ctx context.Context, in *UpdateShopsReq, opts ...grpc.CallOption) (*UpdateShopsResp, error) - DelShops(ctx context.Context, in *DelShopsReq, opts ...grpc.CallOption) (*DelShopsResp, error) - GetShopsById(ctx context.Context, in *GetShopsByIdReq, opts ...grpc.CallOption) (*GetShopsByIdResp, error) - SearchShops(ctx context.Context, in *SearchShopsReq, opts ...grpc.CallOption) (*SearchShopsResp, error) - } - - defaultGamePublic struct { - cli zrpc.Client - } -) - -func NewGamePublic(cli zrpc.Client) GamePublic { - return &defaultGamePublic{ - cli: cli, - } -} - -// -----------------------games----------------------- -func (m *defaultGamePublic) AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.AddGames(ctx, in, opts...) -} - -func (m *defaultGamePublic) UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.UpdateGames(ctx, in, opts...) -} - -func (m *defaultGamePublic) DelGames(ctx context.Context, in *DelGamesReq, opts ...grpc.CallOption) (*DelGamesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.DelGames(ctx, in, opts...) -} - -func (m *defaultGamePublic) GetGamesById(ctx context.Context, in *GetGamesByIdReq, opts ...grpc.CallOption) (*GetGamesByIdResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.GetGamesById(ctx, in, opts...) -} - -func (m *defaultGamePublic) SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.SearchGames(ctx, in, opts...) -} - -// -----------------------playerServices----------------------- -func (m *defaultGamePublic) AddPlayerServices(ctx context.Context, in *AddPlayerServicesReq, opts ...grpc.CallOption) (*AddPlayerServicesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.AddPlayerServices(ctx, in, opts...) -} - -func (m *defaultGamePublic) UpdatePlayerServices(ctx context.Context, in *UpdatePlayerServicesReq, opts ...grpc.CallOption) (*UpdatePlayerServicesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.UpdatePlayerServices(ctx, in, opts...) -} - -func (m *defaultGamePublic) DelPlayerServices(ctx context.Context, in *DelPlayerServicesReq, opts ...grpc.CallOption) (*DelPlayerServicesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.DelPlayerServices(ctx, in, opts...) -} - -func (m *defaultGamePublic) GetPlayerServicesById(ctx context.Context, in *GetPlayerServicesByIdReq, opts ...grpc.CallOption) (*GetPlayerServicesByIdResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.GetPlayerServicesById(ctx, in, opts...) -} - -func (m *defaultGamePublic) SearchPlayerServices(ctx context.Context, in *SearchPlayerServicesReq, opts ...grpc.CallOption) (*SearchPlayerServicesResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.SearchPlayerServices(ctx, in, opts...) -} - -// -----------------------players----------------------- -func (m *defaultGamePublic) AddPlayers(ctx context.Context, in *AddPlayersReq, opts ...grpc.CallOption) (*AddPlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.AddPlayers(ctx, in, opts...) -} - -func (m *defaultGamePublic) UpdatePlayers(ctx context.Context, in *UpdatePlayersReq, opts ...grpc.CallOption) (*UpdatePlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.UpdatePlayers(ctx, in, opts...) -} - -func (m *defaultGamePublic) DelPlayers(ctx context.Context, in *DelPlayersReq, opts ...grpc.CallOption) (*DelPlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.DelPlayers(ctx, in, opts...) -} - -func (m *defaultGamePublic) GetPlayersById(ctx context.Context, in *GetPlayersByIdReq, opts ...grpc.CallOption) (*GetPlayersByIdResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.GetPlayersById(ctx, in, opts...) -} - -func (m *defaultGamePublic) SearchPlayers(ctx context.Context, in *SearchPlayersReq, opts ...grpc.CallOption) (*SearchPlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.SearchPlayers(ctx, in, opts...) -} - -// -----------------------shopInvitations----------------------- -func (m *defaultGamePublic) AddShopInvitations(ctx context.Context, in *AddShopInvitationsReq, opts ...grpc.CallOption) (*AddShopInvitationsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.AddShopInvitations(ctx, in, opts...) -} - -func (m *defaultGamePublic) UpdateShopInvitations(ctx context.Context, in *UpdateShopInvitationsReq, opts ...grpc.CallOption) (*UpdateShopInvitationsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.UpdateShopInvitations(ctx, in, opts...) -} - -func (m *defaultGamePublic) DelShopInvitations(ctx context.Context, in *DelShopInvitationsReq, opts ...grpc.CallOption) (*DelShopInvitationsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.DelShopInvitations(ctx, in, opts...) -} - -func (m *defaultGamePublic) GetShopInvitationsById(ctx context.Context, in *GetShopInvitationsByIdReq, opts ...grpc.CallOption) (*GetShopInvitationsByIdResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.GetShopInvitationsById(ctx, in, opts...) -} - -func (m *defaultGamePublic) SearchShopInvitations(ctx context.Context, in *SearchShopInvitationsReq, opts ...grpc.CallOption) (*SearchShopInvitationsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.SearchShopInvitations(ctx, in, opts...) -} - -// -----------------------shopPlayers----------------------- -func (m *defaultGamePublic) AddShopPlayers(ctx context.Context, in *AddShopPlayersReq, opts ...grpc.CallOption) (*AddShopPlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.AddShopPlayers(ctx, in, opts...) -} - -func (m *defaultGamePublic) UpdateShopPlayers(ctx context.Context, in *UpdateShopPlayersReq, opts ...grpc.CallOption) (*UpdateShopPlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.UpdateShopPlayers(ctx, in, opts...) -} - -func (m *defaultGamePublic) DelShopPlayers(ctx context.Context, in *DelShopPlayersReq, opts ...grpc.CallOption) (*DelShopPlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.DelShopPlayers(ctx, in, opts...) -} - -func (m *defaultGamePublic) GetShopPlayersById(ctx context.Context, in *GetShopPlayersByIdReq, opts ...grpc.CallOption) (*GetShopPlayersByIdResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.GetShopPlayersById(ctx, in, opts...) -} - -func (m *defaultGamePublic) SearchShopPlayers(ctx context.Context, in *SearchShopPlayersReq, opts ...grpc.CallOption) (*SearchShopPlayersResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.SearchShopPlayers(ctx, in, opts...) -} - -// -----------------------shops----------------------- -func (m *defaultGamePublic) AddShops(ctx context.Context, in *AddShopsReq, opts ...grpc.CallOption) (*AddShopsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.AddShops(ctx, in, opts...) -} - -func (m *defaultGamePublic) UpdateShops(ctx context.Context, in *UpdateShopsReq, opts ...grpc.CallOption) (*UpdateShopsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.UpdateShops(ctx, in, opts...) -} - -func (m *defaultGamePublic) DelShops(ctx context.Context, in *DelShopsReq, opts ...grpc.CallOption) (*DelShopsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.DelShops(ctx, in, opts...) -} - -func (m *defaultGamePublic) GetShopsById(ctx context.Context, in *GetShopsByIdReq, opts ...grpc.CallOption) (*GetShopsByIdResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.GetShopsById(ctx, in, opts...) -} - -func (m *defaultGamePublic) SearchShops(ctx context.Context, in *SearchShopsReq, opts ...grpc.CallOption) (*SearchShopsResp, error) { - client := pb.NewGamePublicClient(m.cli.Conn()) - return client.SearchShops(ctx, in, opts...) -} diff --git a/app/game/rpc/public/public.go b/app/game/rpc/gameservice/gameService.go similarity index 58% rename from app/game/rpc/public/public.go rename to app/game/rpc/gameservice/gameService.go index 56c730f..15b344a 100644 --- a/app/game/rpc/public/public.go +++ b/app/game/rpc/gameservice/gameService.go @@ -2,7 +2,7 @@ // goctl 1.9.2 // Source: game.proto -package public +package gameservice import ( "context" @@ -26,7 +26,7 @@ type ( UpdateGamesReq = pb.UpdateGamesReq UpdateGamesResp = pb.UpdateGamesResp - Public interface { + GameService interface { // -----------------------games----------------------- AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) @@ -35,39 +35,39 @@ type ( SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) } - defaultPublic struct { + defaultGameService struct { cli zrpc.Client } ) -func NewPublic(cli zrpc.Client) Public { - return &defaultPublic{ +func NewGameService(cli zrpc.Client) GameService { + return &defaultGameService{ cli: cli, } } // -----------------------games----------------------- -func (m *defaultPublic) AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) { - client := pb.NewPublicClient(m.cli.Conn()) +func (m *defaultGameService) AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) { + client := pb.NewGameServiceClient(m.cli.Conn()) return client.AddGames(ctx, in, opts...) } -func (m *defaultPublic) UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) { - client := pb.NewPublicClient(m.cli.Conn()) +func (m *defaultGameService) UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) { + client := pb.NewGameServiceClient(m.cli.Conn()) return client.UpdateGames(ctx, in, opts...) } -func (m *defaultPublic) DelGames(ctx context.Context, in *DelGamesReq, opts ...grpc.CallOption) (*DelGamesResp, error) { - client := pb.NewPublicClient(m.cli.Conn()) +func (m *defaultGameService) DelGames(ctx context.Context, in *DelGamesReq, opts ...grpc.CallOption) (*DelGamesResp, error) { + client := pb.NewGameServiceClient(m.cli.Conn()) return client.DelGames(ctx, in, opts...) } -func (m *defaultPublic) GetGamesById(ctx context.Context, in *GetGamesByIdReq, opts ...grpc.CallOption) (*GetGamesByIdResp, error) { - client := pb.NewPublicClient(m.cli.Conn()) +func (m *defaultGameService) GetGamesById(ctx context.Context, in *GetGamesByIdReq, opts ...grpc.CallOption) (*GetGamesByIdResp, error) { + client := pb.NewGameServiceClient(m.cli.Conn()) return client.GetGamesById(ctx, in, opts...) } -func (m *defaultPublic) SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) { - client := pb.NewPublicClient(m.cli.Conn()) +func (m *defaultGameService) SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) { + client := pb.NewGameServiceClient(m.cli.Conn()) return client.SearchGames(ctx, in, opts...) } diff --git a/app/game/rpc/internal/logic/searchGamesLogic.go b/app/game/rpc/internal/logic/searchGamesLogic.go index 36b5698..09320c2 100644 --- a/app/game/rpc/internal/logic/searchGamesLogic.go +++ b/app/game/rpc/internal/logic/searchGamesLogic.go @@ -3,9 +3,6 @@ package logic import ( "context" "errors" - "juwan-backend/app/game/rpc/internal/models/games" - "juwan-backend/app/game/rpc/internal/models/predicate" - "juwan-backend/app/game/rpc/internal/svc" "juwan-backend/app/game/rpc/pb" @@ -28,79 +25,26 @@ func NewSearchGamesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Searc } func (l *SearchGamesLogic) SearchGames(in *pb.SearchGamesReq) (*pb.SearchGamesResp, error) { - if in.Limit > 1000 { - return nil, errors.New("limit too large") + if in.Page <= 0 || in.Limit <= 0 || in.Page > 1000 || in.Limit > 100 { + return nil, errors.New("invalid pagination parameters") } - - preds := make([]predicate.Games, 0, 8) - if in.IdOpt != nil { - preds = append(preds, games.IDEQ(*in.IdOpt)) - } else if in.Id != 0 { - preds = append(preds, games.IDEQ(in.Id)) - } - if in.NameOpt != nil { - if *in.NameOpt != "" { - preds = append(preds, games.NameContainsFold(*in.NameOpt)) - } - } else if in.Name != "" { - preds = append(preds, games.NameContainsFold(in.Name)) - } - if in.IconOpt != nil { - if *in.IconOpt != "" { - preds = append(preds, games.IconContainsFold(*in.IconOpt)) - } - } else if in.Icon != "" { - preds = append(preds, games.IconContainsFold(in.Icon)) - } - if in.CategoryOpt != nil { - if *in.CategoryOpt != "" { - preds = append(preds, games.CategoryContainsFold(*in.CategoryOpt)) - } - } else if in.Category != "" { - preds = append(preds, games.CategoryContainsFold(in.Category)) - } - if in.SortOrderOpt != nil { - preds = append(preds, games.SortOrderEQ(int(*in.SortOrderOpt))) - } else if in.SortOrder != 0 { - preds = append(preds, games.SortOrderEQ(int(in.SortOrder))) - } - if in.IsActiveOpt != nil { - preds = append(preds, games.IsActiveEQ(*in.IsActiveOpt)) - } else if in.IsActive { - preds = append(preds, games.IsActiveEQ(true)) - } - - query := l.svcCtx.GameModelRO.Games.Query() - if len(preds) > 0 { - if in.MatchMode == pb.MatchMode_MATCH_MODE_AND { - query = query.Where(games.And(preds...)) - } else { - query = query.Where(games.Or(preds...)) - } - } - - all, err := query. - Offset(int(in.Page * in.Limit)). - Limit(int(in.Limit)). - All(l.ctx) + all, err := l.svcCtx.GameModelRO.Games.Query().Limit(int(in.Limit)).Offset(int(in.Limit * (in.Page - 1))).All(l.ctx) if err != nil { - logx.Errorf("search games failed, %s", err.Error()) - return nil, errors.New("search games failed") + logx.Errorf("failed to query games: %v", err) + return nil, errors.New("failed to query games") } - list := make([]*pb.Games, 0, len(all)) for _, v := range all { temp := &pb.Games{} - err = copier.Copy(temp, &v) + err := copier.Copy(temp, v) if err != nil { - logx.Errorf("search games failed, %s", err.Error()) - continue + logx.Errorf("failed to copy games: %v", err) + return nil, errors.New("failed to copy games") } temp.CreatedAt = v.CreatedAt.Unix() temp.UpdatedAt = v.UpdatedAt.Unix() list = append(list, temp) } - return &pb.SearchGamesResp{ Games: list, }, nil diff --git a/app/game/rpc/internal/logic/updateGamesLogic.go b/app/game/rpc/internal/logic/updateGamesLogic.go index e7a5dd6..ca5cceb 100644 --- a/app/game/rpc/internal/logic/updateGamesLogic.go +++ b/app/game/rpc/internal/logic/updateGamesLogic.go @@ -2,9 +2,6 @@ package logic import ( "context" - "errors" - "time" - "juwan-backend/app/game/rpc/internal/svc" "juwan-backend/app/game/rpc/pb" @@ -26,60 +23,6 @@ func NewUpdateGamesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Updat } func (l *UpdateGamesLogic) UpdateGames(in *pb.UpdateGamesReq) (*pb.UpdateGamesResp, error) { - update := l.svcCtx.GameModelRW.Games.UpdateOneID(in.Id) - updated := false - - if in.NameOpt != nil { - update.SetNillableName(in.NameOpt) - updated = true - } else if in.Name != "" { - update.SetName(in.Name) - updated = true - } - - if in.IconOpt != nil { - update.SetNillableIcon(in.IconOpt) - updated = true - } else if in.Icon != "" { - update.SetIcon(in.Icon) - updated = true - } - - if in.CategoryOpt != nil { - update.SetNillableCategory(in.CategoryOpt) - updated = true - } else if in.Category != "" { - update.SetCategory(in.Category) - updated = true - } - - if in.SortOrderOpt != nil { - sortOrder := int(*in.SortOrderOpt) - update.SetNillableSortOrder(&sortOrder) - updated = true - } else if in.SortOrder != 0 { - sortOrder := int(in.SortOrder) - update.SetSortOrder(sortOrder) - updated = true - } - - if in.IsActiveOpt != nil { - update.SetNillableIsActive(in.IsActiveOpt) - updated = true - } else if in.IsActive { - update.SetIsActive(true) - updated = true - } - - if !updated { - return nil, errors.New("no fields to update") - } - - update.SetUpdatedAt(time.Now()) - if err := update.Exec(l.ctx); err != nil { - logx.WithContext(l.ctx).Errorf("UpdateGamesLogic err: %v", err) - return nil, errors.New("update games failed") - } return &pb.UpdateGamesResp{}, nil } diff --git a/app/game/rpc/internal/models/client.go b/app/game/rpc/internal/models/client.go new file mode 100644 index 0000000..f4a918d --- /dev/null +++ b/app/game/rpc/internal/models/client.go @@ -0,0 +1,341 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "juwan-backend/app/game/rpc/internal/models/migrate" + + "juwan-backend/app/game/rpc/internal/models/games" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Games is the client for interacting with the Games builders. + Games *GamesClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Games = NewGamesClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("models: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Games: NewGamesClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Games: NewGamesClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Games. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Games.Use(hooks...) +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.Games.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *GamesMutation: + return c.Games.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// GamesClient is a client for the Games schema. +type GamesClient struct { + config +} + +// NewGamesClient returns a client for the Games from the given config. +func NewGamesClient(c config) *GamesClient { + return &GamesClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `games.Hooks(f(g(h())))`. +func (c *GamesClient) Use(hooks ...Hook) { + c.hooks.Games = append(c.hooks.Games, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `games.Intercept(f(g(h())))`. +func (c *GamesClient) Intercept(interceptors ...Interceptor) { + c.inters.Games = append(c.inters.Games, interceptors...) +} + +// Create returns a builder for creating a Games entity. +func (c *GamesClient) Create() *GamesCreate { + mutation := newGamesMutation(c.config, OpCreate) + return &GamesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Games entities. +func (c *GamesClient) CreateBulk(builders ...*GamesCreate) *GamesCreateBulk { + return &GamesCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *GamesClient) MapCreateBulk(slice any, setFunc func(*GamesCreate, int)) *GamesCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &GamesCreateBulk{err: fmt.Errorf("calling to GamesClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*GamesCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &GamesCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Games. +func (c *GamesClient) Update() *GamesUpdate { + mutation := newGamesMutation(c.config, OpUpdate) + return &GamesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *GamesClient) UpdateOne(_m *Games) *GamesUpdateOne { + mutation := newGamesMutation(c.config, OpUpdateOne, withGames(_m)) + return &GamesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *GamesClient) UpdateOneID(id int64) *GamesUpdateOne { + mutation := newGamesMutation(c.config, OpUpdateOne, withGamesID(id)) + return &GamesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Games. +func (c *GamesClient) Delete() *GamesDelete { + mutation := newGamesMutation(c.config, OpDelete) + return &GamesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *GamesClient) DeleteOne(_m *Games) *GamesDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *GamesClient) DeleteOneID(id int64) *GamesDeleteOne { + builder := c.Delete().Where(games.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &GamesDeleteOne{builder} +} + +// Query returns a query builder for Games. +func (c *GamesClient) Query() *GamesQuery { + return &GamesQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGames}, + inters: c.Interceptors(), + } +} + +// Get returns a Games entity by its id. +func (c *GamesClient) Get(ctx context.Context, id int64) (*Games, error) { + return c.Query().Where(games.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *GamesClient) GetX(ctx context.Context, id int64) *Games { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *GamesClient) Hooks() []Hook { + return c.hooks.Games +} + +// Interceptors returns the client interceptors. +func (c *GamesClient) Interceptors() []Interceptor { + return c.inters.Games +} + +func (c *GamesClient) mutate(ctx context.Context, m *GamesMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GamesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GamesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GamesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GamesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Games mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Games []ent.Hook + } + inters struct { + Games []ent.Interceptor + } +) diff --git a/app/game/rpc/internal/models/ent.go b/app/game/rpc/internal/models/ent.go new file mode 100644 index 0000000..60ec06b --- /dev/null +++ b/app/game/rpc/internal/models/ent.go @@ -0,0 +1,608 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/game/rpc/internal/models/games" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(t, c string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + games.Table: games.ValidColumn, + }) + }) + return columnCheck(t, c) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "models: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "models: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "models: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "models: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/app/game/rpc/internal/models/enttest/enttest.go b/app/game/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..108cde6 --- /dev/null +++ b/app/game/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/game/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/game/rpc/internal/models/runtime" + + "juwan-backend/app/game/rpc/internal/models/migrate" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []models.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...models.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls models.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client { + o := newOptions(opts) + c, err := models.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls models.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *models.Client { + o := newOptions(opts) + c := models.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *models.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/app/game/rpc/internal/models/games.go b/app/game/rpc/internal/models/games.go new file mode 100644 index 0000000..15df66c --- /dev/null +++ b/app/game/rpc/internal/models/games.go @@ -0,0 +1,174 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/game/rpc/internal/models/games" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Games is the model entity for the Games schema. +type Games struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Icon holds the value of the "icon" field. + Icon string `json:"icon,omitempty"` + // Category holds the value of the "category" field. + Category string `json:"category,omitempty"` + // SortOrder holds the value of the "sort_order" field. + SortOrder int `json:"sort_order,omitempty"` + // IsActive holds the value of the "is_active" field. + IsActive bool `json:"is_active,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Games) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case games.FieldIsActive: + values[i] = new(sql.NullBool) + case games.FieldID, games.FieldSortOrder: + values[i] = new(sql.NullInt64) + case games.FieldName, games.FieldIcon, games.FieldCategory: + values[i] = new(sql.NullString) + case games.FieldCreatedAt, games.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Games fields. +func (_m *Games) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case games.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case games.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case games.FieldIcon: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field icon", values[i]) + } else if value.Valid { + _m.Icon = value.String + } + case games.FieldCategory: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field category", values[i]) + } else if value.Valid { + _m.Category = value.String + } + case games.FieldSortOrder: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field sort_order", values[i]) + } else if value.Valid { + _m.SortOrder = int(value.Int64) + } + case games.FieldIsActive: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_active", values[i]) + } else if value.Valid { + _m.IsActive = value.Bool + } + case games.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case games.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Games. +// This includes values selected through modifiers, order, etc. +func (_m *Games) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Games. +// Note that you need to call Games.Unwrap() before calling this method if this Games +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Games) Update() *GamesUpdateOne { + return NewGamesClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Games entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Games) Unwrap() *Games { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Games is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Games) String() string { + var builder strings.Builder + builder.WriteString("Games(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("icon=") + builder.WriteString(_m.Icon) + builder.WriteString(", ") + builder.WriteString("category=") + builder.WriteString(_m.Category) + builder.WriteString(", ") + builder.WriteString("sort_order=") + builder.WriteString(fmt.Sprintf("%v", _m.SortOrder)) + builder.WriteString(", ") + builder.WriteString("is_active=") + builder.WriteString(fmt.Sprintf("%v", _m.IsActive)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// GamesSlice is a parsable slice of Games. +type GamesSlice []*Games diff --git a/app/game/rpc/internal/models/games/games.go b/app/game/rpc/internal/models/games/games.go new file mode 100644 index 0000000..da8596e --- /dev/null +++ b/app/game/rpc/internal/models/games/games.go @@ -0,0 +1,114 @@ +// Code generated by ent, DO NOT EDIT. + +package games + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the games type in the database. + Label = "games" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldIcon holds the string denoting the icon field in the database. + FieldIcon = "icon" + // FieldCategory holds the string denoting the category field in the database. + FieldCategory = "category" + // FieldSortOrder holds the string denoting the sort_order field in the database. + FieldSortOrder = "sort_order" + // FieldIsActive holds the string denoting the is_active field in the database. + FieldIsActive = "is_active" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // Table holds the table name of the games in the database. + Table = "games" +) + +// Columns holds all SQL columns for games fields. +var Columns = []string{ + FieldID, + FieldName, + FieldIcon, + FieldCategory, + FieldSortOrder, + FieldIsActive, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // CategoryValidator is a validator for the "category" field. It is called by the builders before save. + CategoryValidator func(string) error + // DefaultSortOrder holds the default value on creation for the "sort_order" field. + DefaultSortOrder int + // DefaultIsActive holds the default value on creation for the "is_active" field. + DefaultIsActive bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Games queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByIcon orders the results by the icon field. +func ByIcon(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIcon, opts...).ToFunc() +} + +// ByCategory orders the results by the category field. +func ByCategory(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCategory, opts...).ToFunc() +} + +// BySortOrder orders the results by the sort_order field. +func BySortOrder(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSortOrder, opts...).ToFunc() +} + +// ByIsActive orders the results by the is_active field. +func ByIsActive(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsActive, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} diff --git a/app/game/rpc/internal/models/games/where.go b/app/game/rpc/internal/models/games/where.go new file mode 100644 index 0000000..446f39e --- /dev/null +++ b/app/game/rpc/internal/models/games/where.go @@ -0,0 +1,440 @@ +// Code generated by ent, DO NOT EDIT. + +package games + +import ( + "juwan-backend/app/game/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Games { + return predicate.Games(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Games { + return predicate.Games(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Games { + return predicate.Games(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Games { + return predicate.Games(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Games { + return predicate.Games(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Games { + return predicate.Games(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldName, v)) +} + +// Icon applies equality check predicate on the "icon" field. It's identical to IconEQ. +func Icon(v string) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldIcon, v)) +} + +// Category applies equality check predicate on the "category" field. It's identical to CategoryEQ. +func Category(v string) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldCategory, v)) +} + +// SortOrder applies equality check predicate on the "sort_order" field. It's identical to SortOrderEQ. +func SortOrder(v int) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldSortOrder, v)) +} + +// IsActive applies equality check predicate on the "is_active" field. It's identical to IsActiveEQ. +func IsActive(v bool) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldIsActive, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Games { + return predicate.Games(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Games { + return predicate.Games(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Games { + return predicate.Games(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Games { + return predicate.Games(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Games { + return predicate.Games(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Games { + return predicate.Games(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Games { + return predicate.Games(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Games { + return predicate.Games(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Games { + return predicate.Games(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Games { + return predicate.Games(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Games { + return predicate.Games(sql.FieldContainsFold(FieldName, v)) +} + +// IconEQ applies the EQ predicate on the "icon" field. +func IconEQ(v string) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldIcon, v)) +} + +// IconNEQ applies the NEQ predicate on the "icon" field. +func IconNEQ(v string) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldIcon, v)) +} + +// IconIn applies the In predicate on the "icon" field. +func IconIn(vs ...string) predicate.Games { + return predicate.Games(sql.FieldIn(FieldIcon, vs...)) +} + +// IconNotIn applies the NotIn predicate on the "icon" field. +func IconNotIn(vs ...string) predicate.Games { + return predicate.Games(sql.FieldNotIn(FieldIcon, vs...)) +} + +// IconGT applies the GT predicate on the "icon" field. +func IconGT(v string) predicate.Games { + return predicate.Games(sql.FieldGT(FieldIcon, v)) +} + +// IconGTE applies the GTE predicate on the "icon" field. +func IconGTE(v string) predicate.Games { + return predicate.Games(sql.FieldGTE(FieldIcon, v)) +} + +// IconLT applies the LT predicate on the "icon" field. +func IconLT(v string) predicate.Games { + return predicate.Games(sql.FieldLT(FieldIcon, v)) +} + +// IconLTE applies the LTE predicate on the "icon" field. +func IconLTE(v string) predicate.Games { + return predicate.Games(sql.FieldLTE(FieldIcon, v)) +} + +// IconContains applies the Contains predicate on the "icon" field. +func IconContains(v string) predicate.Games { + return predicate.Games(sql.FieldContains(FieldIcon, v)) +} + +// IconHasPrefix applies the HasPrefix predicate on the "icon" field. +func IconHasPrefix(v string) predicate.Games { + return predicate.Games(sql.FieldHasPrefix(FieldIcon, v)) +} + +// IconHasSuffix applies the HasSuffix predicate on the "icon" field. +func IconHasSuffix(v string) predicate.Games { + return predicate.Games(sql.FieldHasSuffix(FieldIcon, v)) +} + +// IconEqualFold applies the EqualFold predicate on the "icon" field. +func IconEqualFold(v string) predicate.Games { + return predicate.Games(sql.FieldEqualFold(FieldIcon, v)) +} + +// IconContainsFold applies the ContainsFold predicate on the "icon" field. +func IconContainsFold(v string) predicate.Games { + return predicate.Games(sql.FieldContainsFold(FieldIcon, v)) +} + +// CategoryEQ applies the EQ predicate on the "category" field. +func CategoryEQ(v string) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldCategory, v)) +} + +// CategoryNEQ applies the NEQ predicate on the "category" field. +func CategoryNEQ(v string) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldCategory, v)) +} + +// CategoryIn applies the In predicate on the "category" field. +func CategoryIn(vs ...string) predicate.Games { + return predicate.Games(sql.FieldIn(FieldCategory, vs...)) +} + +// CategoryNotIn applies the NotIn predicate on the "category" field. +func CategoryNotIn(vs ...string) predicate.Games { + return predicate.Games(sql.FieldNotIn(FieldCategory, vs...)) +} + +// CategoryGT applies the GT predicate on the "category" field. +func CategoryGT(v string) predicate.Games { + return predicate.Games(sql.FieldGT(FieldCategory, v)) +} + +// CategoryGTE applies the GTE predicate on the "category" field. +func CategoryGTE(v string) predicate.Games { + return predicate.Games(sql.FieldGTE(FieldCategory, v)) +} + +// CategoryLT applies the LT predicate on the "category" field. +func CategoryLT(v string) predicate.Games { + return predicate.Games(sql.FieldLT(FieldCategory, v)) +} + +// CategoryLTE applies the LTE predicate on the "category" field. +func CategoryLTE(v string) predicate.Games { + return predicate.Games(sql.FieldLTE(FieldCategory, v)) +} + +// CategoryContains applies the Contains predicate on the "category" field. +func CategoryContains(v string) predicate.Games { + return predicate.Games(sql.FieldContains(FieldCategory, v)) +} + +// CategoryHasPrefix applies the HasPrefix predicate on the "category" field. +func CategoryHasPrefix(v string) predicate.Games { + return predicate.Games(sql.FieldHasPrefix(FieldCategory, v)) +} + +// CategoryHasSuffix applies the HasSuffix predicate on the "category" field. +func CategoryHasSuffix(v string) predicate.Games { + return predicate.Games(sql.FieldHasSuffix(FieldCategory, v)) +} + +// CategoryEqualFold applies the EqualFold predicate on the "category" field. +func CategoryEqualFold(v string) predicate.Games { + return predicate.Games(sql.FieldEqualFold(FieldCategory, v)) +} + +// CategoryContainsFold applies the ContainsFold predicate on the "category" field. +func CategoryContainsFold(v string) predicate.Games { + return predicate.Games(sql.FieldContainsFold(FieldCategory, v)) +} + +// SortOrderEQ applies the EQ predicate on the "sort_order" field. +func SortOrderEQ(v int) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldSortOrder, v)) +} + +// SortOrderNEQ applies the NEQ predicate on the "sort_order" field. +func SortOrderNEQ(v int) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldSortOrder, v)) +} + +// SortOrderIn applies the In predicate on the "sort_order" field. +func SortOrderIn(vs ...int) predicate.Games { + return predicate.Games(sql.FieldIn(FieldSortOrder, vs...)) +} + +// SortOrderNotIn applies the NotIn predicate on the "sort_order" field. +func SortOrderNotIn(vs ...int) predicate.Games { + return predicate.Games(sql.FieldNotIn(FieldSortOrder, vs...)) +} + +// SortOrderGT applies the GT predicate on the "sort_order" field. +func SortOrderGT(v int) predicate.Games { + return predicate.Games(sql.FieldGT(FieldSortOrder, v)) +} + +// SortOrderGTE applies the GTE predicate on the "sort_order" field. +func SortOrderGTE(v int) predicate.Games { + return predicate.Games(sql.FieldGTE(FieldSortOrder, v)) +} + +// SortOrderLT applies the LT predicate on the "sort_order" field. +func SortOrderLT(v int) predicate.Games { + return predicate.Games(sql.FieldLT(FieldSortOrder, v)) +} + +// SortOrderLTE applies the LTE predicate on the "sort_order" field. +func SortOrderLTE(v int) predicate.Games { + return predicate.Games(sql.FieldLTE(FieldSortOrder, v)) +} + +// IsActiveEQ applies the EQ predicate on the "is_active" field. +func IsActiveEQ(v bool) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldIsActive, v)) +} + +// IsActiveNEQ applies the NEQ predicate on the "is_active" field. +func IsActiveNEQ(v bool) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldIsActive, v)) +} + +// IsActiveIsNil applies the IsNil predicate on the "is_active" field. +func IsActiveIsNil() predicate.Games { + return predicate.Games(sql.FieldIsNull(FieldIsActive)) +} + +// IsActiveNotNil applies the NotNil predicate on the "is_active" field. +func IsActiveNotNil() predicate.Games { + return predicate.Games(sql.FieldNotNull(FieldIsActive)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Games { + return predicate.Games(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Games { + return predicate.Games(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Games { + return predicate.Games(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Games { + return predicate.Games(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Games { + return predicate.Games(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Games { + return predicate.Games(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Games { + return predicate.Games(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Games { + return predicate.Games(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Games { + return predicate.Games(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Games { + return predicate.Games(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Games { + return predicate.Games(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Games { + return predicate.Games(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Games { + return predicate.Games(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Games { + return predicate.Games(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Games) predicate.Games { + return predicate.Games(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Games) predicate.Games { + return predicate.Games(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Games) predicate.Games { + return predicate.Games(sql.NotPredicates(p)) +} diff --git a/app/game/rpc/internal/models/games_create.go b/app/game/rpc/internal/models/games_create.go new file mode 100644 index 0000000..8ed7990 --- /dev/null +++ b/app/game/rpc/internal/models/games_create.go @@ -0,0 +1,335 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/game/rpc/internal/models/games" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GamesCreate is the builder for creating a Games entity. +type GamesCreate struct { + config + mutation *GamesMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (_c *GamesCreate) SetName(v string) *GamesCreate { + _c.mutation.SetName(v) + return _c +} + +// SetIcon sets the "icon" field. +func (_c *GamesCreate) SetIcon(v string) *GamesCreate { + _c.mutation.SetIcon(v) + return _c +} + +// SetCategory sets the "category" field. +func (_c *GamesCreate) SetCategory(v string) *GamesCreate { + _c.mutation.SetCategory(v) + return _c +} + +// SetSortOrder sets the "sort_order" field. +func (_c *GamesCreate) SetSortOrder(v int) *GamesCreate { + _c.mutation.SetSortOrder(v) + return _c +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_c *GamesCreate) SetNillableSortOrder(v *int) *GamesCreate { + if v != nil { + _c.SetSortOrder(*v) + } + return _c +} + +// SetIsActive sets the "is_active" field. +func (_c *GamesCreate) SetIsActive(v bool) *GamesCreate { + _c.mutation.SetIsActive(v) + return _c +} + +// SetNillableIsActive sets the "is_active" field if the given value is not nil. +func (_c *GamesCreate) SetNillableIsActive(v *bool) *GamesCreate { + if v != nil { + _c.SetIsActive(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *GamesCreate) SetCreatedAt(v time.Time) *GamesCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *GamesCreate) SetNillableCreatedAt(v *time.Time) *GamesCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *GamesCreate) SetUpdatedAt(v time.Time) *GamesCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *GamesCreate) SetNillableUpdatedAt(v *time.Time) *GamesCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *GamesCreate) SetID(v int64) *GamesCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the GamesMutation object of the builder. +func (_c *GamesCreate) Mutation() *GamesMutation { + return _c.mutation +} + +// Save creates the Games in the database. +func (_c *GamesCreate) Save(ctx context.Context) (*Games, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *GamesCreate) SaveX(ctx context.Context) *Games { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *GamesCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *GamesCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *GamesCreate) defaults() { + if _, ok := _c.mutation.SortOrder(); !ok { + v := games.DefaultSortOrder + _c.mutation.SetSortOrder(v) + } + if _, ok := _c.mutation.IsActive(); !ok { + v := games.DefaultIsActive + _c.mutation.SetIsActive(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := games.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := games.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *GamesCreate) check() error { + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`models: missing required field "Games.name"`)} + } + if v, ok := _c.mutation.Name(); ok { + if err := games.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`models: validator failed for field "Games.name": %w`, err)} + } + } + if _, ok := _c.mutation.Icon(); !ok { + return &ValidationError{Name: "icon", err: errors.New(`models: missing required field "Games.icon"`)} + } + if _, ok := _c.mutation.Category(); !ok { + return &ValidationError{Name: "category", err: errors.New(`models: missing required field "Games.category"`)} + } + if v, ok := _c.mutation.Category(); ok { + if err := games.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`models: validator failed for field "Games.category": %w`, err)} + } + } + if _, ok := _c.mutation.SortOrder(); !ok { + return &ValidationError{Name: "sort_order", err: errors.New(`models: missing required field "Games.sort_order"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Games.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Games.updated_at"`)} + } + return nil +} + +func (_c *GamesCreate) sqlSave(ctx context.Context) (*Games, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *GamesCreate) createSpec() (*Games, *sqlgraph.CreateSpec) { + var ( + _node = &Games{config: _c.config} + _spec = sqlgraph.NewCreateSpec(games.Table, sqlgraph.NewFieldSpec(games.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(games.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Icon(); ok { + _spec.SetField(games.FieldIcon, field.TypeString, value) + _node.Icon = value + } + if value, ok := _c.mutation.Category(); ok { + _spec.SetField(games.FieldCategory, field.TypeString, value) + _node.Category = value + } + if value, ok := _c.mutation.SortOrder(); ok { + _spec.SetField(games.FieldSortOrder, field.TypeInt, value) + _node.SortOrder = value + } + if value, ok := _c.mutation.IsActive(); ok { + _spec.SetField(games.FieldIsActive, field.TypeBool, value) + _node.IsActive = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(games.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(games.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + return _node, _spec +} + +// GamesCreateBulk is the builder for creating many Games entities in bulk. +type GamesCreateBulk struct { + config + err error + builders []*GamesCreate +} + +// Save creates the Games entities in the database. +func (_c *GamesCreateBulk) Save(ctx context.Context) ([]*Games, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Games, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GamesMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *GamesCreateBulk) SaveX(ctx context.Context) []*Games { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *GamesCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *GamesCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/game/rpc/internal/models/games_delete.go b/app/game/rpc/internal/models/games_delete.go new file mode 100644 index 0000000..e4b604c --- /dev/null +++ b/app/game/rpc/internal/models/games_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/game/rpc/internal/models/games" + "juwan-backend/app/game/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GamesDelete is the builder for deleting a Games entity. +type GamesDelete struct { + config + hooks []Hook + mutation *GamesMutation +} + +// Where appends a list predicates to the GamesDelete builder. +func (_d *GamesDelete) Where(ps ...predicate.Games) *GamesDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *GamesDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *GamesDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *GamesDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(games.Table, sqlgraph.NewFieldSpec(games.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// GamesDeleteOne is the builder for deleting a single Games entity. +type GamesDeleteOne struct { + _d *GamesDelete +} + +// Where appends a list predicates to the GamesDelete builder. +func (_d *GamesDeleteOne) Where(ps ...predicate.Games) *GamesDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *GamesDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{games.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *GamesDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/game/rpc/internal/models/games_query.go b/app/game/rpc/internal/models/games_query.go new file mode 100644 index 0000000..aaea7c8 --- /dev/null +++ b/app/game/rpc/internal/models/games_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/game/rpc/internal/models/games" + "juwan-backend/app/game/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GamesQuery is the builder for querying Games entities. +type GamesQuery struct { + config + ctx *QueryContext + order []games.OrderOption + inters []Interceptor + predicates []predicate.Games + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the GamesQuery builder. +func (_q *GamesQuery) Where(ps ...predicate.Games) *GamesQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *GamesQuery) Limit(limit int) *GamesQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *GamesQuery) Offset(offset int) *GamesQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *GamesQuery) Unique(unique bool) *GamesQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *GamesQuery) Order(o ...games.OrderOption) *GamesQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Games entity from the query. +// Returns a *NotFoundError when no Games was found. +func (_q *GamesQuery) First(ctx context.Context) (*Games, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{games.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *GamesQuery) FirstX(ctx context.Context) *Games { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Games ID from the query. +// Returns a *NotFoundError when no Games ID was found. +func (_q *GamesQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{games.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *GamesQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Games entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Games entity is found. +// Returns a *NotFoundError when no Games entities are found. +func (_q *GamesQuery) Only(ctx context.Context) (*Games, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{games.Label} + default: + return nil, &NotSingularError{games.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *GamesQuery) OnlyX(ctx context.Context) *Games { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Games ID in the query. +// Returns a *NotSingularError when more than one Games ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *GamesQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{games.Label} + default: + err = &NotSingularError{games.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *GamesQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of GamesSlice. +func (_q *GamesQuery) All(ctx context.Context) ([]*Games, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Games, *GamesQuery]() + return withInterceptors[[]*Games](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *GamesQuery) AllX(ctx context.Context) []*Games { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Games IDs. +func (_q *GamesQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(games.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *GamesQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *GamesQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*GamesQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *GamesQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *GamesQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *GamesQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the GamesQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *GamesQuery) Clone() *GamesQuery { + if _q == nil { + return nil + } + return &GamesQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]games.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Games{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Games.Query(). +// GroupBy(games.FieldName). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *GamesQuery) GroupBy(field string, fields ...string) *GamesGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &GamesGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = games.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.Games.Query(). +// Select(games.FieldName). +// Scan(ctx, &v) +func (_q *GamesQuery) Select(fields ...string) *GamesSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &GamesSelect{GamesQuery: _q} + sbuild.label = games.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GamesSelect configured with the given aggregations. +func (_q *GamesQuery) Aggregate(fns ...AggregateFunc) *GamesSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *GamesQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !games.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *GamesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Games, error) { + var ( + nodes = []*Games{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Games).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Games{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *GamesQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *GamesQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(games.Table, games.Columns, sqlgraph.NewFieldSpec(games.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, games.FieldID) + for i := range fields { + if fields[i] != games.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *GamesQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(games.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = games.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// GamesGroupBy is the group-by builder for Games entities. +type GamesGroupBy struct { + selector + build *GamesQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *GamesGroupBy) Aggregate(fns ...AggregateFunc) *GamesGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *GamesGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GamesQuery, *GamesGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *GamesGroupBy) sqlScan(ctx context.Context, root *GamesQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// GamesSelect is the builder for selecting fields of Games entities. +type GamesSelect struct { + *GamesQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *GamesSelect) Aggregate(fns ...AggregateFunc) *GamesSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *GamesSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GamesQuery, *GamesSelect](ctx, _s.GamesQuery, _s, _s.inters, v) +} + +func (_s *GamesSelect) sqlScan(ctx context.Context, root *GamesQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/game/rpc/internal/models/games_update.go b/app/game/rpc/internal/models/games_update.go new file mode 100644 index 0000000..77eb092 --- /dev/null +++ b/app/game/rpc/internal/models/games_update.go @@ -0,0 +1,456 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/game/rpc/internal/models/games" + "juwan-backend/app/game/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GamesUpdate is the builder for updating Games entities. +type GamesUpdate struct { + config + hooks []Hook + mutation *GamesMutation +} + +// Where appends a list predicates to the GamesUpdate builder. +func (_u *GamesUpdate) Where(ps ...predicate.Games) *GamesUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *GamesUpdate) SetName(v string) *GamesUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *GamesUpdate) SetNillableName(v *string) *GamesUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetIcon sets the "icon" field. +func (_u *GamesUpdate) SetIcon(v string) *GamesUpdate { + _u.mutation.SetIcon(v) + return _u +} + +// SetNillableIcon sets the "icon" field if the given value is not nil. +func (_u *GamesUpdate) SetNillableIcon(v *string) *GamesUpdate { + if v != nil { + _u.SetIcon(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *GamesUpdate) SetCategory(v string) *GamesUpdate { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *GamesUpdate) SetNillableCategory(v *string) *GamesUpdate { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetSortOrder sets the "sort_order" field. +func (_u *GamesUpdate) SetSortOrder(v int) *GamesUpdate { + _u.mutation.ResetSortOrder() + _u.mutation.SetSortOrder(v) + return _u +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_u *GamesUpdate) SetNillableSortOrder(v *int) *GamesUpdate { + if v != nil { + _u.SetSortOrder(*v) + } + return _u +} + +// AddSortOrder adds value to the "sort_order" field. +func (_u *GamesUpdate) AddSortOrder(v int) *GamesUpdate { + _u.mutation.AddSortOrder(v) + return _u +} + +// SetIsActive sets the "is_active" field. +func (_u *GamesUpdate) SetIsActive(v bool) *GamesUpdate { + _u.mutation.SetIsActive(v) + return _u +} + +// SetNillableIsActive sets the "is_active" field if the given value is not nil. +func (_u *GamesUpdate) SetNillableIsActive(v *bool) *GamesUpdate { + if v != nil { + _u.SetIsActive(*v) + } + return _u +} + +// ClearIsActive clears the value of the "is_active" field. +func (_u *GamesUpdate) ClearIsActive() *GamesUpdate { + _u.mutation.ClearIsActive() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *GamesUpdate) SetUpdatedAt(v time.Time) *GamesUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the GamesMutation object of the builder. +func (_u *GamesUpdate) Mutation() *GamesMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *GamesUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *GamesUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *GamesUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *GamesUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *GamesUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := games.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *GamesUpdate) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := games.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`models: validator failed for field "Games.name": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := games.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`models: validator failed for field "Games.category": %w`, err)} + } + } + return nil +} + +func (_u *GamesUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(games.Table, games.Columns, sqlgraph.NewFieldSpec(games.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(games.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Icon(); ok { + _spec.SetField(games.FieldIcon, field.TypeString, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(games.FieldCategory, field.TypeString, value) + } + if value, ok := _u.mutation.SortOrder(); ok { + _spec.SetField(games.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortOrder(); ok { + _spec.AddField(games.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.IsActive(); ok { + _spec.SetField(games.FieldIsActive, field.TypeBool, value) + } + if _u.mutation.IsActiveCleared() { + _spec.ClearField(games.FieldIsActive, field.TypeBool) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(games.FieldUpdatedAt, field.TypeTime, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{games.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// GamesUpdateOne is the builder for updating a single Games entity. +type GamesUpdateOne struct { + config + fields []string + hooks []Hook + mutation *GamesMutation +} + +// SetName sets the "name" field. +func (_u *GamesUpdateOne) SetName(v string) *GamesUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *GamesUpdateOne) SetNillableName(v *string) *GamesUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetIcon sets the "icon" field. +func (_u *GamesUpdateOne) SetIcon(v string) *GamesUpdateOne { + _u.mutation.SetIcon(v) + return _u +} + +// SetNillableIcon sets the "icon" field if the given value is not nil. +func (_u *GamesUpdateOne) SetNillableIcon(v *string) *GamesUpdateOne { + if v != nil { + _u.SetIcon(*v) + } + return _u +} + +// SetCategory sets the "category" field. +func (_u *GamesUpdateOne) SetCategory(v string) *GamesUpdateOne { + _u.mutation.SetCategory(v) + return _u +} + +// SetNillableCategory sets the "category" field if the given value is not nil. +func (_u *GamesUpdateOne) SetNillableCategory(v *string) *GamesUpdateOne { + if v != nil { + _u.SetCategory(*v) + } + return _u +} + +// SetSortOrder sets the "sort_order" field. +func (_u *GamesUpdateOne) SetSortOrder(v int) *GamesUpdateOne { + _u.mutation.ResetSortOrder() + _u.mutation.SetSortOrder(v) + return _u +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_u *GamesUpdateOne) SetNillableSortOrder(v *int) *GamesUpdateOne { + if v != nil { + _u.SetSortOrder(*v) + } + return _u +} + +// AddSortOrder adds value to the "sort_order" field. +func (_u *GamesUpdateOne) AddSortOrder(v int) *GamesUpdateOne { + _u.mutation.AddSortOrder(v) + return _u +} + +// SetIsActive sets the "is_active" field. +func (_u *GamesUpdateOne) SetIsActive(v bool) *GamesUpdateOne { + _u.mutation.SetIsActive(v) + return _u +} + +// SetNillableIsActive sets the "is_active" field if the given value is not nil. +func (_u *GamesUpdateOne) SetNillableIsActive(v *bool) *GamesUpdateOne { + if v != nil { + _u.SetIsActive(*v) + } + return _u +} + +// ClearIsActive clears the value of the "is_active" field. +func (_u *GamesUpdateOne) ClearIsActive() *GamesUpdateOne { + _u.mutation.ClearIsActive() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *GamesUpdateOne) SetUpdatedAt(v time.Time) *GamesUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the GamesMutation object of the builder. +func (_u *GamesUpdateOne) Mutation() *GamesMutation { + return _u.mutation +} + +// Where appends a list predicates to the GamesUpdate builder. +func (_u *GamesUpdateOne) Where(ps ...predicate.Games) *GamesUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *GamesUpdateOne) Select(field string, fields ...string) *GamesUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Games entity. +func (_u *GamesUpdateOne) Save(ctx context.Context) (*Games, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *GamesUpdateOne) SaveX(ctx context.Context) *Games { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *GamesUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *GamesUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *GamesUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := games.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *GamesUpdateOne) check() error { + if v, ok := _u.mutation.Name(); ok { + if err := games.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`models: validator failed for field "Games.name": %w`, err)} + } + } + if v, ok := _u.mutation.Category(); ok { + if err := games.CategoryValidator(v); err != nil { + return &ValidationError{Name: "category", err: fmt.Errorf(`models: validator failed for field "Games.category": %w`, err)} + } + } + return nil +} + +func (_u *GamesUpdateOne) sqlSave(ctx context.Context) (_node *Games, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(games.Table, games.Columns, sqlgraph.NewFieldSpec(games.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Games.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, games.FieldID) + for _, f := range fields { + if !games.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != games.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(games.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Icon(); ok { + _spec.SetField(games.FieldIcon, field.TypeString, value) + } + if value, ok := _u.mutation.Category(); ok { + _spec.SetField(games.FieldCategory, field.TypeString, value) + } + if value, ok := _u.mutation.SortOrder(); ok { + _spec.SetField(games.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortOrder(); ok { + _spec.AddField(games.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.IsActive(); ok { + _spec.SetField(games.FieldIsActive, field.TypeBool, value) + } + if _u.mutation.IsActiveCleared() { + _spec.ClearField(games.FieldIsActive, field.TypeBool) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(games.FieldUpdatedAt, field.TypeTime, value) + } + _node = &Games{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{games.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/game/rpc/internal/models/hook/hook.go b/app/game/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..cd916fa --- /dev/null +++ b/app/game/rpc/internal/models/hook/hook.go @@ -0,0 +1,198 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + "juwan-backend/app/game/rpc/internal/models" +) + +// The GamesFunc type is an adapter to allow the use of ordinary +// function as Games mutator. +type GamesFunc func(context.Context, *models.GamesMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f GamesFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.GamesMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.GamesMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, models.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op models.Op) Condition { + return func(_ context.Context, m models.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk models.Hook, cond Condition) models.Hook { + return func(next models.Mutator) models.Mutator { + return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, models.Delete|models.Create) +func On(hk models.Hook, op models.Op) models.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, models.Update|models.UpdateOne) +func Unless(hk models.Hook, op models.Op) models.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) models.Hook { + return func(models.Mutator) models.Mutator { + return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []models.Hook { +// return []models.Hook{ +// Reject(models.Delete|models.Update), +// } +// } +func Reject(op models.Op) models.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []models.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...models.Hook) Chain { + return Chain{append([]models.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() models.Hook { + return func(mutator models.Mutator) models.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...models.Hook) Chain { + newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/app/game/rpc/internal/models/migrate/migrate.go b/app/game/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/game/rpc/internal/models/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/app/game/rpc/internal/models/migrate/schema.go b/app/game/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..f1576c4 --- /dev/null +++ b/app/game/rpc/internal/models/migrate/schema.go @@ -0,0 +1,35 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // GamesColumns holds the columns for the "games" table. + GamesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "name", Type: field.TypeString, Unique: true, Size: 100}, + {Name: "icon", Type: field.TypeString}, + {Name: "category", Type: field.TypeString, Size: 50}, + {Name: "sort_order", Type: field.TypeInt, Default: 0}, + {Name: "is_active", Type: field.TypeBool, Nullable: true, Default: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // GamesTable holds the schema information for the "games" table. + GamesTable = &schema.Table{ + Name: "games", + Columns: GamesColumns, + PrimaryKey: []*schema.Column{GamesColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + GamesTable, + } +) + +func init() { +} diff --git a/app/game/rpc/internal/models/mutation.go b/app/game/rpc/internal/models/mutation.go new file mode 100644 index 0000000..74ebef6 --- /dev/null +++ b/app/game/rpc/internal/models/mutation.go @@ -0,0 +1,742 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/game/rpc/internal/models/games" + "juwan-backend/app/game/rpc/internal/models/predicate" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeGames = "Games" +) + +// GamesMutation represents an operation that mutates the Games nodes in the graph. +type GamesMutation struct { + config + op Op + typ string + id *int64 + name *string + icon *string + category *string + sort_order *int + addsort_order *int + is_active *bool + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Games, error) + predicates []predicate.Games +} + +var _ ent.Mutation = (*GamesMutation)(nil) + +// gamesOption allows management of the mutation configuration using functional options. +type gamesOption func(*GamesMutation) + +// newGamesMutation creates new mutation for the Games entity. +func newGamesMutation(c config, op Op, opts ...gamesOption) *GamesMutation { + m := &GamesMutation{ + config: c, + op: op, + typ: TypeGames, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withGamesID sets the ID field of the mutation. +func withGamesID(id int64) gamesOption { + return func(m *GamesMutation) { + var ( + err error + once sync.Once + value *Games + ) + m.oldValue = func(ctx context.Context) (*Games, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Games.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withGames sets the old Games of the mutation. +func withGames(node *Games) gamesOption { + return func(m *GamesMutation) { + m.oldValue = func(context.Context) (*Games, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m GamesMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m GamesMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Games entities. +func (m *GamesMutation) SetID(id int64) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *GamesMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *GamesMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Games.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *GamesMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *GamesMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Games entity. +// If the Games object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GamesMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *GamesMutation) ResetName() { + m.name = nil +} + +// SetIcon sets the "icon" field. +func (m *GamesMutation) SetIcon(s string) { + m.icon = &s +} + +// Icon returns the value of the "icon" field in the mutation. +func (m *GamesMutation) Icon() (r string, exists bool) { + v := m.icon + if v == nil { + return + } + return *v, true +} + +// OldIcon returns the old "icon" field's value of the Games entity. +// If the Games object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GamesMutation) OldIcon(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIcon is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIcon requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIcon: %w", err) + } + return oldValue.Icon, nil +} + +// ResetIcon resets all changes to the "icon" field. +func (m *GamesMutation) ResetIcon() { + m.icon = nil +} + +// SetCategory sets the "category" field. +func (m *GamesMutation) SetCategory(s string) { + m.category = &s +} + +// Category returns the value of the "category" field in the mutation. +func (m *GamesMutation) Category() (r string, exists bool) { + v := m.category + if v == nil { + return + } + return *v, true +} + +// OldCategory returns the old "category" field's value of the Games entity. +// If the Games object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GamesMutation) OldCategory(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategory is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategory requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategory: %w", err) + } + return oldValue.Category, nil +} + +// ResetCategory resets all changes to the "category" field. +func (m *GamesMutation) ResetCategory() { + m.category = nil +} + +// SetSortOrder sets the "sort_order" field. +func (m *GamesMutation) SetSortOrder(i int) { + m.sort_order = &i + m.addsort_order = nil +} + +// SortOrder returns the value of the "sort_order" field in the mutation. +func (m *GamesMutation) SortOrder() (r int, exists bool) { + v := m.sort_order + if v == nil { + return + } + return *v, true +} + +// OldSortOrder returns the old "sort_order" field's value of the Games entity. +// If the Games object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GamesMutation) OldSortOrder(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSortOrder is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSortOrder requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSortOrder: %w", err) + } + return oldValue.SortOrder, nil +} + +// AddSortOrder adds i to the "sort_order" field. +func (m *GamesMutation) AddSortOrder(i int) { + if m.addsort_order != nil { + *m.addsort_order += i + } else { + m.addsort_order = &i + } +} + +// AddedSortOrder returns the value that was added to the "sort_order" field in this mutation. +func (m *GamesMutation) AddedSortOrder() (r int, exists bool) { + v := m.addsort_order + if v == nil { + return + } + return *v, true +} + +// ResetSortOrder resets all changes to the "sort_order" field. +func (m *GamesMutation) ResetSortOrder() { + m.sort_order = nil + m.addsort_order = nil +} + +// SetIsActive sets the "is_active" field. +func (m *GamesMutation) SetIsActive(b bool) { + m.is_active = &b +} + +// IsActive returns the value of the "is_active" field in the mutation. +func (m *GamesMutation) IsActive() (r bool, exists bool) { + v := m.is_active + if v == nil { + return + } + return *v, true +} + +// OldIsActive returns the old "is_active" field's value of the Games entity. +// If the Games object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GamesMutation) OldIsActive(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIsActive is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIsActive requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIsActive: %w", err) + } + return oldValue.IsActive, nil +} + +// ClearIsActive clears the value of the "is_active" field. +func (m *GamesMutation) ClearIsActive() { + m.is_active = nil + m.clearedFields[games.FieldIsActive] = struct{}{} +} + +// IsActiveCleared returns if the "is_active" field was cleared in this mutation. +func (m *GamesMutation) IsActiveCleared() bool { + _, ok := m.clearedFields[games.FieldIsActive] + return ok +} + +// ResetIsActive resets all changes to the "is_active" field. +func (m *GamesMutation) ResetIsActive() { + m.is_active = nil + delete(m.clearedFields, games.FieldIsActive) +} + +// SetCreatedAt sets the "created_at" field. +func (m *GamesMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *GamesMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the Games entity. +// If the Games object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GamesMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *GamesMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *GamesMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *GamesMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the Games entity. +// If the Games object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GamesMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *GamesMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the GamesMutation builder. +func (m *GamesMutation) Where(ps ...predicate.Games) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GamesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GamesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Games, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *GamesMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *GamesMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Games). +func (m *GamesMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *GamesMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.name != nil { + fields = append(fields, games.FieldName) + } + if m.icon != nil { + fields = append(fields, games.FieldIcon) + } + if m.category != nil { + fields = append(fields, games.FieldCategory) + } + if m.sort_order != nil { + fields = append(fields, games.FieldSortOrder) + } + if m.is_active != nil { + fields = append(fields, games.FieldIsActive) + } + if m.created_at != nil { + fields = append(fields, games.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, games.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *GamesMutation) Field(name string) (ent.Value, bool) { + switch name { + case games.FieldName: + return m.Name() + case games.FieldIcon: + return m.Icon() + case games.FieldCategory: + return m.Category() + case games.FieldSortOrder: + return m.SortOrder() + case games.FieldIsActive: + return m.IsActive() + case games.FieldCreatedAt: + return m.CreatedAt() + case games.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *GamesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case games.FieldName: + return m.OldName(ctx) + case games.FieldIcon: + return m.OldIcon(ctx) + case games.FieldCategory: + return m.OldCategory(ctx) + case games.FieldSortOrder: + return m.OldSortOrder(ctx) + case games.FieldIsActive: + return m.OldIsActive(ctx) + case games.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case games.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Games field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *GamesMutation) SetField(name string, value ent.Value) error { + switch name { + case games.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case games.FieldIcon: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIcon(v) + return nil + case games.FieldCategory: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategory(v) + return nil + case games.FieldSortOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSortOrder(v) + return nil + case games.FieldIsActive: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsActive(v) + return nil + case games.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case games.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Games field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *GamesMutation) AddedFields() []string { + var fields []string + if m.addsort_order != nil { + fields = append(fields, games.FieldSortOrder) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *GamesMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case games.FieldSortOrder: + return m.AddedSortOrder() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *GamesMutation) AddField(name string, value ent.Value) error { + switch name { + case games.FieldSortOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSortOrder(v) + return nil + } + return fmt.Errorf("unknown Games numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *GamesMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(games.FieldIsActive) { + fields = append(fields, games.FieldIsActive) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *GamesMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *GamesMutation) ClearField(name string) error { + switch name { + case games.FieldIsActive: + m.ClearIsActive() + return nil + } + return fmt.Errorf("unknown Games nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *GamesMutation) ResetField(name string) error { + switch name { + case games.FieldName: + m.ResetName() + return nil + case games.FieldIcon: + m.ResetIcon() + return nil + case games.FieldCategory: + m.ResetCategory() + return nil + case games.FieldSortOrder: + m.ResetSortOrder() + return nil + case games.FieldIsActive: + m.ResetIsActive() + return nil + case games.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case games.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Games field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *GamesMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *GamesMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *GamesMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *GamesMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *GamesMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *GamesMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *GamesMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Games unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *GamesMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Games edge %s", name) +} diff --git a/app/game/rpc/internal/models/predicate/predicate.go b/app/game/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..3c0d58b --- /dev/null +++ b/app/game/rpc/internal/models/predicate/predicate.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Games is the predicate function for games builders. +type Games func(*sql.Selector) diff --git a/app/game/rpc/internal/models/runtime.go b/app/game/rpc/internal/models/runtime.go new file mode 100644 index 0000000..7ec988a --- /dev/null +++ b/app/game/rpc/internal/models/runtime.go @@ -0,0 +1,43 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/game/rpc/internal/models/games" + "juwan-backend/app/game/rpc/internal/models/schema" + "time" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + gamesFields := schema.Games{}.Fields() + _ = gamesFields + // gamesDescName is the schema descriptor for name field. + gamesDescName := gamesFields[1].Descriptor() + // games.NameValidator is a validator for the "name" field. It is called by the builders before save. + games.NameValidator = gamesDescName.Validators[0].(func(string) error) + // gamesDescCategory is the schema descriptor for category field. + gamesDescCategory := gamesFields[3].Descriptor() + // games.CategoryValidator is a validator for the "category" field. It is called by the builders before save. + games.CategoryValidator = gamesDescCategory.Validators[0].(func(string) error) + // gamesDescSortOrder is the schema descriptor for sort_order field. + gamesDescSortOrder := gamesFields[4].Descriptor() + // games.DefaultSortOrder holds the default value on creation for the sort_order field. + games.DefaultSortOrder = gamesDescSortOrder.Default.(int) + // gamesDescIsActive is the schema descriptor for is_active field. + gamesDescIsActive := gamesFields[5].Descriptor() + // games.DefaultIsActive holds the default value on creation for the is_active field. + games.DefaultIsActive = gamesDescIsActive.Default.(bool) + // gamesDescCreatedAt is the schema descriptor for created_at field. + gamesDescCreatedAt := gamesFields[6].Descriptor() + // games.DefaultCreatedAt holds the default value on creation for the created_at field. + games.DefaultCreatedAt = gamesDescCreatedAt.Default.(func() time.Time) + // gamesDescUpdatedAt is the schema descriptor for updated_at field. + gamesDescUpdatedAt := gamesFields[7].Descriptor() + // games.DefaultUpdatedAt holds the default value on creation for the updated_at field. + games.DefaultUpdatedAt = gamesDescUpdatedAt.Default.(func() time.Time) + // games.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + games.UpdateDefaultUpdatedAt = gamesDescUpdatedAt.UpdateDefault.(func() time.Time) +} diff --git a/app/game/rpc/internal/models/runtime/runtime.go b/app/game/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..02d021b --- /dev/null +++ b/app/game/rpc/internal/models/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in juwan-backend/app/game/rpc/internal/models/runtime.go + +const ( + Version = "v0.14.5" // Version of ent codegen. + Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. +) diff --git a/app/game/rpc/internal/models/tx.go b/app/game/rpc/internal/models/tx.go new file mode 100644 index 0000000..3671b44 --- /dev/null +++ b/app/game/rpc/internal/models/tx.go @@ -0,0 +1,210 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Games is the client for interacting with the Games builders. + Games *GamesClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Games = NewGamesClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Games.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/app/game/rpc/internal/server/gamePublicServer.go b/app/game/rpc/internal/server/gamePublicServer.go deleted file mode 100644 index fdd3bff..0000000 --- a/app/game/rpc/internal/server/gamePublicServer.go +++ /dev/null @@ -1,180 +0,0 @@ -// Code generated by goctl. DO NOT EDIT. -// goctl 1.9.2 -// Source: game.proto - -package server - -import ( - "context" - - "juwan-backend/app/game/rpc/internal/logic" - "juwan-backend/app/game/rpc/internal/svc" - "juwan-backend/app/game/rpc/pb" -) - -type GamePublicServer struct { - svcCtx *svc.ServiceContext - pb.UnimplementedGamePublicServer -} - -func NewGamePublicServer(svcCtx *svc.ServiceContext) *GamePublicServer { - return &GamePublicServer{ - svcCtx: svcCtx, - } -} - -// -----------------------games----------------------- -func (s *GamePublicServer) AddGames(ctx context.Context, in *pb.AddGamesReq) (*pb.AddGamesResp, error) { - l := logic.NewAddGamesLogic(ctx, s.svcCtx) - return l.AddGames(in) -} - -func (s *GamePublicServer) UpdateGames(ctx context.Context, in *pb.UpdateGamesReq) (*pb.UpdateGamesResp, error) { - l := logic.NewUpdateGamesLogic(ctx, s.svcCtx) - return l.UpdateGames(in) -} - -func (s *GamePublicServer) DelGames(ctx context.Context, in *pb.DelGamesReq) (*pb.DelGamesResp, error) { - l := logic.NewDelGamesLogic(ctx, s.svcCtx) - return l.DelGames(in) -} - -func (s *GamePublicServer) GetGamesById(ctx context.Context, in *pb.GetGamesByIdReq) (*pb.GetGamesByIdResp, error) { - l := logic.NewGetGamesByIdLogic(ctx, s.svcCtx) - return l.GetGamesById(in) -} - -func (s *GamePublicServer) SearchGames(ctx context.Context, in *pb.SearchGamesReq) (*pb.SearchGamesResp, error) { - l := logic.NewSearchGamesLogic(ctx, s.svcCtx) - return l.SearchGames(in) -} - -// -----------------------playerServices----------------------- -func (s *GamePublicServer) AddPlayerServices(ctx context.Context, in *pb.AddPlayerServicesReq) (*pb.AddPlayerServicesResp, error) { - l := logic.NewAddPlayerServicesLogic(ctx, s.svcCtx) - return l.AddPlayerServices(in) -} - -func (s *GamePublicServer) UpdatePlayerServices(ctx context.Context, in *pb.UpdatePlayerServicesReq) (*pb.UpdatePlayerServicesResp, error) { - l := logic.NewUpdatePlayerServicesLogic(ctx, s.svcCtx) - return l.UpdatePlayerServices(in) -} - -func (s *GamePublicServer) DelPlayerServices(ctx context.Context, in *pb.DelPlayerServicesReq) (*pb.DelPlayerServicesResp, error) { - l := logic.NewDelPlayerServicesLogic(ctx, s.svcCtx) - return l.DelPlayerServices(in) -} - -func (s *GamePublicServer) GetPlayerServicesById(ctx context.Context, in *pb.GetPlayerServicesByIdReq) (*pb.GetPlayerServicesByIdResp, error) { - l := logic.NewGetPlayerServicesByIdLogic(ctx, s.svcCtx) - return l.GetPlayerServicesById(in) -} - -func (s *GamePublicServer) SearchPlayerServices(ctx context.Context, in *pb.SearchPlayerServicesReq) (*pb.SearchPlayerServicesResp, error) { - l := logic.NewSearchPlayerServicesLogic(ctx, s.svcCtx) - return l.SearchPlayerServices(in) -} - -// -----------------------players----------------------- -func (s *GamePublicServer) AddPlayers(ctx context.Context, in *pb.AddPlayersReq) (*pb.AddPlayersResp, error) { - l := logic.NewAddPlayersLogic(ctx, s.svcCtx) - return l.AddPlayers(in) -} - -func (s *GamePublicServer) UpdatePlayers(ctx context.Context, in *pb.UpdatePlayersReq) (*pb.UpdatePlayersResp, error) { - l := logic.NewUpdatePlayersLogic(ctx, s.svcCtx) - return l.UpdatePlayers(in) -} - -func (s *GamePublicServer) DelPlayers(ctx context.Context, in *pb.DelPlayersReq) (*pb.DelPlayersResp, error) { - l := logic.NewDelPlayersLogic(ctx, s.svcCtx) - return l.DelPlayers(in) -} - -func (s *GamePublicServer) GetPlayersById(ctx context.Context, in *pb.GetPlayersByIdReq) (*pb.GetPlayersByIdResp, error) { - l := logic.NewGetPlayersByIdLogic(ctx, s.svcCtx) - return l.GetPlayersById(in) -} - -func (s *GamePublicServer) SearchPlayers(ctx context.Context, in *pb.SearchPlayersReq) (*pb.SearchPlayersResp, error) { - l := logic.NewSearchPlayersLogic(ctx, s.svcCtx) - return l.SearchPlayers(in) -} - -// -----------------------shopInvitations----------------------- -func (s *GamePublicServer) AddShopInvitations(ctx context.Context, in *pb.AddShopInvitationsReq) (*pb.AddShopInvitationsResp, error) { - l := logic.NewAddShopInvitationsLogic(ctx, s.svcCtx) - return l.AddShopInvitations(in) -} - -func (s *GamePublicServer) UpdateShopInvitations(ctx context.Context, in *pb.UpdateShopInvitationsReq) (*pb.UpdateShopInvitationsResp, error) { - l := logic.NewUpdateShopInvitationsLogic(ctx, s.svcCtx) - return l.UpdateShopInvitations(in) -} - -func (s *GamePublicServer) DelShopInvitations(ctx context.Context, in *pb.DelShopInvitationsReq) (*pb.DelShopInvitationsResp, error) { - l := logic.NewDelShopInvitationsLogic(ctx, s.svcCtx) - return l.DelShopInvitations(in) -} - -func (s *GamePublicServer) GetShopInvitationsById(ctx context.Context, in *pb.GetShopInvitationsByIdReq) (*pb.GetShopInvitationsByIdResp, error) { - l := logic.NewGetShopInvitationsByIdLogic(ctx, s.svcCtx) - return l.GetShopInvitationsById(in) -} - -func (s *GamePublicServer) SearchShopInvitations(ctx context.Context, in *pb.SearchShopInvitationsReq) (*pb.SearchShopInvitationsResp, error) { - l := logic.NewSearchShopInvitationsLogic(ctx, s.svcCtx) - return l.SearchShopInvitations(in) -} - -// -----------------------shopPlayers----------------------- -func (s *GamePublicServer) AddShopPlayers(ctx context.Context, in *pb.AddShopPlayersReq) (*pb.AddShopPlayersResp, error) { - l := logic.NewAddShopPlayersLogic(ctx, s.svcCtx) - return l.AddShopPlayers(in) -} - -func (s *GamePublicServer) UpdateShopPlayers(ctx context.Context, in *pb.UpdateShopPlayersReq) (*pb.UpdateShopPlayersResp, error) { - l := logic.NewUpdateShopPlayersLogic(ctx, s.svcCtx) - return l.UpdateShopPlayers(in) -} - -func (s *GamePublicServer) DelShopPlayers(ctx context.Context, in *pb.DelShopPlayersReq) (*pb.DelShopPlayersResp, error) { - l := logic.NewDelShopPlayersLogic(ctx, s.svcCtx) - return l.DelShopPlayers(in) -} - -func (s *GamePublicServer) GetShopPlayersById(ctx context.Context, in *pb.GetShopPlayersByIdReq) (*pb.GetShopPlayersByIdResp, error) { - l := logic.NewGetShopPlayersByIdLogic(ctx, s.svcCtx) - return l.GetShopPlayersById(in) -} - -func (s *GamePublicServer) SearchShopPlayers(ctx context.Context, in *pb.SearchShopPlayersReq) (*pb.SearchShopPlayersResp, error) { - l := logic.NewSearchShopPlayersLogic(ctx, s.svcCtx) - return l.SearchShopPlayers(in) -} - -// -----------------------shops----------------------- -func (s *GamePublicServer) AddShops(ctx context.Context, in *pb.AddShopsReq) (*pb.AddShopsResp, error) { - l := logic.NewAddShopsLogic(ctx, s.svcCtx) - return l.AddShops(in) -} - -func (s *GamePublicServer) UpdateShops(ctx context.Context, in *pb.UpdateShopsReq) (*pb.UpdateShopsResp, error) { - l := logic.NewUpdateShopsLogic(ctx, s.svcCtx) - return l.UpdateShops(in) -} - -func (s *GamePublicServer) DelShops(ctx context.Context, in *pb.DelShopsReq) (*pb.DelShopsResp, error) { - l := logic.NewDelShopsLogic(ctx, s.svcCtx) - return l.DelShops(in) -} - -func (s *GamePublicServer) GetShopsById(ctx context.Context, in *pb.GetShopsByIdReq) (*pb.GetShopsByIdResp, error) { - l := logic.NewGetShopsByIdLogic(ctx, s.svcCtx) - return l.GetShopsById(in) -} - -func (s *GamePublicServer) SearchShops(ctx context.Context, in *pb.SearchShopsReq) (*pb.SearchShopsResp, error) { - l := logic.NewSearchShopsLogic(ctx, s.svcCtx) - return l.SearchShops(in) -} diff --git a/app/game/rpc/internal/server/gameServiceServer.go b/app/game/rpc/internal/server/gameServiceServer.go new file mode 100644 index 0000000..3a082d3 --- /dev/null +++ b/app/game/rpc/internal/server/gameServiceServer.go @@ -0,0 +1,50 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 +// Source: game.proto + +package server + +import ( + "context" + + "juwan-backend/app/game/rpc/internal/logic" + "juwan-backend/app/game/rpc/internal/svc" + "juwan-backend/app/game/rpc/pb" +) + +type GameServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedGameServiceServer +} + +func NewGameServiceServer(svcCtx *svc.ServiceContext) *GameServiceServer { + return &GameServiceServer{ + svcCtx: svcCtx, + } +} + +// -----------------------games----------------------- +func (s *GameServiceServer) AddGames(ctx context.Context, in *pb.AddGamesReq) (*pb.AddGamesResp, error) { + l := logic.NewAddGamesLogic(ctx, s.svcCtx) + return l.AddGames(in) +} + +func (s *GameServiceServer) UpdateGames(ctx context.Context, in *pb.UpdateGamesReq) (*pb.UpdateGamesResp, error) { + l := logic.NewUpdateGamesLogic(ctx, s.svcCtx) + return l.UpdateGames(in) +} + +func (s *GameServiceServer) DelGames(ctx context.Context, in *pb.DelGamesReq) (*pb.DelGamesResp, error) { + l := logic.NewDelGamesLogic(ctx, s.svcCtx) + return l.DelGames(in) +} + +func (s *GameServiceServer) GetGamesById(ctx context.Context, in *pb.GetGamesByIdReq) (*pb.GetGamesByIdResp, error) { + l := logic.NewGetGamesByIdLogic(ctx, s.svcCtx) + return l.GetGamesById(in) +} + +func (s *GameServiceServer) SearchGames(ctx context.Context, in *pb.SearchGamesReq) (*pb.SearchGamesResp, error) { + l := logic.NewSearchGamesLogic(ctx, s.svcCtx) + return l.SearchGames(in) +} diff --git a/app/game/rpc/internal/server/publicServer.go b/app/game/rpc/internal/server/publicServer.go deleted file mode 100644 index fe97327..0000000 --- a/app/game/rpc/internal/server/publicServer.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by goctl. DO NOT EDIT. -// goctl 1.9.2 -// Source: game.proto - -package server - -import ( - "context" - - "juwan-backend/app/game/rpc/internal/logic" - "juwan-backend/app/game/rpc/internal/svc" - "juwan-backend/app/game/rpc/pb" -) - -type PublicServer struct { - svcCtx *svc.ServiceContext - pb.UnimplementedPublicServer -} - -func NewPublicServer(svcCtx *svc.ServiceContext) *PublicServer { - return &PublicServer{ - svcCtx: svcCtx, - } -} - -// -----------------------games----------------------- -func (s *PublicServer) AddGames(ctx context.Context, in *pb.AddGamesReq) (*pb.AddGamesResp, error) { - l := logic.NewAddGamesLogic(ctx, s.svcCtx) - return l.AddGames(in) -} - -func (s *PublicServer) UpdateGames(ctx context.Context, in *pb.UpdateGamesReq) (*pb.UpdateGamesResp, error) { - l := logic.NewUpdateGamesLogic(ctx, s.svcCtx) - return l.UpdateGames(in) -} - -func (s *PublicServer) DelGames(ctx context.Context, in *pb.DelGamesReq) (*pb.DelGamesResp, error) { - l := logic.NewDelGamesLogic(ctx, s.svcCtx) - return l.DelGames(in) -} - -func (s *PublicServer) GetGamesById(ctx context.Context, in *pb.GetGamesByIdReq) (*pb.GetGamesByIdResp, error) { - l := logic.NewGetGamesByIdLogic(ctx, s.svcCtx) - return l.GetGamesById(in) -} - -func (s *PublicServer) SearchGames(ctx context.Context, in *pb.SearchGamesReq) (*pb.SearchGamesResp, error) { - l := logic.NewSearchGamesLogic(ctx, s.svcCtx) - return l.SearchGames(in) -} diff --git a/app/game/rpc/internal/svc/serviceContext.go b/app/game/rpc/internal/svc/serviceContext.go index e732072..f8a4499 100644 --- a/app/game/rpc/internal/svc/serviceContext.go +++ b/app/game/rpc/internal/svc/serviceContext.go @@ -12,6 +12,8 @@ import ( "ariga.io/entcache" "entgo.io/ent/dialect/sql" "github.com/zeromicro/go-zero/core/logx" + + _ "github.com/jackc/pgx/v5/stdlib" ) type ServiceContext struct { diff --git a/app/game/rpc/pb.go b/app/game/rpc/pb.go index ceb632d..13acc9e 100644 --- a/app/game/rpc/pb.go +++ b/app/game/rpc/pb.go @@ -22,11 +22,11 @@ func main() { flag.Parse() var c config.Config - conf.MustLoad(*configFile, &c) + conf.MustLoad(*configFile, &c, conf.UseEnv()) ctx := svc.NewServiceContext(c) s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { - pb.RegisterGamePublicServer(grpcServer, server.NewGamePublicServer(ctx)) + pb.RegisterGameServiceServer(grpcServer, server.NewGameServiceServer(ctx)) if c.Mode == service.DevMode || c.Mode == service.TestMode { reflection.Register(grpcServer) diff --git a/app/game/rpc/pb/game.pb.go b/app/game/rpc/pb/game.pb.go index d979884..3ec8b55 100644 --- a/app/game/rpc/pb/game.pb.go +++ b/app/game/rpc/pb/game.pb.go @@ -556,16 +556,16 @@ func (x *GetGamesByIdResp) GetGames() *Games { type SearchGamesReq struct { state protoimpl.MessageState `protogen:"open.v1"` - Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page - Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit - Id int64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` //id - Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"` //name - Icon string `protobuf:"bytes,5,opt,name=icon,proto3" json:"icon,omitempty"` //icon - Category string `protobuf:"bytes,6,opt,name=category,proto3" json:"category,omitempty"` //category - SortOrder int64 `protobuf:"varint,7,opt,name=sortOrder,proto3" json:"sortOrder,omitempty"` //sortOrder - IsActive bool `protobuf:"varint,8,opt,name=isActive,proto3" json:"isActive,omitempty"` //isActive - CreatedAt int64 `protobuf:"varint,9,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt - UpdatedAt int64 `protobuf:"varint,10,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + Id int64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` //id + Name *string `protobuf:"bytes,4,opt,name=name,proto3,oneof" json:"name,omitempty"` //name + Icon *string `protobuf:"bytes,5,opt,name=icon,proto3,oneof" json:"icon,omitempty"` //icon + Category *string `protobuf:"bytes,6,opt,name=category,proto3,oneof" json:"category,omitempty"` //category + SortOrder *int64 `protobuf:"varint,7,opt,name=sortOrder,proto3,oneof" json:"sortOrder,omitempty"` //sortOrder + IsActive *bool `protobuf:"varint,8,opt,name=isActive,proto3,oneof" json:"isActive,omitempty"` //isActive + CreatedAt *int64 `protobuf:"varint,9,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + UpdatedAt *int64 `protobuf:"varint,10,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -622,50 +622,50 @@ func (x *SearchGamesReq) GetId() int64 { } func (x *SearchGamesReq) GetName() string { - if x != nil { - return x.Name + if x != nil && x.Name != nil { + return *x.Name } return "" } func (x *SearchGamesReq) GetIcon() string { - if x != nil { - return x.Icon + if x != nil && x.Icon != nil { + return *x.Icon } return "" } func (x *SearchGamesReq) GetCategory() string { - if x != nil { - return x.Category + if x != nil && x.Category != nil { + return *x.Category } return "" } func (x *SearchGamesReq) GetSortOrder() int64 { - if x != nil { - return x.SortOrder + if x != nil && x.SortOrder != nil { + return *x.SortOrder } return 0 } func (x *SearchGamesReq) GetIsActive() bool { - if x != nil { - return x.IsActive + if x != nil && x.IsActive != nil { + return *x.IsActive } return false } func (x *SearchGamesReq) GetCreatedAt() int64 { - if x != nil { - return x.CreatedAt + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt } return 0 } func (x *SearchGamesReq) GetUpdatedAt() int64 { - if x != nil { - return x.UpdatedAt + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt } return 0 } @@ -754,22 +754,32 @@ const file_game_proto_rawDesc = "" + "\x0fGetGamesByIdReq\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\"3\n" + "\x10GetGamesByIdResp\x12\x1f\n" + - "\x05games\x18\x01 \x01(\v2\t.pb.GamesR\x05games\"\x84\x02\n" + + "\x05games\x18\x01 \x01(\v2\t.pb.GamesR\x05games\"\xfd\x02\n" + "\x0eSearchGamesReq\x12\x12\n" + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x0e\n" + - "\x02id\x18\x03 \x01(\x03R\x02id\x12\x12\n" + - "\x04name\x18\x04 \x01(\tR\x04name\x12\x12\n" + - "\x04icon\x18\x05 \x01(\tR\x04icon\x12\x1a\n" + - "\bcategory\x18\x06 \x01(\tR\bcategory\x12\x1c\n" + - "\tsortOrder\x18\a \x01(\x03R\tsortOrder\x12\x1a\n" + - "\bisActive\x18\b \x01(\bR\bisActive\x12\x1c\n" + - "\tcreatedAt\x18\t \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\x02id\x18\x03 \x01(\x03R\x02id\x12\x17\n" + + "\x04name\x18\x04 \x01(\tH\x00R\x04name\x88\x01\x01\x12\x17\n" + + "\x04icon\x18\x05 \x01(\tH\x01R\x04icon\x88\x01\x01\x12\x1f\n" + + "\bcategory\x18\x06 \x01(\tH\x02R\bcategory\x88\x01\x01\x12!\n" + + "\tsortOrder\x18\a \x01(\x03H\x03R\tsortOrder\x88\x01\x01\x12\x1f\n" + + "\bisActive\x18\b \x01(\bH\x04R\bisActive\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\t \x01(\x03H\x05R\tcreatedAt\x88\x01\x01\x12!\n" + "\tupdatedAt\x18\n" + - " \x01(\x03R\tupdatedAt\"2\n" + + " \x01(\x03H\x06R\tupdatedAt\x88\x01\x01B\a\n" + + "\x05_nameB\a\n" + + "\x05_iconB\v\n" + + "\t_categoryB\f\n" + + "\n" + + "_sortOrderB\v\n" + + "\t_isActiveB\f\n" + + "\n" + + "_createdAtB\f\n" + + "\n" + + "_updatedAt\"2\n" + "\x0fSearchGamesResp\x12\x1f\n" + - "\x05games\x18\x01 \x03(\v2\t.pb.GamesR\x05games2\x91\x02\n" + - "\x06public\x12-\n" + + "\x05games\x18\x01 \x03(\v2\t.pb.GamesR\x05games2\x96\x02\n" + + "\vGameService\x12-\n" + "\bAddGames\x12\x0f.pb.AddGamesReq\x1a\x10.pb.AddGamesResp\x126\n" + "\vUpdateGames\x12\x12.pb.UpdateGamesReq\x1a\x13.pb.UpdateGamesResp\x12-\n" + "\bDelGames\x12\x0f.pb.DelGamesReq\x1a\x10.pb.DelGamesResp\x129\n" + @@ -805,16 +815,16 @@ var file_game_proto_goTypes = []any{ var file_game_proto_depIdxs = []int32{ 0, // 0: pb.GetGamesByIdResp.games:type_name -> pb.Games 0, // 1: pb.SearchGamesResp.games:type_name -> pb.Games - 1, // 2: pb.public.AddGames:input_type -> pb.AddGamesReq - 3, // 3: pb.public.UpdateGames:input_type -> pb.UpdateGamesReq - 5, // 4: pb.public.DelGames:input_type -> pb.DelGamesReq - 7, // 5: pb.public.GetGamesById:input_type -> pb.GetGamesByIdReq - 9, // 6: pb.public.SearchGames:input_type -> pb.SearchGamesReq - 2, // 7: pb.public.AddGames:output_type -> pb.AddGamesResp - 4, // 8: pb.public.UpdateGames:output_type -> pb.UpdateGamesResp - 6, // 9: pb.public.DelGames:output_type -> pb.DelGamesResp - 8, // 10: pb.public.GetGamesById:output_type -> pb.GetGamesByIdResp - 10, // 11: pb.public.SearchGames:output_type -> pb.SearchGamesResp + 1, // 2: pb.GameService.AddGames:input_type -> pb.AddGamesReq + 3, // 3: pb.GameService.UpdateGames:input_type -> pb.UpdateGamesReq + 5, // 4: pb.GameService.DelGames:input_type -> pb.DelGamesReq + 7, // 5: pb.GameService.GetGamesById:input_type -> pb.GetGamesByIdReq + 9, // 6: pb.GameService.SearchGames:input_type -> pb.SearchGamesReq + 2, // 7: pb.GameService.AddGames:output_type -> pb.AddGamesResp + 4, // 8: pb.GameService.UpdateGames:output_type -> pb.UpdateGamesResp + 6, // 9: pb.GameService.DelGames:output_type -> pb.DelGamesResp + 8, // 10: pb.GameService.GetGamesById:output_type -> pb.GetGamesByIdResp + 10, // 11: pb.GameService.SearchGames:output_type -> pb.SearchGamesResp 7, // [7:12] is the sub-list for method output_type 2, // [2:7] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name @@ -827,6 +837,7 @@ func file_game_proto_init() { if File_game_proto != nil { return } + file_game_proto_msgTypes[9].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ diff --git a/app/game/rpc/pb/game_grpc.pb.go b/app/game/rpc/pb/game_grpc.pb.go index f29e9b8..53ec847 100644 --- a/app/game/rpc/pb/game_grpc.pb.go +++ b/app/game/rpc/pb/game_grpc.pb.go @@ -19,17 +19,17 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - Public_AddGames_FullMethodName = "/pb.public/AddGames" - Public_UpdateGames_FullMethodName = "/pb.public/UpdateGames" - Public_DelGames_FullMethodName = "/pb.public/DelGames" - Public_GetGamesById_FullMethodName = "/pb.public/GetGamesById" - Public_SearchGames_FullMethodName = "/pb.public/SearchGames" + GameService_AddGames_FullMethodName = "/pb.GameService/AddGames" + GameService_UpdateGames_FullMethodName = "/pb.GameService/UpdateGames" + GameService_DelGames_FullMethodName = "/pb.GameService/DelGames" + GameService_GetGamesById_FullMethodName = "/pb.GameService/GetGamesById" + GameService_SearchGames_FullMethodName = "/pb.GameService/SearchGames" ) -// PublicClient is the client API for Public service. +// GameServiceClient is the client API for GameService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type PublicClient interface { +type GameServiceClient interface { // -----------------------games----------------------- AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) @@ -38,236 +38,236 @@ type PublicClient interface { SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) } -type publicClient struct { +type gameServiceClient struct { cc grpc.ClientConnInterface } -func NewPublicClient(cc grpc.ClientConnInterface) PublicClient { - return &publicClient{cc} +func NewGameServiceClient(cc grpc.ClientConnInterface) GameServiceClient { + return &gameServiceClient{cc} } -func (c *publicClient) AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) { +func (c *gameServiceClient) AddGames(ctx context.Context, in *AddGamesReq, opts ...grpc.CallOption) (*AddGamesResp, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(AddGamesResp) - err := c.cc.Invoke(ctx, Public_AddGames_FullMethodName, in, out, cOpts...) + err := c.cc.Invoke(ctx, GameService_AddGames_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } -func (c *publicClient) UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) { +func (c *gameServiceClient) UpdateGames(ctx context.Context, in *UpdateGamesReq, opts ...grpc.CallOption) (*UpdateGamesResp, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(UpdateGamesResp) - err := c.cc.Invoke(ctx, Public_UpdateGames_FullMethodName, in, out, cOpts...) + err := c.cc.Invoke(ctx, GameService_UpdateGames_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } -func (c *publicClient) DelGames(ctx context.Context, in *DelGamesReq, opts ...grpc.CallOption) (*DelGamesResp, error) { +func (c *gameServiceClient) DelGames(ctx context.Context, in *DelGamesReq, opts ...grpc.CallOption) (*DelGamesResp, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(DelGamesResp) - err := c.cc.Invoke(ctx, Public_DelGames_FullMethodName, in, out, cOpts...) + err := c.cc.Invoke(ctx, GameService_DelGames_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } -func (c *publicClient) GetGamesById(ctx context.Context, in *GetGamesByIdReq, opts ...grpc.CallOption) (*GetGamesByIdResp, error) { +func (c *gameServiceClient) GetGamesById(ctx context.Context, in *GetGamesByIdReq, opts ...grpc.CallOption) (*GetGamesByIdResp, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetGamesByIdResp) - err := c.cc.Invoke(ctx, Public_GetGamesById_FullMethodName, in, out, cOpts...) + err := c.cc.Invoke(ctx, GameService_GetGamesById_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } -func (c *publicClient) SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) { +func (c *gameServiceClient) SearchGames(ctx context.Context, in *SearchGamesReq, opts ...grpc.CallOption) (*SearchGamesResp, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SearchGamesResp) - err := c.cc.Invoke(ctx, Public_SearchGames_FullMethodName, in, out, cOpts...) + err := c.cc.Invoke(ctx, GameService_SearchGames_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } -// PublicServer is the server API for Public service. -// All implementations must embed UnimplementedPublicServer +// GameServiceServer is the server API for GameService service. +// All implementations must embed UnimplementedGameServiceServer // for forward compatibility. -type PublicServer interface { +type GameServiceServer interface { // -----------------------games----------------------- AddGames(context.Context, *AddGamesReq) (*AddGamesResp, error) UpdateGames(context.Context, *UpdateGamesReq) (*UpdateGamesResp, error) DelGames(context.Context, *DelGamesReq) (*DelGamesResp, error) GetGamesById(context.Context, *GetGamesByIdReq) (*GetGamesByIdResp, error) SearchGames(context.Context, *SearchGamesReq) (*SearchGamesResp, error) - mustEmbedUnimplementedPublicServer() + mustEmbedUnimplementedGameServiceServer() } -// UnimplementedPublicServer must be embedded to have +// UnimplementedGameServiceServer must be embedded to have // forward compatible implementations. // // NOTE: this should be embedded by value instead of pointer to avoid a nil // pointer dereference when methods are called. -type UnimplementedPublicServer struct{} +type UnimplementedGameServiceServer struct{} -func (UnimplementedPublicServer) AddGames(context.Context, *AddGamesReq) (*AddGamesResp, error) { +func (UnimplementedGameServiceServer) AddGames(context.Context, *AddGamesReq) (*AddGamesResp, error) { return nil, status.Error(codes.Unimplemented, "method AddGames not implemented") } -func (UnimplementedPublicServer) UpdateGames(context.Context, *UpdateGamesReq) (*UpdateGamesResp, error) { +func (UnimplementedGameServiceServer) UpdateGames(context.Context, *UpdateGamesReq) (*UpdateGamesResp, error) { return nil, status.Error(codes.Unimplemented, "method UpdateGames not implemented") } -func (UnimplementedPublicServer) DelGames(context.Context, *DelGamesReq) (*DelGamesResp, error) { +func (UnimplementedGameServiceServer) DelGames(context.Context, *DelGamesReq) (*DelGamesResp, error) { return nil, status.Error(codes.Unimplemented, "method DelGames not implemented") } -func (UnimplementedPublicServer) GetGamesById(context.Context, *GetGamesByIdReq) (*GetGamesByIdResp, error) { +func (UnimplementedGameServiceServer) GetGamesById(context.Context, *GetGamesByIdReq) (*GetGamesByIdResp, error) { return nil, status.Error(codes.Unimplemented, "method GetGamesById not implemented") } -func (UnimplementedPublicServer) SearchGames(context.Context, *SearchGamesReq) (*SearchGamesResp, error) { +func (UnimplementedGameServiceServer) SearchGames(context.Context, *SearchGamesReq) (*SearchGamesResp, error) { return nil, status.Error(codes.Unimplemented, "method SearchGames not implemented") } -func (UnimplementedPublicServer) mustEmbedUnimplementedPublicServer() {} -func (UnimplementedPublicServer) testEmbeddedByValue() {} +func (UnimplementedGameServiceServer) mustEmbedUnimplementedGameServiceServer() {} +func (UnimplementedGameServiceServer) testEmbeddedByValue() {} -// UnsafePublicServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to PublicServer will +// UnsafeGameServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to GameServiceServer will // result in compilation errors. -type UnsafePublicServer interface { - mustEmbedUnimplementedPublicServer() +type UnsafeGameServiceServer interface { + mustEmbedUnimplementedGameServiceServer() } -func RegisterPublicServer(s grpc.ServiceRegistrar, srv PublicServer) { - // If the following call panics, it indicates UnimplementedPublicServer was +func RegisterGameServiceServer(s grpc.ServiceRegistrar, srv GameServiceServer) { + // If the following call panics, it indicates UnimplementedGameServiceServer was // embedded by pointer and is nil. This will cause panics if an // unimplemented method is ever invoked, so we test this at initialization // time to prevent it from happening at runtime later due to I/O. if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { t.testEmbeddedByValue() } - s.RegisterService(&Public_ServiceDesc, srv) + s.RegisterService(&GameService_ServiceDesc, srv) } -func _Public_AddGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _GameService_AddGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddGamesReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(PublicServer).AddGames(ctx, in) + return srv.(GameServiceServer).AddGames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: Public_AddGames_FullMethodName, + FullMethod: GameService_AddGames_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublicServer).AddGames(ctx, req.(*AddGamesReq)) + return srv.(GameServiceServer).AddGames(ctx, req.(*AddGamesReq)) } return interceptor(ctx, in, info, handler) } -func _Public_UpdateGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _GameService_UpdateGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UpdateGamesReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(PublicServer).UpdateGames(ctx, in) + return srv.(GameServiceServer).UpdateGames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: Public_UpdateGames_FullMethodName, + FullMethod: GameService_UpdateGames_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublicServer).UpdateGames(ctx, req.(*UpdateGamesReq)) + return srv.(GameServiceServer).UpdateGames(ctx, req.(*UpdateGamesReq)) } return interceptor(ctx, in, info, handler) } -func _Public_DelGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _GameService_DelGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DelGamesReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(PublicServer).DelGames(ctx, in) + return srv.(GameServiceServer).DelGames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: Public_DelGames_FullMethodName, + FullMethod: GameService_DelGames_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublicServer).DelGames(ctx, req.(*DelGamesReq)) + return srv.(GameServiceServer).DelGames(ctx, req.(*DelGamesReq)) } return interceptor(ctx, in, info, handler) } -func _Public_GetGamesById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _GameService_GetGamesById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetGamesByIdReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(PublicServer).GetGamesById(ctx, in) + return srv.(GameServiceServer).GetGamesById(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: Public_GetGamesById_FullMethodName, + FullMethod: GameService_GetGamesById_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublicServer).GetGamesById(ctx, req.(*GetGamesByIdReq)) + return srv.(GameServiceServer).GetGamesById(ctx, req.(*GetGamesByIdReq)) } return interceptor(ctx, in, info, handler) } -func _Public_SearchGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _GameService_SearchGames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SearchGamesReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(PublicServer).SearchGames(ctx, in) + return srv.(GameServiceServer).SearchGames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: Public_SearchGames_FullMethodName, + FullMethod: GameService_SearchGames_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublicServer).SearchGames(ctx, req.(*SearchGamesReq)) + return srv.(GameServiceServer).SearchGames(ctx, req.(*SearchGamesReq)) } return interceptor(ctx, in, info, handler) } -// Public_ServiceDesc is the grpc.ServiceDesc for Public service. +// GameService_ServiceDesc is the grpc.ServiceDesc for GameService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) -var Public_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "pb.public", - HandlerType: (*PublicServer)(nil), +var GameService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.GameService", + HandlerType: (*GameServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "AddGames", - Handler: _Public_AddGames_Handler, + Handler: _GameService_AddGames_Handler, }, { MethodName: "UpdateGames", - Handler: _Public_UpdateGames_Handler, + Handler: _GameService_UpdateGames_Handler, }, { MethodName: "DelGames", - Handler: _Public_DelGames_Handler, + Handler: _GameService_DelGames_Handler, }, { MethodName: "GetGamesById", - Handler: _Public_GetGamesById_Handler, + Handler: _GameService_GetGamesById_Handler, }, { MethodName: "SearchGames", - Handler: _Public_SearchGames_Handler, + Handler: _GameService_SearchGames_Handler, }, }, Streams: []grpc.StreamDesc{}, diff --git a/app/objectstory/api/etc/file-api.yaml b/app/objectstory/api/etc/file-api.yaml index 3c8f6d1..231a795 100644 --- a/app/objectstory/api/etc/file-api.yaml +++ b/app/objectstory/api/etc/file-api.yaml @@ -2,5 +2,16 @@ Name: file-api Host: 0.0.0.0 Port: 8888 +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + + FileRpcConf: Target: k8s://juwan/objectstory-rpc-svc:8080 +# +#Log: +# Level: info +# k8s://juwan/:8080 + diff --git a/app/objectstory/api/internal/config/config.go b/app/objectstory/api/internal/config/config.go index 243e22d..ba4b4f3 100644 --- a/app/objectstory/api/internal/config/config.go +++ b/app/objectstory/api/internal/config/config.go @@ -11,8 +11,8 @@ import ( type Config struct { rest.RestConf FileRpcConf zrpc.RpcClientConf - Logger struct { - AccessSecret string - AccessExpire int64 - } + //Logger struct { + // AccessSecret string + // AccessExpire int64 + //} } diff --git a/app/objectstory/api/internal/handler/routes.go b/app/objectstory/api/internal/handler/routes.go index 63c042e..ebe5e60 100644 --- a/app/objectstory/api/internal/handler/routes.go +++ b/app/objectstory/api/internal/handler/routes.go @@ -31,7 +31,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { }, }..., ), - rest.WithJwt(serverCtx.Config.Logger.AccessSecret), rest.WithPrefix("/api/v1"), ) } diff --git a/app/objectstory/api/internal/logic/file/getFileLogic.go b/app/objectstory/api/internal/logic/file/getFileLogic.go index 8204aba..9688dac 100644 --- a/app/objectstory/api/internal/logic/file/getFileLogic.go +++ b/app/objectstory/api/internal/logic/file/getFileLogic.go @@ -11,7 +11,7 @@ import ( "juwan-backend/app/objectstory/api/internal/svc" "juwan-backend/app/objectstory/api/internal/types" "juwan-backend/app/objectstory/rpc/fileservice" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -36,9 +36,9 @@ func (l *GetFileLogic) GetFile(req *types.GetFileReq) (string, error) { return "", errors.New("file id is required") } - userID, err := contextx.UserIDFrom(l.ctx) + userID, err := contextj.UserIDFrom(l.ctx) if err != nil { - return "", contextx.ERRILLEGALUSER + return "", contextj.ERRILLEGALUSER } rpcResp, err := l.svcCtx.FileRpc.GetFileUrl(l.ctx, &fileservice.GetFileUrlReq{ diff --git a/app/objectstory/api/internal/logic/file/uploadLogic.go b/app/objectstory/api/internal/logic/file/uploadLogic.go index af5808b..8480dc4 100644 --- a/app/objectstory/api/internal/logic/file/uploadLogic.go +++ b/app/objectstory/api/internal/logic/file/uploadLogic.go @@ -13,7 +13,7 @@ import ( "juwan-backend/app/objectstory/api/internal/svc" "juwan-backend/app/objectstory/api/internal/types" "juwan-backend/app/objectstory/rpc/fileservice" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -42,7 +42,13 @@ func (l *UploadLogic) Upload(req *types.UploadReq, r *http.Request) (resp *types if err != nil { return nil, errors.New("file is required") } - defer file.Close() + defer func() { + err := file.Close() + if err != nil { + logx.Errorf("failed to close file: %v", err) + return + } + }() fileData, err := io.ReadAll(file) if err != nil { @@ -52,9 +58,9 @@ func (l *UploadLogic) Upload(req *types.UploadReq, r *http.Request) (resp *types return nil, errors.New("empty file is not allowed") } - userID, err := contextx.UserIDFrom(l.ctx) + userID, err := contextj.UserIDFrom(l.ctx) if err != nil { - return nil, contextx.ERRILLEGALUSER + return nil, contextj.ERRILLEGALUSER } rpcResp, err := l.svcCtx.FileRpc.Upload(l.ctx, &fileservice.UploadFileMetadataReq{ diff --git a/app/objectstory/api/objectstory.go b/app/objectstory/api/objectstory.go new file mode 100644 index 0000000..87302be --- /dev/null +++ b/app/objectstory/api/objectstory.go @@ -0,0 +1,34 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/objectstory/api/internal/config" + "juwan-backend/app/objectstory/api/internal/handler" + "juwan-backend/app/objectstory/api/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/file-api.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/app/objectstory/rpc/etc/file.yaml b/app/objectstory/rpc/etc/file.yaml index cc87957..5006916 100644 --- a/app/objectstory/rpc/etc/file.yaml +++ b/app/objectstory/rpc/etc/file.yaml @@ -22,19 +22,19 @@ S3Conf: Region: auto UsePathStyle: true -DB: - Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" - Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" - -CacheConf: - - Host: "${REDIS_M_HOST}" - Type: node - Pass: "${REDIS_PASSWORD}" - User: "default" - - Host: "${REDIS_S_HOST}" - Type: node - Pass: "${REDIS_PASSWORD}" - User: "default" - +#DB: +# Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" +# Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" +# +#CacheConf: +# - Host: "${REDIS_M_HOST}" +# Type: node +# Pass: "${REDIS_PASSWORD}" +# User: "default" +# - Host: "${REDIS_S_HOST}" +# Type: node +# Pass: "${REDIS_PASSWORD}" +# User: "default" +# Log: Level: info diff --git a/app/objectstory/rpc/file.go b/app/objectstory/rpc/pb.go similarity index 100% rename from app/objectstory/rpc/file.go rename to app/objectstory/rpc/pb.go diff --git a/app/order/api/etc/order-api.yaml b/app/order/api/etc/order-api.yaml new file mode 100644 index 0000000..aec1927 --- /dev/null +++ b/app/order/api/etc/order-api.yaml @@ -0,0 +1,19 @@ +Name: order-api +Host: 0.0.0.0 +Port: 8888 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# k8s://juwan/:8080 +OrderRpcConf: + Target: k8s://juwan/order-rpc-svc:8080 + +PlayerRpcConf: + Target: k8s://juwan/player-rpc-svc:8080 + +ShopRpcConf: + Target: k8s://juwan/shop-rpc-svc:8080 + diff --git a/app/order/api/internal/config/config.go b/app/order/api/internal/config/config.go new file mode 100644 index 0000000..0b938c3 --- /dev/null +++ b/app/order/api/internal/config/config.go @@ -0,0 +1,16 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package config + +import ( + "github.com/zeromicro/go-zero/rest" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + rest.RestConf + OrderRpcConf zrpc.RpcClientConf + PlayerRpcConf zrpc.RpcClientConf + ShopRpcConf zrpc.RpcClientConf +} diff --git a/app/order/api/internal/handler/order/acceptOrderHandler.go b/app/order/api/internal/handler/order/acceptOrderHandler.go new file mode 100644 index 0000000..8c67293 --- /dev/null +++ b/app/order/api/internal/handler/order/acceptOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 接单 +func AcceptOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewAcceptOrderLogic(r.Context(), svcCtx) + resp, err := l.AcceptOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/cancelOrderHandler.go b/app/order/api/internal/handler/order/cancelOrderHandler.go new file mode 100644 index 0000000..37d0133 --- /dev/null +++ b/app/order/api/internal/handler/order/cancelOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 取消订单 +func CancelOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewCancelOrderLogic(r.Context(), svcCtx) + resp, err := l.CancelOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/confirmCloseOrderHandler.go b/app/order/api/internal/handler/order/confirmCloseOrderHandler.go new file mode 100644 index 0000000..c3cd3b7 --- /dev/null +++ b/app/order/api/internal/handler/order/confirmCloseOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 确认结算 +func ConfirmCloseOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewConfirmCloseOrderLogic(r.Context(), svcCtx) + resp, err := l.ConfirmCloseOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/createAndPayOrderHandler.go b/app/order/api/internal/handler/order/createAndPayOrderHandler.go new file mode 100644 index 0000000..7385989 --- /dev/null +++ b/app/order/api/internal/handler/order/createAndPayOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 创建并支付订单 +func CreateAndPayOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.CreateOrderReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewCreateAndPayOrderLogic(r.Context(), svcCtx) + resp, err := l.CreateAndPayOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/createOrderHandler.go b/app/order/api/internal/handler/order/createOrderHandler.go new file mode 100644 index 0000000..2c00763 --- /dev/null +++ b/app/order/api/internal/handler/order/createOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 创建订单 +func CreateOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.CreateOrderReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewCreateOrderLogic(r.Context(), svcCtx) + resp, err := l.CreateOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/getOrderHandler.go b/app/order/api/internal/handler/order/getOrderHandler.go new file mode 100644 index 0000000..25acf6e --- /dev/null +++ b/app/order/api/internal/handler/order/getOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 获取订单详情 +func GetOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewGetOrderLogic(r.Context(), svcCtx) + resp, err := l.GetOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/listOrdersHandler.go b/app/order/api/internal/handler/order/listOrdersHandler.go new file mode 100644 index 0000000..bd9dda3 --- /dev/null +++ b/app/order/api/internal/handler/order/listOrdersHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 获取订单列表 +func ListOrdersHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.OrderListReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewListOrdersLogic(r.Context(), svcCtx) + resp, err := l.ListOrders(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/payOrderHandler.go b/app/order/api/internal/handler/order/payOrderHandler.go new file mode 100644 index 0000000..b73f949 --- /dev/null +++ b/app/order/api/internal/handler/order/payOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 支付订单 +func PayOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewPayOrderLogic(r.Context(), svcCtx) + resp, err := l.PayOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/reorderHandler.go b/app/order/api/internal/handler/order/reorderHandler.go new file mode 100644 index 0000000..da3f02f --- /dev/null +++ b/app/order/api/internal/handler/order/reorderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 再来一单 +func ReorderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewReorderLogic(r.Context(), svcCtx) + resp, err := l.Reorder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/order/requestCloseOrderHandler.go b/app/order/api/internal/handler/order/requestCloseOrderHandler.go new file mode 100644 index 0000000..69bea72 --- /dev/null +++ b/app/order/api/internal/handler/order/requestCloseOrderHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/order/api/internal/logic/order" + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" +) + +// 申请结算 +func RequestCloseOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := order.NewRequestCloseOrderLogic(r.Context(), svcCtx) + resp, err := l.RequestCloseOrder(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/order/api/internal/handler/routes.go b/app/order/api/internal/handler/routes.go new file mode 100644 index 0000000..656bd3b --- /dev/null +++ b/app/order/api/internal/handler/routes.go @@ -0,0 +1,81 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 + +package handler + +import ( + "net/http" + + order "juwan-backend/app/order/api/internal/handler/order" + "juwan-backend/app/order/api/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + // 获取订单列表 + Method: http.MethodGet, + Path: "/", + Handler: order.ListOrdersHandler(serverCtx), + }, + { + // 创建订单 + Method: http.MethodPost, + Path: "/", + Handler: order.CreateOrderHandler(serverCtx), + }, + { + // 获取订单详情 + Method: http.MethodGet, + Path: "/:id", + Handler: order.GetOrderHandler(serverCtx), + }, + { + // 接单 + Method: http.MethodPost, + Path: "/:id/accept", + Handler: order.AcceptOrderHandler(serverCtx), + }, + { + // 取消订单 + Method: http.MethodPost, + Path: "/:id/cancel", + Handler: order.CancelOrderHandler(serverCtx), + }, + { + // 确认结算 + Method: http.MethodPost, + Path: "/:id/confirm-close", + Handler: order.ConfirmCloseOrderHandler(serverCtx), + }, + { + // 支付订单 + Method: http.MethodPost, + Path: "/:id/pay", + Handler: order.PayOrderHandler(serverCtx), + }, + { + // 再来一单 + Method: http.MethodPost, + Path: "/:id/reorder", + Handler: order.ReorderHandler(serverCtx), + }, + { + // 申请结算 + Method: http.MethodPost, + Path: "/:id/request-close", + Handler: order.RequestCloseOrderHandler(serverCtx), + }, + { + // 创建并支付订单 + Method: http.MethodPost, + Path: "/paid", + Handler: order.CreateAndPayOrderHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1/orders"), + ) +} diff --git a/app/order/api/internal/logic/order/acceptOrderLogic.go b/app/order/api/internal/logic/order/acceptOrderLogic.go new file mode 100644 index 0000000..922dbea --- /dev/null +++ b/app/order/api/internal/logic/order/acceptOrderLogic.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AcceptOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 接单 +func NewAcceptOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AcceptOrderLogic { + return &AcceptOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *AcceptOrderLogic) AcceptOrder(req *types.PathId) (resp *types.EmptyResp, err error) { + if err = transitionOrderStatus(l.ctx, l.svcCtx, req.Id, "in_progress", true, false, false, false); err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/order/api/internal/logic/order/cancelOrderLogic.go b/app/order/api/internal/logic/order/cancelOrderLogic.go new file mode 100644 index 0000000..6e009e0 --- /dev/null +++ b/app/order/api/internal/logic/order/cancelOrderLogic.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CancelOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 取消订单 +func NewCancelOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelOrderLogic { + return &CancelOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CancelOrderLogic) CancelOrder(req *types.PathId) (resp *types.EmptyResp, err error) { + if err = transitionOrderStatus(l.ctx, l.svcCtx, req.Id, "cancelled", false, false, false, true); err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/order/api/internal/logic/order/confirmCloseOrderLogic.go b/app/order/api/internal/logic/order/confirmCloseOrderLogic.go new file mode 100644 index 0000000..3c5123d --- /dev/null +++ b/app/order/api/internal/logic/order/confirmCloseOrderLogic.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ConfirmCloseOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 确认结算 +func NewConfirmCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConfirmCloseOrderLogic { + return &ConfirmCloseOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ConfirmCloseOrderLogic) ConfirmCloseOrder(req *types.PathId) (resp *types.EmptyResp, err error) { + if err = transitionOrderStatus(l.ctx, l.svcCtx, req.Id, "completed", false, true, true, false); err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/order/api/internal/logic/order/createAndPayOrderLogic.go b/app/order/api/internal/logic/order/createAndPayOrderLogic.go new file mode 100644 index 0000000..ffbee16 --- /dev/null +++ b/app/order/api/internal/logic/order/createAndPayOrderLogic.go @@ -0,0 +1,48 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + + "juwan-backend/app/order/rpc/orderservice" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CreateAndPayOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 创建并支付订单 +func NewCreateAndPayOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAndPayOrderLogic { + return &CreateAndPayOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CreateAndPayOrderLogic) CreateAndPayOrder(req *types.CreateOrderReq) (resp *types.CreateOrderResp, err error) { + created, err := NewCreateOrderLogic(l.ctx, l.svcCtx).CreateOrder(req) + if err != nil { + return nil, err + } + + if err = transitionOrderStatus(l.ctx, l.svcCtx, created.Order.Id, "pending_accept", false, false, false, false); err != nil { + return nil, err + } + + latest, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: created.Order.Id}) + if err != nil { + return nil, err + } + + return &types.CreateOrderResp{Ok: true, Order: toAPIOrder(latest.GetOrders())}, nil +} diff --git a/app/order/api/internal/logic/order/createOrderLogic.go b/app/order/api/internal/logic/order/createOrderLogic.go new file mode 100644 index 0000000..62d5456 --- /dev/null +++ b/app/order/api/internal/logic/order/createOrderLogic.go @@ -0,0 +1,128 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + "encoding/json" + "errors" + "strconv" + "time" + + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/app/player/rpc/playerservice" + "juwan-backend/common/utils/contextj" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CreateOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 创建订单 +func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic { + return &CreateOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq) (resp *types.CreateOrderResp, err error) { + if req.Quantity <= 0 { + return nil, errors.New("quantity must be greater than 0") + } + + consumerID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + serviceResp, err := l.svcCtx.PlayerRpc.GetPlayerServicesById(l.ctx, &playerservice.GetPlayerServicesByIdReq{Id: req.ServiceId}) + if err != nil { + return nil, err + } + service := serviceResp.GetPlayerServices() + if service == nil { + return nil, errors.New("player service not found") + } + + if req.PlayerId > 0 && service.GetPlayerId() != req.PlayerId { + return nil, errors.New("service does not belong to player") + } + + playerID := service.GetPlayerId() + if req.PlayerId > 0 { + playerID = req.PlayerId + } + + price := service.GetPrice() + totalPrice := price * float64(req.Quantity) + totalPriceStr := strconv.FormatFloat(totalPrice, 'f', 2, 64) + + serviceSnapshot := types.PlayerService{ + Id: req.ServiceId, + PlayerId: playerID, + GameId: service.GetGameId(), + Title: service.GetTitle(), + Description: service.GetDescription(), + Price: price, + Unit: service.GetUnit(), + RankRange: service.GetRankRange(), + Availability: service.GetAvailability(), + } + snapshotBytes, err := json.Marshal(serviceSnapshot) + if err != nil { + return nil, err + } + + orderID := time.Now().UnixNano() + consumerName := strconv.FormatInt(consumerID, 10) + playerName := strconv.FormatInt(playerID, 10) + shopName := "" + if req.ShopId > 0 { + shopName = strconv.FormatInt(req.ShopId, 10) + } + now := time.Now().Unix() + status := "pending_payment" + searchText := consumerName + " " + playerName + " " + shopName + " " + req.Note + + addReq := &orderservice.AddOrdersReq{ + Id: orderID, + ConsumerId: consumerID, + ConsumerName: consumerName, + PlayerId: playerID, + PlayerName: playerName, + ServiceSnapshot: string(snapshotBytes), + Status: &status, + TotalPrice: totalPriceStr, + SearchText: &searchText, + CreatedAt: &now, + UpdatedAt: &now, + } + if req.ShopId > 0 { + addReq.ShopId = &req.ShopId + addReq.ShopName = &shopName + } + if req.Note != "" { + addReq.Note = &req.Note + } + + if _, err = l.svcCtx.OrderRpc.AddOrders(l.ctx, addReq); err != nil { + return nil, err + } + + created, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: orderID}) + if err != nil { + return nil, err + } + + return &types.CreateOrderResp{Ok: true, Order: toAPIOrder(created.GetOrders())}, nil +} diff --git a/app/order/api/internal/logic/order/getOrderLogic.go b/app/order/api/internal/logic/order/getOrderLogic.go new file mode 100644 index 0000000..e568bf7 --- /dev/null +++ b/app/order/api/internal/logic/order/getOrderLogic.go @@ -0,0 +1,40 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + + "juwan-backend/app/order/rpc/orderservice" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取订单详情 +func NewGetOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderLogic { + return &GetOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetOrderLogic) GetOrder(req *types.PathId) (resp *types.Order, err error) { + out, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + order := toAPIOrder(out.GetOrders()) + + return &order, nil +} diff --git a/app/order/api/internal/logic/order/helpers.go b/app/order/api/internal/logic/order/helpers.go new file mode 100644 index 0000000..e567430 --- /dev/null +++ b/app/order/api/internal/logic/order/helpers.go @@ -0,0 +1,114 @@ +package order + +import ( + "context" + "encoding/json" + "strconv" + "time" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/common/utils/contextj" +) + +func int64Ptr(v int64) *int64 { + return &v +} + +func stringPtr(v string) *string { + return &v +} + +func formatUnix(ts int64) string { + if ts <= 0 { + return "" + } + return time.Unix(ts, 0).UTC().Format(time.RFC3339) +} + +func toAPIOrder(in *orderservice.Orders) types.Order { + order := types.Order{} + if in == nil { + return order + } + + totalPrice, _ := strconv.ParseFloat(in.GetTotalPrice(), 64) + playerID := strconv.FormatInt(in.GetPlayerId(), 10) + service := types.PlayerService{} + _ = json.Unmarshal([]byte(in.GetServiceSnapshot()), &service) + + order = types.Order{ + Id: in.GetId(), + ConsumerId: in.GetConsumerId(), + ConsumerName: in.GetConsumerName(), + PlayerId: playerID, + PlayerName: in.GetPlayerName(), + ShopId: in.GetShopId(), + ShopName: in.GetShopName(), + Service: service, + Status: in.GetStatus(), + TotalPrice: totalPrice, + Note: in.GetNote(), + CreatedAt: formatUnix(in.GetCreatedAt()), + AcceptedAt: formatUnix(in.GetAcceptedAt()), + CompletedAt: formatUnix(in.GetCompletedAt()), + } + + return order +} + +func transitionOrderStatus(ctx context.Context, svcCtx *svc.ServiceContext, orderID int64, toStatus string, setAcceptedAt bool, setClosedAt bool, setCompletedAt bool, setCancelledAt bool) error { + current, err := svcCtx.OrderRpc.GetOrdersById(ctx, &orderservice.GetOrdersByIdReq{Id: orderID}) + if err != nil { + return err + } + if current.GetOrders() == nil { + return nil + } + + now := time.Now().Unix() + updateReq := &orderservice.UpdateOrdersReq{ + Id: orderID, + Status: stringPtr(toStatus), + UpdatedAt: int64Ptr(now), + } + if setAcceptedAt { + updateReq.AcceptedAt = int64Ptr(now) + } + if setClosedAt { + updateReq.ClosedAt = int64Ptr(now) + } + if setCompletedAt { + updateReq.CompletedAt = int64Ptr(now) + } + if setCancelledAt { + updateReq.CancelledAt = int64Ptr(now) + } + + if _, err = svcCtx.OrderRpc.UpdateOrders(ctx, updateReq); err != nil { + return err + } + + fromStatus := current.Orders.GetStatus() + actorID, _ := contextj.UserIDFrom(ctx) + actorRole := "system" + if actorID > 0 { + actorRole = "user" + } + _, err = svcCtx.OrderRpc.AddOrderStateLogs(ctx, &orderservice.AddOrderStateLogsReq{ + Id: time.Now().UnixNano(), + OrderId: orderID, + FromStatus: &fromStatus, + ToStatus: toStatus, + Action: "status_transition", + ActorId: actorID, + ActorRole: actorRole, + CreatedAt: &now, + }) + if err != nil { + return err + } + + return nil +} diff --git a/app/order/api/internal/logic/order/listOrdersLogic.go b/app/order/api/internal/logic/order/listOrdersLogic.go new file mode 100644 index 0000000..aa99ee2 --- /dev/null +++ b/app/order/api/internal/logic/order/listOrdersLogic.go @@ -0,0 +1,114 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + "strings" + + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/app/shop/rpc/shopservice" + "juwan-backend/common/utils/contextj" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListOrdersLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取订单列表 +func NewListOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListOrdersLogic { + return &ListOrdersLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListOrdersLogic) ListOrders(req *types.OrderListReq) (resp *types.OrderListResp, err error) { + searchReq := &orderservice.SearchOrdersReq{ + Page: req.Offset, + Limit: req.Limit, + } + if req.Status != "" { + searchReq.Status = &req.Status + } + + role := strings.ToLower(req.Role) + if role != "" { + uid, uidErr := contextj.UserIDFrom(l.ctx) + if uidErr != nil { + return nil, uidErr + } + switch role { + case "consumer": + searchReq.ConsumerId = &uid + case "player": + searchReq.PlayerId = &uid + case "owner": + shops, shopErr := l.svcCtx.ShopRpc.SearchShops(l.ctx, &shopservice.SearchShopsReq{ + Page: 0, + Limit: 100, + OwnerId: uid, + }) + if shopErr != nil { + return nil, shopErr + } + + items := make([]types.Order, 0) + for _, shop := range shops.GetShops() { + shopID := shop.GetId() + q := &orderservice.SearchOrdersReq{ + Page: req.Offset, + Limit: req.Limit, + ShopId: &shopID, + } + if req.Status != "" { + q.Status = &req.Status + } + out, rpcErr := l.svcCtx.OrderRpc.SearchOrders(l.ctx, q) + if rpcErr != nil { + return nil, rpcErr + } + for _, item := range out.GetOrders() { + items = append(items, toAPIOrder(item)) + } + } + + return &types.OrderListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: req.Limit, + }, + }, nil + } + } + + out, err := l.svcCtx.OrderRpc.SearchOrders(l.ctx, searchReq) + if err != nil { + return nil, err + } + + items := make([]types.Order, 0, len(out.GetOrders())) + for _, item := range out.GetOrders() { + items = append(items, toAPIOrder(item)) + } + + return &types.OrderListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: req.Limit, + }, + }, nil +} diff --git a/app/order/api/internal/logic/order/payOrderLogic.go b/app/order/api/internal/logic/order/payOrderLogic.go new file mode 100644 index 0000000..17f4909 --- /dev/null +++ b/app/order/api/internal/logic/order/payOrderLogic.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type PayOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 支付订单 +func NewPayOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayOrderLogic { + return &PayOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *PayOrderLogic) PayOrder(req *types.PathId) (resp *types.EmptyResp, err error) { + if err = transitionOrderStatus(l.ctx, l.svcCtx, req.Id, "pending_accept", false, false, false, false); err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/order/api/internal/logic/order/reorderLogic.go b/app/order/api/internal/logic/order/reorderLogic.go new file mode 100644 index 0000000..046186a --- /dev/null +++ b/app/order/api/internal/logic/order/reorderLogic.go @@ -0,0 +1,81 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + "time" + + "juwan-backend/app/order/rpc/orderservice" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ReorderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 再来一单 +func NewReorderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReorderLogic { + return &ReorderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ReorderLogic) Reorder(req *types.PathId) (resp *types.CreateOrderResp, err error) { + oldOrderResp, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + oldOrder := oldOrderResp.GetOrders() + if oldOrder == nil { + return nil, nil + } + + newID := time.Now().UnixNano() + now := time.Now().Unix() + status := "pending_payment" + searchText := oldOrder.GetSearchText() + + addReq := &orderservice.AddOrdersReq{ + Id: newID, + ConsumerId: oldOrder.GetConsumerId(), + ConsumerName: oldOrder.GetConsumerName(), + PlayerId: oldOrder.GetPlayerId(), + PlayerName: oldOrder.GetPlayerName(), + ServiceSnapshot: oldOrder.GetServiceSnapshot(), + Status: &status, + TotalPrice: oldOrder.GetTotalPrice(), + SearchText: &searchText, + CreatedAt: &now, + UpdatedAt: &now, + } + if oldOrder.ShopId != nil { + addReq.ShopId = oldOrder.ShopId + } + if oldOrder.ShopName != nil { + addReq.ShopName = oldOrder.ShopName + } + if oldOrder.Note != nil { + addReq.Note = oldOrder.Note + } + + if _, err = l.svcCtx.OrderRpc.AddOrders(l.ctx, addReq); err != nil { + return nil, err + } + + created, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: newID}) + if err != nil { + return nil, err + } + + return &types.CreateOrderResp{Ok: true, Order: toAPIOrder(created.GetOrders())}, nil +} diff --git a/app/order/api/internal/logic/order/requestCloseOrderLogic.go b/app/order/api/internal/logic/order/requestCloseOrderLogic.go new file mode 100644 index 0000000..1060393 --- /dev/null +++ b/app/order/api/internal/logic/order/requestCloseOrderLogic.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package order + +import ( + "context" + + "juwan-backend/app/order/api/internal/svc" + "juwan-backend/app/order/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type RequestCloseOrderLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 申请结算 +func NewRequestCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RequestCloseOrderLogic { + return &RequestCloseOrderLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *RequestCloseOrderLogic) RequestCloseOrder(req *types.PathId) (resp *types.EmptyResp, err error) { + if err = transitionOrderStatus(l.ctx, l.svcCtx, req.Id, "pending_close", false, false, false, false); err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/order/api/internal/svc/serviceContext.go b/app/order/api/internal/svc/serviceContext.go new file mode 100644 index 0000000..a8a519d --- /dev/null +++ b/app/order/api/internal/svc/serviceContext.go @@ -0,0 +1,29 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package svc + +import ( + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/app/player/rpc/playerservice" + "juwan-backend/app/shop/rpc/shopservice" + "juwan-backend/app/order/api/internal/config" + + "github.com/zeromicro/go-zero/zrpc" +) + +type ServiceContext struct { + Config config.Config + OrderRpc orderservice.OrderService + PlayerRpc playerservice.PlayerService + ShopRpc shopservice.ShopService +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + OrderRpc: orderservice.NewOrderService(zrpc.MustNewClient(c.OrderRpcConf)), + PlayerRpc: playerservice.NewPlayerService(zrpc.MustNewClient(c.PlayerRpcConf)), + ShopRpc: shopservice.NewShopService(zrpc.MustNewClient(c.ShopRpcConf)), + } +} diff --git a/app/order/api/internal/types/types.go b/app/order/api/internal/types/types.go new file mode 100644 index 0000000..aa3bb76 --- /dev/null +++ b/app/order/api/internal/types/types.go @@ -0,0 +1,95 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 + +package types + +type CreateOrderReq struct { + PlayerId int64 `json:"playerId"` + ShopId int64 `json:"shopId,optional"` + ServiceId int64 `json:"serviceId"` + Quantity int `json:"quantity"` + Note string `json:"note,optional"` +} + +type CreateOrderResp struct { + Ok bool `json:"ok"` + Order Order `json:"order"` +} + +type EmptyResp struct { +} + +type Order struct { + Id int64 `json:"id"` + ConsumerId int64 `json:"consumerId"` + ConsumerName string `json:"consumerName"` + PlayerId string `json:"playerId"` + PlayerName string `json:"playerName"` + ShopId int64 `json:"shopId,optional"` + ShopName string `json:"shopName,optional"` + Service PlayerService `json:"service"` + Status string `json:"status"` + TotalPrice float64 `json:"totalPrice"` + Note string `json:"note,optional"` + CreatedAt string `json:"createdAt"` + AcceptedAt string `json:"acceptedAt,optional"` + CompletedAt string `json:"completedAt,optional"` +} + +type OrderListReq struct { + PageReq + Role string `form:"role"` + Status string `form:"status,optional"` +} + +type OrderListResp struct { + Items []Order `json:"items"` + Meta PageMeta `json:"meta"` +} + +type PageMeta struct { + Total int64 `json:"total"` + Offset int64 `json:"offset"` + Limit int64 `json:"limit"` +} + +type PageReq struct { + Offset int64 `form:"offset,default=0"` + Limit int64 `form:"limit,default=20"` +} + +type PathId struct { + Id int64 `path:"id"` +} + +type PlayerService struct { + Id int64 `json:"id"` + PlayerId int64 `json:"playerId"` + GameId int64 `json:"gameId"` + GameName string `json:"gameName"` + Title string `json:"title"` + Description string `json:"description"` + Price float64 `json:"price"` + Unit string `json:"unit"` + RankRange string `json:"rankRange,optional"` + Availability []string `json:"availability"` +} + +type SimpleUser struct { + Id string `json:"id"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` +} + +type UserProfile struct { + Id string `json:"id"` + Username string `json:"username"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` + Role string `json:"role"` // consumer, player, owner, admin + VerifiedRoles []string `json:"verifiedRoles"` + VerificationStatus map[string]string `json:"verificationStatus"` + Phone string `json:"phone,optional"` + Bio string `json:"bio,optional"` + CreatedAt string `json:"createdAt"` +} diff --git a/app/users/api/user.go b/app/order/api/order.go similarity index 69% rename from app/users/api/user.go rename to app/order/api/order.go index b023a60..80cd304 100644 --- a/app/users/api/user.go +++ b/app/order/api/order.go @@ -7,15 +7,15 @@ import ( "flag" "fmt" - "juwan-backend/app/users/api/internal/config" - "juwan-backend/app/users/api/internal/handler" - "juwan-backend/app/users/api/internal/svc" + "juwan-backend/app/order/api/internal/config" + "juwan-backend/app/order/api/internal/handler" + "juwan-backend/app/order/api/internal/svc" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" ) -var configFile = flag.String("f", "etc/user-api.yaml", "the config file") +var configFile = flag.String("f", "etc/order-api.yaml", "the config file") func main() { flag.Parse() diff --git a/app/order/rpc/etc/pb.yaml b/app/order/rpc/etc/pb.yaml new file mode 100644 index 0000000..9e44d04 --- /dev/null +++ b/app/order/rpc/etc/pb.yaml @@ -0,0 +1,38 @@ +Name: pb.rpc +ListenOn: 0.0.0.0:8080 + + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# tcd: +# Hosts: +# - 127.0.0.1:2379 +# Key: pb.rpc + +# Target: k8s://juwan/.:8080 + + +SnowflakeRpcConf: + Target: k8s://juwan/snowflake-svc:8080 + + +DB: + Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + + +CacheConf: + - Host: "${REDIS_M_HOST}" + Type: node + Pass: "${REDIS_PASSWORD}" + User: "default" + - Host: "${REDIS_S_HOST}" + Type: node + Pass: "${REDIS_PASSWORD}" + User: "default" + +Log: + Level: info diff --git a/app/order/rpc/internal/config/config.go b/app/order/rpc/internal/config/config.go new file mode 100644 index 0000000..faeb55a --- /dev/null +++ b/app/order/rpc/internal/config/config.go @@ -0,0 +1,17 @@ +package config + +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + zrpc.RpcServerConf + + SnowflakeRpcConf zrpc.RpcClientConf + DB struct { + Master string + Slaves string + } + CacheConf cache.CacheConf +} diff --git a/app/order/rpc/internal/logic/addOrderStateLogsLogic.go b/app/order/rpc/internal/logic/addOrderStateLogsLogic.go new file mode 100644 index 0000000..413dd0c --- /dev/null +++ b/app/order/rpc/internal/logic/addOrderStateLogsLogic.go @@ -0,0 +1,61 @@ +package logic + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddOrderStateLogsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddOrderStateLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrderStateLogsLogic { + return &AddOrderStateLogsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------orderStateLogs----------------------- +func (l *AddOrderStateLogsLogic) AddOrderStateLogs(in *pb.AddOrderStateLogsReq) (*pb.AddOrderStateLogsResp, error) { + if in == nil { + return nil, errors.New("order state log is required") + } + + builder := l.svcCtx.OrderModelsRW.OrderStateLogs.Create(). + SetID(in.Id). + SetOrderID(in.OrderId). + SetToStatus(in.ToStatus). + SetAction(in.Action). + SetActorID(in.ActorId). + SetActorRole(in.ActorRole) + + if in.FromStatus != nil { + builder = builder.SetFromStatus(*in.FromStatus) + } + if in.Metadata != nil { + metadata, err := parseJSONMap(*in.Metadata) + if err != nil { + return nil, err + } + builder = builder.SetMetadata(metadata) + } + if in.CreatedAt != nil { + builder = builder.SetCreatedAt(time.Unix(*in.CreatedAt, 0)) + } + + if _, err := builder.Save(l.ctx); err != nil { + return nil, err + } + + return &pb.AddOrderStateLogsResp{}, nil +} diff --git a/app/order/rpc/internal/logic/addOrdersLogic.go b/app/order/rpc/internal/logic/addOrdersLogic.go new file mode 100644 index 0000000..c09d9ff --- /dev/null +++ b/app/order/rpc/internal/logic/addOrdersLogic.go @@ -0,0 +1,107 @@ +package logic + +import ( + "context" + "errors" + "time" + + "github.com/shopspring/decimal" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddOrdersLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrdersLogic { + return &AddOrdersLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------orders----------------------- +func (l *AddOrdersLogic) AddOrders(in *pb.AddOrdersReq) (*pb.AddOrdersResp, error) { + orderID := in.Id + if orderID <= 0 { + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, err + } + orderID = idResp.Id + } + + totalPrice, err := parseDecimal(in.GetTotalPrice()) + if err != nil || totalPrice.Cmp(decimal.Zero) <= 0 { + return nil, errors.New("invalid total price") + } + + serviceSnapshot, err := parseJSONMap(in.GetServiceSnapshot()) + if err != nil { + return nil, err + } + + creator := l.svcCtx.OrderModelsRW.Orders.Create(). + SetID(orderID). + SetConsumerID(in.ConsumerId). + SetConsumerName(in.ConsumerName). + SetPlayerID(in.PlayerId). + SetPlayerName(in.PlayerName). + SetServiceSnapshot(serviceSnapshot). + SetTotalPrice(totalPrice) + + if in.ShopId != nil { + creator = creator.SetShopID(*in.ShopId) + } + if in.ShopName != nil { + creator = creator.SetShopName(*in.ShopName) + } + if in.Status != nil && *in.Status != "" { + creator = creator.SetStatus(*in.Status) + } + if in.Note != nil { + creator = creator.SetNote(*in.Note) + } + if in.Version != nil { + creator = creator.SetVersion(int(*in.Version)) + } + if in.TimeoutJobId != nil { + creator = creator.SetTimeoutJobID(*in.TimeoutJobId) + } + if in.SearchText != nil { + creator = creator.SetSearchText(*in.SearchText) + } + if createdAt := unixPtr(in.CreatedAt); createdAt != nil { + creator = creator.SetCreatedAt(*createdAt) + } + if acceptedAt := unixPtr(in.AcceptedAt); acceptedAt != nil { + creator = creator.SetAcceptedAt(*acceptedAt) + } + if closedAt := unixPtr(in.ClosedAt); closedAt != nil { + creator = creator.SetClosedAt(*closedAt) + } + if completedAt := unixPtr(in.CompletedAt); completedAt != nil { + creator = creator.SetCompletedAt(*completedAt) + } + if cancelledAt := unixPtr(in.CancelledAt); cancelledAt != nil { + creator = creator.SetCancelledAt(*cancelledAt) + } + if updatedAt := unixPtr(in.UpdatedAt); updatedAt != nil { + creator = creator.SetUpdatedAt(*updatedAt) + } else { + creator = creator.SetUpdatedAt(time.Now()) + } + + if _, err := creator.Save(l.ctx); err != nil { + return nil, err + } + + return &pb.AddOrdersResp{}, nil +} diff --git a/app/order/rpc/internal/logic/common.go b/app/order/rpc/internal/logic/common.go new file mode 100644 index 0000000..7abafd9 --- /dev/null +++ b/app/order/rpc/internal/logic/common.go @@ -0,0 +1,123 @@ +package logic + +import ( + "encoding/json" + "errors" + "time" + + "github.com/shopspring/decimal" + "juwan-backend/app/order/rpc/internal/models" + "juwan-backend/app/order/rpc/pb" +) + +func parseDecimal(v string) (decimal.Decimal, error) { + if v == "" { + return decimal.Zero, nil + } + d, err := decimal.NewFromString(v) + if err != nil { + return decimal.Zero, errors.New("invalid decimal value") + } + return d, nil +} + +func parseJSONMap(v string) (map[string]any, error) { + if v == "" { + return map[string]any{}, nil + } + var result map[string]any + if err := json.Unmarshal([]byte(v), &result); err != nil { + return nil, errors.New("invalid json value") + } + if result == nil { + return map[string]any{}, nil + } + return result, nil +} + +func unixPtr(v *int64) *time.Time { + if v == nil || *v <= 0 { + return nil + } + t := time.Unix(*v, 0) + return &t +} + +func toPBOrder(item *models.Orders) *pb.Orders { + serviceSnapshot := "{}" + if b, err := json.Marshal(item.ServiceSnapshot); err == nil { + serviceSnapshot = string(b) + } + + result := &pb.Orders{ + Id: item.ID, + ConsumerId: item.ConsumerID, + ConsumerName: item.ConsumerName, + PlayerId: item.PlayerID, + PlayerName: item.PlayerName, + ServiceSnapshot: serviceSnapshot, + Status: item.Status, + TotalPrice: item.TotalPrice.String(), + Version: int64(item.Version), + CreatedAt: item.CreatedAt.Unix(), + UpdatedAt: item.UpdatedAt.Unix(), + } + + if item.ShopID != nil { + result.ShopId = item.ShopID + } + if item.ShopName != nil { + result.ShopName = item.ShopName + } + if item.Note != nil { + result.Note = item.Note + } + if item.TimeoutJobID != nil { + result.TimeoutJobId = item.TimeoutJobID + } + if item.SearchText != nil { + result.SearchText = *item.SearchText + } + if item.AcceptedAt != nil { + t := item.AcceptedAt.Unix() + result.AcceptedAt = &t + } + if item.ClosedAt != nil { + t := item.ClosedAt.Unix() + result.ClosedAt = &t + } + if item.CompletedAt != nil { + t := item.CompletedAt.Unix() + result.CompletedAt = &t + } + if item.CancelledAt != nil { + t := item.CancelledAt.Unix() + result.CancelledAt = &t + } + + return result +} + +func toPBOrderStateLog(item *models.OrderStateLogs) *pb.OrderStateLogs { + result := &pb.OrderStateLogs{ + Id: item.ID, + OrderId: item.OrderID, + ToStatus: item.ToStatus, + Action: item.Action, + ActorId: item.ActorID, + ActorRole: item.ActorRole, + CreatedAt: item.CreatedAt.Unix(), + } + + if item.FromStatus != nil { + result.FromStatus = item.FromStatus + } + if item.Metadata != nil { + if b, err := json.Marshal(item.Metadata); err == nil { + metadata := string(b) + result.Metadata = &metadata + } + } + + return result +} diff --git a/app/order/rpc/internal/logic/delOrderStateLogsLogic.go b/app/order/rpc/internal/logic/delOrderStateLogsLogic.go new file mode 100644 index 0000000..31850cb --- /dev/null +++ b/app/order/rpc/internal/logic/delOrderStateLogsLogic.go @@ -0,0 +1,37 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/order/rpc/internal/models" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelOrderStateLogsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelOrderStateLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelOrderStateLogsLogic { + return &DelOrderStateLogsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelOrderStateLogsLogic) DelOrderStateLogs(in *pb.DelOrderStateLogsReq) (*pb.DelOrderStateLogsResp, error) { + if err := l.svcCtx.OrderModelsRW.OrderStateLogs.DeleteOneID(in.Id).Exec(l.ctx); err != nil { + if models.IsNotFound(err) { + return nil, errors.New("order state log not found") + } + return nil, err + } + + return &pb.DelOrderStateLogsResp{}, nil +} diff --git a/app/order/rpc/internal/logic/delOrdersLogic.go b/app/order/rpc/internal/logic/delOrdersLogic.go new file mode 100644 index 0000000..93e0356 --- /dev/null +++ b/app/order/rpc/internal/logic/delOrdersLogic.go @@ -0,0 +1,32 @@ +package logic + +import ( + "context" + + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelOrdersLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelOrdersLogic { + return &DelOrdersLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelOrdersLogic) DelOrders(in *pb.DelOrdersReq) (*pb.DelOrdersResp, error) { + if err := l.svcCtx.OrderModelsRW.Orders.DeleteOneID(in.Id).Exec(l.ctx); err != nil { + return nil, err + } + + return &pb.DelOrdersResp{}, nil +} diff --git a/app/order/rpc/internal/logic/getOrderStateLogsByIdLogic.go b/app/order/rpc/internal/logic/getOrderStateLogsByIdLogic.go new file mode 100644 index 0000000..5fb7dcc --- /dev/null +++ b/app/order/rpc/internal/logic/getOrderStateLogsByIdLogic.go @@ -0,0 +1,36 @@ +package logic + +import ( + "context" + + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetOrderStateLogsByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetOrderStateLogsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderStateLogsByIdLogic { + return &GetOrderStateLogsByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetOrderStateLogsByIdLogic) GetOrderStateLogsById(in *pb.GetOrderStateLogsByIdReq) (*pb.GetOrderStateLogsByIdResp, error) { + item, err := l.svcCtx.OrderModelsRO.OrderStateLogs.Query(). + Where(orderstatelogs.IDEQ(in.Id)). + Only(l.ctx) + if err != nil { + return nil, err + } + + return &pb.GetOrderStateLogsByIdResp{OrderStateLogs: toPBOrderStateLog(item)}, nil +} diff --git a/app/order/rpc/internal/logic/getOrdersByIdLogic.go b/app/order/rpc/internal/logic/getOrdersByIdLogic.go new file mode 100644 index 0000000..e297630 --- /dev/null +++ b/app/order/rpc/internal/logic/getOrdersByIdLogic.go @@ -0,0 +1,34 @@ +package logic + +import ( + "context" + + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetOrdersByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetOrdersByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrdersByIdLogic { + return &GetOrdersByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetOrdersByIdLogic) GetOrdersById(in *pb.GetOrdersByIdReq) (*pb.GetOrdersByIdResp, error) { + item, err := l.svcCtx.OrderModelsRO.Orders.Query().Where(orders.IDEQ(in.Id)).First(l.ctx) + if err != nil { + return nil, err + } + + return &pb.GetOrdersByIdResp{Orders: toPBOrder(item)}, nil +} diff --git a/app/order/rpc/internal/logic/searchOrderStateLogsLogic.go b/app/order/rpc/internal/logic/searchOrderStateLogsLogic.go new file mode 100644 index 0000000..8e38480 --- /dev/null +++ b/app/order/rpc/internal/logic/searchOrderStateLogsLogic.go @@ -0,0 +1,80 @@ +package logic + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "juwan-backend/app/order/rpc/internal/models/predicate" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchOrderStateLogsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchOrderStateLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchOrderStateLogsLogic { + return &SearchOrderStateLogsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchOrderStateLogsLogic) SearchOrderStateLogs(in *pb.SearchOrderStateLogsReq) (*pb.SearchOrderStateLogsResp, error) { + if in.Limit <= 0 { + in.Limit = 20 + } + if in.Limit > 1000 { + return nil, errors.New("limit too large") + } + + preds := make([]predicate.OrderStateLogs, 0, 8) + if in.Id != nil { + preds = append(preds, orderstatelogs.IDEQ(*in.Id)) + } + if in.OrderId != nil { + preds = append(preds, orderstatelogs.OrderIDEQ(*in.OrderId)) + } + if in.FromStatus != nil && *in.FromStatus != "" { + preds = append(preds, orderstatelogs.FromStatusEQ(*in.FromStatus)) + } + if in.ToStatus != nil && *in.ToStatus != "" { + preds = append(preds, orderstatelogs.ToStatusEQ(*in.ToStatus)) + } + if in.Action != nil && *in.Action != "" { + preds = append(preds, orderstatelogs.ActionContainsFold(*in.Action)) + } + if in.ActorId != nil { + preds = append(preds, orderstatelogs.ActorIDEQ(*in.ActorId)) + } + if in.ActorRole != nil && *in.ActorRole != "" { + preds = append(preds, orderstatelogs.ActorRoleContainsFold(*in.ActorRole)) + } + if in.CreatedAt != nil && *in.CreatedAt > 0 { + preds = append(preds, orderstatelogs.CreatedAtGTE(time.Unix(*in.CreatedAt, 0))) + } + + query := l.svcCtx.OrderModelsRO.OrderStateLogs.Query() + if len(preds) > 0 { + query = query.Where(orderstatelogs.And(preds...)) + } + + items, err := query.Offset(int(in.Page * in.Limit)).Limit(int(in.Limit)).All(l.ctx) + if err != nil { + return nil, err + } + + result := make([]*pb.OrderStateLogs, 0, len(items)) + for _, item := range items { + result = append(result, toPBOrderStateLog(item)) + } + + return &pb.SearchOrderStateLogsResp{OrderStateLogs: result}, nil +} diff --git a/app/order/rpc/internal/logic/searchOrdersLogic.go b/app/order/rpc/internal/logic/searchOrdersLogic.go new file mode 100644 index 0000000..69cbf42 --- /dev/null +++ b/app/order/rpc/internal/logic/searchOrdersLogic.go @@ -0,0 +1,117 @@ +package logic + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/predicate" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchOrdersLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchOrdersLogic { + return &SearchOrdersLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchOrdersLogic) SearchOrders(in *pb.SearchOrdersReq) (*pb.SearchOrdersResp, error) { + if in.Limit <= 0 { + in.Limit = 20 + } + if in.Limit > 1000 { + return nil, errors.New("limit too large") + } + + preds := make([]predicate.Orders, 0, 20) + if in.Id != nil { + preds = append(preds, orders.IDEQ(*in.Id)) + } + if in.ConsumerId != nil { + preds = append(preds, orders.ConsumerIDEQ(*in.ConsumerId)) + } + if in.ConsumerName != nil && *in.ConsumerName != "" { + preds = append(preds, orders.ConsumerNameContainsFold(*in.ConsumerName)) + } + if in.PlayerId != nil { + preds = append(preds, orders.PlayerIDEQ(*in.PlayerId)) + } + if in.PlayerName != nil && *in.PlayerName != "" { + preds = append(preds, orders.PlayerNameContainsFold(*in.PlayerName)) + } + if in.ShopId != nil { + preds = append(preds, orders.ShopIDEQ(*in.ShopId)) + } + if in.ShopName != nil && *in.ShopName != "" { + preds = append(preds, orders.ShopNameContainsFold(*in.ShopName)) + } + if in.Status != nil && *in.Status != "" { + preds = append(preds, orders.StatusEQ(*in.Status)) + } + if in.TotalPrice != nil && *in.TotalPrice != "" { + price, err := parseDecimal(*in.TotalPrice) + if err != nil { + return nil, err + } + preds = append(preds, orders.TotalPriceEQ(price)) + } + if in.Note != nil && *in.Note != "" { + preds = append(preds, orders.NoteContainsFold(*in.Note)) + } + if in.Version != nil { + preds = append(preds, orders.VersionEQ(int(*in.Version))) + } + if in.TimeoutJobId != nil && *in.TimeoutJobId != "" { + preds = append(preds, orders.TimeoutJobIDEQ(*in.TimeoutJobId)) + } + if in.SearchText != nil && *in.SearchText != "" { + preds = append(preds, orders.SearchTextContainsFold(*in.SearchText)) + } + if in.CreatedAt != nil && *in.CreatedAt > 0 { + preds = append(preds, orders.CreatedAtGTE(time.Unix(*in.CreatedAt, 0))) + } + if in.AcceptedAt != nil && *in.AcceptedAt > 0 { + preds = append(preds, orders.AcceptedAtGTE(time.Unix(*in.AcceptedAt, 0))) + } + if in.ClosedAt != nil && *in.ClosedAt > 0 { + preds = append(preds, orders.ClosedAtGTE(time.Unix(*in.ClosedAt, 0))) + } + if in.CompletedAt != nil && *in.CompletedAt > 0 { + preds = append(preds, orders.CompletedAtGTE(time.Unix(*in.CompletedAt, 0))) + } + if in.CancelledAt != nil && *in.CancelledAt > 0 { + preds = append(preds, orders.CancelledAtGTE(time.Unix(*in.CancelledAt, 0))) + } + if in.UpdatedAt != nil && *in.UpdatedAt > 0 { + preds = append(preds, orders.UpdatedAtGTE(time.Unix(*in.UpdatedAt, 0))) + } + + query := l.svcCtx.OrderModelsRO.Orders.Query() + if len(preds) > 0 { + query = query.Where(orders.And(preds...)) + } + + items, err := query.Offset(int(in.Page * in.Limit)).Limit(int(in.Limit)).All(l.ctx) + if err != nil { + return nil, err + } + + result := make([]*pb.Orders, 0, len(items)) + for _, item := range items { + result = append(result, toPBOrder(item)) + } + + return &pb.SearchOrdersResp{Orders: result}, nil +} diff --git a/app/order/rpc/internal/logic/updateOrderStateLogsLogic.go b/app/order/rpc/internal/logic/updateOrderStateLogsLogic.go new file mode 100644 index 0000000..c0d0d5f --- /dev/null +++ b/app/order/rpc/internal/logic/updateOrderStateLogsLogic.go @@ -0,0 +1,68 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/order/rpc/internal/models" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateOrderStateLogsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateOrderStateLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateOrderStateLogsLogic { + return &UpdateOrderStateLogsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateOrderStateLogsLogic) UpdateOrderStateLogs(in *pb.UpdateOrderStateLogsReq) (*pb.UpdateOrderStateLogsResp, error) { + if in == nil { + return nil, errors.New("order state log is required") + } + + builder := l.svcCtx.OrderModelsRW.OrderStateLogs.UpdateOneID(in.Id) + + if in.OrderId != nil { + builder = builder.SetOrderID(*in.OrderId) + } + if in.FromStatus != nil { + builder = builder.SetFromStatus(*in.FromStatus) + } + if in.ToStatus != nil { + builder = builder.SetToStatus(*in.ToStatus) + } + if in.Action != nil { + builder = builder.SetAction(*in.Action) + } + if in.ActorId != nil { + builder = builder.SetActorID(*in.ActorId) + } + if in.ActorRole != nil { + builder = builder.SetActorRole(*in.ActorRole) + } + if in.Metadata != nil { + metadata, err := parseJSONMap(*in.Metadata) + if err != nil { + return nil, err + } + builder = builder.SetMetadata(metadata) + } + if _, err := builder.Save(l.ctx); err != nil { + if models.IsNotFound(err) { + return nil, errors.New("order state log not found") + } + return nil, err + } + + return &pb.UpdateOrderStateLogsResp{}, nil +} diff --git a/app/order/rpc/internal/logic/updateOrdersLogic.go b/app/order/rpc/internal/logic/updateOrdersLogic.go new file mode 100644 index 0000000..83a24b4 --- /dev/null +++ b/app/order/rpc/internal/logic/updateOrdersLogic.go @@ -0,0 +1,99 @@ +package logic + +import ( + "context" + "errors" + + "github.com/shopspring/decimal" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateOrdersLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateOrdersLogic { + return &UpdateOrdersLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateOrdersLogic) UpdateOrders(in *pb.UpdateOrdersReq) (*pb.UpdateOrdersResp, error) { + updater := l.svcCtx.OrderModelsRW.Orders.UpdateOneID(in.Id) + + if in.ConsumerId != nil { + updater = updater.SetConsumerID(*in.ConsumerId) + } + if in.ConsumerName != nil { + updater = updater.SetConsumerName(*in.ConsumerName) + } + if in.PlayerId != nil { + updater = updater.SetPlayerID(*in.PlayerId) + } + if in.PlayerName != nil { + updater = updater.SetPlayerName(*in.PlayerName) + } + if in.ShopId != nil { + updater = updater.SetShopID(*in.ShopId) + } + if in.ShopName != nil { + updater = updater.SetShopName(*in.ShopName) + } + if in.ServiceSnapshot != nil { + snapshot, err := parseJSONMap(*in.ServiceSnapshot) + if err != nil { + return nil, err + } + updater = updater.SetServiceSnapshot(snapshot) + } + if in.Status != nil { + updater = updater.SetStatus(*in.Status) + } + if in.TotalPrice != nil { + price, err := parseDecimal(*in.TotalPrice) + if err != nil || price.Cmp(decimal.Zero) <= 0 { + return nil, errors.New("invalid total price") + } + updater = updater.SetTotalPrice(price) + } + if in.Note != nil { + updater = updater.SetNote(*in.Note) + } + if in.Version != nil { + updater = updater.SetVersion(int(*in.Version)) + } + if in.TimeoutJobId != nil { + updater = updater.SetTimeoutJobID(*in.TimeoutJobId) + } + if in.SearchText != nil { + updater = updater.SetSearchText(*in.SearchText) + } + if acceptedAt := unixPtr(in.AcceptedAt); acceptedAt != nil { + updater = updater.SetAcceptedAt(*acceptedAt) + } + if closedAt := unixPtr(in.ClosedAt); closedAt != nil { + updater = updater.SetClosedAt(*closedAt) + } + if completedAt := unixPtr(in.CompletedAt); completedAt != nil { + updater = updater.SetCompletedAt(*completedAt) + } + if cancelledAt := unixPtr(in.CancelledAt); cancelledAt != nil { + updater = updater.SetCancelledAt(*cancelledAt) + } + if updatedAt := unixPtr(in.UpdatedAt); updatedAt != nil { + updater = updater.SetUpdatedAt(*updatedAt) + } + + if _, err := updater.Save(l.ctx); err != nil { + return nil, err + } + + return &pb.UpdateOrdersResp{}, nil +} diff --git a/app/order/rpc/internal/models/client.go b/app/order/rpc/internal/models/client.go new file mode 100644 index 0000000..2303170 --- /dev/null +++ b/app/order/rpc/internal/models/client.go @@ -0,0 +1,484 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "juwan-backend/app/order/rpc/internal/models/migrate" + + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // OrderStateLogs is the client for interacting with the OrderStateLogs builders. + OrderStateLogs *OrderStateLogsClient + // Orders is the client for interacting with the Orders builders. + Orders *OrdersClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.OrderStateLogs = NewOrderStateLogsClient(c.config) + c.Orders = NewOrdersClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("models: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + OrderStateLogs: NewOrderStateLogsClient(cfg), + Orders: NewOrdersClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + OrderStateLogs: NewOrderStateLogsClient(cfg), + Orders: NewOrdersClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// OrderStateLogs. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.OrderStateLogs.Use(hooks...) + c.Orders.Use(hooks...) +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.OrderStateLogs.Intercept(interceptors...) + c.Orders.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *OrderStateLogsMutation: + return c.OrderStateLogs.mutate(ctx, m) + case *OrdersMutation: + return c.Orders.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// OrderStateLogsClient is a client for the OrderStateLogs schema. +type OrderStateLogsClient struct { + config +} + +// NewOrderStateLogsClient returns a client for the OrderStateLogs from the given config. +func NewOrderStateLogsClient(c config) *OrderStateLogsClient { + return &OrderStateLogsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `orderstatelogs.Hooks(f(g(h())))`. +func (c *OrderStateLogsClient) Use(hooks ...Hook) { + c.hooks.OrderStateLogs = append(c.hooks.OrderStateLogs, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `orderstatelogs.Intercept(f(g(h())))`. +func (c *OrderStateLogsClient) Intercept(interceptors ...Interceptor) { + c.inters.OrderStateLogs = append(c.inters.OrderStateLogs, interceptors...) +} + +// Create returns a builder for creating a OrderStateLogs entity. +func (c *OrderStateLogsClient) Create() *OrderStateLogsCreate { + mutation := newOrderStateLogsMutation(c.config, OpCreate) + return &OrderStateLogsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of OrderStateLogs entities. +func (c *OrderStateLogsClient) CreateBulk(builders ...*OrderStateLogsCreate) *OrderStateLogsCreateBulk { + return &OrderStateLogsCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *OrderStateLogsClient) MapCreateBulk(slice any, setFunc func(*OrderStateLogsCreate, int)) *OrderStateLogsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &OrderStateLogsCreateBulk{err: fmt.Errorf("calling to OrderStateLogsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*OrderStateLogsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &OrderStateLogsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for OrderStateLogs. +func (c *OrderStateLogsClient) Update() *OrderStateLogsUpdate { + mutation := newOrderStateLogsMutation(c.config, OpUpdate) + return &OrderStateLogsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *OrderStateLogsClient) UpdateOne(_m *OrderStateLogs) *OrderStateLogsUpdateOne { + mutation := newOrderStateLogsMutation(c.config, OpUpdateOne, withOrderStateLogs(_m)) + return &OrderStateLogsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *OrderStateLogsClient) UpdateOneID(id int64) *OrderStateLogsUpdateOne { + mutation := newOrderStateLogsMutation(c.config, OpUpdateOne, withOrderStateLogsID(id)) + return &OrderStateLogsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for OrderStateLogs. +func (c *OrderStateLogsClient) Delete() *OrderStateLogsDelete { + mutation := newOrderStateLogsMutation(c.config, OpDelete) + return &OrderStateLogsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *OrderStateLogsClient) DeleteOne(_m *OrderStateLogs) *OrderStateLogsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *OrderStateLogsClient) DeleteOneID(id int64) *OrderStateLogsDeleteOne { + builder := c.Delete().Where(orderstatelogs.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &OrderStateLogsDeleteOne{builder} +} + +// Query returns a query builder for OrderStateLogs. +func (c *OrderStateLogsClient) Query() *OrderStateLogsQuery { + return &OrderStateLogsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeOrderStateLogs}, + inters: c.Interceptors(), + } +} + +// Get returns a OrderStateLogs entity by its id. +func (c *OrderStateLogsClient) Get(ctx context.Context, id int64) (*OrderStateLogs, error) { + return c.Query().Where(orderstatelogs.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *OrderStateLogsClient) GetX(ctx context.Context, id int64) *OrderStateLogs { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *OrderStateLogsClient) Hooks() []Hook { + return c.hooks.OrderStateLogs +} + +// Interceptors returns the client interceptors. +func (c *OrderStateLogsClient) Interceptors() []Interceptor { + return c.inters.OrderStateLogs +} + +func (c *OrderStateLogsClient) mutate(ctx context.Context, m *OrderStateLogsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&OrderStateLogsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&OrderStateLogsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&OrderStateLogsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&OrderStateLogsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown OrderStateLogs mutation op: %q", m.Op()) + } +} + +// OrdersClient is a client for the Orders schema. +type OrdersClient struct { + config +} + +// NewOrdersClient returns a client for the Orders from the given config. +func NewOrdersClient(c config) *OrdersClient { + return &OrdersClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `orders.Hooks(f(g(h())))`. +func (c *OrdersClient) Use(hooks ...Hook) { + c.hooks.Orders = append(c.hooks.Orders, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `orders.Intercept(f(g(h())))`. +func (c *OrdersClient) Intercept(interceptors ...Interceptor) { + c.inters.Orders = append(c.inters.Orders, interceptors...) +} + +// Create returns a builder for creating a Orders entity. +func (c *OrdersClient) Create() *OrdersCreate { + mutation := newOrdersMutation(c.config, OpCreate) + return &OrdersCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Orders entities. +func (c *OrdersClient) CreateBulk(builders ...*OrdersCreate) *OrdersCreateBulk { + return &OrdersCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *OrdersClient) MapCreateBulk(slice any, setFunc func(*OrdersCreate, int)) *OrdersCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &OrdersCreateBulk{err: fmt.Errorf("calling to OrdersClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*OrdersCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &OrdersCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Orders. +func (c *OrdersClient) Update() *OrdersUpdate { + mutation := newOrdersMutation(c.config, OpUpdate) + return &OrdersUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *OrdersClient) UpdateOne(_m *Orders) *OrdersUpdateOne { + mutation := newOrdersMutation(c.config, OpUpdateOne, withOrders(_m)) + return &OrdersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *OrdersClient) UpdateOneID(id int64) *OrdersUpdateOne { + mutation := newOrdersMutation(c.config, OpUpdateOne, withOrdersID(id)) + return &OrdersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Orders. +func (c *OrdersClient) Delete() *OrdersDelete { + mutation := newOrdersMutation(c.config, OpDelete) + return &OrdersDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *OrdersClient) DeleteOne(_m *Orders) *OrdersDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *OrdersClient) DeleteOneID(id int64) *OrdersDeleteOne { + builder := c.Delete().Where(orders.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &OrdersDeleteOne{builder} +} + +// Query returns a query builder for Orders. +func (c *OrdersClient) Query() *OrdersQuery { + return &OrdersQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeOrders}, + inters: c.Interceptors(), + } +} + +// Get returns a Orders entity by its id. +func (c *OrdersClient) Get(ctx context.Context, id int64) (*Orders, error) { + return c.Query().Where(orders.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *OrdersClient) GetX(ctx context.Context, id int64) *Orders { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *OrdersClient) Hooks() []Hook { + return c.hooks.Orders +} + +// Interceptors returns the client interceptors. +func (c *OrdersClient) Interceptors() []Interceptor { + return c.inters.Orders +} + +func (c *OrdersClient) mutate(ctx context.Context, m *OrdersMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&OrdersCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&OrdersUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&OrdersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&OrdersDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Orders mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + OrderStateLogs, Orders []ent.Hook + } + inters struct { + OrderStateLogs, Orders []ent.Interceptor + } +) diff --git a/app/order/rpc/internal/models/ent.go b/app/order/rpc/internal/models/ent.go new file mode 100644 index 0000000..14dd9bf --- /dev/null +++ b/app/order/rpc/internal/models/ent.go @@ -0,0 +1,610 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(t, c string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + orderstatelogs.Table: orderstatelogs.ValidColumn, + orders.Table: orders.ValidColumn, + }) + }) + return columnCheck(t, c) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "models: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "models: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "models: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "models: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/app/order/rpc/internal/models/enttest/enttest.go b/app/order/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..bfe36f1 --- /dev/null +++ b/app/order/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/order/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/order/rpc/internal/models/runtime" + + "juwan-backend/app/order/rpc/internal/models/migrate" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []models.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...models.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls models.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client { + o := newOptions(opts) + c, err := models.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls models.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *models.Client { + o := newOptions(opts) + c := models.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *models.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/app/order/rpc/internal/models/generate.go b/app/order/rpc/internal/models/generate.go new file mode 100644 index 0000000..d441aca --- /dev/null +++ b/app/order/rpc/internal/models/generate.go @@ -0,0 +1,3 @@ +package models + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema diff --git a/app/order/rpc/internal/models/hook/hook.go b/app/order/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..76082a5 --- /dev/null +++ b/app/order/rpc/internal/models/hook/hook.go @@ -0,0 +1,210 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + "juwan-backend/app/order/rpc/internal/models" +) + +// The OrderStateLogsFunc type is an adapter to allow the use of ordinary +// function as OrderStateLogs mutator. +type OrderStateLogsFunc func(context.Context, *models.OrderStateLogsMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f OrderStateLogsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.OrderStateLogsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.OrderStateLogsMutation", m) +} + +// The OrdersFunc type is an adapter to allow the use of ordinary +// function as Orders mutator. +type OrdersFunc func(context.Context, *models.OrdersMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f OrdersFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.OrdersMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.OrdersMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, models.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op models.Op) Condition { + return func(_ context.Context, m models.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk models.Hook, cond Condition) models.Hook { + return func(next models.Mutator) models.Mutator { + return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, models.Delete|models.Create) +func On(hk models.Hook, op models.Op) models.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, models.Update|models.UpdateOne) +func Unless(hk models.Hook, op models.Op) models.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) models.Hook { + return func(models.Mutator) models.Mutator { + return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []models.Hook { +// return []models.Hook{ +// Reject(models.Delete|models.Update), +// } +// } +func Reject(op models.Op) models.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []models.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...models.Hook) Chain { + return Chain{append([]models.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() models.Hook { + return func(mutator models.Mutator) models.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...models.Hook) Chain { + newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/app/order/rpc/internal/models/migrate/migrate.go b/app/order/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/order/rpc/internal/models/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/app/order/rpc/internal/models/migrate/schema.go b/app/order/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..332c0c7 --- /dev/null +++ b/app/order/rpc/internal/models/migrate/schema.go @@ -0,0 +1,77 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // OrderStateLogsColumns holds the columns for the "order_state_logs" table. + OrderStateLogsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "order_id", Type: field.TypeInt64}, + {Name: "from_status", Type: field.TypeString, Nullable: true, Size: 30}, + {Name: "to_status", Type: field.TypeString, Size: 30}, + {Name: "action", Type: field.TypeString, Size: 50}, + {Name: "actor_id", Type: field.TypeInt64}, + {Name: "actor_role", Type: field.TypeString, Size: 20}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + } + // OrderStateLogsTable holds the schema information for the "order_state_logs" table. + OrderStateLogsTable = &schema.Table{ + Name: "order_state_logs", + Columns: OrderStateLogsColumns, + PrimaryKey: []*schema.Column{OrderStateLogsColumns[0]}, + } + // OrdersColumns holds the columns for the "orders" table. + OrdersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "consumer_id", Type: field.TypeInt64}, + {Name: "consumer_name", Type: field.TypeString, Size: 100}, + {Name: "player_id", Type: field.TypeInt64}, + {Name: "player_name", Type: field.TypeString, Size: 100}, + {Name: "shop_id", Type: field.TypeInt64, Nullable: true}, + {Name: "shop_name", Type: field.TypeString, Nullable: true, Size: 200}, + {Name: "service_snapshot", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "status", Type: field.TypeString, Size: 30, Default: "pending_payment"}, + {Name: "total_price", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "decimal(10,2)"}}, + {Name: "note", Type: field.TypeString, Nullable: true}, + {Name: "version", Type: field.TypeInt, Default: 1}, + {Name: "timeout_job_id", Type: field.TypeString, Nullable: true, Size: 100}, + {Name: "search_text", Type: field.TypeString, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "accepted_at", Type: field.TypeTime, Nullable: true}, + {Name: "closed_at", Type: field.TypeTime, Nullable: true}, + {Name: "completed_at", Type: field.TypeTime, Nullable: true}, + {Name: "cancelled_at", Type: field.TypeTime, Nullable: true}, + {Name: "updated_at", Type: field.TypeTime}, + } + // OrdersTable holds the schema information for the "orders" table. + OrdersTable = &schema.Table{ + Name: "orders", + Columns: OrdersColumns, + PrimaryKey: []*schema.Column{OrdersColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + OrderStateLogsTable, + OrdersTable, + } +) + +func init() { + OrderStateLogsTable.Annotation = &entsql.Annotation{ + Table: "order_state_logs", + } + OrdersTable.Annotation = &entsql.Annotation{ + Table: "orders", + } + OrdersTable.Annotation.Checks = map[string]string{ + "chk_order_status": "status IN ('pending_payment', 'pending_accept', 'in_progress', 'pending_close', 'pending_review', 'disputed', 'completed', 'cancelled')", + "chk_price_positive": "total_price > 0", + } +} diff --git a/app/order/rpc/internal/models/mutation.go b/app/order/rpc/internal/models/mutation.go new file mode 100644 index 0000000..a0048ec --- /dev/null +++ b/app/order/rpc/internal/models/mutation.go @@ -0,0 +1,2465 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "juwan-backend/app/order/rpc/internal/models/predicate" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeOrderStateLogs = "OrderStateLogs" + TypeOrders = "Orders" +) + +// OrderStateLogsMutation represents an operation that mutates the OrderStateLogs nodes in the graph. +type OrderStateLogsMutation struct { + config + op Op + typ string + id *int64 + order_id *int64 + addorder_id *int64 + from_status *string + to_status *string + action *string + actor_id *int64 + addactor_id *int64 + actor_role *string + metadata *map[string]interface{} + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*OrderStateLogs, error) + predicates []predicate.OrderStateLogs +} + +var _ ent.Mutation = (*OrderStateLogsMutation)(nil) + +// orderstatelogsOption allows management of the mutation configuration using functional options. +type orderstatelogsOption func(*OrderStateLogsMutation) + +// newOrderStateLogsMutation creates new mutation for the OrderStateLogs entity. +func newOrderStateLogsMutation(c config, op Op, opts ...orderstatelogsOption) *OrderStateLogsMutation { + m := &OrderStateLogsMutation{ + config: c, + op: op, + typ: TypeOrderStateLogs, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withOrderStateLogsID sets the ID field of the mutation. +func withOrderStateLogsID(id int64) orderstatelogsOption { + return func(m *OrderStateLogsMutation) { + var ( + err error + once sync.Once + value *OrderStateLogs + ) + m.oldValue = func(ctx context.Context) (*OrderStateLogs, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().OrderStateLogs.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withOrderStateLogs sets the old OrderStateLogs of the mutation. +func withOrderStateLogs(node *OrderStateLogs) orderstatelogsOption { + return func(m *OrderStateLogsMutation) { + m.oldValue = func(context.Context) (*OrderStateLogs, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m OrderStateLogsMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m OrderStateLogsMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of OrderStateLogs entities. +func (m *OrderStateLogsMutation) SetID(id int64) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *OrderStateLogsMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *OrderStateLogsMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().OrderStateLogs.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetOrderID sets the "order_id" field. +func (m *OrderStateLogsMutation) SetOrderID(i int64) { + m.order_id = &i + m.addorder_id = nil +} + +// OrderID returns the value of the "order_id" field in the mutation. +func (m *OrderStateLogsMutation) OrderID() (r int64, exists bool) { + v := m.order_id + if v == nil { + return + } + return *v, true +} + +// OldOrderID returns the old "order_id" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldOrderID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOrderID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOrderID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOrderID: %w", err) + } + return oldValue.OrderID, nil +} + +// AddOrderID adds i to the "order_id" field. +func (m *OrderStateLogsMutation) AddOrderID(i int64) { + if m.addorder_id != nil { + *m.addorder_id += i + } else { + m.addorder_id = &i + } +} + +// AddedOrderID returns the value that was added to the "order_id" field in this mutation. +func (m *OrderStateLogsMutation) AddedOrderID() (r int64, exists bool) { + v := m.addorder_id + if v == nil { + return + } + return *v, true +} + +// ResetOrderID resets all changes to the "order_id" field. +func (m *OrderStateLogsMutation) ResetOrderID() { + m.order_id = nil + m.addorder_id = nil +} + +// SetFromStatus sets the "from_status" field. +func (m *OrderStateLogsMutation) SetFromStatus(s string) { + m.from_status = &s +} + +// FromStatus returns the value of the "from_status" field in the mutation. +func (m *OrderStateLogsMutation) FromStatus() (r string, exists bool) { + v := m.from_status + if v == nil { + return + } + return *v, true +} + +// OldFromStatus returns the old "from_status" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldFromStatus(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFromStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFromStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFromStatus: %w", err) + } + return oldValue.FromStatus, nil +} + +// ClearFromStatus clears the value of the "from_status" field. +func (m *OrderStateLogsMutation) ClearFromStatus() { + m.from_status = nil + m.clearedFields[orderstatelogs.FieldFromStatus] = struct{}{} +} + +// FromStatusCleared returns if the "from_status" field was cleared in this mutation. +func (m *OrderStateLogsMutation) FromStatusCleared() bool { + _, ok := m.clearedFields[orderstatelogs.FieldFromStatus] + return ok +} + +// ResetFromStatus resets all changes to the "from_status" field. +func (m *OrderStateLogsMutation) ResetFromStatus() { + m.from_status = nil + delete(m.clearedFields, orderstatelogs.FieldFromStatus) +} + +// SetToStatus sets the "to_status" field. +func (m *OrderStateLogsMutation) SetToStatus(s string) { + m.to_status = &s +} + +// ToStatus returns the value of the "to_status" field in the mutation. +func (m *OrderStateLogsMutation) ToStatus() (r string, exists bool) { + v := m.to_status + if v == nil { + return + } + return *v, true +} + +// OldToStatus returns the old "to_status" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldToStatus(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldToStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldToStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldToStatus: %w", err) + } + return oldValue.ToStatus, nil +} + +// ResetToStatus resets all changes to the "to_status" field. +func (m *OrderStateLogsMutation) ResetToStatus() { + m.to_status = nil +} + +// SetAction sets the "action" field. +func (m *OrderStateLogsMutation) SetAction(s string) { + m.action = &s +} + +// Action returns the value of the "action" field in the mutation. +func (m *OrderStateLogsMutation) Action() (r string, exists bool) { + v := m.action + if v == nil { + return + } + return *v, true +} + +// OldAction returns the old "action" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldAction(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAction is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAction requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAction: %w", err) + } + return oldValue.Action, nil +} + +// ResetAction resets all changes to the "action" field. +func (m *OrderStateLogsMutation) ResetAction() { + m.action = nil +} + +// SetActorID sets the "actor_id" field. +func (m *OrderStateLogsMutation) SetActorID(i int64) { + m.actor_id = &i + m.addactor_id = nil +} + +// ActorID returns the value of the "actor_id" field in the mutation. +func (m *OrderStateLogsMutation) ActorID() (r int64, exists bool) { + v := m.actor_id + if v == nil { + return + } + return *v, true +} + +// OldActorID returns the old "actor_id" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldActorID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActorID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActorID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActorID: %w", err) + } + return oldValue.ActorID, nil +} + +// AddActorID adds i to the "actor_id" field. +func (m *OrderStateLogsMutation) AddActorID(i int64) { + if m.addactor_id != nil { + *m.addactor_id += i + } else { + m.addactor_id = &i + } +} + +// AddedActorID returns the value that was added to the "actor_id" field in this mutation. +func (m *OrderStateLogsMutation) AddedActorID() (r int64, exists bool) { + v := m.addactor_id + if v == nil { + return + } + return *v, true +} + +// ResetActorID resets all changes to the "actor_id" field. +func (m *OrderStateLogsMutation) ResetActorID() { + m.actor_id = nil + m.addactor_id = nil +} + +// SetActorRole sets the "actor_role" field. +func (m *OrderStateLogsMutation) SetActorRole(s string) { + m.actor_role = &s +} + +// ActorRole returns the value of the "actor_role" field in the mutation. +func (m *OrderStateLogsMutation) ActorRole() (r string, exists bool) { + v := m.actor_role + if v == nil { + return + } + return *v, true +} + +// OldActorRole returns the old "actor_role" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldActorRole(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActorRole is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActorRole requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActorRole: %w", err) + } + return oldValue.ActorRole, nil +} + +// ResetActorRole resets all changes to the "actor_role" field. +func (m *OrderStateLogsMutation) ResetActorRole() { + m.actor_role = nil +} + +// SetMetadata sets the "metadata" field. +func (m *OrderStateLogsMutation) SetMetadata(value map[string]interface{}) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *OrderStateLogsMutation) Metadata() (r map[string]interface{}, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldMetadata(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *OrderStateLogsMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[orderstatelogs.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *OrderStateLogsMutation) MetadataCleared() bool { + _, ok := m.clearedFields[orderstatelogs.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *OrderStateLogsMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, orderstatelogs.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *OrderStateLogsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *OrderStateLogsMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the OrderStateLogs entity. +// If the OrderStateLogs object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrderStateLogsMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *OrderStateLogsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// Where appends a list predicates to the OrderStateLogsMutation builder. +func (m *OrderStateLogsMutation) Where(ps ...predicate.OrderStateLogs) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the OrderStateLogsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *OrderStateLogsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.OrderStateLogs, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *OrderStateLogsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *OrderStateLogsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (OrderStateLogs). +func (m *OrderStateLogsMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *OrderStateLogsMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.order_id != nil { + fields = append(fields, orderstatelogs.FieldOrderID) + } + if m.from_status != nil { + fields = append(fields, orderstatelogs.FieldFromStatus) + } + if m.to_status != nil { + fields = append(fields, orderstatelogs.FieldToStatus) + } + if m.action != nil { + fields = append(fields, orderstatelogs.FieldAction) + } + if m.actor_id != nil { + fields = append(fields, orderstatelogs.FieldActorID) + } + if m.actor_role != nil { + fields = append(fields, orderstatelogs.FieldActorRole) + } + if m.metadata != nil { + fields = append(fields, orderstatelogs.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, orderstatelogs.FieldCreatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *OrderStateLogsMutation) Field(name string) (ent.Value, bool) { + switch name { + case orderstatelogs.FieldOrderID: + return m.OrderID() + case orderstatelogs.FieldFromStatus: + return m.FromStatus() + case orderstatelogs.FieldToStatus: + return m.ToStatus() + case orderstatelogs.FieldAction: + return m.Action() + case orderstatelogs.FieldActorID: + return m.ActorID() + case orderstatelogs.FieldActorRole: + return m.ActorRole() + case orderstatelogs.FieldMetadata: + return m.Metadata() + case orderstatelogs.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *OrderStateLogsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case orderstatelogs.FieldOrderID: + return m.OldOrderID(ctx) + case orderstatelogs.FieldFromStatus: + return m.OldFromStatus(ctx) + case orderstatelogs.FieldToStatus: + return m.OldToStatus(ctx) + case orderstatelogs.FieldAction: + return m.OldAction(ctx) + case orderstatelogs.FieldActorID: + return m.OldActorID(ctx) + case orderstatelogs.FieldActorRole: + return m.OldActorRole(ctx) + case orderstatelogs.FieldMetadata: + return m.OldMetadata(ctx) + case orderstatelogs.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown OrderStateLogs field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrderStateLogsMutation) SetField(name string, value ent.Value) error { + switch name { + case orderstatelogs.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOrderID(v) + return nil + case orderstatelogs.FieldFromStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFromStatus(v) + return nil + case orderstatelogs.FieldToStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetToStatus(v) + return nil + case orderstatelogs.FieldAction: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAction(v) + return nil + case orderstatelogs.FieldActorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActorID(v) + return nil + case orderstatelogs.FieldActorRole: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActorRole(v) + return nil + case orderstatelogs.FieldMetadata: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case orderstatelogs.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown OrderStateLogs field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *OrderStateLogsMutation) AddedFields() []string { + var fields []string + if m.addorder_id != nil { + fields = append(fields, orderstatelogs.FieldOrderID) + } + if m.addactor_id != nil { + fields = append(fields, orderstatelogs.FieldActorID) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *OrderStateLogsMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case orderstatelogs.FieldOrderID: + return m.AddedOrderID() + case orderstatelogs.FieldActorID: + return m.AddedActorID() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrderStateLogsMutation) AddField(name string, value ent.Value) error { + switch name { + case orderstatelogs.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOrderID(v) + return nil + case orderstatelogs.FieldActorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddActorID(v) + return nil + } + return fmt.Errorf("unknown OrderStateLogs numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *OrderStateLogsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(orderstatelogs.FieldFromStatus) { + fields = append(fields, orderstatelogs.FieldFromStatus) + } + if m.FieldCleared(orderstatelogs.FieldMetadata) { + fields = append(fields, orderstatelogs.FieldMetadata) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *OrderStateLogsMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *OrderStateLogsMutation) ClearField(name string) error { + switch name { + case orderstatelogs.FieldFromStatus: + m.ClearFromStatus() + return nil + case orderstatelogs.FieldMetadata: + m.ClearMetadata() + return nil + } + return fmt.Errorf("unknown OrderStateLogs nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *OrderStateLogsMutation) ResetField(name string) error { + switch name { + case orderstatelogs.FieldOrderID: + m.ResetOrderID() + return nil + case orderstatelogs.FieldFromStatus: + m.ResetFromStatus() + return nil + case orderstatelogs.FieldToStatus: + m.ResetToStatus() + return nil + case orderstatelogs.FieldAction: + m.ResetAction() + return nil + case orderstatelogs.FieldActorID: + m.ResetActorID() + return nil + case orderstatelogs.FieldActorRole: + m.ResetActorRole() + return nil + case orderstatelogs.FieldMetadata: + m.ResetMetadata() + return nil + case orderstatelogs.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown OrderStateLogs field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *OrderStateLogsMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *OrderStateLogsMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *OrderStateLogsMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *OrderStateLogsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *OrderStateLogsMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *OrderStateLogsMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *OrderStateLogsMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown OrderStateLogs unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *OrderStateLogsMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown OrderStateLogs edge %s", name) +} + +// OrdersMutation represents an operation that mutates the Orders nodes in the graph. +type OrdersMutation struct { + config + op Op + typ string + id *int64 + consumer_id *int64 + addconsumer_id *int64 + consumer_name *string + player_id *int64 + addplayer_id *int64 + player_name *string + shop_id *int64 + addshop_id *int64 + shop_name *string + service_snapshot *map[string]interface{} + status *string + total_price *decimal.Decimal + note *string + version *int + addversion *int + timeout_job_id *string + search_text *string + created_at *time.Time + accepted_at *time.Time + closed_at *time.Time + completed_at *time.Time + cancelled_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Orders, error) + predicates []predicate.Orders +} + +var _ ent.Mutation = (*OrdersMutation)(nil) + +// ordersOption allows management of the mutation configuration using functional options. +type ordersOption func(*OrdersMutation) + +// newOrdersMutation creates new mutation for the Orders entity. +func newOrdersMutation(c config, op Op, opts ...ordersOption) *OrdersMutation { + m := &OrdersMutation{ + config: c, + op: op, + typ: TypeOrders, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withOrdersID sets the ID field of the mutation. +func withOrdersID(id int64) ordersOption { + return func(m *OrdersMutation) { + var ( + err error + once sync.Once + value *Orders + ) + m.oldValue = func(ctx context.Context) (*Orders, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Orders.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withOrders sets the old Orders of the mutation. +func withOrders(node *Orders) ordersOption { + return func(m *OrdersMutation) { + m.oldValue = func(context.Context) (*Orders, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m OrdersMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m OrdersMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Orders entities. +func (m *OrdersMutation) SetID(id int64) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *OrdersMutation) ID() (id int64, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *OrdersMutation) IDs(ctx context.Context) ([]int64, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int64{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Orders.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetConsumerID sets the "consumer_id" field. +func (m *OrdersMutation) SetConsumerID(i int64) { + m.consumer_id = &i + m.addconsumer_id = nil +} + +// ConsumerID returns the value of the "consumer_id" field in the mutation. +func (m *OrdersMutation) ConsumerID() (r int64, exists bool) { + v := m.consumer_id + if v == nil { + return + } + return *v, true +} + +// OldConsumerID returns the old "consumer_id" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldConsumerID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConsumerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConsumerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConsumerID: %w", err) + } + return oldValue.ConsumerID, nil +} + +// AddConsumerID adds i to the "consumer_id" field. +func (m *OrdersMutation) AddConsumerID(i int64) { + if m.addconsumer_id != nil { + *m.addconsumer_id += i + } else { + m.addconsumer_id = &i + } +} + +// AddedConsumerID returns the value that was added to the "consumer_id" field in this mutation. +func (m *OrdersMutation) AddedConsumerID() (r int64, exists bool) { + v := m.addconsumer_id + if v == nil { + return + } + return *v, true +} + +// ResetConsumerID resets all changes to the "consumer_id" field. +func (m *OrdersMutation) ResetConsumerID() { + m.consumer_id = nil + m.addconsumer_id = nil +} + +// SetConsumerName sets the "consumer_name" field. +func (m *OrdersMutation) SetConsumerName(s string) { + m.consumer_name = &s +} + +// ConsumerName returns the value of the "consumer_name" field in the mutation. +func (m *OrdersMutation) ConsumerName() (r string, exists bool) { + v := m.consumer_name + if v == nil { + return + } + return *v, true +} + +// OldConsumerName returns the old "consumer_name" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldConsumerName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConsumerName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConsumerName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConsumerName: %w", err) + } + return oldValue.ConsumerName, nil +} + +// ResetConsumerName resets all changes to the "consumer_name" field. +func (m *OrdersMutation) ResetConsumerName() { + m.consumer_name = nil +} + +// SetPlayerID sets the "player_id" field. +func (m *OrdersMutation) SetPlayerID(i int64) { + m.player_id = &i + m.addplayer_id = nil +} + +// PlayerID returns the value of the "player_id" field in the mutation. +func (m *OrdersMutation) PlayerID() (r int64, exists bool) { + v := m.player_id + if v == nil { + return + } + return *v, true +} + +// OldPlayerID returns the old "player_id" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldPlayerID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlayerID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlayerID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlayerID: %w", err) + } + return oldValue.PlayerID, nil +} + +// AddPlayerID adds i to the "player_id" field. +func (m *OrdersMutation) AddPlayerID(i int64) { + if m.addplayer_id != nil { + *m.addplayer_id += i + } else { + m.addplayer_id = &i + } +} + +// AddedPlayerID returns the value that was added to the "player_id" field in this mutation. +func (m *OrdersMutation) AddedPlayerID() (r int64, exists bool) { + v := m.addplayer_id + if v == nil { + return + } + return *v, true +} + +// ResetPlayerID resets all changes to the "player_id" field. +func (m *OrdersMutation) ResetPlayerID() { + m.player_id = nil + m.addplayer_id = nil +} + +// SetPlayerName sets the "player_name" field. +func (m *OrdersMutation) SetPlayerName(s string) { + m.player_name = &s +} + +// PlayerName returns the value of the "player_name" field in the mutation. +func (m *OrdersMutation) PlayerName() (r string, exists bool) { + v := m.player_name + if v == nil { + return + } + return *v, true +} + +// OldPlayerName returns the old "player_name" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldPlayerName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPlayerName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPlayerName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPlayerName: %w", err) + } + return oldValue.PlayerName, nil +} + +// ResetPlayerName resets all changes to the "player_name" field. +func (m *OrdersMutation) ResetPlayerName() { + m.player_name = nil +} + +// SetShopID sets the "shop_id" field. +func (m *OrdersMutation) SetShopID(i int64) { + m.shop_id = &i + m.addshop_id = nil +} + +// ShopID returns the value of the "shop_id" field in the mutation. +func (m *OrdersMutation) ShopID() (r int64, exists bool) { + v := m.shop_id + if v == nil { + return + } + return *v, true +} + +// OldShopID returns the old "shop_id" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldShopID(ctx context.Context) (v *int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldShopID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldShopID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldShopID: %w", err) + } + return oldValue.ShopID, nil +} + +// AddShopID adds i to the "shop_id" field. +func (m *OrdersMutation) AddShopID(i int64) { + if m.addshop_id != nil { + *m.addshop_id += i + } else { + m.addshop_id = &i + } +} + +// AddedShopID returns the value that was added to the "shop_id" field in this mutation. +func (m *OrdersMutation) AddedShopID() (r int64, exists bool) { + v := m.addshop_id + if v == nil { + return + } + return *v, true +} + +// ClearShopID clears the value of the "shop_id" field. +func (m *OrdersMutation) ClearShopID() { + m.shop_id = nil + m.addshop_id = nil + m.clearedFields[orders.FieldShopID] = struct{}{} +} + +// ShopIDCleared returns if the "shop_id" field was cleared in this mutation. +func (m *OrdersMutation) ShopIDCleared() bool { + _, ok := m.clearedFields[orders.FieldShopID] + return ok +} + +// ResetShopID resets all changes to the "shop_id" field. +func (m *OrdersMutation) ResetShopID() { + m.shop_id = nil + m.addshop_id = nil + delete(m.clearedFields, orders.FieldShopID) +} + +// SetShopName sets the "shop_name" field. +func (m *OrdersMutation) SetShopName(s string) { + m.shop_name = &s +} + +// ShopName returns the value of the "shop_name" field in the mutation. +func (m *OrdersMutation) ShopName() (r string, exists bool) { + v := m.shop_name + if v == nil { + return + } + return *v, true +} + +// OldShopName returns the old "shop_name" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldShopName(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldShopName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldShopName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldShopName: %w", err) + } + return oldValue.ShopName, nil +} + +// ClearShopName clears the value of the "shop_name" field. +func (m *OrdersMutation) ClearShopName() { + m.shop_name = nil + m.clearedFields[orders.FieldShopName] = struct{}{} +} + +// ShopNameCleared returns if the "shop_name" field was cleared in this mutation. +func (m *OrdersMutation) ShopNameCleared() bool { + _, ok := m.clearedFields[orders.FieldShopName] + return ok +} + +// ResetShopName resets all changes to the "shop_name" field. +func (m *OrdersMutation) ResetShopName() { + m.shop_name = nil + delete(m.clearedFields, orders.FieldShopName) +} + +// SetServiceSnapshot sets the "service_snapshot" field. +func (m *OrdersMutation) SetServiceSnapshot(value map[string]interface{}) { + m.service_snapshot = &value +} + +// ServiceSnapshot returns the value of the "service_snapshot" field in the mutation. +func (m *OrdersMutation) ServiceSnapshot() (r map[string]interface{}, exists bool) { + v := m.service_snapshot + if v == nil { + return + } + return *v, true +} + +// OldServiceSnapshot returns the old "service_snapshot" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldServiceSnapshot(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldServiceSnapshot is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldServiceSnapshot requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldServiceSnapshot: %w", err) + } + return oldValue.ServiceSnapshot, nil +} + +// ResetServiceSnapshot resets all changes to the "service_snapshot" field. +func (m *OrdersMutation) ResetServiceSnapshot() { + m.service_snapshot = nil +} + +// SetStatus sets the "status" field. +func (m *OrdersMutation) SetStatus(s string) { + m.status = &s +} + +// Status returns the value of the "status" field in the mutation. +func (m *OrdersMutation) Status() (r string, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldStatus(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *OrdersMutation) ResetStatus() { + m.status = nil +} + +// SetTotalPrice sets the "total_price" field. +func (m *OrdersMutation) SetTotalPrice(d decimal.Decimal) { + m.total_price = &d +} + +// TotalPrice returns the value of the "total_price" field in the mutation. +func (m *OrdersMutation) TotalPrice() (r decimal.Decimal, exists bool) { + v := m.total_price + if v == nil { + return + } + return *v, true +} + +// OldTotalPrice returns the old "total_price" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldTotalPrice(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotalPrice is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotalPrice requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotalPrice: %w", err) + } + return oldValue.TotalPrice, nil +} + +// ResetTotalPrice resets all changes to the "total_price" field. +func (m *OrdersMutation) ResetTotalPrice() { + m.total_price = nil +} + +// SetNote sets the "note" field. +func (m *OrdersMutation) SetNote(s string) { + m.note = &s +} + +// Note returns the value of the "note" field in the mutation. +func (m *OrdersMutation) Note() (r string, exists bool) { + v := m.note + if v == nil { + return + } + return *v, true +} + +// OldNote returns the old "note" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldNote(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNote is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNote requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNote: %w", err) + } + return oldValue.Note, nil +} + +// ClearNote clears the value of the "note" field. +func (m *OrdersMutation) ClearNote() { + m.note = nil + m.clearedFields[orders.FieldNote] = struct{}{} +} + +// NoteCleared returns if the "note" field was cleared in this mutation. +func (m *OrdersMutation) NoteCleared() bool { + _, ok := m.clearedFields[orders.FieldNote] + return ok +} + +// ResetNote resets all changes to the "note" field. +func (m *OrdersMutation) ResetNote() { + m.note = nil + delete(m.clearedFields, orders.FieldNote) +} + +// SetVersion sets the "version" field. +func (m *OrdersMutation) SetVersion(i int) { + m.version = &i + m.addversion = nil +} + +// Version returns the value of the "version" field in the mutation. +func (m *OrdersMutation) Version() (r int, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldVersion(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil +} + +// AddVersion adds i to the "version" field. +func (m *OrdersMutation) AddVersion(i int) { + if m.addversion != nil { + *m.addversion += i + } else { + m.addversion = &i + } +} + +// AddedVersion returns the value that was added to the "version" field in this mutation. +func (m *OrdersMutation) AddedVersion() (r int, exists bool) { + v := m.addversion + if v == nil { + return + } + return *v, true +} + +// ResetVersion resets all changes to the "version" field. +func (m *OrdersMutation) ResetVersion() { + m.version = nil + m.addversion = nil +} + +// SetTimeoutJobID sets the "timeout_job_id" field. +func (m *OrdersMutation) SetTimeoutJobID(s string) { + m.timeout_job_id = &s +} + +// TimeoutJobID returns the value of the "timeout_job_id" field in the mutation. +func (m *OrdersMutation) TimeoutJobID() (r string, exists bool) { + v := m.timeout_job_id + if v == nil { + return + } + return *v, true +} + +// OldTimeoutJobID returns the old "timeout_job_id" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldTimeoutJobID(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTimeoutJobID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTimeoutJobID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTimeoutJobID: %w", err) + } + return oldValue.TimeoutJobID, nil +} + +// ClearTimeoutJobID clears the value of the "timeout_job_id" field. +func (m *OrdersMutation) ClearTimeoutJobID() { + m.timeout_job_id = nil + m.clearedFields[orders.FieldTimeoutJobID] = struct{}{} +} + +// TimeoutJobIDCleared returns if the "timeout_job_id" field was cleared in this mutation. +func (m *OrdersMutation) TimeoutJobIDCleared() bool { + _, ok := m.clearedFields[orders.FieldTimeoutJobID] + return ok +} + +// ResetTimeoutJobID resets all changes to the "timeout_job_id" field. +func (m *OrdersMutation) ResetTimeoutJobID() { + m.timeout_job_id = nil + delete(m.clearedFields, orders.FieldTimeoutJobID) +} + +// SetSearchText sets the "search_text" field. +func (m *OrdersMutation) SetSearchText(s string) { + m.search_text = &s +} + +// SearchText returns the value of the "search_text" field in the mutation. +func (m *OrdersMutation) SearchText() (r string, exists bool) { + v := m.search_text + if v == nil { + return + } + return *v, true +} + +// OldSearchText returns the old "search_text" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldSearchText(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSearchText is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSearchText requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSearchText: %w", err) + } + return oldValue.SearchText, nil +} + +// ClearSearchText clears the value of the "search_text" field. +func (m *OrdersMutation) ClearSearchText() { + m.search_text = nil + m.clearedFields[orders.FieldSearchText] = struct{}{} +} + +// SearchTextCleared returns if the "search_text" field was cleared in this mutation. +func (m *OrdersMutation) SearchTextCleared() bool { + _, ok := m.clearedFields[orders.FieldSearchText] + return ok +} + +// ResetSearchText resets all changes to the "search_text" field. +func (m *OrdersMutation) ResetSearchText() { + m.search_text = nil + delete(m.clearedFields, orders.FieldSearchText) +} + +// SetCreatedAt sets the "created_at" field. +func (m *OrdersMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *OrdersMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *OrdersMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetAcceptedAt sets the "accepted_at" field. +func (m *OrdersMutation) SetAcceptedAt(t time.Time) { + m.accepted_at = &t +} + +// AcceptedAt returns the value of the "accepted_at" field in the mutation. +func (m *OrdersMutation) AcceptedAt() (r time.Time, exists bool) { + v := m.accepted_at + if v == nil { + return + } + return *v, true +} + +// OldAcceptedAt returns the old "accepted_at" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldAcceptedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAcceptedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAcceptedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAcceptedAt: %w", err) + } + return oldValue.AcceptedAt, nil +} + +// ClearAcceptedAt clears the value of the "accepted_at" field. +func (m *OrdersMutation) ClearAcceptedAt() { + m.accepted_at = nil + m.clearedFields[orders.FieldAcceptedAt] = struct{}{} +} + +// AcceptedAtCleared returns if the "accepted_at" field was cleared in this mutation. +func (m *OrdersMutation) AcceptedAtCleared() bool { + _, ok := m.clearedFields[orders.FieldAcceptedAt] + return ok +} + +// ResetAcceptedAt resets all changes to the "accepted_at" field. +func (m *OrdersMutation) ResetAcceptedAt() { + m.accepted_at = nil + delete(m.clearedFields, orders.FieldAcceptedAt) +} + +// SetClosedAt sets the "closed_at" field. +func (m *OrdersMutation) SetClosedAt(t time.Time) { + m.closed_at = &t +} + +// ClosedAt returns the value of the "closed_at" field in the mutation. +func (m *OrdersMutation) ClosedAt() (r time.Time, exists bool) { + v := m.closed_at + if v == nil { + return + } + return *v, true +} + +// OldClosedAt returns the old "closed_at" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldClosedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldClosedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldClosedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldClosedAt: %w", err) + } + return oldValue.ClosedAt, nil +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (m *OrdersMutation) ClearClosedAt() { + m.closed_at = nil + m.clearedFields[orders.FieldClosedAt] = struct{}{} +} + +// ClosedAtCleared returns if the "closed_at" field was cleared in this mutation. +func (m *OrdersMutation) ClosedAtCleared() bool { + _, ok := m.clearedFields[orders.FieldClosedAt] + return ok +} + +// ResetClosedAt resets all changes to the "closed_at" field. +func (m *OrdersMutation) ResetClosedAt() { + m.closed_at = nil + delete(m.clearedFields, orders.FieldClosedAt) +} + +// SetCompletedAt sets the "completed_at" field. +func (m *OrdersMutation) SetCompletedAt(t time.Time) { + m.completed_at = &t +} + +// CompletedAt returns the value of the "completed_at" field in the mutation. +func (m *OrdersMutation) CompletedAt() (r time.Time, exists bool) { + v := m.completed_at + if v == nil { + return + } + return *v, true +} + +// OldCompletedAt returns the old "completed_at" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldCompletedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCompletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCompletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCompletedAt: %w", err) + } + return oldValue.CompletedAt, nil +} + +// ClearCompletedAt clears the value of the "completed_at" field. +func (m *OrdersMutation) ClearCompletedAt() { + m.completed_at = nil + m.clearedFields[orders.FieldCompletedAt] = struct{}{} +} + +// CompletedAtCleared returns if the "completed_at" field was cleared in this mutation. +func (m *OrdersMutation) CompletedAtCleared() bool { + _, ok := m.clearedFields[orders.FieldCompletedAt] + return ok +} + +// ResetCompletedAt resets all changes to the "completed_at" field. +func (m *OrdersMutation) ResetCompletedAt() { + m.completed_at = nil + delete(m.clearedFields, orders.FieldCompletedAt) +} + +// SetCancelledAt sets the "cancelled_at" field. +func (m *OrdersMutation) SetCancelledAt(t time.Time) { + m.cancelled_at = &t +} + +// CancelledAt returns the value of the "cancelled_at" field in the mutation. +func (m *OrdersMutation) CancelledAt() (r time.Time, exists bool) { + v := m.cancelled_at + if v == nil { + return + } + return *v, true +} + +// OldCancelledAt returns the old "cancelled_at" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldCancelledAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCancelledAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCancelledAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCancelledAt: %w", err) + } + return oldValue.CancelledAt, nil +} + +// ClearCancelledAt clears the value of the "cancelled_at" field. +func (m *OrdersMutation) ClearCancelledAt() { + m.cancelled_at = nil + m.clearedFields[orders.FieldCancelledAt] = struct{}{} +} + +// CancelledAtCleared returns if the "cancelled_at" field was cleared in this mutation. +func (m *OrdersMutation) CancelledAtCleared() bool { + _, ok := m.clearedFields[orders.FieldCancelledAt] + return ok +} + +// ResetCancelledAt resets all changes to the "cancelled_at" field. +func (m *OrdersMutation) ResetCancelledAt() { + m.cancelled_at = nil + delete(m.clearedFields, orders.FieldCancelledAt) +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *OrdersMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *OrdersMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the Orders entity. +// If the Orders object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrdersMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *OrdersMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the OrdersMutation builder. +func (m *OrdersMutation) Where(ps ...predicate.Orders) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the OrdersMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *OrdersMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Orders, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *OrdersMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *OrdersMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Orders). +func (m *OrdersMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *OrdersMutation) Fields() []string { + fields := make([]string, 0, 19) + if m.consumer_id != nil { + fields = append(fields, orders.FieldConsumerID) + } + if m.consumer_name != nil { + fields = append(fields, orders.FieldConsumerName) + } + if m.player_id != nil { + fields = append(fields, orders.FieldPlayerID) + } + if m.player_name != nil { + fields = append(fields, orders.FieldPlayerName) + } + if m.shop_id != nil { + fields = append(fields, orders.FieldShopID) + } + if m.shop_name != nil { + fields = append(fields, orders.FieldShopName) + } + if m.service_snapshot != nil { + fields = append(fields, orders.FieldServiceSnapshot) + } + if m.status != nil { + fields = append(fields, orders.FieldStatus) + } + if m.total_price != nil { + fields = append(fields, orders.FieldTotalPrice) + } + if m.note != nil { + fields = append(fields, orders.FieldNote) + } + if m.version != nil { + fields = append(fields, orders.FieldVersion) + } + if m.timeout_job_id != nil { + fields = append(fields, orders.FieldTimeoutJobID) + } + if m.search_text != nil { + fields = append(fields, orders.FieldSearchText) + } + if m.created_at != nil { + fields = append(fields, orders.FieldCreatedAt) + } + if m.accepted_at != nil { + fields = append(fields, orders.FieldAcceptedAt) + } + if m.closed_at != nil { + fields = append(fields, orders.FieldClosedAt) + } + if m.completed_at != nil { + fields = append(fields, orders.FieldCompletedAt) + } + if m.cancelled_at != nil { + fields = append(fields, orders.FieldCancelledAt) + } + if m.updated_at != nil { + fields = append(fields, orders.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *OrdersMutation) Field(name string) (ent.Value, bool) { + switch name { + case orders.FieldConsumerID: + return m.ConsumerID() + case orders.FieldConsumerName: + return m.ConsumerName() + case orders.FieldPlayerID: + return m.PlayerID() + case orders.FieldPlayerName: + return m.PlayerName() + case orders.FieldShopID: + return m.ShopID() + case orders.FieldShopName: + return m.ShopName() + case orders.FieldServiceSnapshot: + return m.ServiceSnapshot() + case orders.FieldStatus: + return m.Status() + case orders.FieldTotalPrice: + return m.TotalPrice() + case orders.FieldNote: + return m.Note() + case orders.FieldVersion: + return m.Version() + case orders.FieldTimeoutJobID: + return m.TimeoutJobID() + case orders.FieldSearchText: + return m.SearchText() + case orders.FieldCreatedAt: + return m.CreatedAt() + case orders.FieldAcceptedAt: + return m.AcceptedAt() + case orders.FieldClosedAt: + return m.ClosedAt() + case orders.FieldCompletedAt: + return m.CompletedAt() + case orders.FieldCancelledAt: + return m.CancelledAt() + case orders.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *OrdersMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case orders.FieldConsumerID: + return m.OldConsumerID(ctx) + case orders.FieldConsumerName: + return m.OldConsumerName(ctx) + case orders.FieldPlayerID: + return m.OldPlayerID(ctx) + case orders.FieldPlayerName: + return m.OldPlayerName(ctx) + case orders.FieldShopID: + return m.OldShopID(ctx) + case orders.FieldShopName: + return m.OldShopName(ctx) + case orders.FieldServiceSnapshot: + return m.OldServiceSnapshot(ctx) + case orders.FieldStatus: + return m.OldStatus(ctx) + case orders.FieldTotalPrice: + return m.OldTotalPrice(ctx) + case orders.FieldNote: + return m.OldNote(ctx) + case orders.FieldVersion: + return m.OldVersion(ctx) + case orders.FieldTimeoutJobID: + return m.OldTimeoutJobID(ctx) + case orders.FieldSearchText: + return m.OldSearchText(ctx) + case orders.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case orders.FieldAcceptedAt: + return m.OldAcceptedAt(ctx) + case orders.FieldClosedAt: + return m.OldClosedAt(ctx) + case orders.FieldCompletedAt: + return m.OldCompletedAt(ctx) + case orders.FieldCancelledAt: + return m.OldCancelledAt(ctx) + case orders.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Orders field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrdersMutation) SetField(name string, value ent.Value) error { + switch name { + case orders.FieldConsumerID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConsumerID(v) + return nil + case orders.FieldConsumerName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConsumerName(v) + return nil + case orders.FieldPlayerID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlayerID(v) + return nil + case orders.FieldPlayerName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlayerName(v) + return nil + case orders.FieldShopID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetShopID(v) + return nil + case orders.FieldShopName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetShopName(v) + return nil + case orders.FieldServiceSnapshot: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetServiceSnapshot(v) + return nil + case orders.FieldStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case orders.FieldTotalPrice: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotalPrice(v) + return nil + case orders.FieldNote: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNote(v) + return nil + case orders.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case orders.FieldTimeoutJobID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTimeoutJobID(v) + return nil + case orders.FieldSearchText: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSearchText(v) + return nil + case orders.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case orders.FieldAcceptedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAcceptedAt(v) + return nil + case orders.FieldClosedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetClosedAt(v) + return nil + case orders.FieldCompletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCompletedAt(v) + return nil + case orders.FieldCancelledAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCancelledAt(v) + return nil + case orders.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Orders field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *OrdersMutation) AddedFields() []string { + var fields []string + if m.addconsumer_id != nil { + fields = append(fields, orders.FieldConsumerID) + } + if m.addplayer_id != nil { + fields = append(fields, orders.FieldPlayerID) + } + if m.addshop_id != nil { + fields = append(fields, orders.FieldShopID) + } + if m.addversion != nil { + fields = append(fields, orders.FieldVersion) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *OrdersMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case orders.FieldConsumerID: + return m.AddedConsumerID() + case orders.FieldPlayerID: + return m.AddedPlayerID() + case orders.FieldShopID: + return m.AddedShopID() + case orders.FieldVersion: + return m.AddedVersion() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrdersMutation) AddField(name string, value ent.Value) error { + switch name { + case orders.FieldConsumerID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddConsumerID(v) + return nil + case orders.FieldPlayerID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPlayerID(v) + return nil + case orders.FieldShopID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddShopID(v) + return nil + case orders.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddVersion(v) + return nil + } + return fmt.Errorf("unknown Orders numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *OrdersMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(orders.FieldShopID) { + fields = append(fields, orders.FieldShopID) + } + if m.FieldCleared(orders.FieldShopName) { + fields = append(fields, orders.FieldShopName) + } + if m.FieldCleared(orders.FieldNote) { + fields = append(fields, orders.FieldNote) + } + if m.FieldCleared(orders.FieldTimeoutJobID) { + fields = append(fields, orders.FieldTimeoutJobID) + } + if m.FieldCleared(orders.FieldSearchText) { + fields = append(fields, orders.FieldSearchText) + } + if m.FieldCleared(orders.FieldAcceptedAt) { + fields = append(fields, orders.FieldAcceptedAt) + } + if m.FieldCleared(orders.FieldClosedAt) { + fields = append(fields, orders.FieldClosedAt) + } + if m.FieldCleared(orders.FieldCompletedAt) { + fields = append(fields, orders.FieldCompletedAt) + } + if m.FieldCleared(orders.FieldCancelledAt) { + fields = append(fields, orders.FieldCancelledAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *OrdersMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *OrdersMutation) ClearField(name string) error { + switch name { + case orders.FieldShopID: + m.ClearShopID() + return nil + case orders.FieldShopName: + m.ClearShopName() + return nil + case orders.FieldNote: + m.ClearNote() + return nil + case orders.FieldTimeoutJobID: + m.ClearTimeoutJobID() + return nil + case orders.FieldSearchText: + m.ClearSearchText() + return nil + case orders.FieldAcceptedAt: + m.ClearAcceptedAt() + return nil + case orders.FieldClosedAt: + m.ClearClosedAt() + return nil + case orders.FieldCompletedAt: + m.ClearCompletedAt() + return nil + case orders.FieldCancelledAt: + m.ClearCancelledAt() + return nil + } + return fmt.Errorf("unknown Orders nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *OrdersMutation) ResetField(name string) error { + switch name { + case orders.FieldConsumerID: + m.ResetConsumerID() + return nil + case orders.FieldConsumerName: + m.ResetConsumerName() + return nil + case orders.FieldPlayerID: + m.ResetPlayerID() + return nil + case orders.FieldPlayerName: + m.ResetPlayerName() + return nil + case orders.FieldShopID: + m.ResetShopID() + return nil + case orders.FieldShopName: + m.ResetShopName() + return nil + case orders.FieldServiceSnapshot: + m.ResetServiceSnapshot() + return nil + case orders.FieldStatus: + m.ResetStatus() + return nil + case orders.FieldTotalPrice: + m.ResetTotalPrice() + return nil + case orders.FieldNote: + m.ResetNote() + return nil + case orders.FieldVersion: + m.ResetVersion() + return nil + case orders.FieldTimeoutJobID: + m.ResetTimeoutJobID() + return nil + case orders.FieldSearchText: + m.ResetSearchText() + return nil + case orders.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case orders.FieldAcceptedAt: + m.ResetAcceptedAt() + return nil + case orders.FieldClosedAt: + m.ResetClosedAt() + return nil + case orders.FieldCompletedAt: + m.ResetCompletedAt() + return nil + case orders.FieldCancelledAt: + m.ResetCancelledAt() + return nil + case orders.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Orders field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *OrdersMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *OrdersMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *OrdersMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *OrdersMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *OrdersMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *OrdersMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *OrdersMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Orders unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *OrdersMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Orders edge %s", name) +} diff --git a/app/order/rpc/internal/models/orders.go b/app/order/rpc/internal/models/orders.go new file mode 100644 index 0000000..d9392ec --- /dev/null +++ b/app/order/rpc/internal/models/orders.go @@ -0,0 +1,339 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orders" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +// Orders is the model entity for the Orders schema. +type Orders struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // ConsumerID holds the value of the "consumer_id" field. + ConsumerID int64 `json:"consumer_id,omitempty"` + // ConsumerName holds the value of the "consumer_name" field. + ConsumerName string `json:"consumer_name,omitempty"` + // PlayerID holds the value of the "player_id" field. + PlayerID int64 `json:"player_id,omitempty"` + // PlayerName holds the value of the "player_name" field. + PlayerName string `json:"player_name,omitempty"` + // ShopID holds the value of the "shop_id" field. + ShopID *int64 `json:"shop_id,omitempty"` + // ShopName holds the value of the "shop_name" field. + ShopName *string `json:"shop_name,omitempty"` + // ServiceSnapshot holds the value of the "service_snapshot" field. + ServiceSnapshot map[string]interface{} `json:"service_snapshot,omitempty"` + // Status holds the value of the "status" field. + Status string `json:"status,omitempty"` + // TotalPrice holds the value of the "total_price" field. + TotalPrice decimal.Decimal `json:"total_price,omitempty"` + // Note holds the value of the "note" field. + Note *string `json:"note,omitempty"` + // Version holds the value of the "version" field. + Version int `json:"version,omitempty"` + // TimeoutJobID holds the value of the "timeout_job_id" field. + TimeoutJobID *string `json:"timeout_job_id,omitempty"` + // SearchText holds the value of the "search_text" field. + SearchText *string `json:"search_text,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // AcceptedAt holds the value of the "accepted_at" field. + AcceptedAt *time.Time `json:"accepted_at,omitempty"` + // ClosedAt holds the value of the "closed_at" field. + ClosedAt *time.Time `json:"closed_at,omitempty"` + // CompletedAt holds the value of the "completed_at" field. + CompletedAt *time.Time `json:"completed_at,omitempty"` + // CancelledAt holds the value of the "cancelled_at" field. + CancelledAt *time.Time `json:"cancelled_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Orders) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case orders.FieldServiceSnapshot: + values[i] = new([]byte) + case orders.FieldTotalPrice: + values[i] = new(decimal.Decimal) + case orders.FieldID, orders.FieldConsumerID, orders.FieldPlayerID, orders.FieldShopID, orders.FieldVersion: + values[i] = new(sql.NullInt64) + case orders.FieldConsumerName, orders.FieldPlayerName, orders.FieldShopName, orders.FieldStatus, orders.FieldNote, orders.FieldTimeoutJobID, orders.FieldSearchText: + values[i] = new(sql.NullString) + case orders.FieldCreatedAt, orders.FieldAcceptedAt, orders.FieldClosedAt, orders.FieldCompletedAt, orders.FieldCancelledAt, orders.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Orders fields. +func (_m *Orders) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case orders.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case orders.FieldConsumerID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field consumer_id", values[i]) + } else if value.Valid { + _m.ConsumerID = value.Int64 + } + case orders.FieldConsumerName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field consumer_name", values[i]) + } else if value.Valid { + _m.ConsumerName = value.String + } + case orders.FieldPlayerID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field player_id", values[i]) + } else if value.Valid { + _m.PlayerID = value.Int64 + } + case orders.FieldPlayerName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field player_name", values[i]) + } else if value.Valid { + _m.PlayerName = value.String + } + case orders.FieldShopID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field shop_id", values[i]) + } else if value.Valid { + _m.ShopID = new(int64) + *_m.ShopID = value.Int64 + } + case orders.FieldShopName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field shop_name", values[i]) + } else if value.Valid { + _m.ShopName = new(string) + *_m.ShopName = value.String + } + case orders.FieldServiceSnapshot: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field service_snapshot", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.ServiceSnapshot); err != nil { + return fmt.Errorf("unmarshal field service_snapshot: %w", err) + } + } + case orders.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + _m.Status = value.String + } + case orders.FieldTotalPrice: + if value, ok := values[i].(*decimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field total_price", values[i]) + } else if value != nil { + _m.TotalPrice = *value + } + case orders.FieldNote: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field note", values[i]) + } else if value.Valid { + _m.Note = new(string) + *_m.Note = value.String + } + case orders.FieldVersion: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + _m.Version = int(value.Int64) + } + case orders.FieldTimeoutJobID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field timeout_job_id", values[i]) + } else if value.Valid { + _m.TimeoutJobID = new(string) + *_m.TimeoutJobID = value.String + } + case orders.FieldSearchText: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field search_text", values[i]) + } else if value.Valid { + _m.SearchText = new(string) + *_m.SearchText = value.String + } + case orders.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case orders.FieldAcceptedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field accepted_at", values[i]) + } else if value.Valid { + _m.AcceptedAt = new(time.Time) + *_m.AcceptedAt = value.Time + } + case orders.FieldClosedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field closed_at", values[i]) + } else if value.Valid { + _m.ClosedAt = new(time.Time) + *_m.ClosedAt = value.Time + } + case orders.FieldCompletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field completed_at", values[i]) + } else if value.Valid { + _m.CompletedAt = new(time.Time) + *_m.CompletedAt = value.Time + } + case orders.FieldCancelledAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field cancelled_at", values[i]) + } else if value.Valid { + _m.CancelledAt = new(time.Time) + *_m.CancelledAt = value.Time + } + case orders.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Orders. +// This includes values selected through modifiers, order, etc. +func (_m *Orders) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Orders. +// Note that you need to call Orders.Unwrap() before calling this method if this Orders +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Orders) Update() *OrdersUpdateOne { + return NewOrdersClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Orders entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Orders) Unwrap() *Orders { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Orders is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Orders) String() string { + var builder strings.Builder + builder.WriteString("Orders(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("consumer_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ConsumerID)) + builder.WriteString(", ") + builder.WriteString("consumer_name=") + builder.WriteString(_m.ConsumerName) + builder.WriteString(", ") + builder.WriteString("player_id=") + builder.WriteString(fmt.Sprintf("%v", _m.PlayerID)) + builder.WriteString(", ") + builder.WriteString("player_name=") + builder.WriteString(_m.PlayerName) + builder.WriteString(", ") + if v := _m.ShopID; v != nil { + builder.WriteString("shop_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.ShopName; v != nil { + builder.WriteString("shop_name=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("service_snapshot=") + builder.WriteString(fmt.Sprintf("%v", _m.ServiceSnapshot)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(_m.Status) + builder.WriteString(", ") + builder.WriteString("total_price=") + builder.WriteString(fmt.Sprintf("%v", _m.TotalPrice)) + builder.WriteString(", ") + if v := _m.Note; v != nil { + builder.WriteString("note=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(fmt.Sprintf("%v", _m.Version)) + builder.WriteString(", ") + if v := _m.TimeoutJobID; v != nil { + builder.WriteString("timeout_job_id=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.SearchText; v != nil { + builder.WriteString("search_text=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.AcceptedAt; v != nil { + builder.WriteString("accepted_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.ClosedAt; v != nil { + builder.WriteString("closed_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.CompletedAt; v != nil { + builder.WriteString("completed_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.CancelledAt; v != nil { + builder.WriteString("cancelled_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// OrdersSlice is a parsable slice of Orders. +type OrdersSlice []*Orders diff --git a/app/order/rpc/internal/models/orders/orders.go b/app/order/rpc/internal/models/orders/orders.go new file mode 100644 index 0000000..c0c9428 --- /dev/null +++ b/app/order/rpc/internal/models/orders/orders.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package orders + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the orders type in the database. + Label = "orders" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldConsumerID holds the string denoting the consumer_id field in the database. + FieldConsumerID = "consumer_id" + // FieldConsumerName holds the string denoting the consumer_name field in the database. + FieldConsumerName = "consumer_name" + // FieldPlayerID holds the string denoting the player_id field in the database. + FieldPlayerID = "player_id" + // FieldPlayerName holds the string denoting the player_name field in the database. + FieldPlayerName = "player_name" + // FieldShopID holds the string denoting the shop_id field in the database. + FieldShopID = "shop_id" + // FieldShopName holds the string denoting the shop_name field in the database. + FieldShopName = "shop_name" + // FieldServiceSnapshot holds the string denoting the service_snapshot field in the database. + FieldServiceSnapshot = "service_snapshot" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldTotalPrice holds the string denoting the total_price field in the database. + FieldTotalPrice = "total_price" + // FieldNote holds the string denoting the note field in the database. + FieldNote = "note" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldTimeoutJobID holds the string denoting the timeout_job_id field in the database. + FieldTimeoutJobID = "timeout_job_id" + // FieldSearchText holds the string denoting the search_text field in the database. + FieldSearchText = "search_text" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldAcceptedAt holds the string denoting the accepted_at field in the database. + FieldAcceptedAt = "accepted_at" + // FieldClosedAt holds the string denoting the closed_at field in the database. + FieldClosedAt = "closed_at" + // FieldCompletedAt holds the string denoting the completed_at field in the database. + FieldCompletedAt = "completed_at" + // FieldCancelledAt holds the string denoting the cancelled_at field in the database. + FieldCancelledAt = "cancelled_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // Table holds the table name of the orders in the database. + Table = "orders" +) + +// Columns holds all SQL columns for orders fields. +var Columns = []string{ + FieldID, + FieldConsumerID, + FieldConsumerName, + FieldPlayerID, + FieldPlayerName, + FieldShopID, + FieldShopName, + FieldServiceSnapshot, + FieldStatus, + FieldTotalPrice, + FieldNote, + FieldVersion, + FieldTimeoutJobID, + FieldSearchText, + FieldCreatedAt, + FieldAcceptedAt, + FieldClosedAt, + FieldCompletedAt, + FieldCancelledAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // ConsumerNameValidator is a validator for the "consumer_name" field. It is called by the builders before save. + ConsumerNameValidator func(string) error + // PlayerNameValidator is a validator for the "player_name" field. It is called by the builders before save. + PlayerNameValidator func(string) error + // ShopNameValidator is a validator for the "shop_name" field. It is called by the builders before save. + ShopNameValidator func(string) error + // DefaultStatus holds the default value on creation for the "status" field. + DefaultStatus string + // StatusValidator is a validator for the "status" field. It is called by the builders before save. + StatusValidator func(string) error + // DefaultVersion holds the default value on creation for the "version" field. + DefaultVersion int + // TimeoutJobIDValidator is a validator for the "timeout_job_id" field. It is called by the builders before save. + TimeoutJobIDValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Orders queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByConsumerID orders the results by the consumer_id field. +func ByConsumerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldConsumerID, opts...).ToFunc() +} + +// ByConsumerName orders the results by the consumer_name field. +func ByConsumerName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldConsumerName, opts...).ToFunc() +} + +// ByPlayerID orders the results by the player_id field. +func ByPlayerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPlayerID, opts...).ToFunc() +} + +// ByPlayerName orders the results by the player_name field. +func ByPlayerName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPlayerName, opts...).ToFunc() +} + +// ByShopID orders the results by the shop_id field. +func ByShopID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldShopID, opts...).ToFunc() +} + +// ByShopName orders the results by the shop_name field. +func ByShopName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldShopName, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByTotalPrice orders the results by the total_price field. +func ByTotalPrice(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTotalPrice, opts...).ToFunc() +} + +// ByNote orders the results by the note field. +func ByNote(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNote, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByTimeoutJobID orders the results by the timeout_job_id field. +func ByTimeoutJobID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTimeoutJobID, opts...).ToFunc() +} + +// BySearchText orders the results by the search_text field. +func BySearchText(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSearchText, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByAcceptedAt orders the results by the accepted_at field. +func ByAcceptedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAcceptedAt, opts...).ToFunc() +} + +// ByClosedAt orders the results by the closed_at field. +func ByClosedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldClosedAt, opts...).ToFunc() +} + +// ByCompletedAt orders the results by the completed_at field. +func ByCompletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCompletedAt, opts...).ToFunc() +} + +// ByCancelledAt orders the results by the cancelled_at field. +func ByCancelledAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCancelledAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} diff --git a/app/order/rpc/internal/models/orders/where.go b/app/order/rpc/internal/models/orders/where.go new file mode 100644 index 0000000..943f411 --- /dev/null +++ b/app/order/rpc/internal/models/orders/where.go @@ -0,0 +1,1146 @@ +// Code generated by ent, DO NOT EDIT. + +package orders + +import ( + "juwan-backend/app/order/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldID, id)) +} + +// ConsumerID applies equality check predicate on the "consumer_id" field. It's identical to ConsumerIDEQ. +func ConsumerID(v int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldConsumerID, v)) +} + +// ConsumerName applies equality check predicate on the "consumer_name" field. It's identical to ConsumerNameEQ. +func ConsumerName(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldConsumerName, v)) +} + +// PlayerID applies equality check predicate on the "player_id" field. It's identical to PlayerIDEQ. +func PlayerID(v int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldPlayerID, v)) +} + +// PlayerName applies equality check predicate on the "player_name" field. It's identical to PlayerNameEQ. +func PlayerName(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldPlayerName, v)) +} + +// ShopID applies equality check predicate on the "shop_id" field. It's identical to ShopIDEQ. +func ShopID(v int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldShopID, v)) +} + +// ShopName applies equality check predicate on the "shop_name" field. It's identical to ShopNameEQ. +func ShopName(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldShopName, v)) +} + +// Status applies equality check predicate on the "status" field. It's identical to StatusEQ. +func Status(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldStatus, v)) +} + +// TotalPrice applies equality check predicate on the "total_price" field. It's identical to TotalPriceEQ. +func TotalPrice(v decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldTotalPrice, v)) +} + +// Note applies equality check predicate on the "note" field. It's identical to NoteEQ. +func Note(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldNote, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v int) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldVersion, v)) +} + +// TimeoutJobID applies equality check predicate on the "timeout_job_id" field. It's identical to TimeoutJobIDEQ. +func TimeoutJobID(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldTimeoutJobID, v)) +} + +// SearchText applies equality check predicate on the "search_text" field. It's identical to SearchTextEQ. +func SearchText(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldSearchText, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldCreatedAt, v)) +} + +// AcceptedAt applies equality check predicate on the "accepted_at" field. It's identical to AcceptedAtEQ. +func AcceptedAt(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldAcceptedAt, v)) +} + +// ClosedAt applies equality check predicate on the "closed_at" field. It's identical to ClosedAtEQ. +func ClosedAt(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldClosedAt, v)) +} + +// CompletedAt applies equality check predicate on the "completed_at" field. It's identical to CompletedAtEQ. +func CompletedAt(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldCompletedAt, v)) +} + +// CancelledAt applies equality check predicate on the "cancelled_at" field. It's identical to CancelledAtEQ. +func CancelledAt(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldCancelledAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// ConsumerIDEQ applies the EQ predicate on the "consumer_id" field. +func ConsumerIDEQ(v int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldConsumerID, v)) +} + +// ConsumerIDNEQ applies the NEQ predicate on the "consumer_id" field. +func ConsumerIDNEQ(v int64) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldConsumerID, v)) +} + +// ConsumerIDIn applies the In predicate on the "consumer_id" field. +func ConsumerIDIn(vs ...int64) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldConsumerID, vs...)) +} + +// ConsumerIDNotIn applies the NotIn predicate on the "consumer_id" field. +func ConsumerIDNotIn(vs ...int64) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldConsumerID, vs...)) +} + +// ConsumerIDGT applies the GT predicate on the "consumer_id" field. +func ConsumerIDGT(v int64) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldConsumerID, v)) +} + +// ConsumerIDGTE applies the GTE predicate on the "consumer_id" field. +func ConsumerIDGTE(v int64) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldConsumerID, v)) +} + +// ConsumerIDLT applies the LT predicate on the "consumer_id" field. +func ConsumerIDLT(v int64) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldConsumerID, v)) +} + +// ConsumerIDLTE applies the LTE predicate on the "consumer_id" field. +func ConsumerIDLTE(v int64) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldConsumerID, v)) +} + +// ConsumerNameEQ applies the EQ predicate on the "consumer_name" field. +func ConsumerNameEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldConsumerName, v)) +} + +// ConsumerNameNEQ applies the NEQ predicate on the "consumer_name" field. +func ConsumerNameNEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldConsumerName, v)) +} + +// ConsumerNameIn applies the In predicate on the "consumer_name" field. +func ConsumerNameIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldConsumerName, vs...)) +} + +// ConsumerNameNotIn applies the NotIn predicate on the "consumer_name" field. +func ConsumerNameNotIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldConsumerName, vs...)) +} + +// ConsumerNameGT applies the GT predicate on the "consumer_name" field. +func ConsumerNameGT(v string) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldConsumerName, v)) +} + +// ConsumerNameGTE applies the GTE predicate on the "consumer_name" field. +func ConsumerNameGTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldConsumerName, v)) +} + +// ConsumerNameLT applies the LT predicate on the "consumer_name" field. +func ConsumerNameLT(v string) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldConsumerName, v)) +} + +// ConsumerNameLTE applies the LTE predicate on the "consumer_name" field. +func ConsumerNameLTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldConsumerName, v)) +} + +// ConsumerNameContains applies the Contains predicate on the "consumer_name" field. +func ConsumerNameContains(v string) predicate.Orders { + return predicate.Orders(sql.FieldContains(FieldConsumerName, v)) +} + +// ConsumerNameHasPrefix applies the HasPrefix predicate on the "consumer_name" field. +func ConsumerNameHasPrefix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasPrefix(FieldConsumerName, v)) +} + +// ConsumerNameHasSuffix applies the HasSuffix predicate on the "consumer_name" field. +func ConsumerNameHasSuffix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasSuffix(FieldConsumerName, v)) +} + +// ConsumerNameEqualFold applies the EqualFold predicate on the "consumer_name" field. +func ConsumerNameEqualFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldEqualFold(FieldConsumerName, v)) +} + +// ConsumerNameContainsFold applies the ContainsFold predicate on the "consumer_name" field. +func ConsumerNameContainsFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldContainsFold(FieldConsumerName, v)) +} + +// PlayerIDEQ applies the EQ predicate on the "player_id" field. +func PlayerIDEQ(v int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldPlayerID, v)) +} + +// PlayerIDNEQ applies the NEQ predicate on the "player_id" field. +func PlayerIDNEQ(v int64) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldPlayerID, v)) +} + +// PlayerIDIn applies the In predicate on the "player_id" field. +func PlayerIDIn(vs ...int64) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldPlayerID, vs...)) +} + +// PlayerIDNotIn applies the NotIn predicate on the "player_id" field. +func PlayerIDNotIn(vs ...int64) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldPlayerID, vs...)) +} + +// PlayerIDGT applies the GT predicate on the "player_id" field. +func PlayerIDGT(v int64) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldPlayerID, v)) +} + +// PlayerIDGTE applies the GTE predicate on the "player_id" field. +func PlayerIDGTE(v int64) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldPlayerID, v)) +} + +// PlayerIDLT applies the LT predicate on the "player_id" field. +func PlayerIDLT(v int64) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldPlayerID, v)) +} + +// PlayerIDLTE applies the LTE predicate on the "player_id" field. +func PlayerIDLTE(v int64) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldPlayerID, v)) +} + +// PlayerNameEQ applies the EQ predicate on the "player_name" field. +func PlayerNameEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldPlayerName, v)) +} + +// PlayerNameNEQ applies the NEQ predicate on the "player_name" field. +func PlayerNameNEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldPlayerName, v)) +} + +// PlayerNameIn applies the In predicate on the "player_name" field. +func PlayerNameIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldPlayerName, vs...)) +} + +// PlayerNameNotIn applies the NotIn predicate on the "player_name" field. +func PlayerNameNotIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldPlayerName, vs...)) +} + +// PlayerNameGT applies the GT predicate on the "player_name" field. +func PlayerNameGT(v string) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldPlayerName, v)) +} + +// PlayerNameGTE applies the GTE predicate on the "player_name" field. +func PlayerNameGTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldPlayerName, v)) +} + +// PlayerNameLT applies the LT predicate on the "player_name" field. +func PlayerNameLT(v string) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldPlayerName, v)) +} + +// PlayerNameLTE applies the LTE predicate on the "player_name" field. +func PlayerNameLTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldPlayerName, v)) +} + +// PlayerNameContains applies the Contains predicate on the "player_name" field. +func PlayerNameContains(v string) predicate.Orders { + return predicate.Orders(sql.FieldContains(FieldPlayerName, v)) +} + +// PlayerNameHasPrefix applies the HasPrefix predicate on the "player_name" field. +func PlayerNameHasPrefix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasPrefix(FieldPlayerName, v)) +} + +// PlayerNameHasSuffix applies the HasSuffix predicate on the "player_name" field. +func PlayerNameHasSuffix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasSuffix(FieldPlayerName, v)) +} + +// PlayerNameEqualFold applies the EqualFold predicate on the "player_name" field. +func PlayerNameEqualFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldEqualFold(FieldPlayerName, v)) +} + +// PlayerNameContainsFold applies the ContainsFold predicate on the "player_name" field. +func PlayerNameContainsFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldContainsFold(FieldPlayerName, v)) +} + +// ShopIDEQ applies the EQ predicate on the "shop_id" field. +func ShopIDEQ(v int64) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldShopID, v)) +} + +// ShopIDNEQ applies the NEQ predicate on the "shop_id" field. +func ShopIDNEQ(v int64) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldShopID, v)) +} + +// ShopIDIn applies the In predicate on the "shop_id" field. +func ShopIDIn(vs ...int64) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldShopID, vs...)) +} + +// ShopIDNotIn applies the NotIn predicate on the "shop_id" field. +func ShopIDNotIn(vs ...int64) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldShopID, vs...)) +} + +// ShopIDGT applies the GT predicate on the "shop_id" field. +func ShopIDGT(v int64) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldShopID, v)) +} + +// ShopIDGTE applies the GTE predicate on the "shop_id" field. +func ShopIDGTE(v int64) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldShopID, v)) +} + +// ShopIDLT applies the LT predicate on the "shop_id" field. +func ShopIDLT(v int64) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldShopID, v)) +} + +// ShopIDLTE applies the LTE predicate on the "shop_id" field. +func ShopIDLTE(v int64) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldShopID, v)) +} + +// ShopIDIsNil applies the IsNil predicate on the "shop_id" field. +func ShopIDIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldShopID)) +} + +// ShopIDNotNil applies the NotNil predicate on the "shop_id" field. +func ShopIDNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldShopID)) +} + +// ShopNameEQ applies the EQ predicate on the "shop_name" field. +func ShopNameEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldShopName, v)) +} + +// ShopNameNEQ applies the NEQ predicate on the "shop_name" field. +func ShopNameNEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldShopName, v)) +} + +// ShopNameIn applies the In predicate on the "shop_name" field. +func ShopNameIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldShopName, vs...)) +} + +// ShopNameNotIn applies the NotIn predicate on the "shop_name" field. +func ShopNameNotIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldShopName, vs...)) +} + +// ShopNameGT applies the GT predicate on the "shop_name" field. +func ShopNameGT(v string) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldShopName, v)) +} + +// ShopNameGTE applies the GTE predicate on the "shop_name" field. +func ShopNameGTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldShopName, v)) +} + +// ShopNameLT applies the LT predicate on the "shop_name" field. +func ShopNameLT(v string) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldShopName, v)) +} + +// ShopNameLTE applies the LTE predicate on the "shop_name" field. +func ShopNameLTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldShopName, v)) +} + +// ShopNameContains applies the Contains predicate on the "shop_name" field. +func ShopNameContains(v string) predicate.Orders { + return predicate.Orders(sql.FieldContains(FieldShopName, v)) +} + +// ShopNameHasPrefix applies the HasPrefix predicate on the "shop_name" field. +func ShopNameHasPrefix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasPrefix(FieldShopName, v)) +} + +// ShopNameHasSuffix applies the HasSuffix predicate on the "shop_name" field. +func ShopNameHasSuffix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasSuffix(FieldShopName, v)) +} + +// ShopNameIsNil applies the IsNil predicate on the "shop_name" field. +func ShopNameIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldShopName)) +} + +// ShopNameNotNil applies the NotNil predicate on the "shop_name" field. +func ShopNameNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldShopName)) +} + +// ShopNameEqualFold applies the EqualFold predicate on the "shop_name" field. +func ShopNameEqualFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldEqualFold(FieldShopName, v)) +} + +// ShopNameContainsFold applies the ContainsFold predicate on the "shop_name" field. +func ShopNameContainsFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldContainsFold(FieldShopName, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldStatus, vs...)) +} + +// StatusGT applies the GT predicate on the "status" field. +func StatusGT(v string) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldStatus, v)) +} + +// StatusGTE applies the GTE predicate on the "status" field. +func StatusGTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldStatus, v)) +} + +// StatusLT applies the LT predicate on the "status" field. +func StatusLT(v string) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldStatus, v)) +} + +// StatusLTE applies the LTE predicate on the "status" field. +func StatusLTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldStatus, v)) +} + +// StatusContains applies the Contains predicate on the "status" field. +func StatusContains(v string) predicate.Orders { + return predicate.Orders(sql.FieldContains(FieldStatus, v)) +} + +// StatusHasPrefix applies the HasPrefix predicate on the "status" field. +func StatusHasPrefix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasPrefix(FieldStatus, v)) +} + +// StatusHasSuffix applies the HasSuffix predicate on the "status" field. +func StatusHasSuffix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasSuffix(FieldStatus, v)) +} + +// StatusEqualFold applies the EqualFold predicate on the "status" field. +func StatusEqualFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldEqualFold(FieldStatus, v)) +} + +// StatusContainsFold applies the ContainsFold predicate on the "status" field. +func StatusContainsFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldContainsFold(FieldStatus, v)) +} + +// TotalPriceEQ applies the EQ predicate on the "total_price" field. +func TotalPriceEQ(v decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldTotalPrice, v)) +} + +// TotalPriceNEQ applies the NEQ predicate on the "total_price" field. +func TotalPriceNEQ(v decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldTotalPrice, v)) +} + +// TotalPriceIn applies the In predicate on the "total_price" field. +func TotalPriceIn(vs ...decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldTotalPrice, vs...)) +} + +// TotalPriceNotIn applies the NotIn predicate on the "total_price" field. +func TotalPriceNotIn(vs ...decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldTotalPrice, vs...)) +} + +// TotalPriceGT applies the GT predicate on the "total_price" field. +func TotalPriceGT(v decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldTotalPrice, v)) +} + +// TotalPriceGTE applies the GTE predicate on the "total_price" field. +func TotalPriceGTE(v decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldTotalPrice, v)) +} + +// TotalPriceLT applies the LT predicate on the "total_price" field. +func TotalPriceLT(v decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldTotalPrice, v)) +} + +// TotalPriceLTE applies the LTE predicate on the "total_price" field. +func TotalPriceLTE(v decimal.Decimal) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldTotalPrice, v)) +} + +// NoteEQ applies the EQ predicate on the "note" field. +func NoteEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldNote, v)) +} + +// NoteNEQ applies the NEQ predicate on the "note" field. +func NoteNEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldNote, v)) +} + +// NoteIn applies the In predicate on the "note" field. +func NoteIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldNote, vs...)) +} + +// NoteNotIn applies the NotIn predicate on the "note" field. +func NoteNotIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldNote, vs...)) +} + +// NoteGT applies the GT predicate on the "note" field. +func NoteGT(v string) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldNote, v)) +} + +// NoteGTE applies the GTE predicate on the "note" field. +func NoteGTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldNote, v)) +} + +// NoteLT applies the LT predicate on the "note" field. +func NoteLT(v string) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldNote, v)) +} + +// NoteLTE applies the LTE predicate on the "note" field. +func NoteLTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldNote, v)) +} + +// NoteContains applies the Contains predicate on the "note" field. +func NoteContains(v string) predicate.Orders { + return predicate.Orders(sql.FieldContains(FieldNote, v)) +} + +// NoteHasPrefix applies the HasPrefix predicate on the "note" field. +func NoteHasPrefix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasPrefix(FieldNote, v)) +} + +// NoteHasSuffix applies the HasSuffix predicate on the "note" field. +func NoteHasSuffix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasSuffix(FieldNote, v)) +} + +// NoteIsNil applies the IsNil predicate on the "note" field. +func NoteIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldNote)) +} + +// NoteNotNil applies the NotNil predicate on the "note" field. +func NoteNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldNote)) +} + +// NoteEqualFold applies the EqualFold predicate on the "note" field. +func NoteEqualFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldEqualFold(FieldNote, v)) +} + +// NoteContainsFold applies the ContainsFold predicate on the "note" field. +func NoteContainsFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldContainsFold(FieldNote, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v int) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v int) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...int) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...int) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v int) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v int) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v int) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v int) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldVersion, v)) +} + +// TimeoutJobIDEQ applies the EQ predicate on the "timeout_job_id" field. +func TimeoutJobIDEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDNEQ applies the NEQ predicate on the "timeout_job_id" field. +func TimeoutJobIDNEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDIn applies the In predicate on the "timeout_job_id" field. +func TimeoutJobIDIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldTimeoutJobID, vs...)) +} + +// TimeoutJobIDNotIn applies the NotIn predicate on the "timeout_job_id" field. +func TimeoutJobIDNotIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldTimeoutJobID, vs...)) +} + +// TimeoutJobIDGT applies the GT predicate on the "timeout_job_id" field. +func TimeoutJobIDGT(v string) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDGTE applies the GTE predicate on the "timeout_job_id" field. +func TimeoutJobIDGTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDLT applies the LT predicate on the "timeout_job_id" field. +func TimeoutJobIDLT(v string) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDLTE applies the LTE predicate on the "timeout_job_id" field. +func TimeoutJobIDLTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDContains applies the Contains predicate on the "timeout_job_id" field. +func TimeoutJobIDContains(v string) predicate.Orders { + return predicate.Orders(sql.FieldContains(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDHasPrefix applies the HasPrefix predicate on the "timeout_job_id" field. +func TimeoutJobIDHasPrefix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasPrefix(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDHasSuffix applies the HasSuffix predicate on the "timeout_job_id" field. +func TimeoutJobIDHasSuffix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasSuffix(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDIsNil applies the IsNil predicate on the "timeout_job_id" field. +func TimeoutJobIDIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldTimeoutJobID)) +} + +// TimeoutJobIDNotNil applies the NotNil predicate on the "timeout_job_id" field. +func TimeoutJobIDNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldTimeoutJobID)) +} + +// TimeoutJobIDEqualFold applies the EqualFold predicate on the "timeout_job_id" field. +func TimeoutJobIDEqualFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldEqualFold(FieldTimeoutJobID, v)) +} + +// TimeoutJobIDContainsFold applies the ContainsFold predicate on the "timeout_job_id" field. +func TimeoutJobIDContainsFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldContainsFold(FieldTimeoutJobID, v)) +} + +// SearchTextEQ applies the EQ predicate on the "search_text" field. +func SearchTextEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldSearchText, v)) +} + +// SearchTextNEQ applies the NEQ predicate on the "search_text" field. +func SearchTextNEQ(v string) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldSearchText, v)) +} + +// SearchTextIn applies the In predicate on the "search_text" field. +func SearchTextIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldSearchText, vs...)) +} + +// SearchTextNotIn applies the NotIn predicate on the "search_text" field. +func SearchTextNotIn(vs ...string) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldSearchText, vs...)) +} + +// SearchTextGT applies the GT predicate on the "search_text" field. +func SearchTextGT(v string) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldSearchText, v)) +} + +// SearchTextGTE applies the GTE predicate on the "search_text" field. +func SearchTextGTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldSearchText, v)) +} + +// SearchTextLT applies the LT predicate on the "search_text" field. +func SearchTextLT(v string) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldSearchText, v)) +} + +// SearchTextLTE applies the LTE predicate on the "search_text" field. +func SearchTextLTE(v string) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldSearchText, v)) +} + +// SearchTextContains applies the Contains predicate on the "search_text" field. +func SearchTextContains(v string) predicate.Orders { + return predicate.Orders(sql.FieldContains(FieldSearchText, v)) +} + +// SearchTextHasPrefix applies the HasPrefix predicate on the "search_text" field. +func SearchTextHasPrefix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasPrefix(FieldSearchText, v)) +} + +// SearchTextHasSuffix applies the HasSuffix predicate on the "search_text" field. +func SearchTextHasSuffix(v string) predicate.Orders { + return predicate.Orders(sql.FieldHasSuffix(FieldSearchText, v)) +} + +// SearchTextIsNil applies the IsNil predicate on the "search_text" field. +func SearchTextIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldSearchText)) +} + +// SearchTextNotNil applies the NotNil predicate on the "search_text" field. +func SearchTextNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldSearchText)) +} + +// SearchTextEqualFold applies the EqualFold predicate on the "search_text" field. +func SearchTextEqualFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldEqualFold(FieldSearchText, v)) +} + +// SearchTextContainsFold applies the ContainsFold predicate on the "search_text" field. +func SearchTextContainsFold(v string) predicate.Orders { + return predicate.Orders(sql.FieldContainsFold(FieldSearchText, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldCreatedAt, v)) +} + +// AcceptedAtEQ applies the EQ predicate on the "accepted_at" field. +func AcceptedAtEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldAcceptedAt, v)) +} + +// AcceptedAtNEQ applies the NEQ predicate on the "accepted_at" field. +func AcceptedAtNEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldAcceptedAt, v)) +} + +// AcceptedAtIn applies the In predicate on the "accepted_at" field. +func AcceptedAtIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldAcceptedAt, vs...)) +} + +// AcceptedAtNotIn applies the NotIn predicate on the "accepted_at" field. +func AcceptedAtNotIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldAcceptedAt, vs...)) +} + +// AcceptedAtGT applies the GT predicate on the "accepted_at" field. +func AcceptedAtGT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldAcceptedAt, v)) +} + +// AcceptedAtGTE applies the GTE predicate on the "accepted_at" field. +func AcceptedAtGTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldAcceptedAt, v)) +} + +// AcceptedAtLT applies the LT predicate on the "accepted_at" field. +func AcceptedAtLT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldAcceptedAt, v)) +} + +// AcceptedAtLTE applies the LTE predicate on the "accepted_at" field. +func AcceptedAtLTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldAcceptedAt, v)) +} + +// AcceptedAtIsNil applies the IsNil predicate on the "accepted_at" field. +func AcceptedAtIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldAcceptedAt)) +} + +// AcceptedAtNotNil applies the NotNil predicate on the "accepted_at" field. +func AcceptedAtNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldAcceptedAt)) +} + +// ClosedAtEQ applies the EQ predicate on the "closed_at" field. +func ClosedAtEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldClosedAt, v)) +} + +// ClosedAtNEQ applies the NEQ predicate on the "closed_at" field. +func ClosedAtNEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldClosedAt, v)) +} + +// ClosedAtIn applies the In predicate on the "closed_at" field. +func ClosedAtIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldClosedAt, vs...)) +} + +// ClosedAtNotIn applies the NotIn predicate on the "closed_at" field. +func ClosedAtNotIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldClosedAt, vs...)) +} + +// ClosedAtGT applies the GT predicate on the "closed_at" field. +func ClosedAtGT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldClosedAt, v)) +} + +// ClosedAtGTE applies the GTE predicate on the "closed_at" field. +func ClosedAtGTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldClosedAt, v)) +} + +// ClosedAtLT applies the LT predicate on the "closed_at" field. +func ClosedAtLT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldClosedAt, v)) +} + +// ClosedAtLTE applies the LTE predicate on the "closed_at" field. +func ClosedAtLTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldClosedAt, v)) +} + +// ClosedAtIsNil applies the IsNil predicate on the "closed_at" field. +func ClosedAtIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldClosedAt)) +} + +// ClosedAtNotNil applies the NotNil predicate on the "closed_at" field. +func ClosedAtNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldClosedAt)) +} + +// CompletedAtEQ applies the EQ predicate on the "completed_at" field. +func CompletedAtEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldCompletedAt, v)) +} + +// CompletedAtNEQ applies the NEQ predicate on the "completed_at" field. +func CompletedAtNEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldCompletedAt, v)) +} + +// CompletedAtIn applies the In predicate on the "completed_at" field. +func CompletedAtIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldCompletedAt, vs...)) +} + +// CompletedAtNotIn applies the NotIn predicate on the "completed_at" field. +func CompletedAtNotIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldCompletedAt, vs...)) +} + +// CompletedAtGT applies the GT predicate on the "completed_at" field. +func CompletedAtGT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldCompletedAt, v)) +} + +// CompletedAtGTE applies the GTE predicate on the "completed_at" field. +func CompletedAtGTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldCompletedAt, v)) +} + +// CompletedAtLT applies the LT predicate on the "completed_at" field. +func CompletedAtLT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldCompletedAt, v)) +} + +// CompletedAtLTE applies the LTE predicate on the "completed_at" field. +func CompletedAtLTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldCompletedAt, v)) +} + +// CompletedAtIsNil applies the IsNil predicate on the "completed_at" field. +func CompletedAtIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldCompletedAt)) +} + +// CompletedAtNotNil applies the NotNil predicate on the "completed_at" field. +func CompletedAtNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldCompletedAt)) +} + +// CancelledAtEQ applies the EQ predicate on the "cancelled_at" field. +func CancelledAtEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldCancelledAt, v)) +} + +// CancelledAtNEQ applies the NEQ predicate on the "cancelled_at" field. +func CancelledAtNEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldCancelledAt, v)) +} + +// CancelledAtIn applies the In predicate on the "cancelled_at" field. +func CancelledAtIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldCancelledAt, vs...)) +} + +// CancelledAtNotIn applies the NotIn predicate on the "cancelled_at" field. +func CancelledAtNotIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldCancelledAt, vs...)) +} + +// CancelledAtGT applies the GT predicate on the "cancelled_at" field. +func CancelledAtGT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldCancelledAt, v)) +} + +// CancelledAtGTE applies the GTE predicate on the "cancelled_at" field. +func CancelledAtGTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldCancelledAt, v)) +} + +// CancelledAtLT applies the LT predicate on the "cancelled_at" field. +func CancelledAtLT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldCancelledAt, v)) +} + +// CancelledAtLTE applies the LTE predicate on the "cancelled_at" field. +func CancelledAtLTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldCancelledAt, v)) +} + +// CancelledAtIsNil applies the IsNil predicate on the "cancelled_at" field. +func CancelledAtIsNil() predicate.Orders { + return predicate.Orders(sql.FieldIsNull(FieldCancelledAt)) +} + +// CancelledAtNotNil applies the NotNil predicate on the "cancelled_at" field. +func CancelledAtNotNil() predicate.Orders { + return predicate.Orders(sql.FieldNotNull(FieldCancelledAt)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Orders { + return predicate.Orders(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Orders { + return predicate.Orders(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Orders) predicate.Orders { + return predicate.Orders(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Orders) predicate.Orders { + return predicate.Orders(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Orders) predicate.Orders { + return predicate.Orders(sql.NotPredicates(p)) +} diff --git a/app/order/rpc/internal/models/orders_create.go b/app/order/rpc/internal/models/orders_create.go new file mode 100644 index 0000000..773f362 --- /dev/null +++ b/app/order/rpc/internal/models/orders_create.go @@ -0,0 +1,555 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orders" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +// OrdersCreate is the builder for creating a Orders entity. +type OrdersCreate struct { + config + mutation *OrdersMutation + hooks []Hook +} + +// SetConsumerID sets the "consumer_id" field. +func (_c *OrdersCreate) SetConsumerID(v int64) *OrdersCreate { + _c.mutation.SetConsumerID(v) + return _c +} + +// SetConsumerName sets the "consumer_name" field. +func (_c *OrdersCreate) SetConsumerName(v string) *OrdersCreate { + _c.mutation.SetConsumerName(v) + return _c +} + +// SetPlayerID sets the "player_id" field. +func (_c *OrdersCreate) SetPlayerID(v int64) *OrdersCreate { + _c.mutation.SetPlayerID(v) + return _c +} + +// SetPlayerName sets the "player_name" field. +func (_c *OrdersCreate) SetPlayerName(v string) *OrdersCreate { + _c.mutation.SetPlayerName(v) + return _c +} + +// SetShopID sets the "shop_id" field. +func (_c *OrdersCreate) SetShopID(v int64) *OrdersCreate { + _c.mutation.SetShopID(v) + return _c +} + +// SetNillableShopID sets the "shop_id" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableShopID(v *int64) *OrdersCreate { + if v != nil { + _c.SetShopID(*v) + } + return _c +} + +// SetShopName sets the "shop_name" field. +func (_c *OrdersCreate) SetShopName(v string) *OrdersCreate { + _c.mutation.SetShopName(v) + return _c +} + +// SetNillableShopName sets the "shop_name" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableShopName(v *string) *OrdersCreate { + if v != nil { + _c.SetShopName(*v) + } + return _c +} + +// SetServiceSnapshot sets the "service_snapshot" field. +func (_c *OrdersCreate) SetServiceSnapshot(v map[string]interface{}) *OrdersCreate { + _c.mutation.SetServiceSnapshot(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *OrdersCreate) SetStatus(v string) *OrdersCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableStatus(v *string) *OrdersCreate { + if v != nil { + _c.SetStatus(*v) + } + return _c +} + +// SetTotalPrice sets the "total_price" field. +func (_c *OrdersCreate) SetTotalPrice(v decimal.Decimal) *OrdersCreate { + _c.mutation.SetTotalPrice(v) + return _c +} + +// SetNote sets the "note" field. +func (_c *OrdersCreate) SetNote(v string) *OrdersCreate { + _c.mutation.SetNote(v) + return _c +} + +// SetNillableNote sets the "note" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableNote(v *string) *OrdersCreate { + if v != nil { + _c.SetNote(*v) + } + return _c +} + +// SetVersion sets the "version" field. +func (_c *OrdersCreate) SetVersion(v int) *OrdersCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableVersion(v *int) *OrdersCreate { + if v != nil { + _c.SetVersion(*v) + } + return _c +} + +// SetTimeoutJobID sets the "timeout_job_id" field. +func (_c *OrdersCreate) SetTimeoutJobID(v string) *OrdersCreate { + _c.mutation.SetTimeoutJobID(v) + return _c +} + +// SetNillableTimeoutJobID sets the "timeout_job_id" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableTimeoutJobID(v *string) *OrdersCreate { + if v != nil { + _c.SetTimeoutJobID(*v) + } + return _c +} + +// SetSearchText sets the "search_text" field. +func (_c *OrdersCreate) SetSearchText(v string) *OrdersCreate { + _c.mutation.SetSearchText(v) + return _c +} + +// SetNillableSearchText sets the "search_text" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableSearchText(v *string) *OrdersCreate { + if v != nil { + _c.SetSearchText(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *OrdersCreate) SetCreatedAt(v time.Time) *OrdersCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableCreatedAt(v *time.Time) *OrdersCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetAcceptedAt sets the "accepted_at" field. +func (_c *OrdersCreate) SetAcceptedAt(v time.Time) *OrdersCreate { + _c.mutation.SetAcceptedAt(v) + return _c +} + +// SetNillableAcceptedAt sets the "accepted_at" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableAcceptedAt(v *time.Time) *OrdersCreate { + if v != nil { + _c.SetAcceptedAt(*v) + } + return _c +} + +// SetClosedAt sets the "closed_at" field. +func (_c *OrdersCreate) SetClosedAt(v time.Time) *OrdersCreate { + _c.mutation.SetClosedAt(v) + return _c +} + +// SetNillableClosedAt sets the "closed_at" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableClosedAt(v *time.Time) *OrdersCreate { + if v != nil { + _c.SetClosedAt(*v) + } + return _c +} + +// SetCompletedAt sets the "completed_at" field. +func (_c *OrdersCreate) SetCompletedAt(v time.Time) *OrdersCreate { + _c.mutation.SetCompletedAt(v) + return _c +} + +// SetNillableCompletedAt sets the "completed_at" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableCompletedAt(v *time.Time) *OrdersCreate { + if v != nil { + _c.SetCompletedAt(*v) + } + return _c +} + +// SetCancelledAt sets the "cancelled_at" field. +func (_c *OrdersCreate) SetCancelledAt(v time.Time) *OrdersCreate { + _c.mutation.SetCancelledAt(v) + return _c +} + +// SetNillableCancelledAt sets the "cancelled_at" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableCancelledAt(v *time.Time) *OrdersCreate { + if v != nil { + _c.SetCancelledAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *OrdersCreate) SetUpdatedAt(v time.Time) *OrdersCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *OrdersCreate) SetNillableUpdatedAt(v *time.Time) *OrdersCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *OrdersCreate) SetID(v int64) *OrdersCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the OrdersMutation object of the builder. +func (_c *OrdersCreate) Mutation() *OrdersMutation { + return _c.mutation +} + +// Save creates the Orders in the database. +func (_c *OrdersCreate) Save(ctx context.Context) (*Orders, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *OrdersCreate) SaveX(ctx context.Context) *Orders { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OrdersCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OrdersCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *OrdersCreate) defaults() { + if _, ok := _c.mutation.Status(); !ok { + v := orders.DefaultStatus + _c.mutation.SetStatus(v) + } + if _, ok := _c.mutation.Version(); !ok { + v := orders.DefaultVersion + _c.mutation.SetVersion(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := orders.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := orders.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *OrdersCreate) check() error { + if _, ok := _c.mutation.ConsumerID(); !ok { + return &ValidationError{Name: "consumer_id", err: errors.New(`models: missing required field "Orders.consumer_id"`)} + } + if _, ok := _c.mutation.ConsumerName(); !ok { + return &ValidationError{Name: "consumer_name", err: errors.New(`models: missing required field "Orders.consumer_name"`)} + } + if v, ok := _c.mutation.ConsumerName(); ok { + if err := orders.ConsumerNameValidator(v); err != nil { + return &ValidationError{Name: "consumer_name", err: fmt.Errorf(`models: validator failed for field "Orders.consumer_name": %w`, err)} + } + } + if _, ok := _c.mutation.PlayerID(); !ok { + return &ValidationError{Name: "player_id", err: errors.New(`models: missing required field "Orders.player_id"`)} + } + if _, ok := _c.mutation.PlayerName(); !ok { + return &ValidationError{Name: "player_name", err: errors.New(`models: missing required field "Orders.player_name"`)} + } + if v, ok := _c.mutation.PlayerName(); ok { + if err := orders.PlayerNameValidator(v); err != nil { + return &ValidationError{Name: "player_name", err: fmt.Errorf(`models: validator failed for field "Orders.player_name": %w`, err)} + } + } + if v, ok := _c.mutation.ShopName(); ok { + if err := orders.ShopNameValidator(v); err != nil { + return &ValidationError{Name: "shop_name", err: fmt.Errorf(`models: validator failed for field "Orders.shop_name": %w`, err)} + } + } + if _, ok := _c.mutation.ServiceSnapshot(); !ok { + return &ValidationError{Name: "service_snapshot", err: errors.New(`models: missing required field "Orders.service_snapshot"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`models: missing required field "Orders.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := orders.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Orders.status": %w`, err)} + } + } + if _, ok := _c.mutation.TotalPrice(); !ok { + return &ValidationError{Name: "total_price", err: errors.New(`models: missing required field "Orders.total_price"`)} + } + if _, ok := _c.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`models: missing required field "Orders.version"`)} + } + if v, ok := _c.mutation.TimeoutJobID(); ok { + if err := orders.TimeoutJobIDValidator(v); err != nil { + return &ValidationError{Name: "timeout_job_id", err: fmt.Errorf(`models: validator failed for field "Orders.timeout_job_id": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Orders.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Orders.updated_at"`)} + } + return nil +} + +func (_c *OrdersCreate) sqlSave(ctx context.Context) (*Orders, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *OrdersCreate) createSpec() (*Orders, *sqlgraph.CreateSpec) { + var ( + _node = &Orders{config: _c.config} + _spec = sqlgraph.NewCreateSpec(orders.Table, sqlgraph.NewFieldSpec(orders.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.ConsumerID(); ok { + _spec.SetField(orders.FieldConsumerID, field.TypeInt64, value) + _node.ConsumerID = value + } + if value, ok := _c.mutation.ConsumerName(); ok { + _spec.SetField(orders.FieldConsumerName, field.TypeString, value) + _node.ConsumerName = value + } + if value, ok := _c.mutation.PlayerID(); ok { + _spec.SetField(orders.FieldPlayerID, field.TypeInt64, value) + _node.PlayerID = value + } + if value, ok := _c.mutation.PlayerName(); ok { + _spec.SetField(orders.FieldPlayerName, field.TypeString, value) + _node.PlayerName = value + } + if value, ok := _c.mutation.ShopID(); ok { + _spec.SetField(orders.FieldShopID, field.TypeInt64, value) + _node.ShopID = &value + } + if value, ok := _c.mutation.ShopName(); ok { + _spec.SetField(orders.FieldShopName, field.TypeString, value) + _node.ShopName = &value + } + if value, ok := _c.mutation.ServiceSnapshot(); ok { + _spec.SetField(orders.FieldServiceSnapshot, field.TypeJSON, value) + _node.ServiceSnapshot = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(orders.FieldStatus, field.TypeString, value) + _node.Status = value + } + if value, ok := _c.mutation.TotalPrice(); ok { + _spec.SetField(orders.FieldTotalPrice, field.TypeOther, value) + _node.TotalPrice = value + } + if value, ok := _c.mutation.Note(); ok { + _spec.SetField(orders.FieldNote, field.TypeString, value) + _node.Note = &value + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(orders.FieldVersion, field.TypeInt, value) + _node.Version = value + } + if value, ok := _c.mutation.TimeoutJobID(); ok { + _spec.SetField(orders.FieldTimeoutJobID, field.TypeString, value) + _node.TimeoutJobID = &value + } + if value, ok := _c.mutation.SearchText(); ok { + _spec.SetField(orders.FieldSearchText, field.TypeString, value) + _node.SearchText = &value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(orders.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.AcceptedAt(); ok { + _spec.SetField(orders.FieldAcceptedAt, field.TypeTime, value) + _node.AcceptedAt = &value + } + if value, ok := _c.mutation.ClosedAt(); ok { + _spec.SetField(orders.FieldClosedAt, field.TypeTime, value) + _node.ClosedAt = &value + } + if value, ok := _c.mutation.CompletedAt(); ok { + _spec.SetField(orders.FieldCompletedAt, field.TypeTime, value) + _node.CompletedAt = &value + } + if value, ok := _c.mutation.CancelledAt(); ok { + _spec.SetField(orders.FieldCancelledAt, field.TypeTime, value) + _node.CancelledAt = &value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(orders.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + return _node, _spec +} + +// OrdersCreateBulk is the builder for creating many Orders entities in bulk. +type OrdersCreateBulk struct { + config + err error + builders []*OrdersCreate +} + +// Save creates the Orders entities in the database. +func (_c *OrdersCreateBulk) Save(ctx context.Context) ([]*Orders, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Orders, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*OrdersMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *OrdersCreateBulk) SaveX(ctx context.Context) []*Orders { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OrdersCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OrdersCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/order/rpc/internal/models/orders_delete.go b/app/order/rpc/internal/models/orders_delete.go new file mode 100644 index 0000000..e996cdf --- /dev/null +++ b/app/order/rpc/internal/models/orders_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OrdersDelete is the builder for deleting a Orders entity. +type OrdersDelete struct { + config + hooks []Hook + mutation *OrdersMutation +} + +// Where appends a list predicates to the OrdersDelete builder. +func (_d *OrdersDelete) Where(ps ...predicate.Orders) *OrdersDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *OrdersDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *OrdersDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *OrdersDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(orders.Table, sqlgraph.NewFieldSpec(orders.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// OrdersDeleteOne is the builder for deleting a single Orders entity. +type OrdersDeleteOne struct { + _d *OrdersDelete +} + +// Where appends a list predicates to the OrdersDelete builder. +func (_d *OrdersDeleteOne) Where(ps ...predicate.Orders) *OrdersDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *OrdersDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{orders.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *OrdersDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/order/rpc/internal/models/orders_query.go b/app/order/rpc/internal/models/orders_query.go new file mode 100644 index 0000000..9a939f5 --- /dev/null +++ b/app/order/rpc/internal/models/orders_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OrdersQuery is the builder for querying Orders entities. +type OrdersQuery struct { + config + ctx *QueryContext + order []orders.OrderOption + inters []Interceptor + predicates []predicate.Orders + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the OrdersQuery builder. +func (_q *OrdersQuery) Where(ps ...predicate.Orders) *OrdersQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *OrdersQuery) Limit(limit int) *OrdersQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *OrdersQuery) Offset(offset int) *OrdersQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *OrdersQuery) Unique(unique bool) *OrdersQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *OrdersQuery) Order(o ...orders.OrderOption) *OrdersQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Orders entity from the query. +// Returns a *NotFoundError when no Orders was found. +func (_q *OrdersQuery) First(ctx context.Context) (*Orders, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{orders.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *OrdersQuery) FirstX(ctx context.Context) *Orders { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Orders ID from the query. +// Returns a *NotFoundError when no Orders ID was found. +func (_q *OrdersQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{orders.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *OrdersQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Orders entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Orders entity is found. +// Returns a *NotFoundError when no Orders entities are found. +func (_q *OrdersQuery) Only(ctx context.Context) (*Orders, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{orders.Label} + default: + return nil, &NotSingularError{orders.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *OrdersQuery) OnlyX(ctx context.Context) *Orders { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Orders ID in the query. +// Returns a *NotSingularError when more than one Orders ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *OrdersQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{orders.Label} + default: + err = &NotSingularError{orders.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *OrdersQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of OrdersSlice. +func (_q *OrdersQuery) All(ctx context.Context) ([]*Orders, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Orders, *OrdersQuery]() + return withInterceptors[[]*Orders](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *OrdersQuery) AllX(ctx context.Context) []*Orders { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Orders IDs. +func (_q *OrdersQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(orders.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *OrdersQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *OrdersQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*OrdersQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *OrdersQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *OrdersQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *OrdersQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the OrdersQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *OrdersQuery) Clone() *OrdersQuery { + if _q == nil { + return nil + } + return &OrdersQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]orders.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Orders{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// ConsumerID int64 `json:"consumer_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Orders.Query(). +// GroupBy(orders.FieldConsumerID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *OrdersQuery) GroupBy(field string, fields ...string) *OrdersGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &OrdersGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = orders.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// ConsumerID int64 `json:"consumer_id,omitempty"` +// } +// +// client.Orders.Query(). +// Select(orders.FieldConsumerID). +// Scan(ctx, &v) +func (_q *OrdersQuery) Select(fields ...string) *OrdersSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &OrdersSelect{OrdersQuery: _q} + sbuild.label = orders.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a OrdersSelect configured with the given aggregations. +func (_q *OrdersQuery) Aggregate(fns ...AggregateFunc) *OrdersSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *OrdersQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !orders.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *OrdersQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Orders, error) { + var ( + nodes = []*Orders{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Orders).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Orders{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *OrdersQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *OrdersQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(orders.Table, orders.Columns, sqlgraph.NewFieldSpec(orders.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, orders.FieldID) + for i := range fields { + if fields[i] != orders.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *OrdersQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(orders.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = orders.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// OrdersGroupBy is the group-by builder for Orders entities. +type OrdersGroupBy struct { + selector + build *OrdersQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *OrdersGroupBy) Aggregate(fns ...AggregateFunc) *OrdersGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *OrdersGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrdersQuery, *OrdersGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *OrdersGroupBy) sqlScan(ctx context.Context, root *OrdersQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// OrdersSelect is the builder for selecting fields of Orders entities. +type OrdersSelect struct { + *OrdersQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *OrdersSelect) Aggregate(fns ...AggregateFunc) *OrdersSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *OrdersSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrdersQuery, *OrdersSelect](ctx, _s.OrdersQuery, _s, _s.inters, v) +} + +func (_s *OrdersSelect) sqlScan(ctx context.Context, root *OrdersQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/order/rpc/internal/models/orders_update.go b/app/order/rpc/internal/models/orders_update.go new file mode 100644 index 0000000..9f47ca1 --- /dev/null +++ b/app/order/rpc/internal/models/orders_update.go @@ -0,0 +1,1083 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +// OrdersUpdate is the builder for updating Orders entities. +type OrdersUpdate struct { + config + hooks []Hook + mutation *OrdersMutation +} + +// Where appends a list predicates to the OrdersUpdate builder. +func (_u *OrdersUpdate) Where(ps ...predicate.Orders) *OrdersUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetConsumerID sets the "consumer_id" field. +func (_u *OrdersUpdate) SetConsumerID(v int64) *OrdersUpdate { + _u.mutation.ResetConsumerID() + _u.mutation.SetConsumerID(v) + return _u +} + +// SetNillableConsumerID sets the "consumer_id" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableConsumerID(v *int64) *OrdersUpdate { + if v != nil { + _u.SetConsumerID(*v) + } + return _u +} + +// AddConsumerID adds value to the "consumer_id" field. +func (_u *OrdersUpdate) AddConsumerID(v int64) *OrdersUpdate { + _u.mutation.AddConsumerID(v) + return _u +} + +// SetConsumerName sets the "consumer_name" field. +func (_u *OrdersUpdate) SetConsumerName(v string) *OrdersUpdate { + _u.mutation.SetConsumerName(v) + return _u +} + +// SetNillableConsumerName sets the "consumer_name" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableConsumerName(v *string) *OrdersUpdate { + if v != nil { + _u.SetConsumerName(*v) + } + return _u +} + +// SetPlayerID sets the "player_id" field. +func (_u *OrdersUpdate) SetPlayerID(v int64) *OrdersUpdate { + _u.mutation.ResetPlayerID() + _u.mutation.SetPlayerID(v) + return _u +} + +// SetNillablePlayerID sets the "player_id" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillablePlayerID(v *int64) *OrdersUpdate { + if v != nil { + _u.SetPlayerID(*v) + } + return _u +} + +// AddPlayerID adds value to the "player_id" field. +func (_u *OrdersUpdate) AddPlayerID(v int64) *OrdersUpdate { + _u.mutation.AddPlayerID(v) + return _u +} + +// SetPlayerName sets the "player_name" field. +func (_u *OrdersUpdate) SetPlayerName(v string) *OrdersUpdate { + _u.mutation.SetPlayerName(v) + return _u +} + +// SetNillablePlayerName sets the "player_name" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillablePlayerName(v *string) *OrdersUpdate { + if v != nil { + _u.SetPlayerName(*v) + } + return _u +} + +// SetShopID sets the "shop_id" field. +func (_u *OrdersUpdate) SetShopID(v int64) *OrdersUpdate { + _u.mutation.ResetShopID() + _u.mutation.SetShopID(v) + return _u +} + +// SetNillableShopID sets the "shop_id" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableShopID(v *int64) *OrdersUpdate { + if v != nil { + _u.SetShopID(*v) + } + return _u +} + +// AddShopID adds value to the "shop_id" field. +func (_u *OrdersUpdate) AddShopID(v int64) *OrdersUpdate { + _u.mutation.AddShopID(v) + return _u +} + +// ClearShopID clears the value of the "shop_id" field. +func (_u *OrdersUpdate) ClearShopID() *OrdersUpdate { + _u.mutation.ClearShopID() + return _u +} + +// SetShopName sets the "shop_name" field. +func (_u *OrdersUpdate) SetShopName(v string) *OrdersUpdate { + _u.mutation.SetShopName(v) + return _u +} + +// SetNillableShopName sets the "shop_name" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableShopName(v *string) *OrdersUpdate { + if v != nil { + _u.SetShopName(*v) + } + return _u +} + +// ClearShopName clears the value of the "shop_name" field. +func (_u *OrdersUpdate) ClearShopName() *OrdersUpdate { + _u.mutation.ClearShopName() + return _u +} + +// SetServiceSnapshot sets the "service_snapshot" field. +func (_u *OrdersUpdate) SetServiceSnapshot(v map[string]interface{}) *OrdersUpdate { + _u.mutation.SetServiceSnapshot(v) + return _u +} + +// SetStatus sets the "status" field. +func (_u *OrdersUpdate) SetStatus(v string) *OrdersUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableStatus(v *string) *OrdersUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetTotalPrice sets the "total_price" field. +func (_u *OrdersUpdate) SetTotalPrice(v decimal.Decimal) *OrdersUpdate { + _u.mutation.SetTotalPrice(v) + return _u +} + +// SetNillableTotalPrice sets the "total_price" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableTotalPrice(v *decimal.Decimal) *OrdersUpdate { + if v != nil { + _u.SetTotalPrice(*v) + } + return _u +} + +// SetNote sets the "note" field. +func (_u *OrdersUpdate) SetNote(v string) *OrdersUpdate { + _u.mutation.SetNote(v) + return _u +} + +// SetNillableNote sets the "note" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableNote(v *string) *OrdersUpdate { + if v != nil { + _u.SetNote(*v) + } + return _u +} + +// ClearNote clears the value of the "note" field. +func (_u *OrdersUpdate) ClearNote() *OrdersUpdate { + _u.mutation.ClearNote() + return _u +} + +// SetVersion sets the "version" field. +func (_u *OrdersUpdate) SetVersion(v int) *OrdersUpdate { + _u.mutation.ResetVersion() + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableVersion(v *int) *OrdersUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// AddVersion adds value to the "version" field. +func (_u *OrdersUpdate) AddVersion(v int) *OrdersUpdate { + _u.mutation.AddVersion(v) + return _u +} + +// SetTimeoutJobID sets the "timeout_job_id" field. +func (_u *OrdersUpdate) SetTimeoutJobID(v string) *OrdersUpdate { + _u.mutation.SetTimeoutJobID(v) + return _u +} + +// SetNillableTimeoutJobID sets the "timeout_job_id" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableTimeoutJobID(v *string) *OrdersUpdate { + if v != nil { + _u.SetTimeoutJobID(*v) + } + return _u +} + +// ClearTimeoutJobID clears the value of the "timeout_job_id" field. +func (_u *OrdersUpdate) ClearTimeoutJobID() *OrdersUpdate { + _u.mutation.ClearTimeoutJobID() + return _u +} + +// SetSearchText sets the "search_text" field. +func (_u *OrdersUpdate) SetSearchText(v string) *OrdersUpdate { + _u.mutation.SetSearchText(v) + return _u +} + +// SetNillableSearchText sets the "search_text" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableSearchText(v *string) *OrdersUpdate { + if v != nil { + _u.SetSearchText(*v) + } + return _u +} + +// ClearSearchText clears the value of the "search_text" field. +func (_u *OrdersUpdate) ClearSearchText() *OrdersUpdate { + _u.mutation.ClearSearchText() + return _u +} + +// SetAcceptedAt sets the "accepted_at" field. +func (_u *OrdersUpdate) SetAcceptedAt(v time.Time) *OrdersUpdate { + _u.mutation.SetAcceptedAt(v) + return _u +} + +// SetNillableAcceptedAt sets the "accepted_at" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableAcceptedAt(v *time.Time) *OrdersUpdate { + if v != nil { + _u.SetAcceptedAt(*v) + } + return _u +} + +// ClearAcceptedAt clears the value of the "accepted_at" field. +func (_u *OrdersUpdate) ClearAcceptedAt() *OrdersUpdate { + _u.mutation.ClearAcceptedAt() + return _u +} + +// SetClosedAt sets the "closed_at" field. +func (_u *OrdersUpdate) SetClosedAt(v time.Time) *OrdersUpdate { + _u.mutation.SetClosedAt(v) + return _u +} + +// SetNillableClosedAt sets the "closed_at" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableClosedAt(v *time.Time) *OrdersUpdate { + if v != nil { + _u.SetClosedAt(*v) + } + return _u +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (_u *OrdersUpdate) ClearClosedAt() *OrdersUpdate { + _u.mutation.ClearClosedAt() + return _u +} + +// SetCompletedAt sets the "completed_at" field. +func (_u *OrdersUpdate) SetCompletedAt(v time.Time) *OrdersUpdate { + _u.mutation.SetCompletedAt(v) + return _u +} + +// SetNillableCompletedAt sets the "completed_at" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableCompletedAt(v *time.Time) *OrdersUpdate { + if v != nil { + _u.SetCompletedAt(*v) + } + return _u +} + +// ClearCompletedAt clears the value of the "completed_at" field. +func (_u *OrdersUpdate) ClearCompletedAt() *OrdersUpdate { + _u.mutation.ClearCompletedAt() + return _u +} + +// SetCancelledAt sets the "cancelled_at" field. +func (_u *OrdersUpdate) SetCancelledAt(v time.Time) *OrdersUpdate { + _u.mutation.SetCancelledAt(v) + return _u +} + +// SetNillableCancelledAt sets the "cancelled_at" field if the given value is not nil. +func (_u *OrdersUpdate) SetNillableCancelledAt(v *time.Time) *OrdersUpdate { + if v != nil { + _u.SetCancelledAt(*v) + } + return _u +} + +// ClearCancelledAt clears the value of the "cancelled_at" field. +func (_u *OrdersUpdate) ClearCancelledAt() *OrdersUpdate { + _u.mutation.ClearCancelledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *OrdersUpdate) SetUpdatedAt(v time.Time) *OrdersUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the OrdersMutation object of the builder. +func (_u *OrdersUpdate) Mutation() *OrdersMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *OrdersUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *OrdersUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *OrdersUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OrdersUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *OrdersUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := orders.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OrdersUpdate) check() error { + if v, ok := _u.mutation.ConsumerName(); ok { + if err := orders.ConsumerNameValidator(v); err != nil { + return &ValidationError{Name: "consumer_name", err: fmt.Errorf(`models: validator failed for field "Orders.consumer_name": %w`, err)} + } + } + if v, ok := _u.mutation.PlayerName(); ok { + if err := orders.PlayerNameValidator(v); err != nil { + return &ValidationError{Name: "player_name", err: fmt.Errorf(`models: validator failed for field "Orders.player_name": %w`, err)} + } + } + if v, ok := _u.mutation.ShopName(); ok { + if err := orders.ShopNameValidator(v); err != nil { + return &ValidationError{Name: "shop_name", err: fmt.Errorf(`models: validator failed for field "Orders.shop_name": %w`, err)} + } + } + if v, ok := _u.mutation.Status(); ok { + if err := orders.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Orders.status": %w`, err)} + } + } + if v, ok := _u.mutation.TimeoutJobID(); ok { + if err := orders.TimeoutJobIDValidator(v); err != nil { + return &ValidationError{Name: "timeout_job_id", err: fmt.Errorf(`models: validator failed for field "Orders.timeout_job_id": %w`, err)} + } + } + return nil +} + +func (_u *OrdersUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(orders.Table, orders.Columns, sqlgraph.NewFieldSpec(orders.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ConsumerID(); ok { + _spec.SetField(orders.FieldConsumerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedConsumerID(); ok { + _spec.AddField(orders.FieldConsumerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.ConsumerName(); ok { + _spec.SetField(orders.FieldConsumerName, field.TypeString, value) + } + if value, ok := _u.mutation.PlayerID(); ok { + _spec.SetField(orders.FieldPlayerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPlayerID(); ok { + _spec.AddField(orders.FieldPlayerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.PlayerName(); ok { + _spec.SetField(orders.FieldPlayerName, field.TypeString, value) + } + if value, ok := _u.mutation.ShopID(); ok { + _spec.SetField(orders.FieldShopID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedShopID(); ok { + _spec.AddField(orders.FieldShopID, field.TypeInt64, value) + } + if _u.mutation.ShopIDCleared() { + _spec.ClearField(orders.FieldShopID, field.TypeInt64) + } + if value, ok := _u.mutation.ShopName(); ok { + _spec.SetField(orders.FieldShopName, field.TypeString, value) + } + if _u.mutation.ShopNameCleared() { + _spec.ClearField(orders.FieldShopName, field.TypeString) + } + if value, ok := _u.mutation.ServiceSnapshot(); ok { + _spec.SetField(orders.FieldServiceSnapshot, field.TypeJSON, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(orders.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.TotalPrice(); ok { + _spec.SetField(orders.FieldTotalPrice, field.TypeOther, value) + } + if value, ok := _u.mutation.Note(); ok { + _spec.SetField(orders.FieldNote, field.TypeString, value) + } + if _u.mutation.NoteCleared() { + _spec.ClearField(orders.FieldNote, field.TypeString) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(orders.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedVersion(); ok { + _spec.AddField(orders.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.TimeoutJobID(); ok { + _spec.SetField(orders.FieldTimeoutJobID, field.TypeString, value) + } + if _u.mutation.TimeoutJobIDCleared() { + _spec.ClearField(orders.FieldTimeoutJobID, field.TypeString) + } + if value, ok := _u.mutation.SearchText(); ok { + _spec.SetField(orders.FieldSearchText, field.TypeString, value) + } + if _u.mutation.SearchTextCleared() { + _spec.ClearField(orders.FieldSearchText, field.TypeString) + } + if value, ok := _u.mutation.AcceptedAt(); ok { + _spec.SetField(orders.FieldAcceptedAt, field.TypeTime, value) + } + if _u.mutation.AcceptedAtCleared() { + _spec.ClearField(orders.FieldAcceptedAt, field.TypeTime) + } + if value, ok := _u.mutation.ClosedAt(); ok { + _spec.SetField(orders.FieldClosedAt, field.TypeTime, value) + } + if _u.mutation.ClosedAtCleared() { + _spec.ClearField(orders.FieldClosedAt, field.TypeTime) + } + if value, ok := _u.mutation.CompletedAt(); ok { + _spec.SetField(orders.FieldCompletedAt, field.TypeTime, value) + } + if _u.mutation.CompletedAtCleared() { + _spec.ClearField(orders.FieldCompletedAt, field.TypeTime) + } + if value, ok := _u.mutation.CancelledAt(); ok { + _spec.SetField(orders.FieldCancelledAt, field.TypeTime, value) + } + if _u.mutation.CancelledAtCleared() { + _spec.ClearField(orders.FieldCancelledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(orders.FieldUpdatedAt, field.TypeTime, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{orders.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// OrdersUpdateOne is the builder for updating a single Orders entity. +type OrdersUpdateOne struct { + config + fields []string + hooks []Hook + mutation *OrdersMutation +} + +// SetConsumerID sets the "consumer_id" field. +func (_u *OrdersUpdateOne) SetConsumerID(v int64) *OrdersUpdateOne { + _u.mutation.ResetConsumerID() + _u.mutation.SetConsumerID(v) + return _u +} + +// SetNillableConsumerID sets the "consumer_id" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableConsumerID(v *int64) *OrdersUpdateOne { + if v != nil { + _u.SetConsumerID(*v) + } + return _u +} + +// AddConsumerID adds value to the "consumer_id" field. +func (_u *OrdersUpdateOne) AddConsumerID(v int64) *OrdersUpdateOne { + _u.mutation.AddConsumerID(v) + return _u +} + +// SetConsumerName sets the "consumer_name" field. +func (_u *OrdersUpdateOne) SetConsumerName(v string) *OrdersUpdateOne { + _u.mutation.SetConsumerName(v) + return _u +} + +// SetNillableConsumerName sets the "consumer_name" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableConsumerName(v *string) *OrdersUpdateOne { + if v != nil { + _u.SetConsumerName(*v) + } + return _u +} + +// SetPlayerID sets the "player_id" field. +func (_u *OrdersUpdateOne) SetPlayerID(v int64) *OrdersUpdateOne { + _u.mutation.ResetPlayerID() + _u.mutation.SetPlayerID(v) + return _u +} + +// SetNillablePlayerID sets the "player_id" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillablePlayerID(v *int64) *OrdersUpdateOne { + if v != nil { + _u.SetPlayerID(*v) + } + return _u +} + +// AddPlayerID adds value to the "player_id" field. +func (_u *OrdersUpdateOne) AddPlayerID(v int64) *OrdersUpdateOne { + _u.mutation.AddPlayerID(v) + return _u +} + +// SetPlayerName sets the "player_name" field. +func (_u *OrdersUpdateOne) SetPlayerName(v string) *OrdersUpdateOne { + _u.mutation.SetPlayerName(v) + return _u +} + +// SetNillablePlayerName sets the "player_name" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillablePlayerName(v *string) *OrdersUpdateOne { + if v != nil { + _u.SetPlayerName(*v) + } + return _u +} + +// SetShopID sets the "shop_id" field. +func (_u *OrdersUpdateOne) SetShopID(v int64) *OrdersUpdateOne { + _u.mutation.ResetShopID() + _u.mutation.SetShopID(v) + return _u +} + +// SetNillableShopID sets the "shop_id" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableShopID(v *int64) *OrdersUpdateOne { + if v != nil { + _u.SetShopID(*v) + } + return _u +} + +// AddShopID adds value to the "shop_id" field. +func (_u *OrdersUpdateOne) AddShopID(v int64) *OrdersUpdateOne { + _u.mutation.AddShopID(v) + return _u +} + +// ClearShopID clears the value of the "shop_id" field. +func (_u *OrdersUpdateOne) ClearShopID() *OrdersUpdateOne { + _u.mutation.ClearShopID() + return _u +} + +// SetShopName sets the "shop_name" field. +func (_u *OrdersUpdateOne) SetShopName(v string) *OrdersUpdateOne { + _u.mutation.SetShopName(v) + return _u +} + +// SetNillableShopName sets the "shop_name" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableShopName(v *string) *OrdersUpdateOne { + if v != nil { + _u.SetShopName(*v) + } + return _u +} + +// ClearShopName clears the value of the "shop_name" field. +func (_u *OrdersUpdateOne) ClearShopName() *OrdersUpdateOne { + _u.mutation.ClearShopName() + return _u +} + +// SetServiceSnapshot sets the "service_snapshot" field. +func (_u *OrdersUpdateOne) SetServiceSnapshot(v map[string]interface{}) *OrdersUpdateOne { + _u.mutation.SetServiceSnapshot(v) + return _u +} + +// SetStatus sets the "status" field. +func (_u *OrdersUpdateOne) SetStatus(v string) *OrdersUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableStatus(v *string) *OrdersUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetTotalPrice sets the "total_price" field. +func (_u *OrdersUpdateOne) SetTotalPrice(v decimal.Decimal) *OrdersUpdateOne { + _u.mutation.SetTotalPrice(v) + return _u +} + +// SetNillableTotalPrice sets the "total_price" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableTotalPrice(v *decimal.Decimal) *OrdersUpdateOne { + if v != nil { + _u.SetTotalPrice(*v) + } + return _u +} + +// SetNote sets the "note" field. +func (_u *OrdersUpdateOne) SetNote(v string) *OrdersUpdateOne { + _u.mutation.SetNote(v) + return _u +} + +// SetNillableNote sets the "note" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableNote(v *string) *OrdersUpdateOne { + if v != nil { + _u.SetNote(*v) + } + return _u +} + +// ClearNote clears the value of the "note" field. +func (_u *OrdersUpdateOne) ClearNote() *OrdersUpdateOne { + _u.mutation.ClearNote() + return _u +} + +// SetVersion sets the "version" field. +func (_u *OrdersUpdateOne) SetVersion(v int) *OrdersUpdateOne { + _u.mutation.ResetVersion() + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableVersion(v *int) *OrdersUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// AddVersion adds value to the "version" field. +func (_u *OrdersUpdateOne) AddVersion(v int) *OrdersUpdateOne { + _u.mutation.AddVersion(v) + return _u +} + +// SetTimeoutJobID sets the "timeout_job_id" field. +func (_u *OrdersUpdateOne) SetTimeoutJobID(v string) *OrdersUpdateOne { + _u.mutation.SetTimeoutJobID(v) + return _u +} + +// SetNillableTimeoutJobID sets the "timeout_job_id" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableTimeoutJobID(v *string) *OrdersUpdateOne { + if v != nil { + _u.SetTimeoutJobID(*v) + } + return _u +} + +// ClearTimeoutJobID clears the value of the "timeout_job_id" field. +func (_u *OrdersUpdateOne) ClearTimeoutJobID() *OrdersUpdateOne { + _u.mutation.ClearTimeoutJobID() + return _u +} + +// SetSearchText sets the "search_text" field. +func (_u *OrdersUpdateOne) SetSearchText(v string) *OrdersUpdateOne { + _u.mutation.SetSearchText(v) + return _u +} + +// SetNillableSearchText sets the "search_text" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableSearchText(v *string) *OrdersUpdateOne { + if v != nil { + _u.SetSearchText(*v) + } + return _u +} + +// ClearSearchText clears the value of the "search_text" field. +func (_u *OrdersUpdateOne) ClearSearchText() *OrdersUpdateOne { + _u.mutation.ClearSearchText() + return _u +} + +// SetAcceptedAt sets the "accepted_at" field. +func (_u *OrdersUpdateOne) SetAcceptedAt(v time.Time) *OrdersUpdateOne { + _u.mutation.SetAcceptedAt(v) + return _u +} + +// SetNillableAcceptedAt sets the "accepted_at" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableAcceptedAt(v *time.Time) *OrdersUpdateOne { + if v != nil { + _u.SetAcceptedAt(*v) + } + return _u +} + +// ClearAcceptedAt clears the value of the "accepted_at" field. +func (_u *OrdersUpdateOne) ClearAcceptedAt() *OrdersUpdateOne { + _u.mutation.ClearAcceptedAt() + return _u +} + +// SetClosedAt sets the "closed_at" field. +func (_u *OrdersUpdateOne) SetClosedAt(v time.Time) *OrdersUpdateOne { + _u.mutation.SetClosedAt(v) + return _u +} + +// SetNillableClosedAt sets the "closed_at" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableClosedAt(v *time.Time) *OrdersUpdateOne { + if v != nil { + _u.SetClosedAt(*v) + } + return _u +} + +// ClearClosedAt clears the value of the "closed_at" field. +func (_u *OrdersUpdateOne) ClearClosedAt() *OrdersUpdateOne { + _u.mutation.ClearClosedAt() + return _u +} + +// SetCompletedAt sets the "completed_at" field. +func (_u *OrdersUpdateOne) SetCompletedAt(v time.Time) *OrdersUpdateOne { + _u.mutation.SetCompletedAt(v) + return _u +} + +// SetNillableCompletedAt sets the "completed_at" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableCompletedAt(v *time.Time) *OrdersUpdateOne { + if v != nil { + _u.SetCompletedAt(*v) + } + return _u +} + +// ClearCompletedAt clears the value of the "completed_at" field. +func (_u *OrdersUpdateOne) ClearCompletedAt() *OrdersUpdateOne { + _u.mutation.ClearCompletedAt() + return _u +} + +// SetCancelledAt sets the "cancelled_at" field. +func (_u *OrdersUpdateOne) SetCancelledAt(v time.Time) *OrdersUpdateOne { + _u.mutation.SetCancelledAt(v) + return _u +} + +// SetNillableCancelledAt sets the "cancelled_at" field if the given value is not nil. +func (_u *OrdersUpdateOne) SetNillableCancelledAt(v *time.Time) *OrdersUpdateOne { + if v != nil { + _u.SetCancelledAt(*v) + } + return _u +} + +// ClearCancelledAt clears the value of the "cancelled_at" field. +func (_u *OrdersUpdateOne) ClearCancelledAt() *OrdersUpdateOne { + _u.mutation.ClearCancelledAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *OrdersUpdateOne) SetUpdatedAt(v time.Time) *OrdersUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the OrdersMutation object of the builder. +func (_u *OrdersUpdateOne) Mutation() *OrdersMutation { + return _u.mutation +} + +// Where appends a list predicates to the OrdersUpdate builder. +func (_u *OrdersUpdateOne) Where(ps ...predicate.Orders) *OrdersUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *OrdersUpdateOne) Select(field string, fields ...string) *OrdersUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Orders entity. +func (_u *OrdersUpdateOne) Save(ctx context.Context) (*Orders, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *OrdersUpdateOne) SaveX(ctx context.Context) *Orders { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *OrdersUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OrdersUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *OrdersUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := orders.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OrdersUpdateOne) check() error { + if v, ok := _u.mutation.ConsumerName(); ok { + if err := orders.ConsumerNameValidator(v); err != nil { + return &ValidationError{Name: "consumer_name", err: fmt.Errorf(`models: validator failed for field "Orders.consumer_name": %w`, err)} + } + } + if v, ok := _u.mutation.PlayerName(); ok { + if err := orders.PlayerNameValidator(v); err != nil { + return &ValidationError{Name: "player_name", err: fmt.Errorf(`models: validator failed for field "Orders.player_name": %w`, err)} + } + } + if v, ok := _u.mutation.ShopName(); ok { + if err := orders.ShopNameValidator(v); err != nil { + return &ValidationError{Name: "shop_name", err: fmt.Errorf(`models: validator failed for field "Orders.shop_name": %w`, err)} + } + } + if v, ok := _u.mutation.Status(); ok { + if err := orders.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Orders.status": %w`, err)} + } + } + if v, ok := _u.mutation.TimeoutJobID(); ok { + if err := orders.TimeoutJobIDValidator(v); err != nil { + return &ValidationError{Name: "timeout_job_id", err: fmt.Errorf(`models: validator failed for field "Orders.timeout_job_id": %w`, err)} + } + } + return nil +} + +func (_u *OrdersUpdateOne) sqlSave(ctx context.Context) (_node *Orders, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(orders.Table, orders.Columns, sqlgraph.NewFieldSpec(orders.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Orders.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, orders.FieldID) + for _, f := range fields { + if !orders.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != orders.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ConsumerID(); ok { + _spec.SetField(orders.FieldConsumerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedConsumerID(); ok { + _spec.AddField(orders.FieldConsumerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.ConsumerName(); ok { + _spec.SetField(orders.FieldConsumerName, field.TypeString, value) + } + if value, ok := _u.mutation.PlayerID(); ok { + _spec.SetField(orders.FieldPlayerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedPlayerID(); ok { + _spec.AddField(orders.FieldPlayerID, field.TypeInt64, value) + } + if value, ok := _u.mutation.PlayerName(); ok { + _spec.SetField(orders.FieldPlayerName, field.TypeString, value) + } + if value, ok := _u.mutation.ShopID(); ok { + _spec.SetField(orders.FieldShopID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedShopID(); ok { + _spec.AddField(orders.FieldShopID, field.TypeInt64, value) + } + if _u.mutation.ShopIDCleared() { + _spec.ClearField(orders.FieldShopID, field.TypeInt64) + } + if value, ok := _u.mutation.ShopName(); ok { + _spec.SetField(orders.FieldShopName, field.TypeString, value) + } + if _u.mutation.ShopNameCleared() { + _spec.ClearField(orders.FieldShopName, field.TypeString) + } + if value, ok := _u.mutation.ServiceSnapshot(); ok { + _spec.SetField(orders.FieldServiceSnapshot, field.TypeJSON, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(orders.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.TotalPrice(); ok { + _spec.SetField(orders.FieldTotalPrice, field.TypeOther, value) + } + if value, ok := _u.mutation.Note(); ok { + _spec.SetField(orders.FieldNote, field.TypeString, value) + } + if _u.mutation.NoteCleared() { + _spec.ClearField(orders.FieldNote, field.TypeString) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(orders.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedVersion(); ok { + _spec.AddField(orders.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.TimeoutJobID(); ok { + _spec.SetField(orders.FieldTimeoutJobID, field.TypeString, value) + } + if _u.mutation.TimeoutJobIDCleared() { + _spec.ClearField(orders.FieldTimeoutJobID, field.TypeString) + } + if value, ok := _u.mutation.SearchText(); ok { + _spec.SetField(orders.FieldSearchText, field.TypeString, value) + } + if _u.mutation.SearchTextCleared() { + _spec.ClearField(orders.FieldSearchText, field.TypeString) + } + if value, ok := _u.mutation.AcceptedAt(); ok { + _spec.SetField(orders.FieldAcceptedAt, field.TypeTime, value) + } + if _u.mutation.AcceptedAtCleared() { + _spec.ClearField(orders.FieldAcceptedAt, field.TypeTime) + } + if value, ok := _u.mutation.ClosedAt(); ok { + _spec.SetField(orders.FieldClosedAt, field.TypeTime, value) + } + if _u.mutation.ClosedAtCleared() { + _spec.ClearField(orders.FieldClosedAt, field.TypeTime) + } + if value, ok := _u.mutation.CompletedAt(); ok { + _spec.SetField(orders.FieldCompletedAt, field.TypeTime, value) + } + if _u.mutation.CompletedAtCleared() { + _spec.ClearField(orders.FieldCompletedAt, field.TypeTime) + } + if value, ok := _u.mutation.CancelledAt(); ok { + _spec.SetField(orders.FieldCancelledAt, field.TypeTime, value) + } + if _u.mutation.CancelledAtCleared() { + _spec.ClearField(orders.FieldCancelledAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(orders.FieldUpdatedAt, field.TypeTime, value) + } + _node = &Orders{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{orders.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/order/rpc/internal/models/orderstatelogs.go b/app/order/rpc/internal/models/orderstatelogs.go new file mode 100644 index 0000000..0d853a2 --- /dev/null +++ b/app/order/rpc/internal/models/orderstatelogs.go @@ -0,0 +1,191 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// OrderStateLogs is the model entity for the OrderStateLogs schema. +type OrderStateLogs struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // OrderID holds the value of the "order_id" field. + OrderID int64 `json:"order_id,omitempty"` + // FromStatus holds the value of the "from_status" field. + FromStatus *string `json:"from_status,omitempty"` + // ToStatus holds the value of the "to_status" field. + ToStatus string `json:"to_status,omitempty"` + // Action holds the value of the "action" field. + Action string `json:"action,omitempty"` + // ActorID holds the value of the "actor_id" field. + ActorID int64 `json:"actor_id,omitempty"` + // ActorRole holds the value of the "actor_role" field. + ActorRole string `json:"actor_role,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]interface{} `json:"metadata,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*OrderStateLogs) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case orderstatelogs.FieldMetadata: + values[i] = new([]byte) + case orderstatelogs.FieldID, orderstatelogs.FieldOrderID, orderstatelogs.FieldActorID: + values[i] = new(sql.NullInt64) + case orderstatelogs.FieldFromStatus, orderstatelogs.FieldToStatus, orderstatelogs.FieldAction, orderstatelogs.FieldActorRole: + values[i] = new(sql.NullString) + case orderstatelogs.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the OrderStateLogs fields. +func (_m *OrderStateLogs) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case orderstatelogs.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int64(value.Int64) + case orderstatelogs.FieldOrderID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field order_id", values[i]) + } else if value.Valid { + _m.OrderID = value.Int64 + } + case orderstatelogs.FieldFromStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field from_status", values[i]) + } else if value.Valid { + _m.FromStatus = new(string) + *_m.FromStatus = value.String + } + case orderstatelogs.FieldToStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field to_status", values[i]) + } else if value.Valid { + _m.ToStatus = value.String + } + case orderstatelogs.FieldAction: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field action", values[i]) + } else if value.Valid { + _m.Action = value.String + } + case orderstatelogs.FieldActorID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field actor_id", values[i]) + } else if value.Valid { + _m.ActorID = value.Int64 + } + case orderstatelogs.FieldActorRole: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field actor_role", values[i]) + } else if value.Valid { + _m.ActorRole = value.String + } + case orderstatelogs.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case orderstatelogs.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the OrderStateLogs. +// This includes values selected through modifiers, order, etc. +func (_m *OrderStateLogs) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this OrderStateLogs. +// Note that you need to call OrderStateLogs.Unwrap() before calling this method if this OrderStateLogs +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *OrderStateLogs) Update() *OrderStateLogsUpdateOne { + return NewOrderStateLogsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the OrderStateLogs entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *OrderStateLogs) Unwrap() *OrderStateLogs { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: OrderStateLogs is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *OrderStateLogs) String() string { + var builder strings.Builder + builder.WriteString("OrderStateLogs(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("order_id=") + builder.WriteString(fmt.Sprintf("%v", _m.OrderID)) + builder.WriteString(", ") + if v := _m.FromStatus; v != nil { + builder.WriteString("from_status=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("to_status=") + builder.WriteString(_m.ToStatus) + builder.WriteString(", ") + builder.WriteString("action=") + builder.WriteString(_m.Action) + builder.WriteString(", ") + builder.WriteString("actor_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ActorID)) + builder.WriteString(", ") + builder.WriteString("actor_role=") + builder.WriteString(_m.ActorRole) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// OrderStateLogsSlice is a parsable slice of OrderStateLogs. +type OrderStateLogsSlice []*OrderStateLogs diff --git a/app/order/rpc/internal/models/orderstatelogs/orderstatelogs.go b/app/order/rpc/internal/models/orderstatelogs/orderstatelogs.go new file mode 100644 index 0000000..026ea65 --- /dev/null +++ b/app/order/rpc/internal/models/orderstatelogs/orderstatelogs.go @@ -0,0 +1,113 @@ +// Code generated by ent, DO NOT EDIT. + +package orderstatelogs + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the orderstatelogs type in the database. + Label = "order_state_logs" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldOrderID holds the string denoting the order_id field in the database. + FieldOrderID = "order_id" + // FieldFromStatus holds the string denoting the from_status field in the database. + FieldFromStatus = "from_status" + // FieldToStatus holds the string denoting the to_status field in the database. + FieldToStatus = "to_status" + // FieldAction holds the string denoting the action field in the database. + FieldAction = "action" + // FieldActorID holds the string denoting the actor_id field in the database. + FieldActorID = "actor_id" + // FieldActorRole holds the string denoting the actor_role field in the database. + FieldActorRole = "actor_role" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // Table holds the table name of the orderstatelogs in the database. + Table = "order_state_logs" +) + +// Columns holds all SQL columns for orderstatelogs fields. +var Columns = []string{ + FieldID, + FieldOrderID, + FieldFromStatus, + FieldToStatus, + FieldAction, + FieldActorID, + FieldActorRole, + FieldMetadata, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // FromStatusValidator is a validator for the "from_status" field. It is called by the builders before save. + FromStatusValidator func(string) error + // ToStatusValidator is a validator for the "to_status" field. It is called by the builders before save. + ToStatusValidator func(string) error + // ActionValidator is a validator for the "action" field. It is called by the builders before save. + ActionValidator func(string) error + // ActorRoleValidator is a validator for the "actor_role" field. It is called by the builders before save. + ActorRoleValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the OrderStateLogs queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByOrderID orders the results by the order_id field. +func ByOrderID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOrderID, opts...).ToFunc() +} + +// ByFromStatus orders the results by the from_status field. +func ByFromStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFromStatus, opts...).ToFunc() +} + +// ByToStatus orders the results by the to_status field. +func ByToStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldToStatus, opts...).ToFunc() +} + +// ByAction orders the results by the action field. +func ByAction(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAction, opts...).ToFunc() +} + +// ByActorID orders the results by the actor_id field. +func ByActorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActorID, opts...).ToFunc() +} + +// ByActorRole orders the results by the actor_role field. +func ByActorRole(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActorRole, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} diff --git a/app/order/rpc/internal/models/orderstatelogs/where.go b/app/order/rpc/internal/models/orderstatelogs/where.go new file mode 100644 index 0000000..d6fb772 --- /dev/null +++ b/app/order/rpc/internal/models/orderstatelogs/where.go @@ -0,0 +1,505 @@ +// Code generated by ent, DO NOT EDIT. + +package orderstatelogs + +import ( + "juwan-backend/app/order/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldID, id)) +} + +// OrderID applies equality check predicate on the "order_id" field. It's identical to OrderIDEQ. +func OrderID(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldOrderID, v)) +} + +// FromStatus applies equality check predicate on the "from_status" field. It's identical to FromStatusEQ. +func FromStatus(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldFromStatus, v)) +} + +// ToStatus applies equality check predicate on the "to_status" field. It's identical to ToStatusEQ. +func ToStatus(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldToStatus, v)) +} + +// Action applies equality check predicate on the "action" field. It's identical to ActionEQ. +func Action(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldAction, v)) +} + +// ActorID applies equality check predicate on the "actor_id" field. It's identical to ActorIDEQ. +func ActorID(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldActorID, v)) +} + +// ActorRole applies equality check predicate on the "actor_role" field. It's identical to ActorRoleEQ. +func ActorRole(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldActorRole, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldCreatedAt, v)) +} + +// OrderIDEQ applies the EQ predicate on the "order_id" field. +func OrderIDEQ(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldOrderID, v)) +} + +// OrderIDNEQ applies the NEQ predicate on the "order_id" field. +func OrderIDNEQ(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldOrderID, v)) +} + +// OrderIDIn applies the In predicate on the "order_id" field. +func OrderIDIn(vs ...int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldOrderID, vs...)) +} + +// OrderIDNotIn applies the NotIn predicate on the "order_id" field. +func OrderIDNotIn(vs ...int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldOrderID, vs...)) +} + +// OrderIDGT applies the GT predicate on the "order_id" field. +func OrderIDGT(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldOrderID, v)) +} + +// OrderIDGTE applies the GTE predicate on the "order_id" field. +func OrderIDGTE(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldOrderID, v)) +} + +// OrderIDLT applies the LT predicate on the "order_id" field. +func OrderIDLT(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldOrderID, v)) +} + +// OrderIDLTE applies the LTE predicate on the "order_id" field. +func OrderIDLTE(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldOrderID, v)) +} + +// FromStatusEQ applies the EQ predicate on the "from_status" field. +func FromStatusEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldFromStatus, v)) +} + +// FromStatusNEQ applies the NEQ predicate on the "from_status" field. +func FromStatusNEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldFromStatus, v)) +} + +// FromStatusIn applies the In predicate on the "from_status" field. +func FromStatusIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldFromStatus, vs...)) +} + +// FromStatusNotIn applies the NotIn predicate on the "from_status" field. +func FromStatusNotIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldFromStatus, vs...)) +} + +// FromStatusGT applies the GT predicate on the "from_status" field. +func FromStatusGT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldFromStatus, v)) +} + +// FromStatusGTE applies the GTE predicate on the "from_status" field. +func FromStatusGTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldFromStatus, v)) +} + +// FromStatusLT applies the LT predicate on the "from_status" field. +func FromStatusLT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldFromStatus, v)) +} + +// FromStatusLTE applies the LTE predicate on the "from_status" field. +func FromStatusLTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldFromStatus, v)) +} + +// FromStatusContains applies the Contains predicate on the "from_status" field. +func FromStatusContains(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContains(FieldFromStatus, v)) +} + +// FromStatusHasPrefix applies the HasPrefix predicate on the "from_status" field. +func FromStatusHasPrefix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasPrefix(FieldFromStatus, v)) +} + +// FromStatusHasSuffix applies the HasSuffix predicate on the "from_status" field. +func FromStatusHasSuffix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasSuffix(FieldFromStatus, v)) +} + +// FromStatusIsNil applies the IsNil predicate on the "from_status" field. +func FromStatusIsNil() predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIsNull(FieldFromStatus)) +} + +// FromStatusNotNil applies the NotNil predicate on the "from_status" field. +func FromStatusNotNil() predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotNull(FieldFromStatus)) +} + +// FromStatusEqualFold applies the EqualFold predicate on the "from_status" field. +func FromStatusEqualFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEqualFold(FieldFromStatus, v)) +} + +// FromStatusContainsFold applies the ContainsFold predicate on the "from_status" field. +func FromStatusContainsFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContainsFold(FieldFromStatus, v)) +} + +// ToStatusEQ applies the EQ predicate on the "to_status" field. +func ToStatusEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldToStatus, v)) +} + +// ToStatusNEQ applies the NEQ predicate on the "to_status" field. +func ToStatusNEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldToStatus, v)) +} + +// ToStatusIn applies the In predicate on the "to_status" field. +func ToStatusIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldToStatus, vs...)) +} + +// ToStatusNotIn applies the NotIn predicate on the "to_status" field. +func ToStatusNotIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldToStatus, vs...)) +} + +// ToStatusGT applies the GT predicate on the "to_status" field. +func ToStatusGT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldToStatus, v)) +} + +// ToStatusGTE applies the GTE predicate on the "to_status" field. +func ToStatusGTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldToStatus, v)) +} + +// ToStatusLT applies the LT predicate on the "to_status" field. +func ToStatusLT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldToStatus, v)) +} + +// ToStatusLTE applies the LTE predicate on the "to_status" field. +func ToStatusLTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldToStatus, v)) +} + +// ToStatusContains applies the Contains predicate on the "to_status" field. +func ToStatusContains(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContains(FieldToStatus, v)) +} + +// ToStatusHasPrefix applies the HasPrefix predicate on the "to_status" field. +func ToStatusHasPrefix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasPrefix(FieldToStatus, v)) +} + +// ToStatusHasSuffix applies the HasSuffix predicate on the "to_status" field. +func ToStatusHasSuffix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasSuffix(FieldToStatus, v)) +} + +// ToStatusEqualFold applies the EqualFold predicate on the "to_status" field. +func ToStatusEqualFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEqualFold(FieldToStatus, v)) +} + +// ToStatusContainsFold applies the ContainsFold predicate on the "to_status" field. +func ToStatusContainsFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContainsFold(FieldToStatus, v)) +} + +// ActionEQ applies the EQ predicate on the "action" field. +func ActionEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldAction, v)) +} + +// ActionNEQ applies the NEQ predicate on the "action" field. +func ActionNEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldAction, v)) +} + +// ActionIn applies the In predicate on the "action" field. +func ActionIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldAction, vs...)) +} + +// ActionNotIn applies the NotIn predicate on the "action" field. +func ActionNotIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldAction, vs...)) +} + +// ActionGT applies the GT predicate on the "action" field. +func ActionGT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldAction, v)) +} + +// ActionGTE applies the GTE predicate on the "action" field. +func ActionGTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldAction, v)) +} + +// ActionLT applies the LT predicate on the "action" field. +func ActionLT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldAction, v)) +} + +// ActionLTE applies the LTE predicate on the "action" field. +func ActionLTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldAction, v)) +} + +// ActionContains applies the Contains predicate on the "action" field. +func ActionContains(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContains(FieldAction, v)) +} + +// ActionHasPrefix applies the HasPrefix predicate on the "action" field. +func ActionHasPrefix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasPrefix(FieldAction, v)) +} + +// ActionHasSuffix applies the HasSuffix predicate on the "action" field. +func ActionHasSuffix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasSuffix(FieldAction, v)) +} + +// ActionEqualFold applies the EqualFold predicate on the "action" field. +func ActionEqualFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEqualFold(FieldAction, v)) +} + +// ActionContainsFold applies the ContainsFold predicate on the "action" field. +func ActionContainsFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContainsFold(FieldAction, v)) +} + +// ActorIDEQ applies the EQ predicate on the "actor_id" field. +func ActorIDEQ(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldActorID, v)) +} + +// ActorIDNEQ applies the NEQ predicate on the "actor_id" field. +func ActorIDNEQ(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldActorID, v)) +} + +// ActorIDIn applies the In predicate on the "actor_id" field. +func ActorIDIn(vs ...int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldActorID, vs...)) +} + +// ActorIDNotIn applies the NotIn predicate on the "actor_id" field. +func ActorIDNotIn(vs ...int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldActorID, vs...)) +} + +// ActorIDGT applies the GT predicate on the "actor_id" field. +func ActorIDGT(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldActorID, v)) +} + +// ActorIDGTE applies the GTE predicate on the "actor_id" field. +func ActorIDGTE(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldActorID, v)) +} + +// ActorIDLT applies the LT predicate on the "actor_id" field. +func ActorIDLT(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldActorID, v)) +} + +// ActorIDLTE applies the LTE predicate on the "actor_id" field. +func ActorIDLTE(v int64) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldActorID, v)) +} + +// ActorRoleEQ applies the EQ predicate on the "actor_role" field. +func ActorRoleEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldActorRole, v)) +} + +// ActorRoleNEQ applies the NEQ predicate on the "actor_role" field. +func ActorRoleNEQ(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldActorRole, v)) +} + +// ActorRoleIn applies the In predicate on the "actor_role" field. +func ActorRoleIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldActorRole, vs...)) +} + +// ActorRoleNotIn applies the NotIn predicate on the "actor_role" field. +func ActorRoleNotIn(vs ...string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldActorRole, vs...)) +} + +// ActorRoleGT applies the GT predicate on the "actor_role" field. +func ActorRoleGT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldActorRole, v)) +} + +// ActorRoleGTE applies the GTE predicate on the "actor_role" field. +func ActorRoleGTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldActorRole, v)) +} + +// ActorRoleLT applies the LT predicate on the "actor_role" field. +func ActorRoleLT(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldActorRole, v)) +} + +// ActorRoleLTE applies the LTE predicate on the "actor_role" field. +func ActorRoleLTE(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldActorRole, v)) +} + +// ActorRoleContains applies the Contains predicate on the "actor_role" field. +func ActorRoleContains(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContains(FieldActorRole, v)) +} + +// ActorRoleHasPrefix applies the HasPrefix predicate on the "actor_role" field. +func ActorRoleHasPrefix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasPrefix(FieldActorRole, v)) +} + +// ActorRoleHasSuffix applies the HasSuffix predicate on the "actor_role" field. +func ActorRoleHasSuffix(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldHasSuffix(FieldActorRole, v)) +} + +// ActorRoleEqualFold applies the EqualFold predicate on the "actor_role" field. +func ActorRoleEqualFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEqualFold(FieldActorRole, v)) +} + +// ActorRoleContainsFold applies the ContainsFold predicate on the "actor_role" field. +func ActorRoleContainsFold(v string) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldContainsFold(FieldActorRole, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.FieldLTE(FieldCreatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.OrderStateLogs) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.OrderStateLogs) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.OrderStateLogs) predicate.OrderStateLogs { + return predicate.OrderStateLogs(sql.NotPredicates(p)) +} diff --git a/app/order/rpc/internal/models/orderstatelogs_create.go b/app/order/rpc/internal/models/orderstatelogs_create.go new file mode 100644 index 0000000..2fbd98b --- /dev/null +++ b/app/order/rpc/internal/models/orderstatelogs_create.go @@ -0,0 +1,327 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OrderStateLogsCreate is the builder for creating a OrderStateLogs entity. +type OrderStateLogsCreate struct { + config + mutation *OrderStateLogsMutation + hooks []Hook +} + +// SetOrderID sets the "order_id" field. +func (_c *OrderStateLogsCreate) SetOrderID(v int64) *OrderStateLogsCreate { + _c.mutation.SetOrderID(v) + return _c +} + +// SetFromStatus sets the "from_status" field. +func (_c *OrderStateLogsCreate) SetFromStatus(v string) *OrderStateLogsCreate { + _c.mutation.SetFromStatus(v) + return _c +} + +// SetNillableFromStatus sets the "from_status" field if the given value is not nil. +func (_c *OrderStateLogsCreate) SetNillableFromStatus(v *string) *OrderStateLogsCreate { + if v != nil { + _c.SetFromStatus(*v) + } + return _c +} + +// SetToStatus sets the "to_status" field. +func (_c *OrderStateLogsCreate) SetToStatus(v string) *OrderStateLogsCreate { + _c.mutation.SetToStatus(v) + return _c +} + +// SetAction sets the "action" field. +func (_c *OrderStateLogsCreate) SetAction(v string) *OrderStateLogsCreate { + _c.mutation.SetAction(v) + return _c +} + +// SetActorID sets the "actor_id" field. +func (_c *OrderStateLogsCreate) SetActorID(v int64) *OrderStateLogsCreate { + _c.mutation.SetActorID(v) + return _c +} + +// SetActorRole sets the "actor_role" field. +func (_c *OrderStateLogsCreate) SetActorRole(v string) *OrderStateLogsCreate { + _c.mutation.SetActorRole(v) + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *OrderStateLogsCreate) SetMetadata(v map[string]interface{}) *OrderStateLogsCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *OrderStateLogsCreate) SetCreatedAt(v time.Time) *OrderStateLogsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *OrderStateLogsCreate) SetNillableCreatedAt(v *time.Time) *OrderStateLogsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *OrderStateLogsCreate) SetID(v int64) *OrderStateLogsCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the OrderStateLogsMutation object of the builder. +func (_c *OrderStateLogsCreate) Mutation() *OrderStateLogsMutation { + return _c.mutation +} + +// Save creates the OrderStateLogs in the database. +func (_c *OrderStateLogsCreate) Save(ctx context.Context) (*OrderStateLogs, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *OrderStateLogsCreate) SaveX(ctx context.Context) *OrderStateLogs { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OrderStateLogsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OrderStateLogsCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *OrderStateLogsCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := orderstatelogs.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *OrderStateLogsCreate) check() error { + if _, ok := _c.mutation.OrderID(); !ok { + return &ValidationError{Name: "order_id", err: errors.New(`models: missing required field "OrderStateLogs.order_id"`)} + } + if v, ok := _c.mutation.FromStatus(); ok { + if err := orderstatelogs.FromStatusValidator(v); err != nil { + return &ValidationError{Name: "from_status", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.from_status": %w`, err)} + } + } + if _, ok := _c.mutation.ToStatus(); !ok { + return &ValidationError{Name: "to_status", err: errors.New(`models: missing required field "OrderStateLogs.to_status"`)} + } + if v, ok := _c.mutation.ToStatus(); ok { + if err := orderstatelogs.ToStatusValidator(v); err != nil { + return &ValidationError{Name: "to_status", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.to_status": %w`, err)} + } + } + if _, ok := _c.mutation.Action(); !ok { + return &ValidationError{Name: "action", err: errors.New(`models: missing required field "OrderStateLogs.action"`)} + } + if v, ok := _c.mutation.Action(); ok { + if err := orderstatelogs.ActionValidator(v); err != nil { + return &ValidationError{Name: "action", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.action": %w`, err)} + } + } + if _, ok := _c.mutation.ActorID(); !ok { + return &ValidationError{Name: "actor_id", err: errors.New(`models: missing required field "OrderStateLogs.actor_id"`)} + } + if _, ok := _c.mutation.ActorRole(); !ok { + return &ValidationError{Name: "actor_role", err: errors.New(`models: missing required field "OrderStateLogs.actor_role"`)} + } + if v, ok := _c.mutation.ActorRole(); ok { + if err := orderstatelogs.ActorRoleValidator(v); err != nil { + return &ValidationError{Name: "actor_role", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.actor_role": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "OrderStateLogs.created_at"`)} + } + return nil +} + +func (_c *OrderStateLogsCreate) sqlSave(ctx context.Context) (*OrderStateLogs, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int64(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *OrderStateLogsCreate) createSpec() (*OrderStateLogs, *sqlgraph.CreateSpec) { + var ( + _node = &OrderStateLogs{config: _c.config} + _spec = sqlgraph.NewCreateSpec(orderstatelogs.Table, sqlgraph.NewFieldSpec(orderstatelogs.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.OrderID(); ok { + _spec.SetField(orderstatelogs.FieldOrderID, field.TypeInt64, value) + _node.OrderID = value + } + if value, ok := _c.mutation.FromStatus(); ok { + _spec.SetField(orderstatelogs.FieldFromStatus, field.TypeString, value) + _node.FromStatus = &value + } + if value, ok := _c.mutation.ToStatus(); ok { + _spec.SetField(orderstatelogs.FieldToStatus, field.TypeString, value) + _node.ToStatus = value + } + if value, ok := _c.mutation.Action(); ok { + _spec.SetField(orderstatelogs.FieldAction, field.TypeString, value) + _node.Action = value + } + if value, ok := _c.mutation.ActorID(); ok { + _spec.SetField(orderstatelogs.FieldActorID, field.TypeInt64, value) + _node.ActorID = value + } + if value, ok := _c.mutation.ActorRole(); ok { + _spec.SetField(orderstatelogs.FieldActorRole, field.TypeString, value) + _node.ActorRole = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(orderstatelogs.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(orderstatelogs.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + return _node, _spec +} + +// OrderStateLogsCreateBulk is the builder for creating many OrderStateLogs entities in bulk. +type OrderStateLogsCreateBulk struct { + config + err error + builders []*OrderStateLogsCreate +} + +// Save creates the OrderStateLogs entities in the database. +func (_c *OrderStateLogsCreateBulk) Save(ctx context.Context) ([]*OrderStateLogs, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*OrderStateLogs, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*OrderStateLogsMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int64(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *OrderStateLogsCreateBulk) SaveX(ctx context.Context) []*OrderStateLogs { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *OrderStateLogsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *OrderStateLogsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/order/rpc/internal/models/orderstatelogs_delete.go b/app/order/rpc/internal/models/orderstatelogs_delete.go new file mode 100644 index 0000000..753af2b --- /dev/null +++ b/app/order/rpc/internal/models/orderstatelogs_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "juwan-backend/app/order/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OrderStateLogsDelete is the builder for deleting a OrderStateLogs entity. +type OrderStateLogsDelete struct { + config + hooks []Hook + mutation *OrderStateLogsMutation +} + +// Where appends a list predicates to the OrderStateLogsDelete builder. +func (_d *OrderStateLogsDelete) Where(ps ...predicate.OrderStateLogs) *OrderStateLogsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *OrderStateLogsDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *OrderStateLogsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *OrderStateLogsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(orderstatelogs.Table, sqlgraph.NewFieldSpec(orderstatelogs.FieldID, field.TypeInt64)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// OrderStateLogsDeleteOne is the builder for deleting a single OrderStateLogs entity. +type OrderStateLogsDeleteOne struct { + _d *OrderStateLogsDelete +} + +// Where appends a list predicates to the OrderStateLogsDelete builder. +func (_d *OrderStateLogsDeleteOne) Where(ps ...predicate.OrderStateLogs) *OrderStateLogsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *OrderStateLogsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{orderstatelogs.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *OrderStateLogsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/order/rpc/internal/models/orderstatelogs_query.go b/app/order/rpc/internal/models/orderstatelogs_query.go new file mode 100644 index 0000000..632e1cd --- /dev/null +++ b/app/order/rpc/internal/models/orderstatelogs_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "juwan-backend/app/order/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OrderStateLogsQuery is the builder for querying OrderStateLogs entities. +type OrderStateLogsQuery struct { + config + ctx *QueryContext + order []orderstatelogs.OrderOption + inters []Interceptor + predicates []predicate.OrderStateLogs + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the OrderStateLogsQuery builder. +func (_q *OrderStateLogsQuery) Where(ps ...predicate.OrderStateLogs) *OrderStateLogsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *OrderStateLogsQuery) Limit(limit int) *OrderStateLogsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *OrderStateLogsQuery) Offset(offset int) *OrderStateLogsQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *OrderStateLogsQuery) Unique(unique bool) *OrderStateLogsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *OrderStateLogsQuery) Order(o ...orderstatelogs.OrderOption) *OrderStateLogsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first OrderStateLogs entity from the query. +// Returns a *NotFoundError when no OrderStateLogs was found. +func (_q *OrderStateLogsQuery) First(ctx context.Context) (*OrderStateLogs, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{orderstatelogs.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *OrderStateLogsQuery) FirstX(ctx context.Context) *OrderStateLogs { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first OrderStateLogs ID from the query. +// Returns a *NotFoundError when no OrderStateLogs ID was found. +func (_q *OrderStateLogsQuery) FirstID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{orderstatelogs.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *OrderStateLogsQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single OrderStateLogs entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one OrderStateLogs entity is found. +// Returns a *NotFoundError when no OrderStateLogs entities are found. +func (_q *OrderStateLogsQuery) Only(ctx context.Context) (*OrderStateLogs, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{orderstatelogs.Label} + default: + return nil, &NotSingularError{orderstatelogs.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *OrderStateLogsQuery) OnlyX(ctx context.Context) *OrderStateLogs { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only OrderStateLogs ID in the query. +// Returns a *NotSingularError when more than one OrderStateLogs ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *OrderStateLogsQuery) OnlyID(ctx context.Context) (id int64, err error) { + var ids []int64 + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{orderstatelogs.Label} + default: + err = &NotSingularError{orderstatelogs.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *OrderStateLogsQuery) OnlyIDX(ctx context.Context) int64 { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of OrderStateLogsSlice. +func (_q *OrderStateLogsQuery) All(ctx context.Context) ([]*OrderStateLogs, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*OrderStateLogs, *OrderStateLogsQuery]() + return withInterceptors[[]*OrderStateLogs](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *OrderStateLogsQuery) AllX(ctx context.Context) []*OrderStateLogs { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of OrderStateLogs IDs. +func (_q *OrderStateLogsQuery) IDs(ctx context.Context) (ids []int64, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(orderstatelogs.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *OrderStateLogsQuery) IDsX(ctx context.Context) []int64 { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *OrderStateLogsQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*OrderStateLogsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *OrderStateLogsQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *OrderStateLogsQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *OrderStateLogsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the OrderStateLogsQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *OrderStateLogsQuery) Clone() *OrderStateLogsQuery { + if _q == nil { + return nil + } + return &OrderStateLogsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]orderstatelogs.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.OrderStateLogs{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// OrderID int64 `json:"order_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.OrderStateLogs.Query(). +// GroupBy(orderstatelogs.FieldOrderID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *OrderStateLogsQuery) GroupBy(field string, fields ...string) *OrderStateLogsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &OrderStateLogsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = orderstatelogs.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// OrderID int64 `json:"order_id,omitempty"` +// } +// +// client.OrderStateLogs.Query(). +// Select(orderstatelogs.FieldOrderID). +// Scan(ctx, &v) +func (_q *OrderStateLogsQuery) Select(fields ...string) *OrderStateLogsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &OrderStateLogsSelect{OrderStateLogsQuery: _q} + sbuild.label = orderstatelogs.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a OrderStateLogsSelect configured with the given aggregations. +func (_q *OrderStateLogsQuery) Aggregate(fns ...AggregateFunc) *OrderStateLogsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *OrderStateLogsQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !orderstatelogs.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *OrderStateLogsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OrderStateLogs, error) { + var ( + nodes = []*OrderStateLogs{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*OrderStateLogs).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &OrderStateLogs{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *OrderStateLogsQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *OrderStateLogsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(orderstatelogs.Table, orderstatelogs.Columns, sqlgraph.NewFieldSpec(orderstatelogs.FieldID, field.TypeInt64)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, orderstatelogs.FieldID) + for i := range fields { + if fields[i] != orderstatelogs.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *OrderStateLogsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(orderstatelogs.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = orderstatelogs.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// OrderStateLogsGroupBy is the group-by builder for OrderStateLogs entities. +type OrderStateLogsGroupBy struct { + selector + build *OrderStateLogsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *OrderStateLogsGroupBy) Aggregate(fns ...AggregateFunc) *OrderStateLogsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *OrderStateLogsGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrderStateLogsQuery, *OrderStateLogsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *OrderStateLogsGroupBy) sqlScan(ctx context.Context, root *OrderStateLogsQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// OrderStateLogsSelect is the builder for selecting fields of OrderStateLogs entities. +type OrderStateLogsSelect struct { + *OrderStateLogsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *OrderStateLogsSelect) Aggregate(fns ...AggregateFunc) *OrderStateLogsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *OrderStateLogsSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrderStateLogsQuery, *OrderStateLogsSelect](ctx, _s.OrderStateLogsQuery, _s, _s.inters, v) +} + +func (_s *OrderStateLogsSelect) sqlScan(ctx context.Context, root *OrderStateLogsQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/order/rpc/internal/models/orderstatelogs_update.go b/app/order/rpc/internal/models/orderstatelogs_update.go new file mode 100644 index 0000000..d570a96 --- /dev/null +++ b/app/order/rpc/internal/models/orderstatelogs_update.go @@ -0,0 +1,529 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "juwan-backend/app/order/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OrderStateLogsUpdate is the builder for updating OrderStateLogs entities. +type OrderStateLogsUpdate struct { + config + hooks []Hook + mutation *OrderStateLogsMutation +} + +// Where appends a list predicates to the OrderStateLogsUpdate builder. +func (_u *OrderStateLogsUpdate) Where(ps ...predicate.OrderStateLogs) *OrderStateLogsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetOrderID sets the "order_id" field. +func (_u *OrderStateLogsUpdate) SetOrderID(v int64) *OrderStateLogsUpdate { + _u.mutation.ResetOrderID() + _u.mutation.SetOrderID(v) + return _u +} + +// SetNillableOrderID sets the "order_id" field if the given value is not nil. +func (_u *OrderStateLogsUpdate) SetNillableOrderID(v *int64) *OrderStateLogsUpdate { + if v != nil { + _u.SetOrderID(*v) + } + return _u +} + +// AddOrderID adds value to the "order_id" field. +func (_u *OrderStateLogsUpdate) AddOrderID(v int64) *OrderStateLogsUpdate { + _u.mutation.AddOrderID(v) + return _u +} + +// SetFromStatus sets the "from_status" field. +func (_u *OrderStateLogsUpdate) SetFromStatus(v string) *OrderStateLogsUpdate { + _u.mutation.SetFromStatus(v) + return _u +} + +// SetNillableFromStatus sets the "from_status" field if the given value is not nil. +func (_u *OrderStateLogsUpdate) SetNillableFromStatus(v *string) *OrderStateLogsUpdate { + if v != nil { + _u.SetFromStatus(*v) + } + return _u +} + +// ClearFromStatus clears the value of the "from_status" field. +func (_u *OrderStateLogsUpdate) ClearFromStatus() *OrderStateLogsUpdate { + _u.mutation.ClearFromStatus() + return _u +} + +// SetToStatus sets the "to_status" field. +func (_u *OrderStateLogsUpdate) SetToStatus(v string) *OrderStateLogsUpdate { + _u.mutation.SetToStatus(v) + return _u +} + +// SetNillableToStatus sets the "to_status" field if the given value is not nil. +func (_u *OrderStateLogsUpdate) SetNillableToStatus(v *string) *OrderStateLogsUpdate { + if v != nil { + _u.SetToStatus(*v) + } + return _u +} + +// SetAction sets the "action" field. +func (_u *OrderStateLogsUpdate) SetAction(v string) *OrderStateLogsUpdate { + _u.mutation.SetAction(v) + return _u +} + +// SetNillableAction sets the "action" field if the given value is not nil. +func (_u *OrderStateLogsUpdate) SetNillableAction(v *string) *OrderStateLogsUpdate { + if v != nil { + _u.SetAction(*v) + } + return _u +} + +// SetActorID sets the "actor_id" field. +func (_u *OrderStateLogsUpdate) SetActorID(v int64) *OrderStateLogsUpdate { + _u.mutation.ResetActorID() + _u.mutation.SetActorID(v) + return _u +} + +// SetNillableActorID sets the "actor_id" field if the given value is not nil. +func (_u *OrderStateLogsUpdate) SetNillableActorID(v *int64) *OrderStateLogsUpdate { + if v != nil { + _u.SetActorID(*v) + } + return _u +} + +// AddActorID adds value to the "actor_id" field. +func (_u *OrderStateLogsUpdate) AddActorID(v int64) *OrderStateLogsUpdate { + _u.mutation.AddActorID(v) + return _u +} + +// SetActorRole sets the "actor_role" field. +func (_u *OrderStateLogsUpdate) SetActorRole(v string) *OrderStateLogsUpdate { + _u.mutation.SetActorRole(v) + return _u +} + +// SetNillableActorRole sets the "actor_role" field if the given value is not nil. +func (_u *OrderStateLogsUpdate) SetNillableActorRole(v *string) *OrderStateLogsUpdate { + if v != nil { + _u.SetActorRole(*v) + } + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *OrderStateLogsUpdate) SetMetadata(v map[string]interface{}) *OrderStateLogsUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *OrderStateLogsUpdate) ClearMetadata() *OrderStateLogsUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// Mutation returns the OrderStateLogsMutation object of the builder. +func (_u *OrderStateLogsUpdate) Mutation() *OrderStateLogsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *OrderStateLogsUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *OrderStateLogsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *OrderStateLogsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OrderStateLogsUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OrderStateLogsUpdate) check() error { + if v, ok := _u.mutation.FromStatus(); ok { + if err := orderstatelogs.FromStatusValidator(v); err != nil { + return &ValidationError{Name: "from_status", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.from_status": %w`, err)} + } + } + if v, ok := _u.mutation.ToStatus(); ok { + if err := orderstatelogs.ToStatusValidator(v); err != nil { + return &ValidationError{Name: "to_status", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.to_status": %w`, err)} + } + } + if v, ok := _u.mutation.Action(); ok { + if err := orderstatelogs.ActionValidator(v); err != nil { + return &ValidationError{Name: "action", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.action": %w`, err)} + } + } + if v, ok := _u.mutation.ActorRole(); ok { + if err := orderstatelogs.ActorRoleValidator(v); err != nil { + return &ValidationError{Name: "actor_role", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.actor_role": %w`, err)} + } + } + return nil +} + +func (_u *OrderStateLogsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(orderstatelogs.Table, orderstatelogs.Columns, sqlgraph.NewFieldSpec(orderstatelogs.FieldID, field.TypeInt64)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.OrderID(); ok { + _spec.SetField(orderstatelogs.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedOrderID(); ok { + _spec.AddField(orderstatelogs.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.FromStatus(); ok { + _spec.SetField(orderstatelogs.FieldFromStatus, field.TypeString, value) + } + if _u.mutation.FromStatusCleared() { + _spec.ClearField(orderstatelogs.FieldFromStatus, field.TypeString) + } + if value, ok := _u.mutation.ToStatus(); ok { + _spec.SetField(orderstatelogs.FieldToStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Action(); ok { + _spec.SetField(orderstatelogs.FieldAction, field.TypeString, value) + } + if value, ok := _u.mutation.ActorID(); ok { + _spec.SetField(orderstatelogs.FieldActorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedActorID(); ok { + _spec.AddField(orderstatelogs.FieldActorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.ActorRole(); ok { + _spec.SetField(orderstatelogs.FieldActorRole, field.TypeString, value) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(orderstatelogs.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(orderstatelogs.FieldMetadata, field.TypeJSON) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{orderstatelogs.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// OrderStateLogsUpdateOne is the builder for updating a single OrderStateLogs entity. +type OrderStateLogsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *OrderStateLogsMutation +} + +// SetOrderID sets the "order_id" field. +func (_u *OrderStateLogsUpdateOne) SetOrderID(v int64) *OrderStateLogsUpdateOne { + _u.mutation.ResetOrderID() + _u.mutation.SetOrderID(v) + return _u +} + +// SetNillableOrderID sets the "order_id" field if the given value is not nil. +func (_u *OrderStateLogsUpdateOne) SetNillableOrderID(v *int64) *OrderStateLogsUpdateOne { + if v != nil { + _u.SetOrderID(*v) + } + return _u +} + +// AddOrderID adds value to the "order_id" field. +func (_u *OrderStateLogsUpdateOne) AddOrderID(v int64) *OrderStateLogsUpdateOne { + _u.mutation.AddOrderID(v) + return _u +} + +// SetFromStatus sets the "from_status" field. +func (_u *OrderStateLogsUpdateOne) SetFromStatus(v string) *OrderStateLogsUpdateOne { + _u.mutation.SetFromStatus(v) + return _u +} + +// SetNillableFromStatus sets the "from_status" field if the given value is not nil. +func (_u *OrderStateLogsUpdateOne) SetNillableFromStatus(v *string) *OrderStateLogsUpdateOne { + if v != nil { + _u.SetFromStatus(*v) + } + return _u +} + +// ClearFromStatus clears the value of the "from_status" field. +func (_u *OrderStateLogsUpdateOne) ClearFromStatus() *OrderStateLogsUpdateOne { + _u.mutation.ClearFromStatus() + return _u +} + +// SetToStatus sets the "to_status" field. +func (_u *OrderStateLogsUpdateOne) SetToStatus(v string) *OrderStateLogsUpdateOne { + _u.mutation.SetToStatus(v) + return _u +} + +// SetNillableToStatus sets the "to_status" field if the given value is not nil. +func (_u *OrderStateLogsUpdateOne) SetNillableToStatus(v *string) *OrderStateLogsUpdateOne { + if v != nil { + _u.SetToStatus(*v) + } + return _u +} + +// SetAction sets the "action" field. +func (_u *OrderStateLogsUpdateOne) SetAction(v string) *OrderStateLogsUpdateOne { + _u.mutation.SetAction(v) + return _u +} + +// SetNillableAction sets the "action" field if the given value is not nil. +func (_u *OrderStateLogsUpdateOne) SetNillableAction(v *string) *OrderStateLogsUpdateOne { + if v != nil { + _u.SetAction(*v) + } + return _u +} + +// SetActorID sets the "actor_id" field. +func (_u *OrderStateLogsUpdateOne) SetActorID(v int64) *OrderStateLogsUpdateOne { + _u.mutation.ResetActorID() + _u.mutation.SetActorID(v) + return _u +} + +// SetNillableActorID sets the "actor_id" field if the given value is not nil. +func (_u *OrderStateLogsUpdateOne) SetNillableActorID(v *int64) *OrderStateLogsUpdateOne { + if v != nil { + _u.SetActorID(*v) + } + return _u +} + +// AddActorID adds value to the "actor_id" field. +func (_u *OrderStateLogsUpdateOne) AddActorID(v int64) *OrderStateLogsUpdateOne { + _u.mutation.AddActorID(v) + return _u +} + +// SetActorRole sets the "actor_role" field. +func (_u *OrderStateLogsUpdateOne) SetActorRole(v string) *OrderStateLogsUpdateOne { + _u.mutation.SetActorRole(v) + return _u +} + +// SetNillableActorRole sets the "actor_role" field if the given value is not nil. +func (_u *OrderStateLogsUpdateOne) SetNillableActorRole(v *string) *OrderStateLogsUpdateOne { + if v != nil { + _u.SetActorRole(*v) + } + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *OrderStateLogsUpdateOne) SetMetadata(v map[string]interface{}) *OrderStateLogsUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *OrderStateLogsUpdateOne) ClearMetadata() *OrderStateLogsUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// Mutation returns the OrderStateLogsMutation object of the builder. +func (_u *OrderStateLogsUpdateOne) Mutation() *OrderStateLogsMutation { + return _u.mutation +} + +// Where appends a list predicates to the OrderStateLogsUpdate builder. +func (_u *OrderStateLogsUpdateOne) Where(ps ...predicate.OrderStateLogs) *OrderStateLogsUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *OrderStateLogsUpdateOne) Select(field string, fields ...string) *OrderStateLogsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated OrderStateLogs entity. +func (_u *OrderStateLogsUpdateOne) Save(ctx context.Context) (*OrderStateLogs, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *OrderStateLogsUpdateOne) SaveX(ctx context.Context) *OrderStateLogs { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *OrderStateLogsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *OrderStateLogsUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *OrderStateLogsUpdateOne) check() error { + if v, ok := _u.mutation.FromStatus(); ok { + if err := orderstatelogs.FromStatusValidator(v); err != nil { + return &ValidationError{Name: "from_status", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.from_status": %w`, err)} + } + } + if v, ok := _u.mutation.ToStatus(); ok { + if err := orderstatelogs.ToStatusValidator(v); err != nil { + return &ValidationError{Name: "to_status", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.to_status": %w`, err)} + } + } + if v, ok := _u.mutation.Action(); ok { + if err := orderstatelogs.ActionValidator(v); err != nil { + return &ValidationError{Name: "action", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.action": %w`, err)} + } + } + if v, ok := _u.mutation.ActorRole(); ok { + if err := orderstatelogs.ActorRoleValidator(v); err != nil { + return &ValidationError{Name: "actor_role", err: fmt.Errorf(`models: validator failed for field "OrderStateLogs.actor_role": %w`, err)} + } + } + return nil +} + +func (_u *OrderStateLogsUpdateOne) sqlSave(ctx context.Context) (_node *OrderStateLogs, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(orderstatelogs.Table, orderstatelogs.Columns, sqlgraph.NewFieldSpec(orderstatelogs.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "OrderStateLogs.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, orderstatelogs.FieldID) + for _, f := range fields { + if !orderstatelogs.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != orderstatelogs.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.OrderID(); ok { + _spec.SetField(orderstatelogs.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedOrderID(); ok { + _spec.AddField(orderstatelogs.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.FromStatus(); ok { + _spec.SetField(orderstatelogs.FieldFromStatus, field.TypeString, value) + } + if _u.mutation.FromStatusCleared() { + _spec.ClearField(orderstatelogs.FieldFromStatus, field.TypeString) + } + if value, ok := _u.mutation.ToStatus(); ok { + _spec.SetField(orderstatelogs.FieldToStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Action(); ok { + _spec.SetField(orderstatelogs.FieldAction, field.TypeString, value) + } + if value, ok := _u.mutation.ActorID(); ok { + _spec.SetField(orderstatelogs.FieldActorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedActorID(); ok { + _spec.AddField(orderstatelogs.FieldActorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.ActorRole(); ok { + _spec.SetField(orderstatelogs.FieldActorRole, field.TypeString, value) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(orderstatelogs.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(orderstatelogs.FieldMetadata, field.TypeJSON) + } + _node = &OrderStateLogs{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{orderstatelogs.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/order/rpc/internal/models/predicate/predicate.go b/app/order/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..fed817f --- /dev/null +++ b/app/order/rpc/internal/models/predicate/predicate.go @@ -0,0 +1,13 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// OrderStateLogs is the predicate function for orderstatelogs builders. +type OrderStateLogs func(*sql.Selector) + +// Orders is the predicate function for orders builders. +type Orders func(*sql.Selector) diff --git a/app/order/rpc/internal/models/runtime.go b/app/order/rpc/internal/models/runtime.go new file mode 100644 index 0000000..0342bba --- /dev/null +++ b/app/order/rpc/internal/models/runtime.go @@ -0,0 +1,76 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/order/rpc/internal/models/orders" + "juwan-backend/app/order/rpc/internal/models/orderstatelogs" + "juwan-backend/app/order/rpc/internal/models/schema" + "time" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + orderstatelogsFields := schema.OrderStateLogs{}.Fields() + _ = orderstatelogsFields + // orderstatelogsDescFromStatus is the schema descriptor for from_status field. + orderstatelogsDescFromStatus := orderstatelogsFields[2].Descriptor() + // orderstatelogs.FromStatusValidator is a validator for the "from_status" field. It is called by the builders before save. + orderstatelogs.FromStatusValidator = orderstatelogsDescFromStatus.Validators[0].(func(string) error) + // orderstatelogsDescToStatus is the schema descriptor for to_status field. + orderstatelogsDescToStatus := orderstatelogsFields[3].Descriptor() + // orderstatelogs.ToStatusValidator is a validator for the "to_status" field. It is called by the builders before save. + orderstatelogs.ToStatusValidator = orderstatelogsDescToStatus.Validators[0].(func(string) error) + // orderstatelogsDescAction is the schema descriptor for action field. + orderstatelogsDescAction := orderstatelogsFields[4].Descriptor() + // orderstatelogs.ActionValidator is a validator for the "action" field. It is called by the builders before save. + orderstatelogs.ActionValidator = orderstatelogsDescAction.Validators[0].(func(string) error) + // orderstatelogsDescActorRole is the schema descriptor for actor_role field. + orderstatelogsDescActorRole := orderstatelogsFields[6].Descriptor() + // orderstatelogs.ActorRoleValidator is a validator for the "actor_role" field. It is called by the builders before save. + orderstatelogs.ActorRoleValidator = orderstatelogsDescActorRole.Validators[0].(func(string) error) + // orderstatelogsDescCreatedAt is the schema descriptor for created_at field. + orderstatelogsDescCreatedAt := orderstatelogsFields[8].Descriptor() + // orderstatelogs.DefaultCreatedAt holds the default value on creation for the created_at field. + orderstatelogs.DefaultCreatedAt = orderstatelogsDescCreatedAt.Default.(func() time.Time) + ordersFields := schema.Orders{}.Fields() + _ = ordersFields + // ordersDescConsumerName is the schema descriptor for consumer_name field. + ordersDescConsumerName := ordersFields[2].Descriptor() + // orders.ConsumerNameValidator is a validator for the "consumer_name" field. It is called by the builders before save. + orders.ConsumerNameValidator = ordersDescConsumerName.Validators[0].(func(string) error) + // ordersDescPlayerName is the schema descriptor for player_name field. + ordersDescPlayerName := ordersFields[4].Descriptor() + // orders.PlayerNameValidator is a validator for the "player_name" field. It is called by the builders before save. + orders.PlayerNameValidator = ordersDescPlayerName.Validators[0].(func(string) error) + // ordersDescShopName is the schema descriptor for shop_name field. + ordersDescShopName := ordersFields[6].Descriptor() + // orders.ShopNameValidator is a validator for the "shop_name" field. It is called by the builders before save. + orders.ShopNameValidator = ordersDescShopName.Validators[0].(func(string) error) + // ordersDescStatus is the schema descriptor for status field. + ordersDescStatus := ordersFields[8].Descriptor() + // orders.DefaultStatus holds the default value on creation for the status field. + orders.DefaultStatus = ordersDescStatus.Default.(string) + // orders.StatusValidator is a validator for the "status" field. It is called by the builders before save. + orders.StatusValidator = ordersDescStatus.Validators[0].(func(string) error) + // ordersDescVersion is the schema descriptor for version field. + ordersDescVersion := ordersFields[11].Descriptor() + // orders.DefaultVersion holds the default value on creation for the version field. + orders.DefaultVersion = ordersDescVersion.Default.(int) + // ordersDescTimeoutJobID is the schema descriptor for timeout_job_id field. + ordersDescTimeoutJobID := ordersFields[12].Descriptor() + // orders.TimeoutJobIDValidator is a validator for the "timeout_job_id" field. It is called by the builders before save. + orders.TimeoutJobIDValidator = ordersDescTimeoutJobID.Validators[0].(func(string) error) + // ordersDescCreatedAt is the schema descriptor for created_at field. + ordersDescCreatedAt := ordersFields[14].Descriptor() + // orders.DefaultCreatedAt holds the default value on creation for the created_at field. + orders.DefaultCreatedAt = ordersDescCreatedAt.Default.(func() time.Time) + // ordersDescUpdatedAt is the schema descriptor for updated_at field. + ordersDescUpdatedAt := ordersFields[19].Descriptor() + // orders.DefaultUpdatedAt holds the default value on creation for the updated_at field. + orders.DefaultUpdatedAt = ordersDescUpdatedAt.Default.(func() time.Time) + // orders.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + orders.UpdateDefaultUpdatedAt = ordersDescUpdatedAt.UpdateDefault.(func() time.Time) +} diff --git a/app/order/rpc/internal/models/runtime/runtime.go b/app/order/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..1d0b06c --- /dev/null +++ b/app/order/rpc/internal/models/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in juwan-backend/app/order/rpc/internal/models/runtime.go + +const ( + Version = "v0.14.5" // Version of ent codegen. + Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. +) diff --git a/app/order/rpc/internal/models/schema/orders.go b/app/order/rpc/internal/models/schema/orders.go new file mode 100644 index 0000000..200cc0d --- /dev/null +++ b/app/order/rpc/internal/models/schema/orders.go @@ -0,0 +1,63 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +// Orders holds the schema definition for the Orders entity. +type Orders struct { + ent.Schema +} + +// Annotations of the Orders. +func (Orders) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{ + Table: "orders", + Checks: map[string]string{ + "chk_order_status": "status IN ('pending_payment', 'pending_accept', 'in_progress', 'pending_close', 'pending_review', 'disputed', 'completed', 'cancelled')", + "chk_price_positive": "total_price > 0", + }, + }, + } +} + +// Fields of the Orders. +func (Orders) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Immutable().Unique(), + field.Int64("consumer_id"), + field.String("consumer_name").MaxLen(100), + field.Int64("player_id"), + field.String("player_name").MaxLen(100), + field.Int64("shop_id").Optional().Nillable(), + field.String("shop_name").Optional().Nillable().MaxLen(200), + field.JSON("service_snapshot", map[string]any{}). + SchemaType(map[string]string{dialect.Postgres: "jsonb"}), + field.String("status").Default("pending_payment").MaxLen(30), + field.Other("total_price", decimal.Decimal{}). + SchemaType(map[string]string{dialect.Postgres: "decimal(10,2)"}), + field.String("note").Optional().Nillable(), + field.Int("version").Default(1), + field.String("timeout_job_id").Optional().Nillable().MaxLen(100), + field.String("search_text").Optional().Nillable(), + field.Time("created_at").Default(time.Now).Immutable(), + field.Time("accepted_at").Optional().Nillable(), + field.Time("closed_at").Optional().Nillable(), + field.Time("completed_at").Optional().Nillable(), + field.Time("cancelled_at").Optional().Nillable(), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the Orders. +func (Orders) Edges() []ent.Edge { + return nil +} diff --git a/app/order/rpc/internal/models/schema/orderstatelogs.go b/app/order/rpc/internal/models/schema/orderstatelogs.go new file mode 100644 index 0000000..29e7e92 --- /dev/null +++ b/app/order/rpc/internal/models/schema/orderstatelogs.go @@ -0,0 +1,47 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// OrderStateLogs holds the schema definition for the OrderStateLogs entity. +type OrderStateLogs struct { + ent.Schema +} + +// Annotations of the OrderStateLogs. +func (OrderStateLogs) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{ + Table: "order_state_logs", + }, + } +} + +// Fields of the OrderStateLogs. +func (OrderStateLogs) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Immutable().Unique(), + field.Int64("order_id"), + field.String("from_status").Optional().Nillable().MaxLen(30), + field.String("to_status").MaxLen(30), + field.String("action").MaxLen(50), + field.Int64("actor_id"), + field.String("actor_role").MaxLen(20), + field.JSON("metadata", map[string]any{}). + Optional(). + SchemaType(map[string]string{dialect.Postgres: "jsonb"}), + field.Time("created_at").Default(time.Now).Immutable(), + } +} + +// Edges of the OrderStateLogs. +func (OrderStateLogs) Edges() []ent.Edge { + return nil +} diff --git a/app/order/rpc/internal/models/tx.go b/app/order/rpc/internal/models/tx.go new file mode 100644 index 0000000..ac403f7 --- /dev/null +++ b/app/order/rpc/internal/models/tx.go @@ -0,0 +1,213 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // OrderStateLogs is the client for interacting with the OrderStateLogs builders. + OrderStateLogs *OrderStateLogsClient + // Orders is the client for interacting with the Orders builders. + Orders *OrdersClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.OrderStateLogs = NewOrderStateLogsClient(tx.config) + tx.Orders = NewOrdersClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: OrderStateLogs.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/app/order/rpc/internal/server/orderServiceServer.go b/app/order/rpc/internal/server/orderServiceServer.go new file mode 100644 index 0000000..bf8116e --- /dev/null +++ b/app/order/rpc/internal/server/orderServiceServer.go @@ -0,0 +1,76 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 +// Source: order.proto + +package server + +import ( + "context" + + "juwan-backend/app/order/rpc/internal/logic" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" +) + +type OrderServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedOrderServiceServer +} + +func NewOrderServiceServer(svcCtx *svc.ServiceContext) *OrderServiceServer { + return &OrderServiceServer{ + svcCtx: svcCtx, + } +} + +// -----------------------orders----------------------- +func (s *OrderServiceServer) AddOrders(ctx context.Context, in *pb.AddOrdersReq) (*pb.AddOrdersResp, error) { + l := logic.NewAddOrdersLogic(ctx, s.svcCtx) + return l.AddOrders(in) +} + +func (s *OrderServiceServer) UpdateOrders(ctx context.Context, in *pb.UpdateOrdersReq) (*pb.UpdateOrdersResp, error) { + l := logic.NewUpdateOrdersLogic(ctx, s.svcCtx) + return l.UpdateOrders(in) +} + +func (s *OrderServiceServer) DelOrders(ctx context.Context, in *pb.DelOrdersReq) (*pb.DelOrdersResp, error) { + l := logic.NewDelOrdersLogic(ctx, s.svcCtx) + return l.DelOrders(in) +} + +func (s *OrderServiceServer) GetOrdersById(ctx context.Context, in *pb.GetOrdersByIdReq) (*pb.GetOrdersByIdResp, error) { + l := logic.NewGetOrdersByIdLogic(ctx, s.svcCtx) + return l.GetOrdersById(in) +} + +func (s *OrderServiceServer) SearchOrders(ctx context.Context, in *pb.SearchOrdersReq) (*pb.SearchOrdersResp, error) { + l := logic.NewSearchOrdersLogic(ctx, s.svcCtx) + return l.SearchOrders(in) +} + +// -----------------------orderStateLogs----------------------- +func (s *OrderServiceServer) AddOrderStateLogs(ctx context.Context, in *pb.AddOrderStateLogsReq) (*pb.AddOrderStateLogsResp, error) { + l := logic.NewAddOrderStateLogsLogic(ctx, s.svcCtx) + return l.AddOrderStateLogs(in) +} + +func (s *OrderServiceServer) UpdateOrderStateLogs(ctx context.Context, in *pb.UpdateOrderStateLogsReq) (*pb.UpdateOrderStateLogsResp, error) { + l := logic.NewUpdateOrderStateLogsLogic(ctx, s.svcCtx) + return l.UpdateOrderStateLogs(in) +} + +func (s *OrderServiceServer) DelOrderStateLogs(ctx context.Context, in *pb.DelOrderStateLogsReq) (*pb.DelOrderStateLogsResp, error) { + l := logic.NewDelOrderStateLogsLogic(ctx, s.svcCtx) + return l.DelOrderStateLogs(in) +} + +func (s *OrderServiceServer) GetOrderStateLogsById(ctx context.Context, in *pb.GetOrderStateLogsByIdReq) (*pb.GetOrderStateLogsByIdResp, error) { + l := logic.NewGetOrderStateLogsByIdLogic(ctx, s.svcCtx) + return l.GetOrderStateLogsById(in) +} + +func (s *OrderServiceServer) SearchOrderStateLogs(ctx context.Context, in *pb.SearchOrderStateLogsReq) (*pb.SearchOrderStateLogsResp, error) { + l := logic.NewSearchOrderStateLogsLogic(ctx, s.svcCtx) + return l.SearchOrderStateLogs(in) +} diff --git a/app/order/rpc/internal/svc/serviceContext.go b/app/order/rpc/internal/svc/serviceContext.go new file mode 100644 index 0000000..4dff72f --- /dev/null +++ b/app/order/rpc/internal/svc/serviceContext.go @@ -0,0 +1,63 @@ +package svc + +import ( + "fmt" + "strings" + "time" + + "ariga.io/entcache" + "entgo.io/ent/dialect/sql" + "github.com/zeromicro/go-zero/core/logx" + "juwan-backend/app/order/rpc/internal/config" + "juwan-backend/app/order/rpc/internal/models" + "juwan-backend/app/snowflake/rpc/snowflake" + "juwan-backend/common/redisx" + "juwan-backend/common/snowflakex" + "juwan-backend/pkg/adapter" +) + +type ServiceContext struct { + Config config.Config + Snowflake snowflake.SnowflakeServiceClient + OrderModelsRW *models.Client + OrderModelsRO *models.Client +} + +func NewServiceContext(c config.Config) *ServiceContext { + RWConn, err := sql.Open("pgx", c.DB.Master) + if err != nil { + panic(err) + } + ROConn, err := sql.Open("pgx", c.DB.Slaves) + if err != nil { + panic(err) + } + + redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second) + if redisCluster == nil || err != nil { + logx.Errorf("failed to connect to Redis cluster: %v", err) + panic(err) + } + // snowflakex.NewClient(c.SnowflakeRpcConf) + + RWDrv := entcache.NewDriver(RWConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) + RODrv := entcache.NewDriver(ROConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) + + entLogFn := func(v ...any) { + logx.Infof("[ent][order] %s", fmt.Sprint(v...)) + } + + rwOpts := []models.Option{models.Driver(RWDrv), models.Log(entLogFn)} + roOpts := []models.Option{models.Driver(RODrv), models.Log(entLogFn)} + if strings.EqualFold(c.Log.Level, "debug") { + rwOpts = append(rwOpts, models.Debug()) + roOpts = append(roOpts, models.Debug()) + } + + return &ServiceContext{ + Config: c, + Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), + OrderModelsRW: models.NewClient(rwOpts...), + OrderModelsRO: models.NewClient(roOpts...), + } +} diff --git a/app/order/rpc/orderservice/orderService.go b/app/order/rpc/orderservice/orderService.go new file mode 100644 index 0000000..969c7fa --- /dev/null +++ b/app/order/rpc/orderservice/orderService.go @@ -0,0 +1,116 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 +// Source: order.proto + +package orderservice + +import ( + "context" + + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + AddOrderStateLogsReq = pb.AddOrderStateLogsReq + AddOrderStateLogsResp = pb.AddOrderStateLogsResp + AddOrdersReq = pb.AddOrdersReq + AddOrdersResp = pb.AddOrdersResp + DelOrderStateLogsReq = pb.DelOrderStateLogsReq + DelOrderStateLogsResp = pb.DelOrderStateLogsResp + DelOrdersReq = pb.DelOrdersReq + DelOrdersResp = pb.DelOrdersResp + GetOrderStateLogsByIdReq = pb.GetOrderStateLogsByIdReq + GetOrderStateLogsByIdResp = pb.GetOrderStateLogsByIdResp + GetOrdersByIdReq = pb.GetOrdersByIdReq + GetOrdersByIdResp = pb.GetOrdersByIdResp + OrderStateLogs = pb.OrderStateLogs + Orders = pb.Orders + SearchOrderStateLogsReq = pb.SearchOrderStateLogsReq + SearchOrderStateLogsResp = pb.SearchOrderStateLogsResp + SearchOrdersReq = pb.SearchOrdersReq + SearchOrdersResp = pb.SearchOrdersResp + UpdateOrderStateLogsReq = pb.UpdateOrderStateLogsReq + UpdateOrderStateLogsResp = pb.UpdateOrderStateLogsResp + UpdateOrdersReq = pb.UpdateOrdersReq + UpdateOrdersResp = pb.UpdateOrdersResp + + OrderService interface { + // -----------------------orders----------------------- + AddOrders(ctx context.Context, in *AddOrdersReq, opts ...grpc.CallOption) (*AddOrdersResp, error) + UpdateOrders(ctx context.Context, in *UpdateOrdersReq, opts ...grpc.CallOption) (*UpdateOrdersResp, error) + DelOrders(ctx context.Context, in *DelOrdersReq, opts ...grpc.CallOption) (*DelOrdersResp, error) + GetOrdersById(ctx context.Context, in *GetOrdersByIdReq, opts ...grpc.CallOption) (*GetOrdersByIdResp, error) + SearchOrders(ctx context.Context, in *SearchOrdersReq, opts ...grpc.CallOption) (*SearchOrdersResp, error) + // -----------------------orderStateLogs----------------------- + AddOrderStateLogs(ctx context.Context, in *AddOrderStateLogsReq, opts ...grpc.CallOption) (*AddOrderStateLogsResp, error) + UpdateOrderStateLogs(ctx context.Context, in *UpdateOrderStateLogsReq, opts ...grpc.CallOption) (*UpdateOrderStateLogsResp, error) + DelOrderStateLogs(ctx context.Context, in *DelOrderStateLogsReq, opts ...grpc.CallOption) (*DelOrderStateLogsResp, error) + GetOrderStateLogsById(ctx context.Context, in *GetOrderStateLogsByIdReq, opts ...grpc.CallOption) (*GetOrderStateLogsByIdResp, error) + SearchOrderStateLogs(ctx context.Context, in *SearchOrderStateLogsReq, opts ...grpc.CallOption) (*SearchOrderStateLogsResp, error) + } + + defaultOrderService struct { + cli zrpc.Client + } +) + +func NewOrderService(cli zrpc.Client) OrderService { + return &defaultOrderService{ + cli: cli, + } +} + +// -----------------------orders----------------------- +func (m *defaultOrderService) AddOrders(ctx context.Context, in *AddOrdersReq, opts ...grpc.CallOption) (*AddOrdersResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.AddOrders(ctx, in, opts...) +} + +func (m *defaultOrderService) UpdateOrders(ctx context.Context, in *UpdateOrdersReq, opts ...grpc.CallOption) (*UpdateOrdersResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.UpdateOrders(ctx, in, opts...) +} + +func (m *defaultOrderService) DelOrders(ctx context.Context, in *DelOrdersReq, opts ...grpc.CallOption) (*DelOrdersResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.DelOrders(ctx, in, opts...) +} + +func (m *defaultOrderService) GetOrdersById(ctx context.Context, in *GetOrdersByIdReq, opts ...grpc.CallOption) (*GetOrdersByIdResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.GetOrdersById(ctx, in, opts...) +} + +func (m *defaultOrderService) SearchOrders(ctx context.Context, in *SearchOrdersReq, opts ...grpc.CallOption) (*SearchOrdersResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.SearchOrders(ctx, in, opts...) +} + +// -----------------------orderStateLogs----------------------- +func (m *defaultOrderService) AddOrderStateLogs(ctx context.Context, in *AddOrderStateLogsReq, opts ...grpc.CallOption) (*AddOrderStateLogsResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.AddOrderStateLogs(ctx, in, opts...) +} + +func (m *defaultOrderService) UpdateOrderStateLogs(ctx context.Context, in *UpdateOrderStateLogsReq, opts ...grpc.CallOption) (*UpdateOrderStateLogsResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.UpdateOrderStateLogs(ctx, in, opts...) +} + +func (m *defaultOrderService) DelOrderStateLogs(ctx context.Context, in *DelOrderStateLogsReq, opts ...grpc.CallOption) (*DelOrderStateLogsResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.DelOrderStateLogs(ctx, in, opts...) +} + +func (m *defaultOrderService) GetOrderStateLogsById(ctx context.Context, in *GetOrderStateLogsByIdReq, opts ...grpc.CallOption) (*GetOrderStateLogsByIdResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.GetOrderStateLogsById(ctx, in, opts...) +} + +func (m *defaultOrderService) SearchOrderStateLogs(ctx context.Context, in *SearchOrderStateLogsReq, opts ...grpc.CallOption) (*SearchOrderStateLogsResp, error) { + client := pb.NewOrderServiceClient(m.cli.Conn()) + return client.SearchOrderStateLogs(ctx, in, opts...) +} diff --git a/app/order/rpc/pb.go b/app/order/rpc/pb.go new file mode 100644 index 0000000..9f44f99 --- /dev/null +++ b/app/order/rpc/pb.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/order/rpc/internal/config" + "juwan-backend/app/order/rpc/internal/server" + "juwan-backend/app/order/rpc/internal/svc" + "juwan-backend/app/order/rpc/pb" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/core/service" + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" + "google.golang.org/grpc/reflection" +) + +var configFile = flag.String("f", "etc/pb.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + ctx := svc.NewServiceContext(c) + + s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { + pb.RegisterOrderServiceServer(grpcServer, server.NewOrderServiceServer(ctx)) + + if c.Mode == service.DevMode || c.Mode == service.TestMode { + reflection.Register(grpcServer) + } + }) + defer s.Stop() + + fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) + s.Start() +} diff --git a/app/order/rpc/pb/order.pb.go b/app/order/rpc/pb/order.pb.go new file mode 100644 index 0000000..00004c9 --- /dev/null +++ b/app/order/rpc/pb/order.pb.go @@ -0,0 +1,2266 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v5.29.6 +// source: order.proto + +package pb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// --------------------------------orders-------------------------------- +type Orders struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + ConsumerId int64 `protobuf:"varint,2,opt,name=consumerId,proto3" json:"consumerId,omitempty"` //consumerId + ConsumerName string `protobuf:"bytes,3,opt,name=consumerName,proto3" json:"consumerName,omitempty"` //consumerName + PlayerId int64 `protobuf:"varint,4,opt,name=playerId,proto3" json:"playerId,omitempty"` //playerId + PlayerName string `protobuf:"bytes,5,opt,name=playerName,proto3" json:"playerName,omitempty"` //playerName + ShopId *int64 `protobuf:"varint,6,opt,name=shopId,proto3,oneof" json:"shopId,omitempty"` //shopId + ShopName *string `protobuf:"bytes,7,opt,name=shopName,proto3,oneof" json:"shopName,omitempty"` //shopName + ServiceSnapshot string `protobuf:"bytes,8,opt,name=serviceSnapshot,proto3" json:"serviceSnapshot,omitempty"` //serviceSnapshot + Status string `protobuf:"bytes,9,opt,name=status,proto3" json:"status,omitempty"` //status + TotalPrice string `protobuf:"bytes,10,opt,name=totalPrice,proto3" json:"totalPrice,omitempty"` //totalPrice + Note *string `protobuf:"bytes,11,opt,name=note,proto3,oneof" json:"note,omitempty"` //note + Version int64 `protobuf:"varint,12,opt,name=version,proto3" json:"version,omitempty"` //version + TimeoutJobId *string `protobuf:"bytes,13,opt,name=timeoutJobId,proto3,oneof" json:"timeoutJobId,omitempty"` //timeoutJobId + SearchText string `protobuf:"bytes,14,opt,name=searchText,proto3" json:"searchText,omitempty"` //searchText + CreatedAt int64 `protobuf:"varint,15,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + AcceptedAt *int64 `protobuf:"varint,16,opt,name=acceptedAt,proto3,oneof" json:"acceptedAt,omitempty"` //acceptedAt + ClosedAt *int64 `protobuf:"varint,17,opt,name=closedAt,proto3,oneof" json:"closedAt,omitempty"` //closedAt + CompletedAt *int64 `protobuf:"varint,18,opt,name=completedAt,proto3,oneof" json:"completedAt,omitempty"` //completedAt + CancelledAt *int64 `protobuf:"varint,19,opt,name=cancelledAt,proto3,oneof" json:"cancelledAt,omitempty"` //cancelledAt + UpdatedAt int64 `protobuf:"varint,20,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Orders) Reset() { + *x = Orders{} + mi := &file_order_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Orders) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Orders) ProtoMessage() {} + +func (x *Orders) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Orders.ProtoReflect.Descriptor instead. +func (*Orders) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{0} +} + +func (x *Orders) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Orders) GetConsumerId() int64 { + if x != nil { + return x.ConsumerId + } + return 0 +} + +func (x *Orders) GetConsumerName() string { + if x != nil { + return x.ConsumerName + } + return "" +} + +func (x *Orders) GetPlayerId() int64 { + if x != nil { + return x.PlayerId + } + return 0 +} + +func (x *Orders) GetPlayerName() string { + if x != nil { + return x.PlayerName + } + return "" +} + +func (x *Orders) GetShopId() int64 { + if x != nil && x.ShopId != nil { + return *x.ShopId + } + return 0 +} + +func (x *Orders) GetShopName() string { + if x != nil && x.ShopName != nil { + return *x.ShopName + } + return "" +} + +func (x *Orders) GetServiceSnapshot() string { + if x != nil { + return x.ServiceSnapshot + } + return "" +} + +func (x *Orders) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *Orders) GetTotalPrice() string { + if x != nil { + return x.TotalPrice + } + return "" +} + +func (x *Orders) GetNote() string { + if x != nil && x.Note != nil { + return *x.Note + } + return "" +} + +func (x *Orders) GetVersion() int64 { + if x != nil { + return x.Version + } + return 0 +} + +func (x *Orders) GetTimeoutJobId() string { + if x != nil && x.TimeoutJobId != nil { + return *x.TimeoutJobId + } + return "" +} + +func (x *Orders) GetSearchText() string { + if x != nil { + return x.SearchText + } + return "" +} + +func (x *Orders) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *Orders) GetAcceptedAt() int64 { + if x != nil && x.AcceptedAt != nil { + return *x.AcceptedAt + } + return 0 +} + +func (x *Orders) GetClosedAt() int64 { + if x != nil && x.ClosedAt != nil { + return *x.ClosedAt + } + return 0 +} + +func (x *Orders) GetCompletedAt() int64 { + if x != nil && x.CompletedAt != nil { + return *x.CompletedAt + } + return 0 +} + +func (x *Orders) GetCancelledAt() int64 { + if x != nil && x.CancelledAt != nil { + return *x.CancelledAt + } + return 0 +} + +func (x *Orders) GetUpdatedAt() int64 { + if x != nil { + return x.UpdatedAt + } + return 0 +} + +type AddOrdersReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + ConsumerId int64 `protobuf:"varint,2,opt,name=consumerId,proto3" json:"consumerId,omitempty"` //consumerId + ConsumerName string `protobuf:"bytes,3,opt,name=consumerName,proto3" json:"consumerName,omitempty"` //consumerName + PlayerId int64 `protobuf:"varint,4,opt,name=playerId,proto3" json:"playerId,omitempty"` //playerId + PlayerName string `protobuf:"bytes,5,opt,name=playerName,proto3" json:"playerName,omitempty"` //playerName + ShopId *int64 `protobuf:"varint,6,opt,name=shopId,proto3,oneof" json:"shopId,omitempty"` //shopId + ShopName *string `protobuf:"bytes,7,opt,name=shopName,proto3,oneof" json:"shopName,omitempty"` //shopName + ServiceSnapshot string `protobuf:"bytes,8,opt,name=serviceSnapshot,proto3" json:"serviceSnapshot,omitempty"` //serviceSnapshot + Status *string `protobuf:"bytes,9,opt,name=status,proto3,oneof" json:"status,omitempty"` //status + TotalPrice string `protobuf:"bytes,10,opt,name=totalPrice,proto3" json:"totalPrice,omitempty"` //totalPrice + Note *string `protobuf:"bytes,11,opt,name=note,proto3,oneof" json:"note,omitempty"` //note + Version *int64 `protobuf:"varint,12,opt,name=version,proto3,oneof" json:"version,omitempty"` //version + TimeoutJobId *string `protobuf:"bytes,13,opt,name=timeoutJobId,proto3,oneof" json:"timeoutJobId,omitempty"` //timeoutJobId + SearchText *string `protobuf:"bytes,14,opt,name=searchText,proto3,oneof" json:"searchText,omitempty"` //searchText + CreatedAt *int64 `protobuf:"varint,15,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + AcceptedAt *int64 `protobuf:"varint,16,opt,name=acceptedAt,proto3,oneof" json:"acceptedAt,omitempty"` //acceptedAt + ClosedAt *int64 `protobuf:"varint,17,opt,name=closedAt,proto3,oneof" json:"closedAt,omitempty"` //closedAt + CompletedAt *int64 `protobuf:"varint,18,opt,name=completedAt,proto3,oneof" json:"completedAt,omitempty"` //completedAt + CancelledAt *int64 `protobuf:"varint,19,opt,name=cancelledAt,proto3,oneof" json:"cancelledAt,omitempty"` //cancelledAt + UpdatedAt *int64 `protobuf:"varint,20,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddOrdersReq) Reset() { + *x = AddOrdersReq{} + mi := &file_order_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddOrdersReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddOrdersReq) ProtoMessage() {} + +func (x *AddOrdersReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddOrdersReq.ProtoReflect.Descriptor instead. +func (*AddOrdersReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{1} +} + +func (x *AddOrdersReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *AddOrdersReq) GetConsumerId() int64 { + if x != nil { + return x.ConsumerId + } + return 0 +} + +func (x *AddOrdersReq) GetConsumerName() string { + if x != nil { + return x.ConsumerName + } + return "" +} + +func (x *AddOrdersReq) GetPlayerId() int64 { + if x != nil { + return x.PlayerId + } + return 0 +} + +func (x *AddOrdersReq) GetPlayerName() string { + if x != nil { + return x.PlayerName + } + return "" +} + +func (x *AddOrdersReq) GetShopId() int64 { + if x != nil && x.ShopId != nil { + return *x.ShopId + } + return 0 +} + +func (x *AddOrdersReq) GetShopName() string { + if x != nil && x.ShopName != nil { + return *x.ShopName + } + return "" +} + +func (x *AddOrdersReq) GetServiceSnapshot() string { + if x != nil { + return x.ServiceSnapshot + } + return "" +} + +func (x *AddOrdersReq) GetStatus() string { + if x != nil && x.Status != nil { + return *x.Status + } + return "" +} + +func (x *AddOrdersReq) GetTotalPrice() string { + if x != nil { + return x.TotalPrice + } + return "" +} + +func (x *AddOrdersReq) GetNote() string { + if x != nil && x.Note != nil { + return *x.Note + } + return "" +} + +func (x *AddOrdersReq) GetVersion() int64 { + if x != nil && x.Version != nil { + return *x.Version + } + return 0 +} + +func (x *AddOrdersReq) GetTimeoutJobId() string { + if x != nil && x.TimeoutJobId != nil { + return *x.TimeoutJobId + } + return "" +} + +func (x *AddOrdersReq) GetSearchText() string { + if x != nil && x.SearchText != nil { + return *x.SearchText + } + return "" +} + +func (x *AddOrdersReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *AddOrdersReq) GetAcceptedAt() int64 { + if x != nil && x.AcceptedAt != nil { + return *x.AcceptedAt + } + return 0 +} + +func (x *AddOrdersReq) GetClosedAt() int64 { + if x != nil && x.ClosedAt != nil { + return *x.ClosedAt + } + return 0 +} + +func (x *AddOrdersReq) GetCompletedAt() int64 { + if x != nil && x.CompletedAt != nil { + return *x.CompletedAt + } + return 0 +} + +func (x *AddOrdersReq) GetCancelledAt() int64 { + if x != nil && x.CancelledAt != nil { + return *x.CancelledAt + } + return 0 +} + +func (x *AddOrdersReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +type AddOrdersResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddOrdersResp) Reset() { + *x = AddOrdersResp{} + mi := &file_order_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddOrdersResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddOrdersResp) ProtoMessage() {} + +func (x *AddOrdersResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddOrdersResp.ProtoReflect.Descriptor instead. +func (*AddOrdersResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{2} +} + +type UpdateOrdersReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + ConsumerId *int64 `protobuf:"varint,2,opt,name=consumerId,proto3,oneof" json:"consumerId,omitempty"` //consumerId + ConsumerName *string `protobuf:"bytes,3,opt,name=consumerName,proto3,oneof" json:"consumerName,omitempty"` //consumerName + PlayerId *int64 `protobuf:"varint,4,opt,name=playerId,proto3,oneof" json:"playerId,omitempty"` //playerId + PlayerName *string `protobuf:"bytes,5,opt,name=playerName,proto3,oneof" json:"playerName,omitempty"` //playerName + ShopId *int64 `protobuf:"varint,6,opt,name=shopId,proto3,oneof" json:"shopId,omitempty"` //shopId + ShopName *string `protobuf:"bytes,7,opt,name=shopName,proto3,oneof" json:"shopName,omitempty"` //shopName + ServiceSnapshot *string `protobuf:"bytes,8,opt,name=serviceSnapshot,proto3,oneof" json:"serviceSnapshot,omitempty"` //serviceSnapshot + Status *string `protobuf:"bytes,9,opt,name=status,proto3,oneof" json:"status,omitempty"` //status + TotalPrice *string `protobuf:"bytes,10,opt,name=totalPrice,proto3,oneof" json:"totalPrice,omitempty"` //totalPrice + Note *string `protobuf:"bytes,11,opt,name=note,proto3,oneof" json:"note,omitempty"` //note + Version *int64 `protobuf:"varint,12,opt,name=version,proto3,oneof" json:"version,omitempty"` //version + TimeoutJobId *string `protobuf:"bytes,13,opt,name=timeoutJobId,proto3,oneof" json:"timeoutJobId,omitempty"` //timeoutJobId + SearchText *string `protobuf:"bytes,14,opt,name=searchText,proto3,oneof" json:"searchText,omitempty"` //searchText + CreatedAt *int64 `protobuf:"varint,15,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + AcceptedAt *int64 `protobuf:"varint,16,opt,name=acceptedAt,proto3,oneof" json:"acceptedAt,omitempty"` //acceptedAt + ClosedAt *int64 `protobuf:"varint,17,opt,name=closedAt,proto3,oneof" json:"closedAt,omitempty"` //closedAt + CompletedAt *int64 `protobuf:"varint,18,opt,name=completedAt,proto3,oneof" json:"completedAt,omitempty"` //completedAt + CancelledAt *int64 `protobuf:"varint,19,opt,name=cancelledAt,proto3,oneof" json:"cancelledAt,omitempty"` //cancelledAt + UpdatedAt *int64 `protobuf:"varint,20,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateOrdersReq) Reset() { + *x = UpdateOrdersReq{} + mi := &file_order_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateOrdersReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateOrdersReq) ProtoMessage() {} + +func (x *UpdateOrdersReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateOrdersReq.ProtoReflect.Descriptor instead. +func (*UpdateOrdersReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{3} +} + +func (x *UpdateOrdersReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateOrdersReq) GetConsumerId() int64 { + if x != nil && x.ConsumerId != nil { + return *x.ConsumerId + } + return 0 +} + +func (x *UpdateOrdersReq) GetConsumerName() string { + if x != nil && x.ConsumerName != nil { + return *x.ConsumerName + } + return "" +} + +func (x *UpdateOrdersReq) GetPlayerId() int64 { + if x != nil && x.PlayerId != nil { + return *x.PlayerId + } + return 0 +} + +func (x *UpdateOrdersReq) GetPlayerName() string { + if x != nil && x.PlayerName != nil { + return *x.PlayerName + } + return "" +} + +func (x *UpdateOrdersReq) GetShopId() int64 { + if x != nil && x.ShopId != nil { + return *x.ShopId + } + return 0 +} + +func (x *UpdateOrdersReq) GetShopName() string { + if x != nil && x.ShopName != nil { + return *x.ShopName + } + return "" +} + +func (x *UpdateOrdersReq) GetServiceSnapshot() string { + if x != nil && x.ServiceSnapshot != nil { + return *x.ServiceSnapshot + } + return "" +} + +func (x *UpdateOrdersReq) GetStatus() string { + if x != nil && x.Status != nil { + return *x.Status + } + return "" +} + +func (x *UpdateOrdersReq) GetTotalPrice() string { + if x != nil && x.TotalPrice != nil { + return *x.TotalPrice + } + return "" +} + +func (x *UpdateOrdersReq) GetNote() string { + if x != nil && x.Note != nil { + return *x.Note + } + return "" +} + +func (x *UpdateOrdersReq) GetVersion() int64 { + if x != nil && x.Version != nil { + return *x.Version + } + return 0 +} + +func (x *UpdateOrdersReq) GetTimeoutJobId() string { + if x != nil && x.TimeoutJobId != nil { + return *x.TimeoutJobId + } + return "" +} + +func (x *UpdateOrdersReq) GetSearchText() string { + if x != nil && x.SearchText != nil { + return *x.SearchText + } + return "" +} + +func (x *UpdateOrdersReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *UpdateOrdersReq) GetAcceptedAt() int64 { + if x != nil && x.AcceptedAt != nil { + return *x.AcceptedAt + } + return 0 +} + +func (x *UpdateOrdersReq) GetClosedAt() int64 { + if x != nil && x.ClosedAt != nil { + return *x.ClosedAt + } + return 0 +} + +func (x *UpdateOrdersReq) GetCompletedAt() int64 { + if x != nil && x.CompletedAt != nil { + return *x.CompletedAt + } + return 0 +} + +func (x *UpdateOrdersReq) GetCancelledAt() int64 { + if x != nil && x.CancelledAt != nil { + return *x.CancelledAt + } + return 0 +} + +func (x *UpdateOrdersReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +type UpdateOrdersResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateOrdersResp) Reset() { + *x = UpdateOrdersResp{} + mi := &file_order_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateOrdersResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateOrdersResp) ProtoMessage() {} + +func (x *UpdateOrdersResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateOrdersResp.ProtoReflect.Descriptor instead. +func (*UpdateOrdersResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{4} +} + +type DelOrdersReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelOrdersReq) Reset() { + *x = DelOrdersReq{} + mi := &file_order_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelOrdersReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelOrdersReq) ProtoMessage() {} + +func (x *DelOrdersReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelOrdersReq.ProtoReflect.Descriptor instead. +func (*DelOrdersReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{5} +} + +func (x *DelOrdersReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelOrdersResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelOrdersResp) Reset() { + *x = DelOrdersResp{} + mi := &file_order_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelOrdersResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelOrdersResp) ProtoMessage() {} + +func (x *DelOrdersResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelOrdersResp.ProtoReflect.Descriptor instead. +func (*DelOrdersResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{6} +} + +type GetOrdersByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrdersByIdReq) Reset() { + *x = GetOrdersByIdReq{} + mi := &file_order_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrdersByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrdersByIdReq) ProtoMessage() {} + +func (x *GetOrdersByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrdersByIdReq.ProtoReflect.Descriptor instead. +func (*GetOrdersByIdReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{7} +} + +func (x *GetOrdersByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetOrdersByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Orders *Orders `protobuf:"bytes,1,opt,name=orders,proto3" json:"orders,omitempty"` //orders + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrdersByIdResp) Reset() { + *x = GetOrdersByIdResp{} + mi := &file_order_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrdersByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrdersByIdResp) ProtoMessage() {} + +func (x *GetOrdersByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrdersByIdResp.ProtoReflect.Descriptor instead. +func (*GetOrdersByIdResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{8} +} + +func (x *GetOrdersByIdResp) GetOrders() *Orders { + if x != nil { + return x.Orders + } + return nil +} + +type SearchOrdersReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + Id *int64 `protobuf:"varint,3,opt,name=id,proto3,oneof" json:"id,omitempty"` //id + ConsumerId *int64 `protobuf:"varint,4,opt,name=consumerId,proto3,oneof" json:"consumerId,omitempty"` //consumerId + ConsumerName *string `protobuf:"bytes,5,opt,name=consumerName,proto3,oneof" json:"consumerName,omitempty"` //consumerName + PlayerId *int64 `protobuf:"varint,6,opt,name=playerId,proto3,oneof" json:"playerId,omitempty"` //playerId + PlayerName *string `protobuf:"bytes,7,opt,name=playerName,proto3,oneof" json:"playerName,omitempty"` //playerName + ShopId *int64 `protobuf:"varint,8,opt,name=shopId,proto3,oneof" json:"shopId,omitempty"` //shopId + ShopName *string `protobuf:"bytes,9,opt,name=shopName,proto3,oneof" json:"shopName,omitempty"` //shopName + ServiceSnapshot *string `protobuf:"bytes,10,opt,name=serviceSnapshot,proto3,oneof" json:"serviceSnapshot,omitempty"` //serviceSnapshot + Status *string `protobuf:"bytes,11,opt,name=status,proto3,oneof" json:"status,omitempty"` //status + TotalPrice *string `protobuf:"bytes,12,opt,name=totalPrice,proto3,oneof" json:"totalPrice,omitempty"` //totalPrice + Note *string `protobuf:"bytes,13,opt,name=note,proto3,oneof" json:"note,omitempty"` //note + Version *int64 `protobuf:"varint,14,opt,name=version,proto3,oneof" json:"version,omitempty"` //version + TimeoutJobId *string `protobuf:"bytes,15,opt,name=timeoutJobId,proto3,oneof" json:"timeoutJobId,omitempty"` //timeoutJobId + SearchText *string `protobuf:"bytes,16,opt,name=searchText,proto3,oneof" json:"searchText,omitempty"` //searchText + CreatedAt *int64 `protobuf:"varint,17,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + AcceptedAt *int64 `protobuf:"varint,18,opt,name=acceptedAt,proto3,oneof" json:"acceptedAt,omitempty"` //acceptedAt + ClosedAt *int64 `protobuf:"varint,19,opt,name=closedAt,proto3,oneof" json:"closedAt,omitempty"` //closedAt + CompletedAt *int64 `protobuf:"varint,20,opt,name=completedAt,proto3,oneof" json:"completedAt,omitempty"` //completedAt + CancelledAt *int64 `protobuf:"varint,21,opt,name=cancelledAt,proto3,oneof" json:"cancelledAt,omitempty"` //cancelledAt + UpdatedAt *int64 `protobuf:"varint,22,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchOrdersReq) Reset() { + *x = SearchOrdersReq{} + mi := &file_order_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchOrdersReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchOrdersReq) ProtoMessage() {} + +func (x *SearchOrdersReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchOrdersReq.ProtoReflect.Descriptor instead. +func (*SearchOrdersReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{9} +} + +func (x *SearchOrdersReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchOrdersReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchOrdersReq) GetId() int64 { + if x != nil && x.Id != nil { + return *x.Id + } + return 0 +} + +func (x *SearchOrdersReq) GetConsumerId() int64 { + if x != nil && x.ConsumerId != nil { + return *x.ConsumerId + } + return 0 +} + +func (x *SearchOrdersReq) GetConsumerName() string { + if x != nil && x.ConsumerName != nil { + return *x.ConsumerName + } + return "" +} + +func (x *SearchOrdersReq) GetPlayerId() int64 { + if x != nil && x.PlayerId != nil { + return *x.PlayerId + } + return 0 +} + +func (x *SearchOrdersReq) GetPlayerName() string { + if x != nil && x.PlayerName != nil { + return *x.PlayerName + } + return "" +} + +func (x *SearchOrdersReq) GetShopId() int64 { + if x != nil && x.ShopId != nil { + return *x.ShopId + } + return 0 +} + +func (x *SearchOrdersReq) GetShopName() string { + if x != nil && x.ShopName != nil { + return *x.ShopName + } + return "" +} + +func (x *SearchOrdersReq) GetServiceSnapshot() string { + if x != nil && x.ServiceSnapshot != nil { + return *x.ServiceSnapshot + } + return "" +} + +func (x *SearchOrdersReq) GetStatus() string { + if x != nil && x.Status != nil { + return *x.Status + } + return "" +} + +func (x *SearchOrdersReq) GetTotalPrice() string { + if x != nil && x.TotalPrice != nil { + return *x.TotalPrice + } + return "" +} + +func (x *SearchOrdersReq) GetNote() string { + if x != nil && x.Note != nil { + return *x.Note + } + return "" +} + +func (x *SearchOrdersReq) GetVersion() int64 { + if x != nil && x.Version != nil { + return *x.Version + } + return 0 +} + +func (x *SearchOrdersReq) GetTimeoutJobId() string { + if x != nil && x.TimeoutJobId != nil { + return *x.TimeoutJobId + } + return "" +} + +func (x *SearchOrdersReq) GetSearchText() string { + if x != nil && x.SearchText != nil { + return *x.SearchText + } + return "" +} + +func (x *SearchOrdersReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *SearchOrdersReq) GetAcceptedAt() int64 { + if x != nil && x.AcceptedAt != nil { + return *x.AcceptedAt + } + return 0 +} + +func (x *SearchOrdersReq) GetClosedAt() int64 { + if x != nil && x.ClosedAt != nil { + return *x.ClosedAt + } + return 0 +} + +func (x *SearchOrdersReq) GetCompletedAt() int64 { + if x != nil && x.CompletedAt != nil { + return *x.CompletedAt + } + return 0 +} + +func (x *SearchOrdersReq) GetCancelledAt() int64 { + if x != nil && x.CancelledAt != nil { + return *x.CancelledAt + } + return 0 +} + +func (x *SearchOrdersReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +type SearchOrdersResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Orders []*Orders `protobuf:"bytes,1,rep,name=orders,proto3" json:"orders,omitempty"` //orders + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchOrdersResp) Reset() { + *x = SearchOrdersResp{} + mi := &file_order_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchOrdersResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchOrdersResp) ProtoMessage() {} + +func (x *SearchOrdersResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchOrdersResp.ProtoReflect.Descriptor instead. +func (*SearchOrdersResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{10} +} + +func (x *SearchOrdersResp) GetOrders() []*Orders { + if x != nil { + return x.Orders + } + return nil +} + +// --------------------------------orderStateLogs-------------------------------- +type OrderStateLogs struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + OrderId int64 `protobuf:"varint,2,opt,name=orderId,proto3" json:"orderId,omitempty"` //orderId + FromStatus *string `protobuf:"bytes,3,opt,name=fromStatus,proto3,oneof" json:"fromStatus,omitempty"` //fromStatus + ToStatus string `protobuf:"bytes,4,opt,name=toStatus,proto3" json:"toStatus,omitempty"` //toStatus + Action string `protobuf:"bytes,5,opt,name=action,proto3" json:"action,omitempty"` //action + ActorId int64 `protobuf:"varint,6,opt,name=actorId,proto3" json:"actorId,omitempty"` //actorId + ActorRole string `protobuf:"bytes,7,opt,name=actorRole,proto3" json:"actorRole,omitempty"` //actorRole + Metadata *string `protobuf:"bytes,8,opt,name=metadata,proto3,oneof" json:"metadata,omitempty"` //metadata + CreatedAt int64 `protobuf:"varint,9,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *OrderStateLogs) Reset() { + *x = OrderStateLogs{} + mi := &file_order_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *OrderStateLogs) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OrderStateLogs) ProtoMessage() {} + +func (x *OrderStateLogs) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OrderStateLogs.ProtoReflect.Descriptor instead. +func (*OrderStateLogs) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{11} +} + +func (x *OrderStateLogs) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *OrderStateLogs) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *OrderStateLogs) GetFromStatus() string { + if x != nil && x.FromStatus != nil { + return *x.FromStatus + } + return "" +} + +func (x *OrderStateLogs) GetToStatus() string { + if x != nil { + return x.ToStatus + } + return "" +} + +func (x *OrderStateLogs) GetAction() string { + if x != nil { + return x.Action + } + return "" +} + +func (x *OrderStateLogs) GetActorId() int64 { + if x != nil { + return x.ActorId + } + return 0 +} + +func (x *OrderStateLogs) GetActorRole() string { + if x != nil { + return x.ActorRole + } + return "" +} + +func (x *OrderStateLogs) GetMetadata() string { + if x != nil && x.Metadata != nil { + return *x.Metadata + } + return "" +} + +func (x *OrderStateLogs) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddOrderStateLogsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + OrderId int64 `protobuf:"varint,2,opt,name=orderId,proto3" json:"orderId,omitempty"` //orderId + FromStatus *string `protobuf:"bytes,3,opt,name=fromStatus,proto3,oneof" json:"fromStatus,omitempty"` //fromStatus + ToStatus string `protobuf:"bytes,4,opt,name=toStatus,proto3" json:"toStatus,omitempty"` //toStatus + Action string `protobuf:"bytes,5,opt,name=action,proto3" json:"action,omitempty"` //action + ActorId int64 `protobuf:"varint,6,opt,name=actorId,proto3" json:"actorId,omitempty"` //actorId + ActorRole string `protobuf:"bytes,7,opt,name=actorRole,proto3" json:"actorRole,omitempty"` //actorRole + Metadata *string `protobuf:"bytes,8,opt,name=metadata,proto3,oneof" json:"metadata,omitempty"` //metadata + CreatedAt *int64 `protobuf:"varint,9,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddOrderStateLogsReq) Reset() { + *x = AddOrderStateLogsReq{} + mi := &file_order_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddOrderStateLogsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddOrderStateLogsReq) ProtoMessage() {} + +func (x *AddOrderStateLogsReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddOrderStateLogsReq.ProtoReflect.Descriptor instead. +func (*AddOrderStateLogsReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{12} +} + +func (x *AddOrderStateLogsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *AddOrderStateLogsReq) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *AddOrderStateLogsReq) GetFromStatus() string { + if x != nil && x.FromStatus != nil { + return *x.FromStatus + } + return "" +} + +func (x *AddOrderStateLogsReq) GetToStatus() string { + if x != nil { + return x.ToStatus + } + return "" +} + +func (x *AddOrderStateLogsReq) GetAction() string { + if x != nil { + return x.Action + } + return "" +} + +func (x *AddOrderStateLogsReq) GetActorId() int64 { + if x != nil { + return x.ActorId + } + return 0 +} + +func (x *AddOrderStateLogsReq) GetActorRole() string { + if x != nil { + return x.ActorRole + } + return "" +} + +func (x *AddOrderStateLogsReq) GetMetadata() string { + if x != nil && x.Metadata != nil { + return *x.Metadata + } + return "" +} + +func (x *AddOrderStateLogsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +type AddOrderStateLogsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddOrderStateLogsResp) Reset() { + *x = AddOrderStateLogsResp{} + mi := &file_order_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddOrderStateLogsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddOrderStateLogsResp) ProtoMessage() {} + +func (x *AddOrderStateLogsResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddOrderStateLogsResp.ProtoReflect.Descriptor instead. +func (*AddOrderStateLogsResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{13} +} + +type UpdateOrderStateLogsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + OrderId *int64 `protobuf:"varint,2,opt,name=orderId,proto3,oneof" json:"orderId,omitempty"` //orderId + FromStatus *string `protobuf:"bytes,3,opt,name=fromStatus,proto3,oneof" json:"fromStatus,omitempty"` //fromStatus + ToStatus *string `protobuf:"bytes,4,opt,name=toStatus,proto3,oneof" json:"toStatus,omitempty"` //toStatus + Action *string `protobuf:"bytes,5,opt,name=action,proto3,oneof" json:"action,omitempty"` //action + ActorId *int64 `protobuf:"varint,6,opt,name=actorId,proto3,oneof" json:"actorId,omitempty"` //actorId + ActorRole *string `protobuf:"bytes,7,opt,name=actorRole,proto3,oneof" json:"actorRole,omitempty"` //actorRole + Metadata *string `protobuf:"bytes,8,opt,name=metadata,proto3,oneof" json:"metadata,omitempty"` //metadata + CreatedAt *int64 `protobuf:"varint,9,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateOrderStateLogsReq) Reset() { + *x = UpdateOrderStateLogsReq{} + mi := &file_order_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateOrderStateLogsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateOrderStateLogsReq) ProtoMessage() {} + +func (x *UpdateOrderStateLogsReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateOrderStateLogsReq.ProtoReflect.Descriptor instead. +func (*UpdateOrderStateLogsReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{14} +} + +func (x *UpdateOrderStateLogsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateOrderStateLogsReq) GetOrderId() int64 { + if x != nil && x.OrderId != nil { + return *x.OrderId + } + return 0 +} + +func (x *UpdateOrderStateLogsReq) GetFromStatus() string { + if x != nil && x.FromStatus != nil { + return *x.FromStatus + } + return "" +} + +func (x *UpdateOrderStateLogsReq) GetToStatus() string { + if x != nil && x.ToStatus != nil { + return *x.ToStatus + } + return "" +} + +func (x *UpdateOrderStateLogsReq) GetAction() string { + if x != nil && x.Action != nil { + return *x.Action + } + return "" +} + +func (x *UpdateOrderStateLogsReq) GetActorId() int64 { + if x != nil && x.ActorId != nil { + return *x.ActorId + } + return 0 +} + +func (x *UpdateOrderStateLogsReq) GetActorRole() string { + if x != nil && x.ActorRole != nil { + return *x.ActorRole + } + return "" +} + +func (x *UpdateOrderStateLogsReq) GetMetadata() string { + if x != nil && x.Metadata != nil { + return *x.Metadata + } + return "" +} + +func (x *UpdateOrderStateLogsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +type UpdateOrderStateLogsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateOrderStateLogsResp) Reset() { + *x = UpdateOrderStateLogsResp{} + mi := &file_order_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateOrderStateLogsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateOrderStateLogsResp) ProtoMessage() {} + +func (x *UpdateOrderStateLogsResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[15] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateOrderStateLogsResp.ProtoReflect.Descriptor instead. +func (*UpdateOrderStateLogsResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{15} +} + +type DelOrderStateLogsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelOrderStateLogsReq) Reset() { + *x = DelOrderStateLogsReq{} + mi := &file_order_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelOrderStateLogsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelOrderStateLogsReq) ProtoMessage() {} + +func (x *DelOrderStateLogsReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[16] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelOrderStateLogsReq.ProtoReflect.Descriptor instead. +func (*DelOrderStateLogsReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{16} +} + +func (x *DelOrderStateLogsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelOrderStateLogsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelOrderStateLogsResp) Reset() { + *x = DelOrderStateLogsResp{} + mi := &file_order_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelOrderStateLogsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelOrderStateLogsResp) ProtoMessage() {} + +func (x *DelOrderStateLogsResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelOrderStateLogsResp.ProtoReflect.Descriptor instead. +func (*DelOrderStateLogsResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{17} +} + +type GetOrderStateLogsByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrderStateLogsByIdReq) Reset() { + *x = GetOrderStateLogsByIdReq{} + mi := &file_order_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrderStateLogsByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrderStateLogsByIdReq) ProtoMessage() {} + +func (x *GetOrderStateLogsByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrderStateLogsByIdReq.ProtoReflect.Descriptor instead. +func (*GetOrderStateLogsByIdReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{18} +} + +func (x *GetOrderStateLogsByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetOrderStateLogsByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrderStateLogs *OrderStateLogs `protobuf:"bytes,1,opt,name=orderStateLogs,proto3" json:"orderStateLogs,omitempty"` //orderStateLogs + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetOrderStateLogsByIdResp) Reset() { + *x = GetOrderStateLogsByIdResp{} + mi := &file_order_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetOrderStateLogsByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetOrderStateLogsByIdResp) ProtoMessage() {} + +func (x *GetOrderStateLogsByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetOrderStateLogsByIdResp.ProtoReflect.Descriptor instead. +func (*GetOrderStateLogsByIdResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{19} +} + +func (x *GetOrderStateLogsByIdResp) GetOrderStateLogs() *OrderStateLogs { + if x != nil { + return x.OrderStateLogs + } + return nil +} + +type SearchOrderStateLogsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + Id *int64 `protobuf:"varint,3,opt,name=id,proto3,oneof" json:"id,omitempty"` //id + OrderId *int64 `protobuf:"varint,4,opt,name=orderId,proto3,oneof" json:"orderId,omitempty"` //orderId + FromStatus *string `protobuf:"bytes,5,opt,name=fromStatus,proto3,oneof" json:"fromStatus,omitempty"` //fromStatus + ToStatus *string `protobuf:"bytes,6,opt,name=toStatus,proto3,oneof" json:"toStatus,omitempty"` //toStatus + Action *string `protobuf:"bytes,7,opt,name=action,proto3,oneof" json:"action,omitempty"` //action + ActorId *int64 `protobuf:"varint,8,opt,name=actorId,proto3,oneof" json:"actorId,omitempty"` //actorId + ActorRole *string `protobuf:"bytes,9,opt,name=actorRole,proto3,oneof" json:"actorRole,omitempty"` //actorRole + Metadata *string `protobuf:"bytes,10,opt,name=metadata,proto3,oneof" json:"metadata,omitempty"` //metadata + CreatedAt *int64 `protobuf:"varint,11,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchOrderStateLogsReq) Reset() { + *x = SearchOrderStateLogsReq{} + mi := &file_order_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchOrderStateLogsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchOrderStateLogsReq) ProtoMessage() {} + +func (x *SearchOrderStateLogsReq) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[20] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchOrderStateLogsReq.ProtoReflect.Descriptor instead. +func (*SearchOrderStateLogsReq) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{20} +} + +func (x *SearchOrderStateLogsReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchOrderStateLogsReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchOrderStateLogsReq) GetId() int64 { + if x != nil && x.Id != nil { + return *x.Id + } + return 0 +} + +func (x *SearchOrderStateLogsReq) GetOrderId() int64 { + if x != nil && x.OrderId != nil { + return *x.OrderId + } + return 0 +} + +func (x *SearchOrderStateLogsReq) GetFromStatus() string { + if x != nil && x.FromStatus != nil { + return *x.FromStatus + } + return "" +} + +func (x *SearchOrderStateLogsReq) GetToStatus() string { + if x != nil && x.ToStatus != nil { + return *x.ToStatus + } + return "" +} + +func (x *SearchOrderStateLogsReq) GetAction() string { + if x != nil && x.Action != nil { + return *x.Action + } + return "" +} + +func (x *SearchOrderStateLogsReq) GetActorId() int64 { + if x != nil && x.ActorId != nil { + return *x.ActorId + } + return 0 +} + +func (x *SearchOrderStateLogsReq) GetActorRole() string { + if x != nil && x.ActorRole != nil { + return *x.ActorRole + } + return "" +} + +func (x *SearchOrderStateLogsReq) GetMetadata() string { + if x != nil && x.Metadata != nil { + return *x.Metadata + } + return "" +} + +func (x *SearchOrderStateLogsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +type SearchOrderStateLogsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrderStateLogs []*OrderStateLogs `protobuf:"bytes,1,rep,name=orderStateLogs,proto3" json:"orderStateLogs,omitempty"` //orderStateLogs + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchOrderStateLogsResp) Reset() { + *x = SearchOrderStateLogsResp{} + mi := &file_order_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchOrderStateLogsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchOrderStateLogsResp) ProtoMessage() {} + +func (x *SearchOrderStateLogsResp) ProtoReflect() protoreflect.Message { + mi := &file_order_proto_msgTypes[21] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchOrderStateLogsResp.ProtoReflect.Descriptor instead. +func (*SearchOrderStateLogsResp) Descriptor() ([]byte, []int) { + return file_order_proto_rawDescGZIP(), []int{21} +} + +func (x *SearchOrderStateLogsResp) GetOrderStateLogs() []*OrderStateLogs { + if x != nil { + return x.OrderStateLogs + } + return nil +} + +var File_order_proto protoreflect.FileDescriptor + +const file_order_proto_rawDesc = "" + + "\n" + + "\vorder.proto\x12\x02pb\"\xf2\x05\n" + + "\x06Orders\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1e\n" + + "\n" + + "consumerId\x18\x02 \x01(\x03R\n" + + "consumerId\x12\"\n" + + "\fconsumerName\x18\x03 \x01(\tR\fconsumerName\x12\x1a\n" + + "\bplayerId\x18\x04 \x01(\x03R\bplayerId\x12\x1e\n" + + "\n" + + "playerName\x18\x05 \x01(\tR\n" + + "playerName\x12\x1b\n" + + "\x06shopId\x18\x06 \x01(\x03H\x00R\x06shopId\x88\x01\x01\x12\x1f\n" + + "\bshopName\x18\a \x01(\tH\x01R\bshopName\x88\x01\x01\x12(\n" + + "\x0fserviceSnapshot\x18\b \x01(\tR\x0fserviceSnapshot\x12\x16\n" + + "\x06status\x18\t \x01(\tR\x06status\x12\x1e\n" + + "\n" + + "totalPrice\x18\n" + + " \x01(\tR\n" + + "totalPrice\x12\x17\n" + + "\x04note\x18\v \x01(\tH\x02R\x04note\x88\x01\x01\x12\x18\n" + + "\aversion\x18\f \x01(\x03R\aversion\x12'\n" + + "\ftimeoutJobId\x18\r \x01(\tH\x03R\ftimeoutJobId\x88\x01\x01\x12\x1e\n" + + "\n" + + "searchText\x18\x0e \x01(\tR\n" + + "searchText\x12\x1c\n" + + "\tcreatedAt\x18\x0f \x01(\x03R\tcreatedAt\x12#\n" + + "\n" + + "acceptedAt\x18\x10 \x01(\x03H\x04R\n" + + "acceptedAt\x88\x01\x01\x12\x1f\n" + + "\bclosedAt\x18\x11 \x01(\x03H\x05R\bclosedAt\x88\x01\x01\x12%\n" + + "\vcompletedAt\x18\x12 \x01(\x03H\x06R\vcompletedAt\x88\x01\x01\x12%\n" + + "\vcancelledAt\x18\x13 \x01(\x03H\aR\vcancelledAt\x88\x01\x01\x12\x1c\n" + + "\tupdatedAt\x18\x14 \x01(\x03R\tupdatedAtB\t\n" + + "\a_shopIdB\v\n" + + "\t_shopNameB\a\n" + + "\x05_noteB\x0f\n" + + "\r_timeoutJobIdB\r\n" + + "\v_acceptedAtB\v\n" + + "\t_closedAtB\x0e\n" + + "\f_completedAtB\x0e\n" + + "\f_cancelledAt\"\xd3\x06\n" + + "\fAddOrdersReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1e\n" + + "\n" + + "consumerId\x18\x02 \x01(\x03R\n" + + "consumerId\x12\"\n" + + "\fconsumerName\x18\x03 \x01(\tR\fconsumerName\x12\x1a\n" + + "\bplayerId\x18\x04 \x01(\x03R\bplayerId\x12\x1e\n" + + "\n" + + "playerName\x18\x05 \x01(\tR\n" + + "playerName\x12\x1b\n" + + "\x06shopId\x18\x06 \x01(\x03H\x00R\x06shopId\x88\x01\x01\x12\x1f\n" + + "\bshopName\x18\a \x01(\tH\x01R\bshopName\x88\x01\x01\x12(\n" + + "\x0fserviceSnapshot\x18\b \x01(\tR\x0fserviceSnapshot\x12\x1b\n" + + "\x06status\x18\t \x01(\tH\x02R\x06status\x88\x01\x01\x12\x1e\n" + + "\n" + + "totalPrice\x18\n" + + " \x01(\tR\n" + + "totalPrice\x12\x17\n" + + "\x04note\x18\v \x01(\tH\x03R\x04note\x88\x01\x01\x12\x1d\n" + + "\aversion\x18\f \x01(\x03H\x04R\aversion\x88\x01\x01\x12'\n" + + "\ftimeoutJobId\x18\r \x01(\tH\x05R\ftimeoutJobId\x88\x01\x01\x12#\n" + + "\n" + + "searchText\x18\x0e \x01(\tH\x06R\n" + + "searchText\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\x0f \x01(\x03H\aR\tcreatedAt\x88\x01\x01\x12#\n" + + "\n" + + "acceptedAt\x18\x10 \x01(\x03H\bR\n" + + "acceptedAt\x88\x01\x01\x12\x1f\n" + + "\bclosedAt\x18\x11 \x01(\x03H\tR\bclosedAt\x88\x01\x01\x12%\n" + + "\vcompletedAt\x18\x12 \x01(\x03H\n" + + "R\vcompletedAt\x88\x01\x01\x12%\n" + + "\vcancelledAt\x18\x13 \x01(\x03H\vR\vcancelledAt\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\x14 \x01(\x03H\fR\tupdatedAt\x88\x01\x01B\t\n" + + "\a_shopIdB\v\n" + + "\t_shopNameB\t\n" + + "\a_statusB\a\n" + + "\x05_noteB\n" + + "\n" + + "\b_versionB\x0f\n" + + "\r_timeoutJobIdB\r\n" + + "\v_searchTextB\f\n" + + "\n" + + "_createdAtB\r\n" + + "\v_acceptedAtB\v\n" + + "\t_closedAtB\x0e\n" + + "\f_completedAtB\x0e\n" + + "\f_cancelledAtB\f\n" + + "\n" + + "_updatedAt\"\x0f\n" + + "\rAddOrdersResp\"\xd3\a\n" + + "\x0fUpdateOrdersReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12#\n" + + "\n" + + "consumerId\x18\x02 \x01(\x03H\x00R\n" + + "consumerId\x88\x01\x01\x12'\n" + + "\fconsumerName\x18\x03 \x01(\tH\x01R\fconsumerName\x88\x01\x01\x12\x1f\n" + + "\bplayerId\x18\x04 \x01(\x03H\x02R\bplayerId\x88\x01\x01\x12#\n" + + "\n" + + "playerName\x18\x05 \x01(\tH\x03R\n" + + "playerName\x88\x01\x01\x12\x1b\n" + + "\x06shopId\x18\x06 \x01(\x03H\x04R\x06shopId\x88\x01\x01\x12\x1f\n" + + "\bshopName\x18\a \x01(\tH\x05R\bshopName\x88\x01\x01\x12-\n" + + "\x0fserviceSnapshot\x18\b \x01(\tH\x06R\x0fserviceSnapshot\x88\x01\x01\x12\x1b\n" + + "\x06status\x18\t \x01(\tH\aR\x06status\x88\x01\x01\x12#\n" + + "\n" + + "totalPrice\x18\n" + + " \x01(\tH\bR\n" + + "totalPrice\x88\x01\x01\x12\x17\n" + + "\x04note\x18\v \x01(\tH\tR\x04note\x88\x01\x01\x12\x1d\n" + + "\aversion\x18\f \x01(\x03H\n" + + "R\aversion\x88\x01\x01\x12'\n" + + "\ftimeoutJobId\x18\r \x01(\tH\vR\ftimeoutJobId\x88\x01\x01\x12#\n" + + "\n" + + "searchText\x18\x0e \x01(\tH\fR\n" + + "searchText\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\x0f \x01(\x03H\rR\tcreatedAt\x88\x01\x01\x12#\n" + + "\n" + + "acceptedAt\x18\x10 \x01(\x03H\x0eR\n" + + "acceptedAt\x88\x01\x01\x12\x1f\n" + + "\bclosedAt\x18\x11 \x01(\x03H\x0fR\bclosedAt\x88\x01\x01\x12%\n" + + "\vcompletedAt\x18\x12 \x01(\x03H\x10R\vcompletedAt\x88\x01\x01\x12%\n" + + "\vcancelledAt\x18\x13 \x01(\x03H\x11R\vcancelledAt\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\x14 \x01(\x03H\x12R\tupdatedAt\x88\x01\x01B\r\n" + + "\v_consumerIdB\x0f\n" + + "\r_consumerNameB\v\n" + + "\t_playerIdB\r\n" + + "\v_playerNameB\t\n" + + "\a_shopIdB\v\n" + + "\t_shopNameB\x12\n" + + "\x10_serviceSnapshotB\t\n" + + "\a_statusB\r\n" + + "\v_totalPriceB\a\n" + + "\x05_noteB\n" + + "\n" + + "\b_versionB\x0f\n" + + "\r_timeoutJobIdB\r\n" + + "\v_searchTextB\f\n" + + "\n" + + "_createdAtB\r\n" + + "\v_acceptedAtB\v\n" + + "\t_closedAtB\x0e\n" + + "\f_completedAtB\x0e\n" + + "\f_cancelledAtB\f\n" + + "\n" + + "_updatedAt\"\x12\n" + + "\x10UpdateOrdersResp\"\x1e\n" + + "\fDelOrdersReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x0f\n" + + "\rDelOrdersResp\"\"\n" + + "\x10GetOrdersByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"7\n" + + "\x11GetOrdersByIdResp\x12\"\n" + + "\x06orders\x18\x01 \x01(\v2\n" + + ".pb.OrdersR\x06orders\"\x89\b\n" + + "\x0fSearchOrdersReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x13\n" + + "\x02id\x18\x03 \x01(\x03H\x00R\x02id\x88\x01\x01\x12#\n" + + "\n" + + "consumerId\x18\x04 \x01(\x03H\x01R\n" + + "consumerId\x88\x01\x01\x12'\n" + + "\fconsumerName\x18\x05 \x01(\tH\x02R\fconsumerName\x88\x01\x01\x12\x1f\n" + + "\bplayerId\x18\x06 \x01(\x03H\x03R\bplayerId\x88\x01\x01\x12#\n" + + "\n" + + "playerName\x18\a \x01(\tH\x04R\n" + + "playerName\x88\x01\x01\x12\x1b\n" + + "\x06shopId\x18\b \x01(\x03H\x05R\x06shopId\x88\x01\x01\x12\x1f\n" + + "\bshopName\x18\t \x01(\tH\x06R\bshopName\x88\x01\x01\x12-\n" + + "\x0fserviceSnapshot\x18\n" + + " \x01(\tH\aR\x0fserviceSnapshot\x88\x01\x01\x12\x1b\n" + + "\x06status\x18\v \x01(\tH\bR\x06status\x88\x01\x01\x12#\n" + + "\n" + + "totalPrice\x18\f \x01(\tH\tR\n" + + "totalPrice\x88\x01\x01\x12\x17\n" + + "\x04note\x18\r \x01(\tH\n" + + "R\x04note\x88\x01\x01\x12\x1d\n" + + "\aversion\x18\x0e \x01(\x03H\vR\aversion\x88\x01\x01\x12'\n" + + "\ftimeoutJobId\x18\x0f \x01(\tH\fR\ftimeoutJobId\x88\x01\x01\x12#\n" + + "\n" + + "searchText\x18\x10 \x01(\tH\rR\n" + + "searchText\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\x11 \x01(\x03H\x0eR\tcreatedAt\x88\x01\x01\x12#\n" + + "\n" + + "acceptedAt\x18\x12 \x01(\x03H\x0fR\n" + + "acceptedAt\x88\x01\x01\x12\x1f\n" + + "\bclosedAt\x18\x13 \x01(\x03H\x10R\bclosedAt\x88\x01\x01\x12%\n" + + "\vcompletedAt\x18\x14 \x01(\x03H\x11R\vcompletedAt\x88\x01\x01\x12%\n" + + "\vcancelledAt\x18\x15 \x01(\x03H\x12R\vcancelledAt\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\x16 \x01(\x03H\x13R\tupdatedAt\x88\x01\x01B\x05\n" + + "\x03_idB\r\n" + + "\v_consumerIdB\x0f\n" + + "\r_consumerNameB\v\n" + + "\t_playerIdB\r\n" + + "\v_playerNameB\t\n" + + "\a_shopIdB\v\n" + + "\t_shopNameB\x12\n" + + "\x10_serviceSnapshotB\t\n" + + "\a_statusB\r\n" + + "\v_totalPriceB\a\n" + + "\x05_noteB\n" + + "\n" + + "\b_versionB\x0f\n" + + "\r_timeoutJobIdB\r\n" + + "\v_searchTextB\f\n" + + "\n" + + "_createdAtB\r\n" + + "\v_acceptedAtB\v\n" + + "\t_closedAtB\x0e\n" + + "\f_completedAtB\x0e\n" + + "\f_cancelledAtB\f\n" + + "\n" + + "_updatedAt\"6\n" + + "\x10SearchOrdersResp\x12\"\n" + + "\x06orders\x18\x01 \x03(\v2\n" + + ".pb.OrdersR\x06orders\"\xa6\x02\n" + + "\x0eOrderStateLogs\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x18\n" + + "\aorderId\x18\x02 \x01(\x03R\aorderId\x12#\n" + + "\n" + + "fromStatus\x18\x03 \x01(\tH\x00R\n" + + "fromStatus\x88\x01\x01\x12\x1a\n" + + "\btoStatus\x18\x04 \x01(\tR\btoStatus\x12\x16\n" + + "\x06action\x18\x05 \x01(\tR\x06action\x12\x18\n" + + "\aactorId\x18\x06 \x01(\x03R\aactorId\x12\x1c\n" + + "\tactorRole\x18\a \x01(\tR\tactorRole\x12\x1f\n" + + "\bmetadata\x18\b \x01(\tH\x01R\bmetadata\x88\x01\x01\x12\x1c\n" + + "\tcreatedAt\x18\t \x01(\x03R\tcreatedAtB\r\n" + + "\v_fromStatusB\v\n" + + "\t_metadata\"\xbf\x02\n" + + "\x14AddOrderStateLogsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x18\n" + + "\aorderId\x18\x02 \x01(\x03R\aorderId\x12#\n" + + "\n" + + "fromStatus\x18\x03 \x01(\tH\x00R\n" + + "fromStatus\x88\x01\x01\x12\x1a\n" + + "\btoStatus\x18\x04 \x01(\tR\btoStatus\x12\x16\n" + + "\x06action\x18\x05 \x01(\tR\x06action\x12\x18\n" + + "\aactorId\x18\x06 \x01(\x03R\aactorId\x12\x1c\n" + + "\tactorRole\x18\a \x01(\tR\tactorRole\x12\x1f\n" + + "\bmetadata\x18\b \x01(\tH\x01R\bmetadata\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\t \x01(\x03H\x02R\tcreatedAt\x88\x01\x01B\r\n" + + "\v_fromStatusB\v\n" + + "\t_metadataB\f\n" + + "\n" + + "_createdAt\"\x17\n" + + "\x15AddOrderStateLogsResp\"\x99\x03\n" + + "\x17UpdateOrderStateLogsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1d\n" + + "\aorderId\x18\x02 \x01(\x03H\x00R\aorderId\x88\x01\x01\x12#\n" + + "\n" + + "fromStatus\x18\x03 \x01(\tH\x01R\n" + + "fromStatus\x88\x01\x01\x12\x1f\n" + + "\btoStatus\x18\x04 \x01(\tH\x02R\btoStatus\x88\x01\x01\x12\x1b\n" + + "\x06action\x18\x05 \x01(\tH\x03R\x06action\x88\x01\x01\x12\x1d\n" + + "\aactorId\x18\x06 \x01(\x03H\x04R\aactorId\x88\x01\x01\x12!\n" + + "\tactorRole\x18\a \x01(\tH\x05R\tactorRole\x88\x01\x01\x12\x1f\n" + + "\bmetadata\x18\b \x01(\tH\x06R\bmetadata\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\t \x01(\x03H\aR\tcreatedAt\x88\x01\x01B\n" + + "\n" + + "\b_orderIdB\r\n" + + "\v_fromStatusB\v\n" + + "\t_toStatusB\t\n" + + "\a_actionB\n" + + "\n" + + "\b_actorIdB\f\n" + + "\n" + + "_actorRoleB\v\n" + + "\t_metadataB\f\n" + + "\n" + + "_createdAt\"\x1a\n" + + "\x18UpdateOrderStateLogsResp\"&\n" + + "\x14DelOrderStateLogsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x17\n" + + "\x15DelOrderStateLogsResp\"*\n" + + "\x18GetOrderStateLogsByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"W\n" + + "\x19GetOrderStateLogsByIdResp\x12:\n" + + "\x0eorderStateLogs\x18\x01 \x01(\v2\x12.pb.OrderStateLogsR\x0eorderStateLogs\"\xcf\x03\n" + + "\x17SearchOrderStateLogsReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x13\n" + + "\x02id\x18\x03 \x01(\x03H\x00R\x02id\x88\x01\x01\x12\x1d\n" + + "\aorderId\x18\x04 \x01(\x03H\x01R\aorderId\x88\x01\x01\x12#\n" + + "\n" + + "fromStatus\x18\x05 \x01(\tH\x02R\n" + + "fromStatus\x88\x01\x01\x12\x1f\n" + + "\btoStatus\x18\x06 \x01(\tH\x03R\btoStatus\x88\x01\x01\x12\x1b\n" + + "\x06action\x18\a \x01(\tH\x04R\x06action\x88\x01\x01\x12\x1d\n" + + "\aactorId\x18\b \x01(\x03H\x05R\aactorId\x88\x01\x01\x12!\n" + + "\tactorRole\x18\t \x01(\tH\x06R\tactorRole\x88\x01\x01\x12\x1f\n" + + "\bmetadata\x18\n" + + " \x01(\tH\aR\bmetadata\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\v \x01(\x03H\bR\tcreatedAt\x88\x01\x01B\x05\n" + + "\x03_idB\n" + + "\n" + + "\b_orderIdB\r\n" + + "\v_fromStatusB\v\n" + + "\t_toStatusB\t\n" + + "\a_actionB\n" + + "\n" + + "\b_actorIdB\f\n" + + "\n" + + "_actorRoleB\v\n" + + "\t_metadataB\f\n" + + "\n" + + "_createdAt\"V\n" + + "\x18SearchOrderStateLogsResp\x12:\n" + + "\x0eorderStateLogs\x18\x01 \x03(\v2\x12.pb.OrderStateLogsR\x0eorderStateLogs2\xb6\x05\n" + + "\forderService\x120\n" + + "\tAddOrders\x12\x10.pb.AddOrdersReq\x1a\x11.pb.AddOrdersResp\x129\n" + + "\fUpdateOrders\x12\x13.pb.UpdateOrdersReq\x1a\x14.pb.UpdateOrdersResp\x120\n" + + "\tDelOrders\x12\x10.pb.DelOrdersReq\x1a\x11.pb.DelOrdersResp\x12<\n" + + "\rGetOrdersById\x12\x14.pb.GetOrdersByIdReq\x1a\x15.pb.GetOrdersByIdResp\x129\n" + + "\fSearchOrders\x12\x13.pb.SearchOrdersReq\x1a\x14.pb.SearchOrdersResp\x12H\n" + + "\x11AddOrderStateLogs\x12\x18.pb.AddOrderStateLogsReq\x1a\x19.pb.AddOrderStateLogsResp\x12Q\n" + + "\x14UpdateOrderStateLogs\x12\x1b.pb.UpdateOrderStateLogsReq\x1a\x1c.pb.UpdateOrderStateLogsResp\x12H\n" + + "\x11DelOrderStateLogs\x12\x18.pb.DelOrderStateLogsReq\x1a\x19.pb.DelOrderStateLogsResp\x12T\n" + + "\x15GetOrderStateLogsById\x12\x1c.pb.GetOrderStateLogsByIdReq\x1a\x1d.pb.GetOrderStateLogsByIdResp\x12Q\n" + + "\x14SearchOrderStateLogs\x12\x1b.pb.SearchOrderStateLogsReq\x1a\x1c.pb.SearchOrderStateLogsRespB\x06Z\x04./pbb\x06proto3" + +var ( + file_order_proto_rawDescOnce sync.Once + file_order_proto_rawDescData []byte +) + +func file_order_proto_rawDescGZIP() []byte { + file_order_proto_rawDescOnce.Do(func() { + file_order_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_order_proto_rawDesc), len(file_order_proto_rawDesc))) + }) + return file_order_proto_rawDescData +} + +var file_order_proto_msgTypes = make([]protoimpl.MessageInfo, 22) +var file_order_proto_goTypes = []any{ + (*Orders)(nil), // 0: pb.Orders + (*AddOrdersReq)(nil), // 1: pb.AddOrdersReq + (*AddOrdersResp)(nil), // 2: pb.AddOrdersResp + (*UpdateOrdersReq)(nil), // 3: pb.UpdateOrdersReq + (*UpdateOrdersResp)(nil), // 4: pb.UpdateOrdersResp + (*DelOrdersReq)(nil), // 5: pb.DelOrdersReq + (*DelOrdersResp)(nil), // 6: pb.DelOrdersResp + (*GetOrdersByIdReq)(nil), // 7: pb.GetOrdersByIdReq + (*GetOrdersByIdResp)(nil), // 8: pb.GetOrdersByIdResp + (*SearchOrdersReq)(nil), // 9: pb.SearchOrdersReq + (*SearchOrdersResp)(nil), // 10: pb.SearchOrdersResp + (*OrderStateLogs)(nil), // 11: pb.OrderStateLogs + (*AddOrderStateLogsReq)(nil), // 12: pb.AddOrderStateLogsReq + (*AddOrderStateLogsResp)(nil), // 13: pb.AddOrderStateLogsResp + (*UpdateOrderStateLogsReq)(nil), // 14: pb.UpdateOrderStateLogsReq + (*UpdateOrderStateLogsResp)(nil), // 15: pb.UpdateOrderStateLogsResp + (*DelOrderStateLogsReq)(nil), // 16: pb.DelOrderStateLogsReq + (*DelOrderStateLogsResp)(nil), // 17: pb.DelOrderStateLogsResp + (*GetOrderStateLogsByIdReq)(nil), // 18: pb.GetOrderStateLogsByIdReq + (*GetOrderStateLogsByIdResp)(nil), // 19: pb.GetOrderStateLogsByIdResp + (*SearchOrderStateLogsReq)(nil), // 20: pb.SearchOrderStateLogsReq + (*SearchOrderStateLogsResp)(nil), // 21: pb.SearchOrderStateLogsResp +} +var file_order_proto_depIdxs = []int32{ + 0, // 0: pb.GetOrdersByIdResp.orders:type_name -> pb.Orders + 0, // 1: pb.SearchOrdersResp.orders:type_name -> pb.Orders + 11, // 2: pb.GetOrderStateLogsByIdResp.orderStateLogs:type_name -> pb.OrderStateLogs + 11, // 3: pb.SearchOrderStateLogsResp.orderStateLogs:type_name -> pb.OrderStateLogs + 1, // 4: pb.orderService.AddOrders:input_type -> pb.AddOrdersReq + 3, // 5: pb.orderService.UpdateOrders:input_type -> pb.UpdateOrdersReq + 5, // 6: pb.orderService.DelOrders:input_type -> pb.DelOrdersReq + 7, // 7: pb.orderService.GetOrdersById:input_type -> pb.GetOrdersByIdReq + 9, // 8: pb.orderService.SearchOrders:input_type -> pb.SearchOrdersReq + 12, // 9: pb.orderService.AddOrderStateLogs:input_type -> pb.AddOrderStateLogsReq + 14, // 10: pb.orderService.UpdateOrderStateLogs:input_type -> pb.UpdateOrderStateLogsReq + 16, // 11: pb.orderService.DelOrderStateLogs:input_type -> pb.DelOrderStateLogsReq + 18, // 12: pb.orderService.GetOrderStateLogsById:input_type -> pb.GetOrderStateLogsByIdReq + 20, // 13: pb.orderService.SearchOrderStateLogs:input_type -> pb.SearchOrderStateLogsReq + 2, // 14: pb.orderService.AddOrders:output_type -> pb.AddOrdersResp + 4, // 15: pb.orderService.UpdateOrders:output_type -> pb.UpdateOrdersResp + 6, // 16: pb.orderService.DelOrders:output_type -> pb.DelOrdersResp + 8, // 17: pb.orderService.GetOrdersById:output_type -> pb.GetOrdersByIdResp + 10, // 18: pb.orderService.SearchOrders:output_type -> pb.SearchOrdersResp + 13, // 19: pb.orderService.AddOrderStateLogs:output_type -> pb.AddOrderStateLogsResp + 15, // 20: pb.orderService.UpdateOrderStateLogs:output_type -> pb.UpdateOrderStateLogsResp + 17, // 21: pb.orderService.DelOrderStateLogs:output_type -> pb.DelOrderStateLogsResp + 19, // 22: pb.orderService.GetOrderStateLogsById:output_type -> pb.GetOrderStateLogsByIdResp + 21, // 23: pb.orderService.SearchOrderStateLogs:output_type -> pb.SearchOrderStateLogsResp + 14, // [14:24] is the sub-list for method output_type + 4, // [4:14] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name +} + +func init() { file_order_proto_init() } +func file_order_proto_init() { + if File_order_proto != nil { + return + } + file_order_proto_msgTypes[0].OneofWrappers = []any{} + file_order_proto_msgTypes[1].OneofWrappers = []any{} + file_order_proto_msgTypes[3].OneofWrappers = []any{} + file_order_proto_msgTypes[9].OneofWrappers = []any{} + file_order_proto_msgTypes[11].OneofWrappers = []any{} + file_order_proto_msgTypes[12].OneofWrappers = []any{} + file_order_proto_msgTypes[14].OneofWrappers = []any{} + file_order_proto_msgTypes[20].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_order_proto_rawDesc), len(file_order_proto_rawDesc)), + NumEnums: 0, + NumMessages: 22, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_order_proto_goTypes, + DependencyIndexes: file_order_proto_depIdxs, + MessageInfos: file_order_proto_msgTypes, + }.Build() + File_order_proto = out.File + file_order_proto_goTypes = nil + file_order_proto_depIdxs = nil +} diff --git a/app/order/rpc/pb/order_grpc.pb.go b/app/order/rpc/pb/order_grpc.pb.go new file mode 100644 index 0000000..6a34302 --- /dev/null +++ b/app/order/rpc/pb/order_grpc.pb.go @@ -0,0 +1,467 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v5.29.6 +// source: order.proto + +package pb + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + OrderService_AddOrders_FullMethodName = "/pb.orderService/AddOrders" + OrderService_UpdateOrders_FullMethodName = "/pb.orderService/UpdateOrders" + OrderService_DelOrders_FullMethodName = "/pb.orderService/DelOrders" + OrderService_GetOrdersById_FullMethodName = "/pb.orderService/GetOrdersById" + OrderService_SearchOrders_FullMethodName = "/pb.orderService/SearchOrders" + OrderService_AddOrderStateLogs_FullMethodName = "/pb.orderService/AddOrderStateLogs" + OrderService_UpdateOrderStateLogs_FullMethodName = "/pb.orderService/UpdateOrderStateLogs" + OrderService_DelOrderStateLogs_FullMethodName = "/pb.orderService/DelOrderStateLogs" + OrderService_GetOrderStateLogsById_FullMethodName = "/pb.orderService/GetOrderStateLogsById" + OrderService_SearchOrderStateLogs_FullMethodName = "/pb.orderService/SearchOrderStateLogs" +) + +// OrderServiceClient is the client API for OrderService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type OrderServiceClient interface { + // -----------------------orders----------------------- + AddOrders(ctx context.Context, in *AddOrdersReq, opts ...grpc.CallOption) (*AddOrdersResp, error) + UpdateOrders(ctx context.Context, in *UpdateOrdersReq, opts ...grpc.CallOption) (*UpdateOrdersResp, error) + DelOrders(ctx context.Context, in *DelOrdersReq, opts ...grpc.CallOption) (*DelOrdersResp, error) + GetOrdersById(ctx context.Context, in *GetOrdersByIdReq, opts ...grpc.CallOption) (*GetOrdersByIdResp, error) + SearchOrders(ctx context.Context, in *SearchOrdersReq, opts ...grpc.CallOption) (*SearchOrdersResp, error) + // -----------------------orderStateLogs----------------------- + AddOrderStateLogs(ctx context.Context, in *AddOrderStateLogsReq, opts ...grpc.CallOption) (*AddOrderStateLogsResp, error) + UpdateOrderStateLogs(ctx context.Context, in *UpdateOrderStateLogsReq, opts ...grpc.CallOption) (*UpdateOrderStateLogsResp, error) + DelOrderStateLogs(ctx context.Context, in *DelOrderStateLogsReq, opts ...grpc.CallOption) (*DelOrderStateLogsResp, error) + GetOrderStateLogsById(ctx context.Context, in *GetOrderStateLogsByIdReq, opts ...grpc.CallOption) (*GetOrderStateLogsByIdResp, error) + SearchOrderStateLogs(ctx context.Context, in *SearchOrderStateLogsReq, opts ...grpc.CallOption) (*SearchOrderStateLogsResp, error) +} + +type orderServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewOrderServiceClient(cc grpc.ClientConnInterface) OrderServiceClient { + return &orderServiceClient{cc} +} + +func (c *orderServiceClient) AddOrders(ctx context.Context, in *AddOrdersReq, opts ...grpc.CallOption) (*AddOrdersResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddOrdersResp) + err := c.cc.Invoke(ctx, OrderService_AddOrders_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) UpdateOrders(ctx context.Context, in *UpdateOrdersReq, opts ...grpc.CallOption) (*UpdateOrdersResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateOrdersResp) + err := c.cc.Invoke(ctx, OrderService_UpdateOrders_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) DelOrders(ctx context.Context, in *DelOrdersReq, opts ...grpc.CallOption) (*DelOrdersResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelOrdersResp) + err := c.cc.Invoke(ctx, OrderService_DelOrders_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) GetOrdersById(ctx context.Context, in *GetOrdersByIdReq, opts ...grpc.CallOption) (*GetOrdersByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetOrdersByIdResp) + err := c.cc.Invoke(ctx, OrderService_GetOrdersById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) SearchOrders(ctx context.Context, in *SearchOrdersReq, opts ...grpc.CallOption) (*SearchOrdersResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchOrdersResp) + err := c.cc.Invoke(ctx, OrderService_SearchOrders_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) AddOrderStateLogs(ctx context.Context, in *AddOrderStateLogsReq, opts ...grpc.CallOption) (*AddOrderStateLogsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddOrderStateLogsResp) + err := c.cc.Invoke(ctx, OrderService_AddOrderStateLogs_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) UpdateOrderStateLogs(ctx context.Context, in *UpdateOrderStateLogsReq, opts ...grpc.CallOption) (*UpdateOrderStateLogsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateOrderStateLogsResp) + err := c.cc.Invoke(ctx, OrderService_UpdateOrderStateLogs_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) DelOrderStateLogs(ctx context.Context, in *DelOrderStateLogsReq, opts ...grpc.CallOption) (*DelOrderStateLogsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelOrderStateLogsResp) + err := c.cc.Invoke(ctx, OrderService_DelOrderStateLogs_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) GetOrderStateLogsById(ctx context.Context, in *GetOrderStateLogsByIdReq, opts ...grpc.CallOption) (*GetOrderStateLogsByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetOrderStateLogsByIdResp) + err := c.cc.Invoke(ctx, OrderService_GetOrderStateLogsById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *orderServiceClient) SearchOrderStateLogs(ctx context.Context, in *SearchOrderStateLogsReq, opts ...grpc.CallOption) (*SearchOrderStateLogsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchOrderStateLogsResp) + err := c.cc.Invoke(ctx, OrderService_SearchOrderStateLogs_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// OrderServiceServer is the server API for OrderService service. +// All implementations must embed UnimplementedOrderServiceServer +// for forward compatibility. +type OrderServiceServer interface { + // -----------------------orders----------------------- + AddOrders(context.Context, *AddOrdersReq) (*AddOrdersResp, error) + UpdateOrders(context.Context, *UpdateOrdersReq) (*UpdateOrdersResp, error) + DelOrders(context.Context, *DelOrdersReq) (*DelOrdersResp, error) + GetOrdersById(context.Context, *GetOrdersByIdReq) (*GetOrdersByIdResp, error) + SearchOrders(context.Context, *SearchOrdersReq) (*SearchOrdersResp, error) + // -----------------------orderStateLogs----------------------- + AddOrderStateLogs(context.Context, *AddOrderStateLogsReq) (*AddOrderStateLogsResp, error) + UpdateOrderStateLogs(context.Context, *UpdateOrderStateLogsReq) (*UpdateOrderStateLogsResp, error) + DelOrderStateLogs(context.Context, *DelOrderStateLogsReq) (*DelOrderStateLogsResp, error) + GetOrderStateLogsById(context.Context, *GetOrderStateLogsByIdReq) (*GetOrderStateLogsByIdResp, error) + SearchOrderStateLogs(context.Context, *SearchOrderStateLogsReq) (*SearchOrderStateLogsResp, error) + mustEmbedUnimplementedOrderServiceServer() +} + +// UnimplementedOrderServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedOrderServiceServer struct{} + +func (UnimplementedOrderServiceServer) AddOrders(context.Context, *AddOrdersReq) (*AddOrdersResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddOrders not implemented") +} +func (UnimplementedOrderServiceServer) UpdateOrders(context.Context, *UpdateOrdersReq) (*UpdateOrdersResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateOrders not implemented") +} +func (UnimplementedOrderServiceServer) DelOrders(context.Context, *DelOrdersReq) (*DelOrdersResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelOrders not implemented") +} +func (UnimplementedOrderServiceServer) GetOrdersById(context.Context, *GetOrdersByIdReq) (*GetOrdersByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetOrdersById not implemented") +} +func (UnimplementedOrderServiceServer) SearchOrders(context.Context, *SearchOrdersReq) (*SearchOrdersResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchOrders not implemented") +} +func (UnimplementedOrderServiceServer) AddOrderStateLogs(context.Context, *AddOrderStateLogsReq) (*AddOrderStateLogsResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddOrderStateLogs not implemented") +} +func (UnimplementedOrderServiceServer) UpdateOrderStateLogs(context.Context, *UpdateOrderStateLogsReq) (*UpdateOrderStateLogsResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateOrderStateLogs not implemented") +} +func (UnimplementedOrderServiceServer) DelOrderStateLogs(context.Context, *DelOrderStateLogsReq) (*DelOrderStateLogsResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelOrderStateLogs not implemented") +} +func (UnimplementedOrderServiceServer) GetOrderStateLogsById(context.Context, *GetOrderStateLogsByIdReq) (*GetOrderStateLogsByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetOrderStateLogsById not implemented") +} +func (UnimplementedOrderServiceServer) SearchOrderStateLogs(context.Context, *SearchOrderStateLogsReq) (*SearchOrderStateLogsResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchOrderStateLogs not implemented") +} +func (UnimplementedOrderServiceServer) mustEmbedUnimplementedOrderServiceServer() {} +func (UnimplementedOrderServiceServer) testEmbeddedByValue() {} + +// UnsafeOrderServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to OrderServiceServer will +// result in compilation errors. +type UnsafeOrderServiceServer interface { + mustEmbedUnimplementedOrderServiceServer() +} + +func RegisterOrderServiceServer(s grpc.ServiceRegistrar, srv OrderServiceServer) { + // If the following call panics, it indicates UnimplementedOrderServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&OrderService_ServiceDesc, srv) +} + +func _OrderService_AddOrders_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddOrdersReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).AddOrders(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_AddOrders_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).AddOrders(ctx, req.(*AddOrdersReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_UpdateOrders_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateOrdersReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).UpdateOrders(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_UpdateOrders_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).UpdateOrders(ctx, req.(*UpdateOrdersReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_DelOrders_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelOrdersReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).DelOrders(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_DelOrders_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).DelOrders(ctx, req.(*DelOrdersReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_GetOrdersById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetOrdersByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).GetOrdersById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_GetOrdersById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).GetOrdersById(ctx, req.(*GetOrdersByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_SearchOrders_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchOrdersReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).SearchOrders(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_SearchOrders_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).SearchOrders(ctx, req.(*SearchOrdersReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_AddOrderStateLogs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddOrderStateLogsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).AddOrderStateLogs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_AddOrderStateLogs_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).AddOrderStateLogs(ctx, req.(*AddOrderStateLogsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_UpdateOrderStateLogs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateOrderStateLogsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).UpdateOrderStateLogs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_UpdateOrderStateLogs_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).UpdateOrderStateLogs(ctx, req.(*UpdateOrderStateLogsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_DelOrderStateLogs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelOrderStateLogsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).DelOrderStateLogs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_DelOrderStateLogs_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).DelOrderStateLogs(ctx, req.(*DelOrderStateLogsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_GetOrderStateLogsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetOrderStateLogsByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).GetOrderStateLogsById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_GetOrderStateLogsById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).GetOrderStateLogsById(ctx, req.(*GetOrderStateLogsByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _OrderService_SearchOrderStateLogs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchOrderStateLogsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OrderServiceServer).SearchOrderStateLogs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OrderService_SearchOrderStateLogs_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OrderServiceServer).SearchOrderStateLogs(ctx, req.(*SearchOrderStateLogsReq)) + } + return interceptor(ctx, in, info, handler) +} + +// OrderService_ServiceDesc is the grpc.ServiceDesc for OrderService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var OrderService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.orderService", + HandlerType: (*OrderServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "AddOrders", + Handler: _OrderService_AddOrders_Handler, + }, + { + MethodName: "UpdateOrders", + Handler: _OrderService_UpdateOrders_Handler, + }, + { + MethodName: "DelOrders", + Handler: _OrderService_DelOrders_Handler, + }, + { + MethodName: "GetOrdersById", + Handler: _OrderService_GetOrdersById_Handler, + }, + { + MethodName: "SearchOrders", + Handler: _OrderService_SearchOrders_Handler, + }, + { + MethodName: "AddOrderStateLogs", + Handler: _OrderService_AddOrderStateLogs_Handler, + }, + { + MethodName: "UpdateOrderStateLogs", + Handler: _OrderService_UpdateOrderStateLogs_Handler, + }, + { + MethodName: "DelOrderStateLogs", + Handler: _OrderService_DelOrderStateLogs_Handler, + }, + { + MethodName: "GetOrderStateLogsById", + Handler: _OrderService_GetOrderStateLogsById_Handler, + }, + { + MethodName: "SearchOrderStateLogs", + Handler: _OrderService_SearchOrderStateLogs_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "order.proto", +} diff --git a/app/player/api/etc/juwan-api.yaml b/app/player/api/etc/player-api.yaml similarity index 91% rename from app/player/api/etc/juwan-api.yaml rename to app/player/api/etc/player-api.yaml index 71d4954..cab123f 100644 --- a/app/player/api/etc/juwan-api.yaml +++ b/app/player/api/etc/player-api.yaml @@ -1,4 +1,4 @@ -Name: juwan-api +Name: player-api Host: 0.0.0.0 Port: 8888 diff --git a/app/player/api/internal/handler/player/deleteServiceHandler.go b/app/player/api/internal/handler/player/deleteServiceHandler.go index 6116bb7..327e825 100644 --- a/app/player/api/internal/handler/player/deleteServiceHandler.go +++ b/app/player/api/internal/handler/player/deleteServiceHandler.go @@ -6,16 +6,17 @@ package player import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/player/api/internal/logic/player" "juwan-backend/app/player/api/internal/svc" "juwan-backend/app/player/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 删除服务 func DeleteServiceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.DeleteServiceReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/player/api/internal/handler/player/getPlayerHandler.go b/app/player/api/internal/handler/player/getPlayerHandler.go index a60df99..0cba830 100644 --- a/app/player/api/internal/handler/player/getPlayerHandler.go +++ b/app/player/api/internal/handler/player/getPlayerHandler.go @@ -6,16 +6,17 @@ package player import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/player/api/internal/logic/player" "juwan-backend/app/player/api/internal/svc" "juwan-backend/app/player/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取打手详情 func GetPlayerHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.GetPlayerReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/player/api/internal/handler/player/getServiceHandler.go b/app/player/api/internal/handler/player/getServiceHandler.go index 24282f4..640cbc7 100644 --- a/app/player/api/internal/handler/player/getServiceHandler.go +++ b/app/player/api/internal/handler/player/getServiceHandler.go @@ -6,16 +6,17 @@ package player import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/player/api/internal/logic/player" "juwan-backend/app/player/api/internal/svc" "juwan-backend/app/player/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取服务详情 func GetServiceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.GetServiceReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/player/api/internal/handler/player/listPlayerServicesHandler.go b/app/player/api/internal/handler/player/listPlayerServicesHandler.go index 62d151e..93ae919 100644 --- a/app/player/api/internal/handler/player/listPlayerServicesHandler.go +++ b/app/player/api/internal/handler/player/listPlayerServicesHandler.go @@ -6,16 +6,17 @@ package player import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/player/api/internal/logic/player" "juwan-backend/app/player/api/internal/svc" "juwan-backend/app/player/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取指定打手的服务列表 func ListPlayerServicesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.PageReq + var req types.ListPlayerServicesReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/player/api/internal/handler/player/updateServiceHandler.go b/app/player/api/internal/handler/player/updateServiceHandler.go index 497f6eb..1c3ef18 100644 --- a/app/player/api/internal/handler/player/updateServiceHandler.go +++ b/app/player/api/internal/handler/player/updateServiceHandler.go @@ -6,16 +6,17 @@ package player import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/player/api/internal/logic/player" "juwan-backend/app/player/api/internal/svc" "juwan-backend/app/player/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 更新服务 func UpdateServiceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.CreateServiceReq + var req types.UpdateServiceReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/player/api/internal/logic/player/updatePlayerStatusLogic.go b/app/player/api/internal/logic/player/updatePlayerStatusLogic.go index 9e81b92..b7a7abb 100644 --- a/app/player/api/internal/logic/player/updatePlayerStatusLogic.go +++ b/app/player/api/internal/logic/player/updatePlayerStatusLogic.go @@ -6,7 +6,7 @@ package player import ( "context" "juwan-backend/app/player/rpc/pb" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "juwan-backend/app/player/api/internal/svc" "juwan-backend/app/player/api/internal/types" @@ -31,7 +31,7 @@ func NewUpdatePlayerStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) func (l *UpdatePlayerStatusLogic) UpdatePlayerStatus(req *types.UpdatePlayerStatusReq) (resp *types.EmptyResp, err error) { // todo: add your logic here and delete this line - userId, err := contextx.UserIDFrom(l.ctx) + userId, err := contextj.UserIDFrom(l.ctx) if err != nil { return nil, err } diff --git a/app/player/api/juwan.go b/app/player/api/player.go similarity index 89% rename from app/player/api/juwan.go rename to app/player/api/player.go index 6dc04d5..17bba4b 100644 --- a/app/player/api/juwan.go +++ b/app/player/api/player.go @@ -15,7 +15,7 @@ import ( "github.com/zeromicro/go-zero/rest" ) -var configFile = flag.String("f", "etc/juwan-api.yaml", "the config file") +var configFile = flag.String("f", "etc/player-api.yaml", "the config file") func main() { flag.Parse() diff --git a/app/player/rpc/etc/pb.yaml b/app/player/rpc/etc/pb.yaml index 3763106..397aa4b 100644 --- a/app/player/rpc/etc/pb.yaml +++ b/app/player/rpc/etc/pb.yaml @@ -7,23 +7,20 @@ Prometheus: Port: 4001 Path: /metrics -# tcd: -# Hosts: -# - 127.0.0.1:2379 -# Key: pb.rpc - -# Target: k8s://juwan/.:8080 - SnowflakeRpcConf: Target: k8s://juwan/snowflake-svc:8080 -DB: - Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" - Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" +#DB: +# Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" +# Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" +DB: + Master: "postgresql://app:7BGs8CdEE8sLPshMjyXkYmxNMTV88EBrd2GN6tdIX1VhIgBzIcgKXbJjVdYiX4a9@user-db-rw:5432/app" + Slaves: "postgresql://app:7BGs8CdEE8sLPshMjyXkYmxNMTV88EBrd2GN6tdIX1VhIgBzIcgKXbJjVdYiX4a9@user-db-ro:5432/app" + CacheConf: - Host: "${REDIS_M_HOST}" Type: node diff --git a/app/player/rpc/internal/svc/serviceContext.go b/app/player/rpc/internal/svc/serviceContext.go index 97e9d66..d0b2d25 100644 --- a/app/player/rpc/internal/svc/serviceContext.go +++ b/app/player/rpc/internal/svc/serviceContext.go @@ -12,6 +12,8 @@ import ( "ariga.io/entcache" "entgo.io/ent/dialect/sql" "github.com/zeromicro/go-zero/core/logx" + + _ "github.com/jackc/pgx/v5/stdlib" ) type ServiceContext struct { diff --git a/app/player/rpc/pb.go b/app/player/rpc/pb.go index 6d25455..a8a3b65 100644 --- a/app/player/rpc/pb.go +++ b/app/player/rpc/pb.go @@ -22,7 +22,7 @@ func main() { flag.Parse() var c config.Config - conf.MustLoad(*configFile, &c) + conf.MustLoad(*configFile, &c, conf.UseEnv()) ctx := svc.NewServiceContext(c) s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { diff --git a/app/shop/api/etc/juwan-api.yaml b/app/shop/api/etc/shop-api.yaml similarity index 91% rename from app/shop/api/etc/juwan-api.yaml rename to app/shop/api/etc/shop-api.yaml index 2ef25ff..d0e4d9a 100644 --- a/app/shop/api/etc/juwan-api.yaml +++ b/app/shop/api/etc/shop-api.yaml @@ -1,4 +1,4 @@ -Name: juwan-api +Name: shop-api Host: 0.0.0.0 Port: 8888 diff --git a/app/shop/api/internal/handler/shop/acceptInvitationHandler.go b/app/shop/api/internal/handler/shop/acceptInvitationHandler.go index 9a2d3fd..29966d7 100644 --- a/app/shop/api/internal/handler/shop/acceptInvitationHandler.go +++ b/app/shop/api/internal/handler/shop/acceptInvitationHandler.go @@ -4,24 +4,34 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 接受邀请 func AcceptInvitationHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.AcceptInvitationReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return } - l := shop.NewAcceptInvitationLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewAcceptInvitationLogic(ctx, svcCtx) resp, err := l.AcceptInvitation(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/addAnnouncementHandler.go b/app/shop/api/internal/handler/shop/addAnnouncementHandler.go index bbea91e..7220258 100644 --- a/app/shop/api/internal/handler/shop/addAnnouncementHandler.go +++ b/app/shop/api/internal/handler/shop/addAnnouncementHandler.go @@ -4,12 +4,17 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 新增店铺公告 @@ -21,7 +26,12 @@ func AddAnnouncementHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return } - l := shop.NewAddAnnouncementLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewAddAnnouncementLogic(ctx, svcCtx) resp, err := l.AddAnnouncement(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/createShopHandler.go b/app/shop/api/internal/handler/shop/createShopHandler.go index e6635d7..bcfba6b 100644 --- a/app/shop/api/internal/handler/shop/createShopHandler.go +++ b/app/shop/api/internal/handler/shop/createShopHandler.go @@ -4,12 +4,17 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 创建店铺 @@ -21,7 +26,12 @@ func CreateShopHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return } - l := shop.NewCreateShopLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewCreateShopLogic(ctx, svcCtx) resp, err := l.CreateShop(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/deleteAnnouncementHandler.go b/app/shop/api/internal/handler/shop/deleteAnnouncementHandler.go index 32a2e80..9a92900 100644 --- a/app/shop/api/internal/handler/shop/deleteAnnouncementHandler.go +++ b/app/shop/api/internal/handler/shop/deleteAnnouncementHandler.go @@ -4,24 +4,34 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 删除店铺公告 func DeleteAnnouncementHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.DeleteAnnouncementReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return } - l := shop.NewDeleteAnnouncementLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewDeleteAnnouncementLogic(ctx, svcCtx) resp, err := l.DeleteAnnouncement(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/getMyShopHandler.go b/app/shop/api/internal/handler/shop/getMyShopHandler.go index 37100e4..2500e74 100644 --- a/app/shop/api/internal/handler/shop/getMyShopHandler.go +++ b/app/shop/api/internal/handler/shop/getMyShopHandler.go @@ -4,12 +4,17 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取当前用户的店铺 @@ -21,7 +26,12 @@ func GetMyShopHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return } - l := shop.NewGetMyShopLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewGetMyShopLogic(ctx, svcCtx) resp, err := l.GetMyShop(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/getShopHandler.go b/app/shop/api/internal/handler/shop/getShopHandler.go index a739964..926579e 100644 --- a/app/shop/api/internal/handler/shop/getShopHandler.go +++ b/app/shop/api/internal/handler/shop/getShopHandler.go @@ -6,16 +6,17 @@ package shop import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取店铺详情 func GetShopHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.ShopIdReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/shop/api/internal/handler/shop/getShopIncomeStatsHandler.go b/app/shop/api/internal/handler/shop/getShopIncomeStatsHandler.go index 1b7913f..08dda35 100644 --- a/app/shop/api/internal/handler/shop/getShopIncomeStatsHandler.go +++ b/app/shop/api/internal/handler/shop/getShopIncomeStatsHandler.go @@ -4,24 +4,34 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取收入统计 func GetShopIncomeStatsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.AcceptInvitationReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return } - l := shop.NewGetShopIncomeStatsLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewGetShopIncomeStatsLogic(ctx, svcCtx) resp, err := l.GetShopIncomeStats(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/getUserShopHandler.go b/app/shop/api/internal/handler/shop/getUserShopHandler.go index 5f4f4a4..1c2ab18 100644 --- a/app/shop/api/internal/handler/shop/getUserShopHandler.go +++ b/app/shop/api/internal/handler/shop/getUserShopHandler.go @@ -6,16 +6,17 @@ package shop import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取店长的店铺 func GetUserShopHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.UserIdReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/shop/api/internal/handler/shop/invitePlayerHandler.go b/app/shop/api/internal/handler/shop/invitePlayerHandler.go index 2d124af..99f1bff 100644 --- a/app/shop/api/internal/handler/shop/invitePlayerHandler.go +++ b/app/shop/api/internal/handler/shop/invitePlayerHandler.go @@ -4,12 +4,17 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 邀请打手 @@ -21,7 +26,12 @@ func InvitePlayerHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return } - l := shop.NewInvitePlayerLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewInvitePlayerLogic(ctx, svcCtx) resp, err := l.InvitePlayer(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/rejectInvitationHandler.go b/app/shop/api/internal/handler/shop/rejectInvitationHandler.go index c17e7f0..a80fa22 100644 --- a/app/shop/api/internal/handler/shop/rejectInvitationHandler.go +++ b/app/shop/api/internal/handler/shop/rejectInvitationHandler.go @@ -4,24 +4,34 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 拒绝邀请 func RejectInvitationHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.AcceptInvitationReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return } - l := shop.NewRejectInvitationLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewRejectInvitationLogic(ctx, svcCtx) resp, err := l.RejectInvitation(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/removePlayerHandler.go b/app/shop/api/internal/handler/shop/removePlayerHandler.go index 4108c65..544589c 100644 --- a/app/shop/api/internal/handler/shop/removePlayerHandler.go +++ b/app/shop/api/internal/handler/shop/removePlayerHandler.go @@ -4,24 +4,34 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 移除打手 func RemovePlayerHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.EmptyResp + var req types.InvitationReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return } - l := shop.NewRemovePlayerLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewRemovePlayerLogic(ctx, svcCtx) resp, err := l.RemovePlayer(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/updateShopHandler.go b/app/shop/api/internal/handler/shop/updateShopHandler.go index 0cd39e9..2e82873 100644 --- a/app/shop/api/internal/handler/shop/updateShopHandler.go +++ b/app/shop/api/internal/handler/shop/updateShopHandler.go @@ -4,12 +4,17 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 更新店铺信息 @@ -21,7 +26,12 @@ func UpdateShopHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return } - l := shop.NewUpdateShopLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewUpdateShopLogic(ctx, svcCtx) resp, err := l.UpdateShop(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/handler/shop/updateShopTemplateHandler.go b/app/shop/api/internal/handler/shop/updateShopTemplateHandler.go index 08b9e6f..2906f93 100644 --- a/app/shop/api/internal/handler/shop/updateShopTemplateHandler.go +++ b/app/shop/api/internal/handler/shop/updateShopTemplateHandler.go @@ -4,12 +4,17 @@ package shop import ( + "errors" + "juwan-backend/common/utils/contextj" + "juwan-backend/common/utils/httpj" + "juwan-backend/common/utils/responses" "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/shop/api/internal/logic/shop" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 更新店铺模板 @@ -21,7 +26,12 @@ func UpdateShopTemplateHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return } - l := shop.NewUpdateShopTemplateLogic(r.Context(), svcCtx) + userId, err := httpj.GetUserIdFromHeader(r.Header) + if err != nil { + httpx.ErrorCtx(r.Context(), w, responses.NewErrorResp(403, errors.New("forbidden: user not authenticated"))) + } + ctx := contextj.WithUserID(r.Context(), userId) + l := shop.NewUpdateShopTemplateLogic(ctx, svcCtx) resp, err := l.UpdateShopTemplate(&req) if err != nil { httpx.ErrorCtx(r.Context(), w, err) diff --git a/app/shop/api/internal/logic/shop/acceptInvitationLogic.go b/app/shop/api/internal/logic/shop/acceptInvitationLogic.go index 8c214a9..35d9395 100644 --- a/app/shop/api/internal/logic/shop/acceptInvitationLogic.go +++ b/app/shop/api/internal/logic/shop/acceptInvitationLogic.go @@ -5,9 +5,12 @@ package shop import ( "context" - + "errors" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" + "time" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +31,44 @@ func NewAcceptInvitationLogic(ctx context.Context, svcCtx *svc.ServiceContext) * } func (l *AcceptInvitationLogic) AcceptInvitation(req *types.AcceptInvitationReq) (resp *types.EmptyResp, err error) { - // todo: add your logic here and delete this line - AcceptInvitationLogic{} - return + userId, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + invitation, err := l.svcCtx.ShopRpc.GetShopInvitationsById(l.ctx, &pb.GetShopInvitationsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if invitation.ShopInvitations == nil { + return nil, errors.New("invitation not found") + } + if invitation.ShopInvitations.PlayerId != userId { + return nil, errors.New("bad request: invitation not found or not owned by user") + } + + i, err := l.svcCtx.ShopRpc.UpdateShopInvitations(l.ctx, &pb.UpdateShopInvitationsReq{ + Id: req.Id, + ShopId: invitation.ShopInvitations.ShopId, + PlayerId: userId, + Status: "accepted", + InvitedBy: invitation.ShopInvitations.InvitedBy, + CreatedAt: invitation.ShopInvitations.CreatedAt, + RespondedAt: time.Now().Unix(), + }) + if err != nil { + return nil, err + } + _, err = l.svcCtx.ShopRpc.AddShopPlayers(l.ctx, &pb.AddShopPlayersReq{ + ShopId: i.ShopInvitations.ShopId, + PlayerId: userId, + IsPrimary: false, + JoinedAt: time.Now().Unix(), + LeftAt: 0, + }) + if err != nil { + return nil, err + } + + _ = i + return &types.EmptyResp{}, nil } diff --git a/app/shop/api/internal/logic/shop/addAnnouncementLogic.go b/app/shop/api/internal/logic/shop/addAnnouncementLogic.go index a273def..f625844 100644 --- a/app/shop/api/internal/logic/shop/addAnnouncementLogic.go +++ b/app/shop/api/internal/logic/shop/addAnnouncementLogic.go @@ -5,6 +5,9 @@ package shop import ( "context" + "errors" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" @@ -28,7 +31,41 @@ func NewAddAnnouncementLogic(ctx context.Context, svcCtx *svc.ServiceContext) *A } func (l *AddAnnouncementLogic) AddAnnouncement(req *types.AnnouncementReq) (resp *types.EmptyResp, err error) { - // todo: add your logic here and delete this line + userId, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + shop, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if shop.Shops == nil { + return nil, errors.New("shop not found") + } + if shop.Shops.OwnerId != userId { + return nil, contextj.ERRILLEGALUSER + } + shop.Shops.Announcements = append(shop.Shops.Announcements, req.Content) + _, err = l.svcCtx.ShopRpc.UpdateShops(l.ctx, &pb.UpdateShopsReq{ + Id: shop.Shops.Id, + OwnerId: shop.Shops.OwnerId, + Name: shop.Shops.Name, + Banner: shop.Shops.Banner, + Description: shop.Shops.Description, + Rating: shop.Shops.Rating, + TotalOrders: shop.Shops.TotalOrders, + PlayerCount: shop.Shops.PlayerCount, + CommissionType: shop.Shops.CommissionType, + CommissionValue: shop.Shops.CommissionValue, + AllowMultiShop: shop.Shops.AllowMultiShop, + AllowIndependentOrders: shop.Shops.AllowIndependentOrders, + DispatchMode: shop.Shops.DispatchMode, + Announcements: shop.Shops.Announcements, + TemplateConfig: shop.Shops.TemplateConfig, + }) + if err != nil { + return nil, err + } - return + return &types.EmptyResp{}, nil } diff --git a/app/shop/api/internal/logic/shop/createShopLogic.go b/app/shop/api/internal/logic/shop/createShopLogic.go index fffee05..143c954 100644 --- a/app/shop/api/internal/logic/shop/createShopLogic.go +++ b/app/shop/api/internal/logic/shop/createShopLogic.go @@ -5,6 +5,10 @@ package shop import ( "context" + "errors" + + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" @@ -28,7 +32,42 @@ func NewCreateShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Create } func (l *CreateShopLogic) CreateShop(req *types.CreateShopReq) (resp *types.ShopProfile, err error) { - // todo: add your logic here and delete this line + ownerID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + if req.Name == "" { + return nil, errors.New("name is required") + } + + _, err = l.svcCtx.ShopRpc.AddShops(l.ctx, &pb.AddShopsReq{ + OwnerId: ownerID, + Name: req.Name, + Description: req.Description, + Rating: "5", + TotalOrders: 0, + PlayerCount: 0, + CommissionType: req.CommissionType, + CommissionValue: req.CommissionValue, + AllowMultiShop: false, + AllowIndependentOrders: true, + DispatchMode: "manual", + Announcements: []string{}, + TemplateConfig: `{}`, + }) + if err != nil { + return nil, err + } + + shop, err := getShopByOwnerID(l.ctx, l.svcCtx.ShopRpc, ownerID) + if err != nil { + return nil, err + } + if shop == nil { + return nil, errors.New("create shop failed") + } + + return toShopProfile(shop), nil - return } diff --git a/app/shop/api/internal/logic/shop/deleteAnnouncementLogic.go b/app/shop/api/internal/logic/shop/deleteAnnouncementLogic.go index 533556c..5d38007 100644 --- a/app/shop/api/internal/logic/shop/deleteAnnouncementLogic.go +++ b/app/shop/api/internal/logic/shop/deleteAnnouncementLogic.go @@ -5,9 +5,12 @@ package shop import ( "context" + "errors" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +31,48 @@ func NewDeleteAnnouncementLogic(ctx context.Context, svcCtx *svc.ServiceContext) } func (l *DeleteAnnouncementLogic) DeleteAnnouncement(req *types.DeleteAnnouncementReq) (resp *types.EmptyResp, err error) { - // todo: add your logic here and delete this line + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } - return + shop, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if shop.Shops == nil { + return nil, errors.New("shop not found") + } + if shop.Shops.OwnerId != userID { + return nil, contextj.ERRILLEGALUSER + } + + index := int(req.Index) + if index < 0 || index >= len(shop.Shops.Announcements) { + return nil, errors.New("announcement index out of range") + } + + shop.Shops.Announcements = append(shop.Shops.Announcements[:index], shop.Shops.Announcements[index+1:]...) + _, err = l.svcCtx.ShopRpc.UpdateShops(l.ctx, &pb.UpdateShopsReq{ + Id: shop.Shops.Id, + OwnerId: shop.Shops.OwnerId, + Name: shop.Shops.Name, + Banner: shop.Shops.Banner, + Description: shop.Shops.Description, + Rating: shop.Shops.Rating, + TotalOrders: shop.Shops.TotalOrders, + PlayerCount: shop.Shops.PlayerCount, + CommissionType: shop.Shops.CommissionType, + CommissionValue: shop.Shops.CommissionValue, + AllowMultiShop: shop.Shops.AllowMultiShop, + AllowIndependentOrders: shop.Shops.AllowIndependentOrders, + DispatchMode: shop.Shops.DispatchMode, + Announcements: shop.Shops.Announcements, + TemplateConfig: shop.Shops.TemplateConfig, + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil } diff --git a/app/shop/api/internal/logic/shop/getMyShopLogic.go b/app/shop/api/internal/logic/shop/getMyShopLogic.go index 709a436..1ab716c 100644 --- a/app/shop/api/internal/logic/shop/getMyShopLogic.go +++ b/app/shop/api/internal/logic/shop/getMyShopLogic.go @@ -5,9 +5,11 @@ package shop import ( "context" + "errors" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +30,19 @@ func NewGetMyShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMySh } func (l *GetMyShopLogic) GetMyShop(req *types.EmptyResp) (resp *types.ShopProfile, err error) { - // todo: add your logic here and delete this line + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + shop, err := getShopByOwnerID(l.ctx, l.svcCtx.ShopRpc, userID) + if err != nil { + return nil, err + } + if shop == nil { + return nil, errors.New("shop not found") + } + + return toShopProfile(shop), nil - return } diff --git a/app/shop/api/internal/logic/shop/getShopIncomeStatsLogic.go b/app/shop/api/internal/logic/shop/getShopIncomeStatsLogic.go index f5f137e..95c3fae 100644 --- a/app/shop/api/internal/logic/shop/getShopIncomeStatsLogic.go +++ b/app/shop/api/internal/logic/shop/getShopIncomeStatsLogic.go @@ -5,9 +5,12 @@ package shop import ( "context" + "errors" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +31,28 @@ func NewGetShopIncomeStatsLogic(ctx context.Context, svcCtx *svc.ServiceContext) } func (l *GetShopIncomeStatsLogic) GetShopIncomeStats(req *types.AcceptInvitationReq) (resp *types.IncomeStatsResp, err error) { - // todo: add your logic here and delete this line + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + shop, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if shop.Shops == nil { + return nil, errors.New("shop not found") + } + if shop.Shops.OwnerId != userID { + return nil, contextj.ERRILLEGALUSER + } + + return &types.IncomeStatsResp{ + MonthlyIncome: "0", + PendingSettlement: "0", + TotalWithdrawn: "0", + TotalOrders: shop.Shops.TotalOrders, + CompletedOrders: shop.Shops.TotalOrders, + }, nil - return } diff --git a/app/shop/api/internal/logic/shop/getShopLogic.go b/app/shop/api/internal/logic/shop/getShopLogic.go index c3fefdf..be93d5c 100644 --- a/app/shop/api/internal/logic/shop/getShopLogic.go +++ b/app/shop/api/internal/logic/shop/getShopLogic.go @@ -5,6 +5,9 @@ package shop import ( "context" + "errors" + + "juwan-backend/app/shop/rpc/pb" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" @@ -28,7 +31,13 @@ func NewGetShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetShopLo } func (l *GetShopLogic) GetShop(req *types.ShopIdReq) (resp *types.ShopProfile, err error) { - // todo: add your logic here and delete this line + result, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if result.Shops == nil { + return nil, errors.New("shop not found") + } + return toShopProfile(result.Shops), nil - return } diff --git a/app/shop/api/internal/logic/shop/getUserShopLogic.go b/app/shop/api/internal/logic/shop/getUserShopLogic.go index f2d8ac0..8637c00 100644 --- a/app/shop/api/internal/logic/shop/getUserShopLogic.go +++ b/app/shop/api/internal/logic/shop/getUserShopLogic.go @@ -5,6 +5,7 @@ package shop import ( "context" + "errors" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" @@ -28,7 +29,13 @@ func NewGetUserShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUs } func (l *GetUserShopLogic) GetUserShop(req *types.UserIdReq) (resp *types.ShopProfile, err error) { - // todo: add your logic here and delete this line + shop, err := getShopByOwnerID(l.ctx, l.svcCtx.ShopRpc, req.Id) + if err != nil { + return nil, err + } + if shop == nil { + return nil, errors.New("shop not found") + } + return toShopProfile(shop), nil - return } diff --git a/app/shop/api/internal/logic/shop/helpers.go b/app/shop/api/internal/logic/shop/helpers.go new file mode 100644 index 0000000..a7ded8d --- /dev/null +++ b/app/shop/api/internal/logic/shop/helpers.go @@ -0,0 +1,65 @@ +package shop + +import ( + "context" + "encoding/json" + "strconv" + + "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/app/shop/rpc/shopservice" +) + +func toShopProfile(in *pb.Shops) *types.ShopProfile { + if in == nil { + return nil + } + + var template any + if in.TemplateConfig != "" { + _ = json.Unmarshal([]byte(in.TemplateConfig), &template) + } + if template == nil { + template = map[string]any{} + } + + ownerID := strconv.FormatInt(in.OwnerId, 10) + return &types.ShopProfile{ + Id: strconv.FormatInt(in.Id, 10), + Owner: types.UserProfile{ + Id: ownerID, + Username: "", + Nickname: "", + Avatar: "", + Role: "owner", + VerifiedRoles: []string{"owner"}, + VerificationStatus: map[string]string{}, + CreatedAt: "", + }, + Name: in.Name, + Banner: in.Banner, + Description: in.Description, + Rating: in.Rating, + TotalOrders: in.TotalOrders, + PlayerCount: in.PlayerCount, + CommissionType: in.CommissionType, + CommissionValue: in.CommissionValue, + Announcements: in.Announcements, + TemplateConfig: template, + } +} + +func getShopByOwnerID(ctx context.Context, rpc shopservice.ShopService, ownerID int64) (*pb.Shops, error) { + list, err := rpc.SearchShops(ctx, &pb.SearchShopsReq{ + Page: 0, + Limit: 1, + OwnerId: ownerID, + }) + if err != nil { + return nil, err + } + if len(list.Shops) == 0 { + return nil, nil + } + return list.Shops[0], nil +} diff --git a/app/shop/api/internal/logic/shop/invitePlayerLogic.go b/app/shop/api/internal/logic/shop/invitePlayerLogic.go index 7d0b98e..e625825 100644 --- a/app/shop/api/internal/logic/shop/invitePlayerLogic.go +++ b/app/shop/api/internal/logic/shop/invitePlayerLogic.go @@ -5,9 +5,13 @@ package shop import ( "context" + "errors" + "time" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +32,33 @@ func NewInvitePlayerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Invi } func (l *InvitePlayerLogic) InvitePlayer(req *types.InvitationReq) (resp *types.EmptyResp, err error) { - // todo: add your logic here and delete this line + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } - return + shop, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if shop.Shops == nil { + return nil, errors.New("shop not found") + } + if shop.Shops.OwnerId != userID { + return nil, contextj.ERRILLEGALUSER + } + + _, err = l.svcCtx.ShopRpc.AddShopInvitations(l.ctx, &pb.AddShopInvitationsReq{ + ShopId: req.Id, + PlayerId: req.PlayerId, + Status: "pending", + InvitedBy: userID, + CreatedAt: time.Now().Unix(), + RespondedAt: 0, + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil } diff --git a/app/shop/api/internal/logic/shop/listShopsLogic.go b/app/shop/api/internal/logic/shop/listShopsLogic.go index e10e730..706d3b9 100644 --- a/app/shop/api/internal/logic/shop/listShopsLogic.go +++ b/app/shop/api/internal/logic/shop/listShopsLogic.go @@ -6,6 +6,8 @@ package shop import ( "context" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" @@ -28,7 +30,33 @@ func NewListShopsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListSho } func (l *ListShopsLogic) ListShops(req *types.PageReq) (resp *types.ShopListResp, err error) { - // todo: add your logic here and delete this line + if req.Limit <= 0 { + req.Limit = 20 + } + + result, err := l.svcCtx.ShopRpc.SearchShops(l.ctx, &pb.SearchShopsReq{ + Page: req.Offset / req.Limit, + Limit: req.Limit, + }) + if err != nil { + return nil, err + } + + items := make([]types.ShopProfile, 0, len(result.Shops)) + for _, item := range result.Shops { + profile := toShopProfile(item) + if profile != nil { + items = append(items, *profile) + } + } + + return &types.ShopListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: req.Limit, + }, + }, nil - return } diff --git a/app/shop/api/internal/logic/shop/rejectInvitationLogic.go b/app/shop/api/internal/logic/shop/rejectInvitationLogic.go index e723d97..ea9fe1e 100644 --- a/app/shop/api/internal/logic/shop/rejectInvitationLogic.go +++ b/app/shop/api/internal/logic/shop/rejectInvitationLogic.go @@ -5,9 +5,13 @@ package shop import ( "context" + "errors" + "time" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +32,34 @@ func NewRejectInvitationLogic(ctx context.Context, svcCtx *svc.ServiceContext) * } func (l *RejectInvitationLogic) RejectInvitation(req *types.AcceptInvitationReq) (resp *types.EmptyResp, err error) { - // todo: add your logic here and delete this line + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } - return + invitation, err := l.svcCtx.ShopRpc.GetShopInvitationsById(l.ctx, &pb.GetShopInvitationsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if invitation.ShopInvitations == nil { + return nil, errors.New("invitation not found") + } + if invitation.ShopInvitations.PlayerId != userID { + return nil, contextj.ERRILLEGALUSER + } + + _, err = l.svcCtx.ShopRpc.UpdateShopInvitations(l.ctx, &pb.UpdateShopInvitationsReq{ + Id: req.Id, + ShopId: invitation.ShopInvitations.ShopId, + PlayerId: invitation.ShopInvitations.PlayerId, + Status: "rejected", + InvitedBy: invitation.ShopInvitations.InvitedBy, + CreatedAt: invitation.ShopInvitations.CreatedAt, + RespondedAt: time.Now().Unix(), + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil } diff --git a/app/shop/api/internal/logic/shop/removePlayerLogic.go b/app/shop/api/internal/logic/shop/removePlayerLogic.go index c81eefd..1f02945 100644 --- a/app/shop/api/internal/logic/shop/removePlayerLogic.go +++ b/app/shop/api/internal/logic/shop/removePlayerLogic.go @@ -5,9 +5,13 @@ package shop import ( "context" + "errors" + "time" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +32,31 @@ func NewRemovePlayerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Remo } func (l *RemovePlayerLogic) RemovePlayer(req *types.InvitationReq) (resp *types.EmptyResp, err error) { - // todo: add your logic here and delete this line + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } - return + shop, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if shop.Shops == nil { + return nil, errors.New("shop not found") + } + if shop.Shops.OwnerId != userID { + return nil, contextj.ERRILLEGALUSER + } + + _, err = l.svcCtx.ShopRpc.UpdateShopPlayers(l.ctx, &pb.UpdateShopPlayersReq{ + ShopId: req.Id, + PlayerId: req.PlayerId, + IsPrimary: false, + LeftAt: time.Now().Unix(), + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil } diff --git a/app/shop/api/internal/logic/shop/updateShopLogic.go b/app/shop/api/internal/logic/shop/updateShopLogic.go index 3c70191..39ab6e7 100644 --- a/app/shop/api/internal/logic/shop/updateShopLogic.go +++ b/app/shop/api/internal/logic/shop/updateShopLogic.go @@ -5,9 +5,12 @@ package shop import ( "context" + "errors" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -27,8 +30,69 @@ func NewUpdateShopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Update } } -func (l *UpdateShopLogic) UpdateShop(req *types.ShopIdReq) (resp *types.ShopProfile, err error) { - // todo: add your logic here and delete this line +func (l *UpdateShopLogic) UpdateShop(req *types.UpdateShopReq) (resp *types.ShopProfile, err error) { + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + current, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if current.Shops == nil { + return nil, errors.New("shop not found") + } + if current.Shops.OwnerId != userID { + return nil, contextj.ERRILLEGALUSER + } + + name := current.Shops.Name + if req.Name != "" { + name = req.Name + } + description := current.Shops.Description + if req.Description != "" { + description = req.Description + } + commissionType := current.Shops.CommissionType + if req.CommissionType != "" { + commissionType = req.CommissionType + } + commissionValue := current.Shops.CommissionValue + if req.CommissionValue != "" { + commissionValue = req.CommissionValue + } + dispatchMode := current.Shops.DispatchMode + if req.DispatchMode != "" { + dispatchMode = req.DispatchMode + } + + _, err = l.svcCtx.ShopRpc.UpdateShops(l.ctx, &pb.UpdateShopsReq{ + Id: current.Shops.Id, + OwnerId: current.Shops.OwnerId, + Name: name, + Banner: current.Shops.Banner, + Description: description, + Rating: current.Shops.Rating, + TotalOrders: current.Shops.TotalOrders, + PlayerCount: current.Shops.PlayerCount, + CommissionType: commissionType, + CommissionValue: commissionValue, + AllowMultiShop: req.AllowMultiShop, + AllowIndependentOrders: req.AllowIndependentOrders, + DispatchMode: dispatchMode, + Announcements: current.Shops.Announcements, + TemplateConfig: current.Shops.TemplateConfig, + }) + if err != nil { + return nil, err + } + + updated, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + return toShopProfile(updated.Shops), nil - return } diff --git a/app/shop/api/internal/logic/shop/updateShopTemplateLogic.go b/app/shop/api/internal/logic/shop/updateShopTemplateLogic.go index 3c75d0d..028cc30 100644 --- a/app/shop/api/internal/logic/shop/updateShopTemplateLogic.go +++ b/app/shop/api/internal/logic/shop/updateShopTemplateLogic.go @@ -5,9 +5,13 @@ package shop import ( "context" + "encoding/json" + "errors" "juwan-backend/app/shop/api/internal/svc" "juwan-backend/app/shop/api/internal/types" + "juwan-backend/app/shop/rpc/pb" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -28,7 +32,48 @@ func NewUpdateShopTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) } func (l *UpdateShopTemplateLogic) UpdateShopTemplate(req *types.UpdateTemplateReq) (resp *types.EmptyResp, err error) { - // todo: add your logic here and delete this line + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + shop, err := l.svcCtx.ShopRpc.GetShopsById(l.ctx, &pb.GetShopsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if shop.Shops == nil { + return nil, errors.New("shop not found") + } + if shop.Shops.OwnerId != userID { + return nil, contextj.ERRILLEGALUSER + } + + templateBytes, err := json.Marshal(map[string]any{"sections": req.Sections}) + if err != nil { + return nil, errors.New("invalid sections") + } + + _, err = l.svcCtx.ShopRpc.UpdateShops(l.ctx, &pb.UpdateShopsReq{ + Id: shop.Shops.Id, + OwnerId: shop.Shops.OwnerId, + Name: shop.Shops.Name, + Banner: shop.Shops.Banner, + Description: shop.Shops.Description, + Rating: shop.Shops.Rating, + TotalOrders: shop.Shops.TotalOrders, + PlayerCount: shop.Shops.PlayerCount, + CommissionType: shop.Shops.CommissionType, + CommissionValue: shop.Shops.CommissionValue, + AllowMultiShop: shop.Shops.AllowMultiShop, + AllowIndependentOrders: shop.Shops.AllowIndependentOrders, + DispatchMode: shop.Shops.DispatchMode, + Announcements: shop.Shops.Announcements, + TemplateConfig: string(templateBytes), + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil - return } diff --git a/app/shop/api/internal/types/types.go b/app/shop/api/internal/types/types.go index 373d918..e4d121f 100644 --- a/app/shop/api/internal/types/types.go +++ b/app/shop/api/internal/types/types.go @@ -13,10 +13,10 @@ type AnnouncementReq struct { } type CreateShopReq struct { - Name string `json:"name"` - Description string `json:"description"` - CommissionType string `json:"commissionType"` - CommissionValue float64 `json:"commissionValue"` + Name string `json:"name"` + Description string `json:"description"` + CommissionType string `json:"commissionType"` + CommissionValue string `json:"commissionValue"` } type DeleteAnnouncementReq struct { @@ -28,11 +28,11 @@ type EmptyResp struct { } type IncomeStatsResp struct { - MonthlyIncome float64 `json:"monthlyIncome"` - PendingSettlement float64 `json:"pendingSettlement"` - TotalWithdrawn float64 `json:"totalWithdrawn"` - TotalOrders int64 `json:"totalOrders"` - CompletedOrders int64 `json:"completedOrders"` + MonthlyIncome string `json:"monthlyIncome"` + PendingSettlement string `json:"pendingSettlement"` + TotalWithdrawn string `json:"totalWithdrawn"` + TotalOrders int64 `json:"totalOrders"` + CompletedOrders int64 `json:"completedOrders"` } type InvitationReq struct { @@ -66,11 +66,11 @@ type ShopProfile struct { Name string `json:"name"` Banner string `json:"banner,optional"` Description string `json:"description"` - Rating float64 `json:"rating"` + Rating string `json:"rating"` TotalOrders int64 `json:"totalOrders"` PlayerCount int64 `json:"playerCount"` CommissionType string `json:"commissionType"` - CommissionValue float64 `json:"commissionValue"` + CommissionValue string `json:"commissionValue"` Announcements []string `json:"announcements"` TemplateConfig interface{} `json:"templateConfig"` } @@ -82,14 +82,14 @@ type SimpleUser struct { } type UpdateShopReq struct { - Id int64 `path:"id"` - Name string `json:"name,optional"` - Description string `json:"description,optional"` - CommissionType string `json:"commissionType,optional"` - CommissionValue float64 `json:"commissionValue,optional"` - AllowMultiShop bool `json:"allowMultiShop,optional"` - AllowIndependentOrders bool `json:"allowIndependentOrders,optional"` - DispatchMode string `json:"dispatchMode,optional"` + Id int64 `path:"id"` + Name string `json:"name,optional"` + Description string `json:"description,optional"` + CommissionType string `json:"commissionType,optional"` + CommissionValue string `json:"commissionValue,optional"` + AllowMultiShop bool `json:"allowMultiShop,optional"` + AllowIndependentOrders bool `json:"allowIndependentOrders,optional"` + DispatchMode string `json:"dispatchMode,optional"` } type UpdateTemplateReq struct { diff --git a/app/shop/api/juwan.go b/app/shop/api/shop.go similarity index 89% rename from app/shop/api/juwan.go rename to app/shop/api/shop.go index d103de6..889504e 100644 --- a/app/shop/api/juwan.go +++ b/app/shop/api/shop.go @@ -15,7 +15,7 @@ import ( "github.com/zeromicro/go-zero/rest" ) -var configFile = flag.String("f", "etc/juwan-api.yaml", "the config file") +var configFile = flag.String("f", "etc/shop-api.yaml", "the config file") func main() { flag.Parse() diff --git a/app/shop/rpc/etc/pb.yaml b/app/shop/rpc/etc/pb.yaml index 1b56cb7..32ca1f7 100644 --- a/app/shop/rpc/etc/pb.yaml +++ b/app/shop/rpc/etc/pb.yaml @@ -14,11 +14,13 @@ Prometheus: # Target: k8s://juwan/.:8080 +SnowflakeRpcConf: + Target: k8s://juwan/snowflake-svc:8080 DB: Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" - Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" CacheConf: diff --git a/app/shop/rpc/internal/logic/addShopsLogic.go b/app/shop/rpc/internal/logic/addShopsLogic.go index d70f763..bab435f 100644 --- a/app/shop/rpc/internal/logic/addShopsLogic.go +++ b/app/shop/rpc/internal/logic/addShopsLogic.go @@ -42,17 +42,26 @@ func (l *AddShopsLogic) AddShops(in *pb.AddShopsReq) (*pb.AddShopsResp, error) { return nil, errors.New("invalid template config") } + rating, err := decimal.NewFromString(in.Rating) + if err != nil { + return nil, errors.New("invalid rating") + } + commissionValue, err := decimal.NewFromString(in.CommissionValue) + if err != nil { + return nil, errors.New("invalid commissionValue") + } + _, err = l.svcCtx.ShopModelRO.Shops.Create(). SetID(idResp.Id). SetOwnerID(in.OwnerId). SetName(in.Name). SetBanner(in.Banner). SetDescription(in.Description). - SetRating(decimal.NewFromFloat(in.Rating)). + SetRating(rating). SetTotalOrders(int(in.TotalOrders)). SetPlayerCount(int(in.PlayerCount)). SetNillableCommissionType(&in.CommissionType). - SetCommissionValue(decimal.NewFromFloat(in.CommissionValue)). + SetCommissionValue(commissionValue). SetAllowMultiShop(in.AllowMultiShop). SetAllowIndependentOrders(in.AllowIndependentOrders). SetDispatchMode(in.DispatchMode). diff --git a/app/shop/rpc/internal/logic/getShopsByIdLogic.go b/app/shop/rpc/internal/logic/getShopsByIdLogic.go index a6d8c4e..df61adb 100644 --- a/app/shop/rpc/internal/logic/getShopsByIdLogic.go +++ b/app/shop/rpc/internal/logic/getShopsByIdLogic.go @@ -43,11 +43,11 @@ func (l *GetShopsByIdLogic) GetShopsById(in *pb.GetShopsByIdReq) (*pb.GetShopsBy Id: shop.ID, OwnerId: shop.OwnerID, Name: shop.Name, - Rating: shop.Rating.InexactFloat64(), + Rating: shop.Rating.String(), TotalOrders: int64(shop.TotalOrders), PlayerCount: int64(shop.PlayerCount), CommissionType: shop.CommissionType, - CommissionValue: shop.CommissionValue.InexactFloat64(), + CommissionValue: shop.CommissionValue.String(), AllowMultiShop: shop.AllowMultiShop, AllowIndependentOrders: shop.AllowIndependentOrders, DispatchMode: shop.DispatchMode, diff --git a/app/shop/rpc/internal/logic/searchShopInvitationsLogic.go b/app/shop/rpc/internal/logic/searchShopInvitationsLogic.go index ce9d14a..2b1e66b 100644 --- a/app/shop/rpc/internal/logic/searchShopInvitationsLogic.go +++ b/app/shop/rpc/internal/logic/searchShopInvitationsLogic.go @@ -2,8 +2,12 @@ package logic import ( "context" + "errors" + "juwan-backend/app/shop/rpc/internal/models/predicate" + "juwan-backend/app/shop/rpc/internal/models/shopinvitations" "juwan-backend/app/shop/rpc/internal/svc" "juwan-backend/app/shop/rpc/pb" + "time" "github.com/zeromicro/go-zero/core/logx" ) @@ -23,6 +27,65 @@ func NewSearchShopInvitationsLogic(ctx context.Context, svcCtx *svc.ServiceConte } func (l *SearchShopInvitationsLogic) SearchShopInvitations(in *pb.SearchShopInvitationsReq) (*pb.SearchShopInvitationsResp, error) { - // TODO: implement search logic based on the provided criteria in the request - return &pb.SearchShopInvitationsResp{}, nil + if in.Limit <= 0 { + in.Limit = 20 + } + if in.Limit > 1000 { + return nil, errors.New("limit too large") + } + + preds := make([]predicate.ShopInvitations, 0, 8) + if in.Id > 0 { + preds = append(preds, shopinvitations.IDEQ(in.Id)) + } + if in.ShopId > 0 { + preds = append(preds, shopinvitations.ShopIDEQ(in.ShopId)) + } + if in.PlayerId > 0 { + preds = append(preds, shopinvitations.PlayerIDEQ(in.PlayerId)) + } + if in.Status != "" { + preds = append(preds, shopinvitations.StatusEQ(in.Status)) + } + if in.InvitedBy > 0 { + preds = append(preds, shopinvitations.InvitedByEQ(in.InvitedBy)) + } + if in.CreatedAt > 0 { + preds = append(preds, shopinvitations.CreatedAtGTE(time.Unix(in.CreatedAt, 0))) + } + if in.RespondedAt > 0 { + preds = append(preds, shopinvitations.RespondedAtGTE(time.Unix(in.RespondedAt, 0))) + } + + query := l.svcCtx.ShopModelRO.ShopInvitations.Query() + if len(preds) > 0 { + query = query.Where(shopinvitations.And(preds...)) + } + + list, err := query. + Offset(int(in.Page * in.Limit)). + Limit(int(in.Limit)). + All(l.ctx) + if err != nil { + logx.Errorf("search shop invitations failed, %s", err.Error()) + return nil, errors.New("search shop invitations failed") + } + + result := make([]*pb.ShopInvitations, 0, len(list)) + for _, item := range list { + pbItem := &pb.ShopInvitations{ + Id: item.ID, + ShopId: item.ShopID, + PlayerId: item.PlayerID, + Status: item.Status, + InvitedBy: item.InvitedBy, + CreatedAt: item.CreatedAt.Unix(), + } + if item.RespondedAt != nil { + pbItem.RespondedAt = item.RespondedAt.Unix() + } + result = append(result, pbItem) + } + + return &pb.SearchShopInvitationsResp{ShopInvitations: result}, nil } diff --git a/app/shop/rpc/internal/logic/searchShopPlayersLogic.go b/app/shop/rpc/internal/logic/searchShopPlayersLogic.go index 59029df..db9042f 100644 --- a/app/shop/rpc/internal/logic/searchShopPlayersLogic.go +++ b/app/shop/rpc/internal/logic/searchShopPlayersLogic.go @@ -2,7 +2,12 @@ package logic import ( "context" + "errors" + "juwan-backend/app/shop/rpc/internal/models/predicate" + "juwan-backend/app/shop/rpc/internal/models/shopplayers" + "juwan-backend/app/shop/rpc/internal/svc" "juwan-backend/app/shop/rpc/pb" + "time" "github.com/zeromicro/go-zero/core/logx" ) @@ -22,5 +27,57 @@ func NewSearchShopPlayersLogic(ctx context.Context, svcCtx *svc.ServiceContext) } func (l *SearchShopPlayersLogic) SearchShopPlayers(in *pb.SearchShopPlayersReq) (*pb.SearchShopPlayersResp, error) { + if in.Limit <= 0 { + in.Limit = 20 + } + if in.Limit > 1000 { + return nil, errors.New("limit too large") + } + preds := make([]predicate.ShopPlayers, 0, 8) + if in.ShopId > 0 { + preds = append(preds, shopplayers.ShopIDEQ(in.ShopId)) + } + if in.PlayerId > 0 { + preds = append(preds, shopplayers.PlayerIDEQ(in.PlayerId)) + } + if in.IsPrimary { + preds = append(preds, shopplayers.IsPrimaryEQ(true)) + } + if in.JoinedAt > 0 { + preds = append(preds, shopplayers.JoinedAtGTE(time.Unix(in.JoinedAt, 0))) + } + if in.LeftAt > 0 { + preds = append(preds, shopplayers.LeftAtGTE(time.Unix(in.LeftAt, 0))) + } + + query := l.svcCtx.ShopModelRO.ShopPlayers.Query() + if len(preds) > 0 { + query = query.Where(shopplayers.And(preds...)) + } + + list, err := query. + Offset(int(in.Page * in.Limit)). + Limit(int(in.Limit)). + All(l.ctx) + if err != nil { + logx.Errorf("search shop players failed, %s", err.Error()) + return nil, errors.New("search shop players failed") + } + + result := make([]*pb.ShopPlayers, 0, len(list)) + for _, item := range list { + pbItem := &pb.ShopPlayers{ + ShopId: item.ShopID, + PlayerId: item.PlayerID, + IsPrimary: item.IsPrimary, + JoinedAt: item.JoinedAt.Unix(), + } + if item.LeftAt != nil { + pbItem.LeftAt = item.LeftAt.Unix() + } + result = append(result, pbItem) + } + + return &pb.SearchShopPlayersResp{ShopPlayers: result}, nil } diff --git a/app/shop/rpc/internal/logic/searchShopsLogic.go b/app/shop/rpc/internal/logic/searchShopsLogic.go index f968368..75bf403 100644 --- a/app/shop/rpc/internal/logic/searchShopsLogic.go +++ b/app/shop/rpc/internal/logic/searchShopsLogic.go @@ -2,9 +2,17 @@ package logic import ( "context" + "errors" + "juwan-backend/app/shop/rpc/internal/models/predicate" + "juwan-backend/app/shop/rpc/internal/models/shops" + "time" + "juwan-backend/app/shop/rpc/internal/svc" "juwan-backend/app/shop/rpc/pb" + "encoding/json" + + "github.com/shopspring/decimal" "github.com/zeromicro/go-zero/core/logx" ) @@ -23,5 +31,112 @@ func NewSearchShopsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Searc } func (l *SearchShopsLogic) SearchShops(in *pb.SearchShopsReq) (*pb.SearchShopsResp, error) { + if in.Limit <= 0 { + in.Limit = 20 + } + if in.Limit > 1000 { + return nil, errors.New("limit too large") + } + preds := make([]predicate.Shops, 0, 12) + if in.Id > 0 { + preds = append(preds, shops.IDEQ(in.Id)) + } + if in.OwnerId > 0 { + preds = append(preds, shops.OwnerIDEQ(in.OwnerId)) + } + if in.Name != "" { + preds = append(preds, shops.NameContainsFold(in.Name)) + } + if in.Description != "" { + preds = append(preds, shops.DescriptionContainsFold(in.Description)) + } + if in.CommissionType != "" { + preds = append(preds, shops.CommissionTypeEQ(in.CommissionType)) + } + if in.DispatchMode != "" { + preds = append(preds, shops.DispatchModeEQ(in.DispatchMode)) + } + if in.Rating != "" { + rating, perr := decimal.NewFromString(in.Rating) + if perr != nil { + return nil, errors.New("invalid rating") + } + preds = append(preds, shops.RatingGTE(rating)) + } + if in.CommissionValue != "" { + commissionValue, perr := decimal.NewFromString(in.CommissionValue) + if perr != nil { + return nil, errors.New("invalid commissionValue") + } + preds = append(preds, shops.CommissionValueGTE(commissionValue)) + } + if in.TotalOrders > 0 { + preds = append(preds, shops.TotalOrdersGTE(int(in.TotalOrders))) + } + if in.PlayerCount > 0 { + preds = append(preds, shops.PlayerCountGTE(int(in.PlayerCount))) + } + if in.AllowMultiShop { + preds = append(preds, shops.AllowMultiShopEQ(true)) + } + if in.AllowIndependentOrders { + preds = append(preds, shops.AllowIndependentOrdersEQ(true)) + } + if in.CreatedAt > 0 { + preds = append(preds, shops.CreatedAtGTE(time.Unix(in.CreatedAt, 0))) + } + if in.UpdatedAt > 0 { + preds = append(preds, shops.UpdatedAtGTE(time.Unix(in.UpdatedAt, 0))) + } + + query := l.svcCtx.ShopModelRO.Shops.Query() + if len(preds) > 0 { + query = query.Where(shops.And(preds...)) + } + + list, err := query. + Offset(int(in.Page * in.Limit)). + Limit(int(in.Limit)). + All(l.ctx) + if err != nil { + logx.Errorf("search shops failed, %s", err.Error()) + return nil, errors.New("search shops failed") + } + + result := make([]*pb.Shops, 0, len(list)) + for _, item := range list { + templateConfigBytes, err := json.Marshal(item.TemplateConfig) + if err != nil { + logx.WithContext(l.ctx).Errorf("marshal template config failed: %v", err) + continue + } + + pbItem := &pb.Shops{ + Id: item.ID, + OwnerId: item.OwnerID, + Name: item.Name, + Rating: item.Rating.String(), + TotalOrders: int64(item.TotalOrders), + PlayerCount: int64(item.PlayerCount), + CommissionType: item.CommissionType, + CommissionValue: item.CommissionValue.String(), + AllowMultiShop: item.AllowMultiShop, + AllowIndependentOrders: item.AllowIndependentOrders, + DispatchMode: item.DispatchMode, + Announcements: item.Announcements, + TemplateConfig: string(templateConfigBytes), + CreatedAt: item.CreatedAt.Unix(), + UpdatedAt: item.UpdatedAt.Unix(), + } + if item.Banner != nil { + pbItem.Banner = *item.Banner + } + if item.Description != nil { + pbItem.Description = *item.Description + } + result = append(result, pbItem) + } + + return &pb.SearchShopsResp{Shops: result}, nil } diff --git a/app/shop/rpc/internal/logic/updateShopInvitationsLogic.go b/app/shop/rpc/internal/logic/updateShopInvitationsLogic.go index 9b9360c..143773a 100644 --- a/app/shop/rpc/internal/logic/updateShopInvitationsLogic.go +++ b/app/shop/rpc/internal/logic/updateShopInvitationsLogic.go @@ -3,11 +3,11 @@ package logic import ( "context" "errors" - "time" - + "juwan-backend/app/shop/rpc/internal/models/shopinvitations" "juwan-backend/app/shop/rpc/internal/svc" "juwan-backend/app/shop/rpc/pb" + "github.com/jinzhu/copier" "github.com/zeromicro/go-zero/core/logx" ) @@ -26,5 +26,19 @@ func NewUpdateShopInvitationsLogic(ctx context.Context, svcCtx *svc.ServiceConte } func (l *UpdateShopInvitationsLogic) UpdateShopInvitations(in *pb.UpdateShopInvitationsReq) (*pb.UpdateShopInvitationsResp, error) { + update, err := l.svcCtx.ShopModelRW.ShopInvitations.UpdateOneID(in.Id). + Where(shopinvitations.PlayerIDEQ(in.PlayerId)). + SetStatus(in.Status).Save(l.ctx) + if err != nil { + logx.Errorf("failed to update shop invitation: %v", err) + return nil, errors.New("failed to update shop invitation") + } + resp := &pb.ShopInvitations{} + err = copier.Copy(resp, update) + if err != nil { + logx.Errorf("failed to copy update: %v", err) + return nil, errors.New("failed to update shop invitation") + } + return &pb.UpdateShopInvitationsResp{ShopInvitations: resp}, nil } diff --git a/app/shop/rpc/internal/logic/updateShopPlayersLogic.go b/app/shop/rpc/internal/logic/updateShopPlayersLogic.go index 08a1642..d0c6650 100644 --- a/app/shop/rpc/internal/logic/updateShopPlayersLogic.go +++ b/app/shop/rpc/internal/logic/updateShopPlayersLogic.go @@ -3,7 +3,7 @@ package logic import ( "context" "errors" - "juwan-backend/app/shop/rpc/internal/models" + "juwan-backend/app/shop/rpc/internal/models/predicate" "juwan-backend/app/shop/rpc/internal/models/shopplayers" "time" @@ -28,5 +28,32 @@ func NewUpdateShopPlayersLogic(ctx context.Context, svcCtx *svc.ServiceContext) } func (l *UpdateShopPlayersLogic) UpdateShopPlayers(in *pb.UpdateShopPlayersReq) (*pb.UpdateShopPlayersResp, error) { + if in.ShopId <= 0 || in.PlayerId <= 0 { + return nil, errors.New("invalid shop_id or player_id") + } + preds := []predicate.ShopPlayers{ + shopplayers.ShopIDEQ(in.ShopId), + shopplayers.PlayerIDEQ(in.PlayerId), + } + + updater := l.svcCtx.ShopModelRW.ShopPlayers.Update(). + Where(shopplayers.And(preds...)). + SetIsPrimary(in.IsPrimary) + + if in.LeftAt > 0 { + t := time.Unix(in.LeftAt, 0) + updater = updater.SetLeftAt(t) + } + + affected, err := updater.Save(l.ctx) + if err != nil { + logx.Errorf("update shop players failed, %s", err.Error()) + return nil, errors.New("update shop players failed") + } + if affected == 0 { + return nil, errors.New("shop player not found") + } + + return &pb.UpdateShopPlayersResp{}, nil } diff --git a/app/shop/rpc/internal/logic/updateShopsLogic.go b/app/shop/rpc/internal/logic/updateShopsLogic.go index 698ccdc..95f7e01 100644 --- a/app/shop/rpc/internal/logic/updateShopsLogic.go +++ b/app/shop/rpc/internal/logic/updateShopsLogic.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "juwan-backend/app/shop/rpc/internal/models/shops" "time" "juwan-backend/app/shop/rpc/internal/svc" @@ -28,5 +29,74 @@ func NewUpdateShopsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Updat } func (l *UpdateShopsLogic) UpdateShops(in *pb.UpdateShopsReq) (*pb.UpdateShopsResp, error) { + updater := l.svcCtx.ShopModelRW.Shops.UpdateOneID(in.Id) + if in.OwnerId > 0 { + updater = updater.SetOwnerID(in.OwnerId) + } + if in.Name != "" { + updater = updater.SetName(in.Name) + } + if in.Banner != "" { + updater = updater.SetBanner(in.Banner) + } + if in.Description != "" { + updater = updater.SetDescription(in.Description) + } + if in.Rating != "" { + rating, perr := decimal.NewFromString(in.Rating) + if perr != nil { + return nil, errors.New("invalid rating") + } + updater = updater.SetRating(rating) + } + if in.TotalOrders > 0 { + updater = updater.SetTotalOrders(int(in.TotalOrders)) + } + if in.PlayerCount > 0 { + updater = updater.SetPlayerCount(int(in.PlayerCount)) + } + if in.CommissionType != "" { + updater = updater.SetCommissionType(in.CommissionType) + } + if in.CommissionValue != "" { + commissionValue, perr := decimal.NewFromString(in.CommissionValue) + if perr != nil { + return nil, errors.New("invalid commissionValue") + } + updater = updater.SetCommissionValue(commissionValue) + } + if in.DispatchMode != "" { + updater = updater.SetDispatchMode(in.DispatchMode) + } + + updater = updater. + SetAllowMultiShop(in.AllowMultiShop). + SetAllowIndependentOrders(in.AllowIndependentOrders) + + if len(in.Announcements) > 0 { + updater = updater.SetAnnouncements(in.Announcements) + } + + if in.TemplateConfig != "" { + var templateConfig map[string]interface{} + err := json.Unmarshal([]byte(in.TemplateConfig), &templateConfig) + if err != nil { + logx.WithContext(l.ctx).Errorf("invalid template config: %v", err) + return nil, errors.New("invalid template config") + } + updater = updater.SetTemplateConfig(templateConfig) + } + + if in.UpdatedAt > 0 { + updater = updater.SetUpdatedAt(time.Unix(in.UpdatedAt, 0)) + } + + _, err := updater.Where(shops.IDEQ(in.Id)).Save(l.ctx) + if err != nil { + logx.WithContext(l.ctx).Errorf("update shops failed: %v", err) + return nil, errors.New("update shops failed") + } + + return &pb.UpdateShopsResp{}, nil } diff --git a/app/shop/rpc/internal/svc/serviceContext.go b/app/shop/rpc/internal/svc/serviceContext.go index 86db977..61f2931 100644 --- a/app/shop/rpc/internal/svc/serviceContext.go +++ b/app/shop/rpc/internal/svc/serviceContext.go @@ -1,16 +1,19 @@ package svc import ( + "fmt" "juwan-backend/app/shop/rpc/internal/config" "juwan-backend/app/shop/rpc/internal/models" "juwan-backend/app/snowflake/rpc/snowflake" "juwan-backend/common/redisx" "juwan-backend/common/snowflakex" "juwan-backend/pkg/adapter" + "strings" "time" "ariga.io/entcache" "entgo.io/ent/dialect/sql" + _ "github.com/jackc/pgx/v5/stdlib" "github.com/zeromicro/go-zero/core/logx" ) @@ -40,10 +43,22 @@ func NewServiceContext(c config.Config) *ServiceContext { RWDrv := entcache.NewDriver(RWConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) RODrv := entcache.NewDriver(ROConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) + + entLogFn := func(v ...any) { + logx.Infof("[ent][shop] %s", fmt.Sprint(v...)) + } + + rwModelOpts := []models.Option{models.Driver(RWDrv), models.Log(entLogFn)} + roModelOpts := []models.Option{models.Driver(RODrv), models.Log(entLogFn)} + if strings.EqualFold(c.Log.Level, "debug") { + rwModelOpts = append(rwModelOpts, models.Debug()) + roModelOpts = append(roModelOpts, models.Debug()) + } + return &ServiceContext{ Config: c, Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), - ShopModelRO: models.NewClient(models.Driver(RODrv)), - ShopModelRW: models.NewClient(models.Driver(RWDrv)), + ShopModelRO: models.NewClient(roModelOpts...), + ShopModelRW: models.NewClient(rwModelOpts...), } } diff --git a/app/shop/rpc/pb.go b/app/shop/rpc/pb.go index 09a35aa..95b488d 100644 --- a/app/shop/rpc/pb.go +++ b/app/shop/rpc/pb.go @@ -22,7 +22,7 @@ func main() { flag.Parse() var c config.Config - conf.MustLoad(*configFile, &c) + conf.MustLoad(*configFile, &c, conf.UseEnv()) ctx := svc.NewServiceContext(c) s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { diff --git a/app/shop/rpc/pb/shop.pb.go b/app/shop/rpc/pb/shop.pb.go index cac520c..ed9a8cc 100644 --- a/app/shop/rpc/pb/shop.pb.go +++ b/app/shop/rpc/pb/shop.pb.go @@ -327,9 +327,10 @@ func (x *UpdateShopInvitationsReq) GetRespondedAt() int64 { } type UpdateShopInvitationsResp struct { - state protoimpl.MessageState `protogen:"open.v1"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + ShopInvitations *ShopInvitations `protobuf:"bytes,1,opt,name=shopInvitations,proto3" json:"shopInvitations,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UpdateShopInvitationsResp) Reset() { @@ -362,6 +363,13 @@ func (*UpdateShopInvitationsResp) Descriptor() ([]byte, []int) { return file_shop_proto_rawDescGZIP(), []int{4} } +func (x *UpdateShopInvitationsResp) GetShopInvitations() *ShopInvitations { + if x != nil { + return x.ShopInvitations + } + return nil +} + type DelShopInvitationsReq struct { state protoimpl.MessageState `protogen:"open.v1"` Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id @@ -1295,11 +1303,11 @@ type Shops struct { Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` //name Banner string `protobuf:"bytes,4,opt,name=banner,proto3" json:"banner,omitempty"` //banner Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"` //description - Rating float64 `protobuf:"fixed64,6,opt,name=rating,proto3" json:"rating,omitempty"` //rating + Rating string `protobuf:"bytes,6,opt,name=rating,proto3" json:"rating,omitempty"` //rating TotalOrders int64 `protobuf:"varint,7,opt,name=totalOrders,proto3" json:"totalOrders,omitempty"` //totalOrders PlayerCount int64 `protobuf:"varint,8,opt,name=playerCount,proto3" json:"playerCount,omitempty"` //playerCount CommissionType string `protobuf:"bytes,9,opt,name=commissionType,proto3" json:"commissionType,omitempty"` //commissionType - CommissionValue float64 `protobuf:"fixed64,10,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue + CommissionValue string `protobuf:"bytes,10,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue AllowMultiShop bool `protobuf:"varint,11,opt,name=allowMultiShop,proto3" json:"allowMultiShop,omitempty"` //allowMultiShop AllowIndependentOrders bool `protobuf:"varint,12,opt,name=allowIndependentOrders,proto3" json:"allowIndependentOrders,omitempty"` //allowIndependentOrders DispatchMode string `protobuf:"bytes,13,opt,name=dispatchMode,proto3" json:"dispatchMode,omitempty"` //dispatchMode @@ -1376,11 +1384,11 @@ func (x *Shops) GetDescription() string { return "" } -func (x *Shops) GetRating() float64 { +func (x *Shops) GetRating() string { if x != nil { return x.Rating } - return 0 + return "" } func (x *Shops) GetTotalOrders() int64 { @@ -1404,11 +1412,11 @@ func (x *Shops) GetCommissionType() string { return "" } -func (x *Shops) GetCommissionValue() float64 { +func (x *Shops) GetCommissionValue() string { if x != nil { return x.CommissionValue } - return 0 + return "" } func (x *Shops) GetAllowMultiShop() bool { @@ -1466,11 +1474,11 @@ type AddShopsReq struct { Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` //name Banner string `protobuf:"bytes,3,opt,name=banner,proto3" json:"banner,omitempty"` //banner Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"` //description - Rating float64 `protobuf:"fixed64,5,opt,name=rating,proto3" json:"rating,omitempty"` //rating + Rating string `protobuf:"bytes,5,opt,name=rating,proto3" json:"rating,omitempty"` //rating TotalOrders int64 `protobuf:"varint,6,opt,name=totalOrders,proto3" json:"totalOrders,omitempty"` //totalOrders PlayerCount int64 `protobuf:"varint,7,opt,name=playerCount,proto3" json:"playerCount,omitempty"` //playerCount CommissionType string `protobuf:"bytes,8,opt,name=commissionType,proto3" json:"commissionType,omitempty"` //commissionType - CommissionValue float64 `protobuf:"fixed64,9,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue + CommissionValue string `protobuf:"bytes,9,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue AllowMultiShop bool `protobuf:"varint,10,opt,name=allowMultiShop,proto3" json:"allowMultiShop,omitempty"` //allowMultiShop AllowIndependentOrders bool `protobuf:"varint,11,opt,name=allowIndependentOrders,proto3" json:"allowIndependentOrders,omitempty"` //allowIndependentOrders DispatchMode string `protobuf:"bytes,12,opt,name=dispatchMode,proto3" json:"dispatchMode,omitempty"` //dispatchMode @@ -1540,11 +1548,11 @@ func (x *AddShopsReq) GetDescription() string { return "" } -func (x *AddShopsReq) GetRating() float64 { +func (x *AddShopsReq) GetRating() string { if x != nil { return x.Rating } - return 0 + return "" } func (x *AddShopsReq) GetTotalOrders() int64 { @@ -1568,11 +1576,11 @@ func (x *AddShopsReq) GetCommissionType() string { return "" } -func (x *AddShopsReq) GetCommissionValue() float64 { +func (x *AddShopsReq) GetCommissionValue() string { if x != nil { return x.CommissionValue } - return 0 + return "" } func (x *AddShopsReq) GetAllowMultiShop() bool { @@ -1667,11 +1675,11 @@ type UpdateShopsReq struct { Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` //name Banner string `protobuf:"bytes,4,opt,name=banner,proto3" json:"banner,omitempty"` //banner Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"` //description - Rating float64 `protobuf:"fixed64,6,opt,name=rating,proto3" json:"rating,omitempty"` //rating + Rating string `protobuf:"bytes,6,opt,name=rating,proto3" json:"rating,omitempty"` //rating TotalOrders int64 `protobuf:"varint,7,opt,name=totalOrders,proto3" json:"totalOrders,omitempty"` //totalOrders PlayerCount int64 `protobuf:"varint,8,opt,name=playerCount,proto3" json:"playerCount,omitempty"` //playerCount CommissionType string `protobuf:"bytes,9,opt,name=commissionType,proto3" json:"commissionType,omitempty"` //commissionType - CommissionValue float64 `protobuf:"fixed64,10,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue + CommissionValue string `protobuf:"bytes,10,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue AllowMultiShop bool `protobuf:"varint,11,opt,name=allowMultiShop,proto3" json:"allowMultiShop,omitempty"` //allowMultiShop AllowIndependentOrders bool `protobuf:"varint,12,opt,name=allowIndependentOrders,proto3" json:"allowIndependentOrders,omitempty"` //allowIndependentOrders DispatchMode string `protobuf:"bytes,13,opt,name=dispatchMode,proto3" json:"dispatchMode,omitempty"` //dispatchMode @@ -1748,11 +1756,11 @@ func (x *UpdateShopsReq) GetDescription() string { return "" } -func (x *UpdateShopsReq) GetRating() float64 { +func (x *UpdateShopsReq) GetRating() string { if x != nil { return x.Rating } - return 0 + return "" } func (x *UpdateShopsReq) GetTotalOrders() int64 { @@ -1776,11 +1784,11 @@ func (x *UpdateShopsReq) GetCommissionType() string { return "" } -func (x *UpdateShopsReq) GetCommissionValue() float64 { +func (x *UpdateShopsReq) GetCommissionValue() string { if x != nil { return x.CommissionValue } - return 0 + return "" } func (x *UpdateShopsReq) GetAllowMultiShop() bool { @@ -2045,11 +2053,11 @@ type SearchShopsReq struct { Name string `protobuf:"bytes,5,opt,name=name,proto3" json:"name,omitempty"` //name Banner string `protobuf:"bytes,6,opt,name=banner,proto3" json:"banner,omitempty"` //banner Description string `protobuf:"bytes,7,opt,name=description,proto3" json:"description,omitempty"` //description - Rating float64 `protobuf:"fixed64,8,opt,name=rating,proto3" json:"rating,omitempty"` //rating + Rating string `protobuf:"bytes,8,opt,name=rating,proto3" json:"rating,omitempty"` //rating TotalOrders int64 `protobuf:"varint,9,opt,name=totalOrders,proto3" json:"totalOrders,omitempty"` //totalOrders PlayerCount int64 `protobuf:"varint,10,opt,name=playerCount,proto3" json:"playerCount,omitempty"` //playerCount CommissionType string `protobuf:"bytes,11,opt,name=commissionType,proto3" json:"commissionType,omitempty"` //commissionType - CommissionValue float64 `protobuf:"fixed64,12,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue + CommissionValue string `protobuf:"bytes,12,opt,name=commissionValue,proto3" json:"commissionValue,omitempty"` //commissionValue AllowMultiShop bool `protobuf:"varint,13,opt,name=allowMultiShop,proto3" json:"allowMultiShop,omitempty"` //allowMultiShop AllowIndependentOrders bool `protobuf:"varint,14,opt,name=allowIndependentOrders,proto3" json:"allowIndependentOrders,omitempty"` //allowIndependentOrders DispatchMode string `protobuf:"bytes,15,opt,name=dispatchMode,proto3" json:"dispatchMode,omitempty"` //dispatchMode @@ -2140,11 +2148,11 @@ func (x *SearchShopsReq) GetDescription() string { return "" } -func (x *SearchShopsReq) GetRating() float64 { +func (x *SearchShopsReq) GetRating() string { if x != nil { return x.Rating } - return 0 + return "" } func (x *SearchShopsReq) GetTotalOrders() int64 { @@ -2168,11 +2176,11 @@ func (x *SearchShopsReq) GetCommissionType() string { return "" } -func (x *SearchShopsReq) GetCommissionValue() float64 { +func (x *SearchShopsReq) GetCommissionValue() string { if x != nil { return x.CommissionValue } - return 0 + return "" } func (x *SearchShopsReq) GetAllowMultiShop() bool { @@ -2297,8 +2305,9 @@ const file_shop_proto_rawDesc = "" + "\x06status\x18\x04 \x01(\tR\x06status\x12\x1c\n" + "\tinvitedBy\x18\x05 \x01(\x03R\tinvitedBy\x12\x1c\n" + "\tcreatedAt\x18\x06 \x01(\x03R\tcreatedAt\x12 \n" + - "\vrespondedAt\x18\a \x01(\x03R\vrespondedAt\"\x1b\n" + - "\x19UpdateShopInvitationsResp\"'\n" + + "\vrespondedAt\x18\a \x01(\x03R\vrespondedAt\"Z\n" + + "\x19UpdateShopInvitationsResp\x12=\n" + + "\x0fshopInvitations\x18\x01 \x01(\v2\x13.pb.ShopInvitationsR\x0fshopInvitations\"'\n" + "\x15DelShopInvitationsReq\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\"\x18\n" + "\x16DelShopInvitationsResp\"+\n" + @@ -2361,12 +2370,12 @@ const file_shop_proto_rawDesc = "" + "\x04name\x18\x03 \x01(\tR\x04name\x12\x16\n" + "\x06banner\x18\x04 \x01(\tR\x06banner\x12 \n" + "\vdescription\x18\x05 \x01(\tR\vdescription\x12\x16\n" + - "\x06rating\x18\x06 \x01(\x01R\x06rating\x12 \n" + + "\x06rating\x18\x06 \x01(\tR\x06rating\x12 \n" + "\vtotalOrders\x18\a \x01(\x03R\vtotalOrders\x12 \n" + "\vplayerCount\x18\b \x01(\x03R\vplayerCount\x12&\n" + "\x0ecommissionType\x18\t \x01(\tR\x0ecommissionType\x12(\n" + "\x0fcommissionValue\x18\n" + - " \x01(\x01R\x0fcommissionValue\x12&\n" + + " \x01(\tR\x0fcommissionValue\x12&\n" + "\x0eallowMultiShop\x18\v \x01(\bR\x0eallowMultiShop\x126\n" + "\x16allowIndependentOrders\x18\f \x01(\bR\x16allowIndependentOrders\x12\"\n" + "\fdispatchMode\x18\r \x01(\tR\fdispatchMode\x12$\n" + @@ -2379,11 +2388,11 @@ const file_shop_proto_rawDesc = "" + "\x04name\x18\x02 \x01(\tR\x04name\x12\x16\n" + "\x06banner\x18\x03 \x01(\tR\x06banner\x12 \n" + "\vdescription\x18\x04 \x01(\tR\vdescription\x12\x16\n" + - "\x06rating\x18\x05 \x01(\x01R\x06rating\x12 \n" + + "\x06rating\x18\x05 \x01(\tR\x06rating\x12 \n" + "\vtotalOrders\x18\x06 \x01(\x03R\vtotalOrders\x12 \n" + "\vplayerCount\x18\a \x01(\x03R\vplayerCount\x12&\n" + "\x0ecommissionType\x18\b \x01(\tR\x0ecommissionType\x12(\n" + - "\x0fcommissionValue\x18\t \x01(\x01R\x0fcommissionValue\x12&\n" + + "\x0fcommissionValue\x18\t \x01(\tR\x0fcommissionValue\x12&\n" + "\x0eallowMultiShop\x18\n" + " \x01(\bR\x0eallowMultiShop\x126\n" + "\x16allowIndependentOrders\x18\v \x01(\bR\x16allowIndependentOrders\x12\"\n" + @@ -2399,12 +2408,12 @@ const file_shop_proto_rawDesc = "" + "\x04name\x18\x03 \x01(\tR\x04name\x12\x16\n" + "\x06banner\x18\x04 \x01(\tR\x06banner\x12 \n" + "\vdescription\x18\x05 \x01(\tR\vdescription\x12\x16\n" + - "\x06rating\x18\x06 \x01(\x01R\x06rating\x12 \n" + + "\x06rating\x18\x06 \x01(\tR\x06rating\x12 \n" + "\vtotalOrders\x18\a \x01(\x03R\vtotalOrders\x12 \n" + "\vplayerCount\x18\b \x01(\x03R\vplayerCount\x12&\n" + "\x0ecommissionType\x18\t \x01(\tR\x0ecommissionType\x12(\n" + "\x0fcommissionValue\x18\n" + - " \x01(\x01R\x0fcommissionValue\x12&\n" + + " \x01(\tR\x0fcommissionValue\x12&\n" + "\x0eallowMultiShop\x18\v \x01(\bR\x0eallowMultiShop\x126\n" + "\x16allowIndependentOrders\x18\f \x01(\bR\x16allowIndependentOrders\x12\"\n" + "\fdispatchMode\x18\r \x01(\tR\fdispatchMode\x12$\n" + @@ -2428,12 +2437,12 @@ const file_shop_proto_rawDesc = "" + "\x04name\x18\x05 \x01(\tR\x04name\x12\x16\n" + "\x06banner\x18\x06 \x01(\tR\x06banner\x12 \n" + "\vdescription\x18\a \x01(\tR\vdescription\x12\x16\n" + - "\x06rating\x18\b \x01(\x01R\x06rating\x12 \n" + + "\x06rating\x18\b \x01(\tR\x06rating\x12 \n" + "\vtotalOrders\x18\t \x01(\x03R\vtotalOrders\x12 \n" + "\vplayerCount\x18\n" + " \x01(\x03R\vplayerCount\x12&\n" + "\x0ecommissionType\x18\v \x01(\tR\x0ecommissionType\x12(\n" + - "\x0fcommissionValue\x18\f \x01(\x01R\x0fcommissionValue\x12&\n" + + "\x0fcommissionValue\x18\f \x01(\tR\x0fcommissionValue\x12&\n" + "\x0eallowMultiShop\x18\r \x01(\bR\x0eallowMultiShop\x126\n" + "\x16allowIndependentOrders\x18\x0e \x01(\bR\x16allowIndependentOrders\x12\"\n" + "\fdispatchMode\x18\x0f \x01(\tR\fdispatchMode\x12$\n" + @@ -2509,47 +2518,48 @@ var file_shop_proto_goTypes = []any{ (*SearchShopsResp)(nil), // 32: pb.SearchShopsResp } var file_shop_proto_depIdxs = []int32{ - 0, // 0: pb.GetShopInvitationsByIdResp.shopInvitations:type_name -> pb.ShopInvitations - 0, // 1: pb.SearchShopInvitationsResp.shopInvitations:type_name -> pb.ShopInvitations - 11, // 2: pb.GetShopPlayersByIdResp.shopPlayers:type_name -> pb.ShopPlayers - 11, // 3: pb.SearchShopPlayersResp.shopPlayers:type_name -> pb.ShopPlayers - 22, // 4: pb.GetShopsByIdResp.shops:type_name -> pb.Shops - 22, // 5: pb.SearchShopsResp.shops:type_name -> pb.Shops - 1, // 6: pb.shopService.AddShopInvitations:input_type -> pb.AddShopInvitationsReq - 3, // 7: pb.shopService.UpdateShopInvitations:input_type -> pb.UpdateShopInvitationsReq - 5, // 8: pb.shopService.DelShopInvitations:input_type -> pb.DelShopInvitationsReq - 7, // 9: pb.shopService.GetShopInvitationsById:input_type -> pb.GetShopInvitationsByIdReq - 9, // 10: pb.shopService.SearchShopInvitations:input_type -> pb.SearchShopInvitationsReq - 12, // 11: pb.shopService.AddShopPlayers:input_type -> pb.AddShopPlayersReq - 14, // 12: pb.shopService.UpdateShopPlayers:input_type -> pb.UpdateShopPlayersReq - 16, // 13: pb.shopService.DelShopPlayers:input_type -> pb.DelShopPlayersReq - 18, // 14: pb.shopService.GetShopPlayersById:input_type -> pb.GetShopPlayersByIdReq - 20, // 15: pb.shopService.SearchShopPlayers:input_type -> pb.SearchShopPlayersReq - 23, // 16: pb.shopService.AddShops:input_type -> pb.AddShopsReq - 25, // 17: pb.shopService.UpdateShops:input_type -> pb.UpdateShopsReq - 27, // 18: pb.shopService.DelShops:input_type -> pb.DelShopsReq - 29, // 19: pb.shopService.GetShopsById:input_type -> pb.GetShopsByIdReq - 31, // 20: pb.shopService.SearchShops:input_type -> pb.SearchShopsReq - 2, // 21: pb.shopService.AddShopInvitations:output_type -> pb.AddShopInvitationsResp - 4, // 22: pb.shopService.UpdateShopInvitations:output_type -> pb.UpdateShopInvitationsResp - 6, // 23: pb.shopService.DelShopInvitations:output_type -> pb.DelShopInvitationsResp - 8, // 24: pb.shopService.GetShopInvitationsById:output_type -> pb.GetShopInvitationsByIdResp - 10, // 25: pb.shopService.SearchShopInvitations:output_type -> pb.SearchShopInvitationsResp - 13, // 26: pb.shopService.AddShopPlayers:output_type -> pb.AddShopPlayersResp - 15, // 27: pb.shopService.UpdateShopPlayers:output_type -> pb.UpdateShopPlayersResp - 17, // 28: pb.shopService.DelShopPlayers:output_type -> pb.DelShopPlayersResp - 19, // 29: pb.shopService.GetShopPlayersById:output_type -> pb.GetShopPlayersByIdResp - 21, // 30: pb.shopService.SearchShopPlayers:output_type -> pb.SearchShopPlayersResp - 24, // 31: pb.shopService.AddShops:output_type -> pb.AddShopsResp - 26, // 32: pb.shopService.UpdateShops:output_type -> pb.UpdateShopsResp - 28, // 33: pb.shopService.DelShops:output_type -> pb.DelShopsResp - 30, // 34: pb.shopService.GetShopsById:output_type -> pb.GetShopsByIdResp - 32, // 35: pb.shopService.SearchShops:output_type -> pb.SearchShopsResp - 21, // [21:36] is the sub-list for method output_type - 6, // [6:21] is the sub-list for method input_type - 6, // [6:6] is the sub-list for extension type_name - 6, // [6:6] is the sub-list for extension extendee - 0, // [0:6] is the sub-list for field type_name + 0, // 0: pb.UpdateShopInvitationsResp.shopInvitations:type_name -> pb.ShopInvitations + 0, // 1: pb.GetShopInvitationsByIdResp.shopInvitations:type_name -> pb.ShopInvitations + 0, // 2: pb.SearchShopInvitationsResp.shopInvitations:type_name -> pb.ShopInvitations + 11, // 3: pb.GetShopPlayersByIdResp.shopPlayers:type_name -> pb.ShopPlayers + 11, // 4: pb.SearchShopPlayersResp.shopPlayers:type_name -> pb.ShopPlayers + 22, // 5: pb.GetShopsByIdResp.shops:type_name -> pb.Shops + 22, // 6: pb.SearchShopsResp.shops:type_name -> pb.Shops + 1, // 7: pb.shopService.AddShopInvitations:input_type -> pb.AddShopInvitationsReq + 3, // 8: pb.shopService.UpdateShopInvitations:input_type -> pb.UpdateShopInvitationsReq + 5, // 9: pb.shopService.DelShopInvitations:input_type -> pb.DelShopInvitationsReq + 7, // 10: pb.shopService.GetShopInvitationsById:input_type -> pb.GetShopInvitationsByIdReq + 9, // 11: pb.shopService.SearchShopInvitations:input_type -> pb.SearchShopInvitationsReq + 12, // 12: pb.shopService.AddShopPlayers:input_type -> pb.AddShopPlayersReq + 14, // 13: pb.shopService.UpdateShopPlayers:input_type -> pb.UpdateShopPlayersReq + 16, // 14: pb.shopService.DelShopPlayers:input_type -> pb.DelShopPlayersReq + 18, // 15: pb.shopService.GetShopPlayersById:input_type -> pb.GetShopPlayersByIdReq + 20, // 16: pb.shopService.SearchShopPlayers:input_type -> pb.SearchShopPlayersReq + 23, // 17: pb.shopService.AddShops:input_type -> pb.AddShopsReq + 25, // 18: pb.shopService.UpdateShops:input_type -> pb.UpdateShopsReq + 27, // 19: pb.shopService.DelShops:input_type -> pb.DelShopsReq + 29, // 20: pb.shopService.GetShopsById:input_type -> pb.GetShopsByIdReq + 31, // 21: pb.shopService.SearchShops:input_type -> pb.SearchShopsReq + 2, // 22: pb.shopService.AddShopInvitations:output_type -> pb.AddShopInvitationsResp + 4, // 23: pb.shopService.UpdateShopInvitations:output_type -> pb.UpdateShopInvitationsResp + 6, // 24: pb.shopService.DelShopInvitations:output_type -> pb.DelShopInvitationsResp + 8, // 25: pb.shopService.GetShopInvitationsById:output_type -> pb.GetShopInvitationsByIdResp + 10, // 26: pb.shopService.SearchShopInvitations:output_type -> pb.SearchShopInvitationsResp + 13, // 27: pb.shopService.AddShopPlayers:output_type -> pb.AddShopPlayersResp + 15, // 28: pb.shopService.UpdateShopPlayers:output_type -> pb.UpdateShopPlayersResp + 17, // 29: pb.shopService.DelShopPlayers:output_type -> pb.DelShopPlayersResp + 19, // 30: pb.shopService.GetShopPlayersById:output_type -> pb.GetShopPlayersByIdResp + 21, // 31: pb.shopService.SearchShopPlayers:output_type -> pb.SearchShopPlayersResp + 24, // 32: pb.shopService.AddShops:output_type -> pb.AddShopsResp + 26, // 33: pb.shopService.UpdateShops:output_type -> pb.UpdateShopsResp + 28, // 34: pb.shopService.DelShops:output_type -> pb.DelShopsResp + 30, // 35: pb.shopService.GetShopsById:output_type -> pb.GetShopsByIdResp + 32, // 36: pb.shopService.SearchShops:output_type -> pb.SearchShopsResp + 22, // [22:37] is the sub-list for method output_type + 7, // [7:22] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name } func init() { file_shop_proto_init() } diff --git a/app/users/api/internal/handler/user/getUserInfoHandler.go b/app/users/api/internal/handler/user/getUserInfoHandler.go index c6b9180..a205c12 100644 --- a/app/users/api/internal/handler/user/getUserInfoHandler.go +++ b/app/users/api/internal/handler/user/getUserInfoHandler.go @@ -6,16 +6,17 @@ package user import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/users/api/internal/logic/user" "juwan-backend/app/users/api/internal/svc" "juwan-backend/app/users/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 获取用户信息 func GetUserInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.GetUserInfoReq + var req types.GetUserReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/users/api/internal/handler/user/updateMeHandler.go b/app/users/api/internal/handler/user/updateMeHandler.go index 1702c99..f98ce34 100644 --- a/app/users/api/internal/handler/user/updateMeHandler.go +++ b/app/users/api/internal/handler/user/updateMeHandler.go @@ -6,16 +6,17 @@ package user import ( "net/http" - "github.com/zeromicro/go-zero/rest/httpx" "juwan-backend/app/users/api/internal/logic/user" "juwan-backend/app/users/api/internal/svc" "juwan-backend/app/users/api/internal/types" + + "github.com/zeromicro/go-zero/rest/httpx" ) // 更改当前登录用户信息 func UpdateMeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var req types.UpdateUserInfoReq + var req types.UpdateUserProfileReq if err := httpx.Parse(r, &req); err != nil { httpx.ErrorCtx(r.Context(), w, err) return diff --git a/app/users/api/internal/logic/auth/logoutLogic.go b/app/users/api/internal/logic/auth/logoutLogic.go index eeab5ea..8719017 100644 --- a/app/users/api/internal/logic/auth/logoutLogic.go +++ b/app/users/api/internal/logic/auth/logoutLogic.go @@ -7,7 +7,7 @@ import ( "context" "errors" "juwan-backend/app/users/rpc/usercenter" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "juwan-backend/app/users/api/internal/svc" "juwan-backend/app/users/api/internal/types" @@ -32,7 +32,7 @@ func NewLogoutLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogoutLogi func (l *LogoutLogic) Logout(_ *types.LogoutReq) (resp *types.EmptyResp, err error) { // todo: add your logic here and delete this line - userId, err := contextx.UserIDFrom(l.ctx) + userId, err := contextj.UserIDFrom(l.ctx) if err != nil { return nil, errors.New("illegal id") } diff --git a/app/users/api/internal/logic/auth/registerLogic.go b/app/users/api/internal/logic/auth/registerLogic.go index e9e36d0..911fd5f 100644 --- a/app/users/api/internal/logic/auth/registerLogic.go +++ b/app/users/api/internal/logic/auth/registerLogic.go @@ -8,7 +8,7 @@ import ( "errors" "juwan-backend/app/users/rpc/pb" "juwan-backend/app/users/rpc/usercenter" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "juwan-backend/common/utils/pwdUtils" "regexp" @@ -57,10 +57,10 @@ func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterRe return nil, errors.New("hash password failed") } - requestId, err := contextx.RequestIdFrom(l.ctx) + requestId, err := contextj.RequestIdFrom(l.ctx) if err != nil { - logx.Errorf("contextx.RequestIdFrom failed: %v", err) - return nil, errors.New("contextx.RequestIdFrom failed") + logx.Errorf("contextj.RequestIdFrom failed: %v", err) + return nil, errors.New("contextj.RequestIdFrom failed") } res, err := l.svcCtx.UserRpc.Register(l.ctx, &usercenter.RegisterReq{ diff --git a/app/users/api/internal/logic/auth/resetPasswordLogic.go b/app/users/api/internal/logic/auth/resetPasswordLogic.go index 1b9a767..186252f 100644 --- a/app/users/api/internal/logic/auth/resetPasswordLogic.go +++ b/app/users/api/internal/logic/auth/resetPasswordLogic.go @@ -7,7 +7,7 @@ import ( "context" "errors" "juwan-backend/app/users/rpc/usercenter" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "juwan-backend/common/utils/pwdUtils" "juwan-backend/app/users/api/internal/svc" @@ -32,7 +32,7 @@ func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Res } func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordReq) (resp *types.EmptyResp, err error) { - requestId, err := contextx.RequestIdFrom(l.ctx) + requestId, err := contextj.RequestIdFrom(l.ctx) if err != nil { logx.Errorf("get request id from context failed, err:%v.", err) return nil, errors.New("bad request") diff --git a/app/users/api/internal/logic/user/getMeLogic.go b/app/users/api/internal/logic/user/getMeLogic.go index 9dcfb8a..325968b 100644 --- a/app/users/api/internal/logic/user/getMeLogic.go +++ b/app/users/api/internal/logic/user/getMeLogic.go @@ -8,7 +8,7 @@ import ( "errors" "juwan-backend/app/users/rpc/usercenter" "juwan-backend/common/converter" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "time" "juwan-backend/app/users/api/internal/svc" @@ -33,7 +33,7 @@ func NewGetMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMeLogic } func (l *GetMeLogic) GetMe() (resp *types.User, err error) { - userId, err := contextx.UserIDFrom(l.ctx) + userId, err := contextj.UserIDFrom(l.ctx) if err != nil { return nil, errors.New("illegal id") } diff --git a/app/users/api/internal/logic/user/switchRoleLogic.go b/app/users/api/internal/logic/user/switchRoleLogic.go index 66bf3c1..e49e7c5 100644 --- a/app/users/api/internal/logic/user/switchRoleLogic.go +++ b/app/users/api/internal/logic/user/switchRoleLogic.go @@ -7,7 +7,7 @@ import ( "context" "errors" "juwan-backend/app/users/rpc/usercenter" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "juwan-backend/app/users/api/internal/svc" "juwan-backend/app/users/api/internal/types" @@ -33,7 +33,7 @@ func NewSwitchRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Switch func (l *SwitchRoleLogic) SwitchRole(req *types.SwitchRoleReq) (resp *types.EmptyResp, err error) { // todo: add your logic here and delete this line - id, err := contextx.UserIDFrom(l.ctx) + id, err := contextj.UserIDFrom(l.ctx) if err != nil { logx.Errorf("get user id from context: %v", err) return nil, errors.New("illegal id") diff --git a/app/users/api/internal/logic/user/updateMeLogic.go b/app/users/api/internal/logic/user/updateMeLogic.go index 1ceda46..fb0dd17 100644 --- a/app/users/api/internal/logic/user/updateMeLogic.go +++ b/app/users/api/internal/logic/user/updateMeLogic.go @@ -8,7 +8,7 @@ import ( "errors" "juwan-backend/app/users/rpc/usercenter" "juwan-backend/common/converter" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "strings" "juwan-backend/app/users/api/internal/svc" @@ -33,7 +33,7 @@ func NewUpdateMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMe } func (l *UpdateMeLogic) UpdateMe(req *types.UpdateUserProfileReq) (resp *types.UpdateUserProfileReq, err error) { - userId, err := contextx.UserIDFrom(l.ctx) + userId, err := contextj.UserIDFrom(l.ctx) if err != nil { return nil, err } diff --git a/app/users/api/internal/logic/verification_admin/approveVerificationLogic.go b/app/users/api/internal/logic/verification_admin/approveVerificationLogic.go index 6d9834d..7f816aa 100644 --- a/app/users/api/internal/logic/verification_admin/approveVerificationLogic.go +++ b/app/users/api/internal/logic/verification_admin/approveVerificationLogic.go @@ -6,7 +6,7 @@ package verification_admin import ( "context" "juwan-backend/app/user_verifications/rpc/pb" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "time" "juwan-backend/app/users/api/internal/svc" @@ -35,7 +35,7 @@ var ( ) func (l *ApproveVerificationLogic) ApproveVerification(req *types.VerificationIdReq) (resp *types.VerificationEmptyResp, err error) { - adminId, err := contextx.AdminIdFrom(l.ctx) + adminId, err := contextj.AdminIdFrom(l.ctx) if err != nil { return nil, err } diff --git a/app/users/api/internal/logic/verification_admin/getVerificationsLogic.go b/app/users/api/internal/logic/verification_admin/getVerificationsLogic.go index 797eb34..b5c660b 100644 --- a/app/users/api/internal/logic/verification_admin/getVerificationsLogic.go +++ b/app/users/api/internal/logic/verification_admin/getVerificationsLogic.go @@ -6,7 +6,7 @@ package verification_admin import ( "context" "juwan-backend/app/user_verifications/rpc/pb" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "time" "juwan-backend/app/users/api/internal/svc" @@ -32,7 +32,7 @@ func NewGetVerificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) * } func (l *GetVerificationsLogic) GetVerifications(req *types.GetPendingListReq) (resp *types.GetPendingListResp, err error) { - _, err = contextx.AdminIdFrom(l.ctx) + _, err = contextj.AdminIdFrom(l.ctx) if err != nil { return nil, err } diff --git a/app/users/api/internal/logic/verification_admin/rejectVerificationLogic.go b/app/users/api/internal/logic/verification_admin/rejectVerificationLogic.go index 6da01f9..a449f51 100644 --- a/app/users/api/internal/logic/verification_admin/rejectVerificationLogic.go +++ b/app/users/api/internal/logic/verification_admin/rejectVerificationLogic.go @@ -6,7 +6,7 @@ package verification_admin import ( "context" "juwan-backend/app/user_verifications/rpc/pb" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "time" "juwan-backend/app/users/api/internal/svc" @@ -34,7 +34,7 @@ var REJECTED = "rejected" func (l *RejectVerificationLogic) RejectVerification(req *types.RejectVerificationReq) (resp *types.VerificationEmptyResp, err error) { // todo: add your logic here and delete this line - adminId, err := contextx.AdminIdFrom(l.ctx) + adminId, err := contextj.AdminIdFrom(l.ctx) if err != nil { return nil, err } diff --git a/app/users/api/internal/logic/verification_user/applyVerificationLogic.go b/app/users/api/internal/logic/verification_user/applyVerificationLogic.go index b7c40f3..ccad0b9 100644 --- a/app/users/api/internal/logic/verification_user/applyVerificationLogic.go +++ b/app/users/api/internal/logic/verification_user/applyVerificationLogic.go @@ -10,7 +10,7 @@ import ( "juwan-backend/app/user_verifications/rpc/pb" "juwan-backend/app/users/api/internal/svc" "juwan-backend/app/users/api/internal/types" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "github.com/zeromicro/go-zero/core/logx" ) @@ -31,10 +31,10 @@ func NewApplyVerificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) } func (l *ApplyVerificationLogic) ApplyVerification(req *types.ApplyVerificationReq) (resp *types.VerificationEmptyResp, err error) { - userId, err := contextx.UserIDFrom(l.ctx) + userId, err := contextj.UserIDFrom(l.ctx) if err != nil { logx.Errorf("get user id from context: %v", err) - return nil, contextx.ERRILLEGALUSER + return nil, contextj.ERRILLEGALUSER } verifications, err := l.svcCtx.UserVerificationsRpc.SearchUserVerifications(l.ctx, &pb.SearchUserVerificationsReq{ UserId: userId, diff --git a/app/users/api/internal/logic/verification_user/getMyVerificationsLogic.go b/app/users/api/internal/logic/verification_user/getMyVerificationsLogic.go index b03bfd2..4f65cf9 100644 --- a/app/users/api/internal/logic/verification_user/getMyVerificationsLogic.go +++ b/app/users/api/internal/logic/verification_user/getMyVerificationsLogic.go @@ -6,7 +6,7 @@ package verification_user import ( "context" "juwan-backend/app/user_verifications/rpc/pb" - "juwan-backend/common/utils/contextx" + "juwan-backend/common/utils/contextj" "time" "juwan-backend/app/users/api/internal/svc" @@ -33,10 +33,10 @@ func NewGetMyVerificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) func (l *GetMyVerificationsLogic) GetMyVerifications() (resp *types.GetMyVerificationsResp, err error) { // todo: add your logic here and delete this line - userId, err := contextx.UserIDFrom(l.ctx) + userId, err := contextj.UserIDFrom(l.ctx) if err != nil { logx.Errorf("get user id from context: %v", err) - return nil, contextx.ERRILLEGALUSER + return nil, contextj.ERRILLEGALUSER } verifications, err := l.svcCtx.UserVerificationsRpc.SearchUserVerifications(l.ctx, &pb.SearchUserVerificationsReq{ diff --git a/app/users/api/internal/types/types.go b/app/users/api/internal/types/types.go index 00eee78..c5c16b1 100644 --- a/app/users/api/internal/types/types.go +++ b/app/users/api/internal/types/types.go @@ -41,8 +41,8 @@ type GetUserReq struct { } type LoginReq struct { - Phone string `json:"phone,omitempty"` // 手机号登录 - Username string `json:"username,omitempty"` // 或用户名登录 + Phone string `json:"phone,omitempty,optional"` // 手机号登录 + Username string `json:"username,omitempty"` // 或用户名登录 Password string `json:"password"` Remember bool `json:"remember,optional"` } @@ -57,8 +57,8 @@ type LogoutReq struct { } type RegisterReq struct { - Phone string `json:"phone,omitempty"` - Email string `json:"email,omitempty"` + Phone string `json:"phone,omitempty,optional"` + Email string `json:"email,omitempty,"` Username string `json:"username"` Password string `json:"password"` Vcode string `json:"vcode,omitempty"` // 验证码 @@ -114,8 +114,8 @@ type User struct { Role string `json:"role"` // consumer, player, owner, admin VerifiedRoles []string `json:"verifiedRoles"` // e.g. ["consumer", "player"] VerificationStatus map[string]string `json:"verificationStatus"` // e.g. {"player": "approved"} - Phone string `json:"phone,omitempty"` - Bio string `json:"bio,omitempty"` + Phone string `json:"phone,omitempty,optional "` + Bio string `json:"bio,omitempty,optional "` CreatedAt string `json:"createdAt"` // ISO 8601 } diff --git a/app/wallet/api/etc/wallet-api.yaml b/app/wallet/api/etc/wallet-api.yaml new file mode 100644 index 0000000..ca8a0e6 --- /dev/null +++ b/app/wallet/api/etc/wallet-api.yaml @@ -0,0 +1,14 @@ +Name: wallet-api +Host: 0.0.0.0 +Port: 8888 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +WalletRpcConf: + Target: k8s://juwan/wallet-rpc:8080 + +# k8s://juwan/:8080 + diff --git a/app/wallet/api/internal/config/config.go b/app/wallet/api/internal/config/config.go new file mode 100644 index 0000000..8be9852 --- /dev/null +++ b/app/wallet/api/internal/config/config.go @@ -0,0 +1,14 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package config + +import ( + "github.com/zeromicro/go-zero/rest" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + rest.RestConf + WalletRpcConf zrpc.RpcClientConf +} diff --git a/app/wallet/api/internal/handler/routes.go b/app/wallet/api/internal/handler/routes.go new file mode 100644 index 0000000..eb775d4 --- /dev/null +++ b/app/wallet/api/internal/handler/routes.go @@ -0,0 +1,45 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 + +package handler + +import ( + "net/http" + + wallet "juwan-backend/app/wallet/api/internal/handler/wallet" + "juwan-backend/app/wallet/api/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + // 获取余额 + Method: http.MethodGet, + Path: "/balance", + Handler: wallet.GetBalanceHandler(serverCtx), + }, + { + // 充值 + Method: http.MethodPost, + Path: "/topup", + Handler: wallet.TopupHandler(serverCtx), + }, + { + // 获取流水 + Method: http.MethodGet, + Path: "/transactions", + Handler: wallet.ListTransactionsHandler(serverCtx), + }, + { + // 提现 + Method: http.MethodPost, + Path: "/withdraw", + Handler: wallet.WithdrawHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1/wallet"), + ) +} diff --git a/app/wallet/api/internal/handler/wallet/getBalanceHandler.go b/app/wallet/api/internal/handler/wallet/getBalanceHandler.go new file mode 100644 index 0000000..8df2aaf --- /dev/null +++ b/app/wallet/api/internal/handler/wallet/getBalanceHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/wallet/api/internal/logic/wallet" + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" +) + +// 获取余额 +func GetBalanceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.EmptyResp + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := wallet.NewGetBalanceLogic(r.Context(), svcCtx) + resp, err := l.GetBalance(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/wallet/api/internal/handler/wallet/listTransactionsHandler.go b/app/wallet/api/internal/handler/wallet/listTransactionsHandler.go new file mode 100644 index 0000000..8e07269 --- /dev/null +++ b/app/wallet/api/internal/handler/wallet/listTransactionsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/wallet/api/internal/logic/wallet" + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" +) + +// 获取流水 +func ListTransactionsHandler(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 { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := wallet.NewListTransactionsLogic(r.Context(), svcCtx) + resp, err := l.ListTransactions(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/wallet/api/internal/handler/wallet/topupHandler.go b/app/wallet/api/internal/handler/wallet/topupHandler.go new file mode 100644 index 0000000..ad9f80a --- /dev/null +++ b/app/wallet/api/internal/handler/wallet/topupHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/wallet/api/internal/logic/wallet" + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" +) + +// 充值 +func TopupHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.TopupReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := wallet.NewTopupLogic(r.Context(), svcCtx) + resp, err := l.Topup(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/wallet/api/internal/handler/wallet/withdrawHandler.go b/app/wallet/api/internal/handler/wallet/withdrawHandler.go new file mode 100644 index 0000000..402f313 --- /dev/null +++ b/app/wallet/api/internal/handler/wallet/withdrawHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/wallet/api/internal/logic/wallet" + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" +) + +// 提现 +func WithdrawHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.TopupReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := wallet.NewWithdrawLogic(r.Context(), svcCtx) + resp, err := l.Withdraw(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/wallet/api/internal/logic/wallet/getBalanceLogic.go b/app/wallet/api/internal/logic/wallet/getBalanceLogic.go new file mode 100644 index 0000000..81e1832 --- /dev/null +++ b/app/wallet/api/internal/logic/wallet/getBalanceLogic.go @@ -0,0 +1,52 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "context" + + "juwan-backend/app/wallet/rpc/pb" + "juwan-backend/common/utils/contextj" + + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetBalanceLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取余额 +func NewGetBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBalanceLogic { + return &GetBalanceLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetBalanceLogic) GetBalance(req *types.EmptyResp) (resp *types.WalletBalance, err error) { + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + out, err := l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID}) + if err != nil { + return nil, err + } + + if out.GetWallets() == nil { + return &types.WalletBalance{Balance: "0", FrozenBalance: "0"}, nil + } + + return &types.WalletBalance{ + Balance: out.Wallets.Balance, + FrozenBalance: out.Wallets.FrozenBalance, + }, nil +} diff --git a/app/wallet/api/internal/logic/wallet/listTransactionsLogic.go b/app/wallet/api/internal/logic/wallet/listTransactionsLogic.go new file mode 100644 index 0000000..1e775a4 --- /dev/null +++ b/app/wallet/api/internal/logic/wallet/listTransactionsLogic.go @@ -0,0 +1,80 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "context" + "strconv" + "time" + + "juwan-backend/app/wallet/rpc/pb" + "juwan-backend/common/utils/contextj" + + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListTransactionsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取流水 +func NewListTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListTransactionsLogic { + return &ListTransactionsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListTransactionsLogic) ListTransactions(req *types.PageReq) (resp *types.TransactionListResp, err error) { + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + if req.Limit <= 0 { + req.Limit = 20 + } + + out, err := l.svcCtx.WalletRpc.SearchWalletTransactions(l.ctx, &pb.SearchWalletTransactionsReq{ + Page: req.Offset / req.Limit, + Limit: req.Limit, + UserId: &userID, + }) + if err != nil { + return nil, err + } + + items := make([]types.Transaction, 0, len(out.GetWalletTransactions())) + for _, item := range out.GetWalletTransactions() { + if item == nil { + continue + } + tx := types.Transaction{ + Id: item.Id, + Type: item.Type, + Amount: item.Amount, + Description: item.Description, + CreatedAt: time.Unix(item.CreatedAt, 0).Format(time.RFC3339), + } + if item.OrderId > 0 { + tx.OrderId = strconv.FormatInt(item.OrderId, 10) + } + items = append(items, tx) + } + + return &types.TransactionListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: req.Limit, + }, + }, nil +} diff --git a/app/wallet/api/internal/logic/wallet/topupLogic.go b/app/wallet/api/internal/logic/wallet/topupLogic.go new file mode 100644 index 0000000..c46c4ce --- /dev/null +++ b/app/wallet/api/internal/logic/wallet/topupLogic.go @@ -0,0 +1,127 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "context" + "errors" + "fmt" + "time" + + "juwan-backend/app/wallet/rpc/pb" + "juwan-backend/common/utils/contextj" + + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" + + "github.com/shopspring/decimal" + "github.com/zeromicro/go-zero/core/logx" +) + +type TopupLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 充值 +func NewTopupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TopupLogic { + return &TopupLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *TopupLogic) Topup(req *types.TopupReq) (resp *types.EmptyResp, err error) { + amount, err := decimal.NewFromString(req.Amount) + if err != nil { + return nil, errors.New("invalid amount") + } + if !amount.GreaterThan(decimal.Zero) { + return nil, errors.New("amount must be greater than 0") + } + + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + walletResp, err := l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID}) + if err != nil { + return nil, err + } + + currentBalance := decimal.Zero + frozenBalance := decimal.Zero + expectedVersion := int64(0) + if walletResp.GetWallets() == nil { + zeroAmount := "0" + _, err = l.svcCtx.WalletRpc.AddWallets(l.ctx, &pb.AddWalletsReq{ + UserId: userID, + Balance: zeroAmount, + FrozenBalance: zeroAmount, + UpdatedAt: time.Now().Unix(), + }) + if err != nil { + return nil, err + } + walletResp, err = l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID}) + if err != nil { + return nil, err + } + if walletResp.GetWallets() == nil { + return nil, errors.New("wallet not found") + } + currentBalance, err = decimal.NewFromString(walletResp.Wallets.Balance) + if err != nil { + return nil, errors.New("invalid wallet balance") + } + frozenBalance, err = decimal.NewFromString(walletResp.Wallets.FrozenBalance) + if err != nil { + return nil, errors.New("invalid wallet frozen balance") + } + expectedVersion = walletResp.Wallets.Version + } else { + currentBalance, err = decimal.NewFromString(walletResp.Wallets.Balance) + if err != nil { + return nil, errors.New("invalid wallet balance") + } + frozenBalance, err = decimal.NewFromString(walletResp.Wallets.FrozenBalance) + if err != nil { + return nil, errors.New("invalid wallet frozen balance") + } + expectedVersion = walletResp.Wallets.Version + } + + newBalance := currentBalance.Add(amount) + newBalanceStr := newBalance.String() + frozenBalanceStr := frozenBalance.String() + updatedAt := time.Now().Unix() + _, err = l.svcCtx.WalletRpc.UpdateWallets(l.ctx, &pb.UpdateWalletsReq{ + UserId: userID, + Balance: &newBalanceStr, + FrozenBalance: &frozenBalanceStr, + UpdatedAt: &updatedAt, + Version: &expectedVersion, + }) + if err != nil { + return nil, err + } + + desc := fmt.Sprintf("topup via %s", req.Method) + _, err = l.svcCtx.WalletRpc.AddWalletTransactions(l.ctx, &pb.AddWalletTransactionsReq{ + UserId: userID, + Type: "topup", + Amount: amount.String(), + BalanceAfter: newBalanceStr, + Description: desc, + CreatedAt: updatedAt, + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/wallet/api/internal/logic/wallet/withdrawLogic.go b/app/wallet/api/internal/logic/wallet/withdrawLogic.go new file mode 100644 index 0000000..b47a0e7 --- /dev/null +++ b/app/wallet/api/internal/logic/wallet/withdrawLogic.go @@ -0,0 +1,101 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package wallet + +import ( + "context" + "errors" + "fmt" + "time" + + "juwan-backend/app/wallet/rpc/pb" + "juwan-backend/common/utils/contextj" + + "juwan-backend/app/wallet/api/internal/svc" + "juwan-backend/app/wallet/api/internal/types" + + "github.com/shopspring/decimal" + "github.com/zeromicro/go-zero/core/logx" +) + +type WithdrawLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 提现 +func NewWithdrawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WithdrawLogic { + return &WithdrawLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *WithdrawLogic) Withdraw(req *types.TopupReq) (resp *types.EmptyResp, err error) { + amount, err := decimal.NewFromString(req.Amount) + if err != nil { + return nil, errors.New("invalid amount") + } + if !amount.GreaterThan(decimal.Zero) { + return nil, errors.New("amount must be greater than 0") + } + + userID, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + walletResp, err := l.svcCtx.WalletRpc.GetWalletsById(l.ctx, &pb.GetWalletsByIdReq{Id: userID}) + if err != nil { + return nil, err + } + if walletResp.GetWallets() == nil { + return nil, errors.New("wallet not found") + } + + currentBalance, err := decimal.NewFromString(walletResp.Wallets.Balance) + if err != nil { + return nil, errors.New("invalid wallet balance") + } + frozenBalance, err := decimal.NewFromString(walletResp.Wallets.FrozenBalance) + if err != nil { + return nil, errors.New("invalid wallet frozen balance") + } + expectedVersion := walletResp.Wallets.Version + if currentBalance.LessThan(amount) { + return nil, errors.New("insufficient balance") + } + + newBalance := currentBalance.Sub(amount) + newBalanceStr := newBalance.String() + frozenBalanceStr := frozenBalance.String() + updatedAt := time.Now().Unix() + _, err = l.svcCtx.WalletRpc.UpdateWallets(l.ctx, &pb.UpdateWalletsReq{ + UserId: userID, + Balance: &newBalanceStr, + FrozenBalance: &frozenBalanceStr, + UpdatedAt: &updatedAt, + Version: &expectedVersion, + }) + if err != nil { + return nil, err + } + + desc := fmt.Sprintf("withdraw via %s", req.Method) + _, err = l.svcCtx.WalletRpc.AddWalletTransactions(l.ctx, &pb.AddWalletTransactionsReq{ + UserId: userID, + Type: "withdrawal", + Amount: amount.String(), + BalanceAfter: newBalanceStr, + Description: desc, + CreatedAt: updatedAt, + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/wallet/api/internal/svc/serviceContext.go b/app/wallet/api/internal/svc/serviceContext.go new file mode 100644 index 0000000..d1af407 --- /dev/null +++ b/app/wallet/api/internal/svc/serviceContext.go @@ -0,0 +1,23 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package svc + +import ( + "juwan-backend/app/wallet/api/internal/config" + "juwan-backend/app/wallet/rpc/walletservice" + + "github.com/zeromicro/go-zero/zrpc" +) + +type ServiceContext struct { + Config config.Config + WalletRpc walletservice.WalletService +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + WalletRpc: walletservice.NewWalletService(zrpc.MustNewClient(c.WalletRpcConf)), + } +} diff --git a/app/wallet/api/internal/types/types.go b/app/wallet/api/internal/types/types.go new file mode 100644 index 0000000..4c3a113 --- /dev/null +++ b/app/wallet/api/internal/types/types.go @@ -0,0 +1,61 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 + +package types + +type EmptyResp struct { +} + +type PageMeta struct { + Total int64 `json:"total"` + Offset int64 `json:"offset"` + Limit int64 `json:"limit"` +} + +type PageReq struct { + Offset int64 `form:"offset,default=0"` + Limit int64 `form:"limit,default=20"` +} + +type SimpleUser struct { + Id string `json:"id"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` +} + +type TopupReq struct { + Amount string `json:"amount"` + Method string `json:"method"` +} + +type Transaction struct { + Id int64 `json:"id"` + Type string `json:"type"` + Amount string `json:"amount"` + Description string `json:"description"` + OrderId string `json:"orderId,optional"` + CreatedAt string `json:"createdAt"` +} + +type TransactionListResp struct { + Items []Transaction `json:"items"` + Meta PageMeta `json:"meta"` +} + +type UserProfile struct { + Id string `json:"id"` + Username string `json:"username"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` + Role string `json:"role"` // consumer, player, owner, admin + VerifiedRoles []string `json:"verifiedRoles"` + VerificationStatus map[string]string `json:"verificationStatus"` + Phone string `json:"phone,optional"` + Bio string `json:"bio,optional"` + CreatedAt string `json:"createdAt"` +} + +type WalletBalance struct { + Balance string `json:"balance"` + FrozenBalance string `json:"frozenBalance"` +} diff --git a/app/wallet/api/wallet.go b/app/wallet/api/wallet.go new file mode 100644 index 0000000..2e32313 --- /dev/null +++ b/app/wallet/api/wallet.go @@ -0,0 +1,34 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.9.2 + +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/wallet/api/internal/config" + "juwan-backend/app/wallet/api/internal/handler" + "juwan-backend/app/wallet/api/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/wallet-api.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/app/wallet/rpc/etc/pb.yaml b/app/wallet/rpc/etc/pb.yaml new file mode 100644 index 0000000..9e44d04 --- /dev/null +++ b/app/wallet/rpc/etc/pb.yaml @@ -0,0 +1,38 @@ +Name: pb.rpc +ListenOn: 0.0.0.0:8080 + + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# tcd: +# Hosts: +# - 127.0.0.1:2379 +# Key: pb.rpc + +# Target: k8s://juwan/.:8080 + + +SnowflakeRpcConf: + Target: k8s://juwan/snowflake-svc:8080 + + +DB: + Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable" + + +CacheConf: + - Host: "${REDIS_M_HOST}" + Type: node + Pass: "${REDIS_PASSWORD}" + User: "default" + - Host: "${REDIS_S_HOST}" + Type: node + Pass: "${REDIS_PASSWORD}" + User: "default" + +Log: + Level: info diff --git a/app/wallet/rpc/internal/config/config.go b/app/wallet/rpc/internal/config/config.go new file mode 100644 index 0000000..faeb55a --- /dev/null +++ b/app/wallet/rpc/internal/config/config.go @@ -0,0 +1,17 @@ +package config + +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + zrpc.RpcServerConf + + SnowflakeRpcConf zrpc.RpcClientConf + DB struct { + Master string + Slaves string + } + CacheConf cache.CacheConf +} diff --git a/app/wallet/rpc/internal/logic/addWalletTransactionsLogic.go b/app/wallet/rpc/internal/logic/addWalletTransactionsLogic.go new file mode 100644 index 0000000..1bf5a5e --- /dev/null +++ b/app/wallet/rpc/internal/logic/addWalletTransactionsLogic.go @@ -0,0 +1,85 @@ +package logic + +import ( + "context" + "errors" + "strconv" + "time" + + "juwan-backend/app/snowflake/rpc/snowflake" + + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/shopspring/decimal" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddWalletTransactionsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddWalletTransactionsLogic { + return &AddWalletTransactionsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------walletTransactions----------------------- +func (l *AddWalletTransactionsLogic) AddWalletTransactions(in *pb.AddWalletTransactionsReq) (*pb.AddWalletTransactionsResp, error) { + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, err + } + + createdAt := time.Now() + if in.CreatedAt > 0 { + createdAt = time.Unix(in.CreatedAt, 0) + } + + searchText := in.SearchText + if searchText == "" { + searchText = in.Type + " " + in.Description + } + + amount, err := decimal.NewFromString(in.GetAmount()) + if err != nil { + return nil, errors.New("invalid amount") + } + balanceAfter, err := decimal.NewFromString(in.GetBalanceAfter()) + if err != nil { + return nil, errors.New("invalid balanceAfter") + } + + tx, err := l.svcCtx.WalletModelsRW.Tx(l.ctx) + if err != nil { + return nil, err + } + + _, err = tx.WalletTransactions.Create(). + SetID(strconv.FormatInt(idResp.Id, 10)). + SetUserID(in.UserId). + SetType(in.Type). + SetAmount(amount). + SetBalanceAfter(balanceAfter). + SetDescription([]string{in.Description}). + SetOrderID(in.OrderId). + SetCreatedAt(createdAt). + SetSearchText(searchText). + Save(l.ctx) + if err != nil { + _ = tx.Rollback() + return nil, err + } + + if err = tx.Commit(); err != nil { + return nil, err + } + + return &pb.AddWalletTransactionsResp{}, nil +} diff --git a/app/wallet/rpc/internal/logic/addWalletsLogic.go b/app/wallet/rpc/internal/logic/addWalletsLogic.go new file mode 100644 index 0000000..9870449 --- /dev/null +++ b/app/wallet/rpc/internal/logic/addWalletsLogic.go @@ -0,0 +1,72 @@ +package logic + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/wallet/rpc/internal/models" + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/shopspring/decimal" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddWalletsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddWalletsLogic { + return &AddWalletsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------wallets----------------------- +func (l *AddWalletsLogic) AddWallets(in *pb.AddWalletsReq) (*pb.AddWalletsResp, error) { + updatedAt := time.Now() + if in.UpdatedAt > 0 { + updatedAt = time.Unix(in.UpdatedAt, 0) + } + + balance, err := decimal.NewFromString(in.GetBalance()) + if err != nil { + return nil, errors.New("invalid balance") + } + frozenBalance, err := decimal.NewFromString(in.GetFrozenBalance()) + if err != nil { + return nil, errors.New("invalid frozenBalance") + } + + tx, err := l.svcCtx.WalletModelsRW.Tx(l.ctx) + if err != nil { + return nil, err + } + + _, err = tx.Wallet.Create(). + SetUserID(in.UserId). + SetBalance(balance). + SetFrozenBalance(frozenBalance). + SetVersion(1). + SetUpdatedAt(updatedAt). + Save(l.ctx) + if err != nil { + _ = tx.Rollback() + if models.IsConstraintError(err) { + return &pb.AddWalletsResp{}, nil + } + return nil, err + } + + if err = tx.Commit(); err != nil { + return nil, err + } + + return &pb.AddWalletsResp{}, nil +} diff --git a/app/wallet/rpc/internal/logic/delWalletTransactionsLogic.go b/app/wallet/rpc/internal/logic/delWalletTransactionsLogic.go new file mode 100644 index 0000000..629f6e6 --- /dev/null +++ b/app/wallet/rpc/internal/logic/delWalletTransactionsLogic.go @@ -0,0 +1,30 @@ +package logic + +import ( + "context" + + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelWalletTransactionsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelWalletTransactionsLogic { + return &DelWalletTransactionsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelWalletTransactionsLogic) DelWalletTransactions(in *pb.DelWalletTransactionsReq) (*pb.DelWalletTransactionsResp, error) { + // todo: add your logic here and delete this line + + return &pb.DelWalletTransactionsResp{}, nil +} diff --git a/app/wallet/rpc/internal/logic/delWalletsLogic.go b/app/wallet/rpc/internal/logic/delWalletsLogic.go new file mode 100644 index 0000000..f4f135d --- /dev/null +++ b/app/wallet/rpc/internal/logic/delWalletsLogic.go @@ -0,0 +1,30 @@ +package logic + +import ( + "context" + + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelWalletsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelWalletsLogic { + return &DelWalletsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelWalletsLogic) DelWallets(in *pb.DelWalletsReq) (*pb.DelWalletsResp, error) { + // todo: add your logic here and delete this line + + return &pb.DelWalletsResp{}, nil +} diff --git a/app/wallet/rpc/internal/logic/getWalletTransactionsByIdLogic.go b/app/wallet/rpc/internal/logic/getWalletTransactionsByIdLogic.go new file mode 100644 index 0000000..edcb66c --- /dev/null +++ b/app/wallet/rpc/internal/logic/getWalletTransactionsByIdLogic.go @@ -0,0 +1,30 @@ +package logic + +import ( + "context" + + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetWalletTransactionsByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetWalletTransactionsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWalletTransactionsByIdLogic { + return &GetWalletTransactionsByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetWalletTransactionsByIdLogic) GetWalletTransactionsById(in *pb.GetWalletTransactionsByIdReq) (*pb.GetWalletTransactionsByIdResp, error) { + // todo: add your logic here and delete this line + + return &pb.GetWalletTransactionsByIdResp{}, nil +} diff --git a/app/wallet/rpc/internal/logic/getWalletsByIdLogic.go b/app/wallet/rpc/internal/logic/getWalletsByIdLogic.go new file mode 100644 index 0000000..d8b238d --- /dev/null +++ b/app/wallet/rpc/internal/logic/getWalletsByIdLogic.go @@ -0,0 +1,52 @@ +package logic + +import ( + "context" + "juwan-backend/app/wallet/rpc/internal/models" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetWalletsByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetWalletsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWalletsByIdLogic { + return &GetWalletsByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetWalletsByIdLogic) GetWalletsById(in *pb.GetWalletsByIdReq) (*pb.GetWalletsByIdResp, error) { + item, err := l.svcCtx.WalletModelsRO.Wallet.Query(). + Where(wallet.UserIDEQ(in.Id)). + First(l.ctx) + if err != nil { + if models.IsNotFound(err) { + return &pb.GetWalletsByIdResp{}, nil + } + return nil, err + } + + updatedAt := int64(0) + if !item.UpdatedAt.IsZero() { + updatedAt = item.UpdatedAt.Unix() + } + + return &pb.GetWalletsByIdResp{ + Wallets: &pb.Wallets{ + UserId: item.UserID, + Balance: item.Balance.String(), + FrozenBalance: item.FrozenBalance.String(), + UpdatedAt: updatedAt, + Version: int64(item.Version), + }, + }, nil +} diff --git a/app/wallet/rpc/internal/logic/searchWalletTransactionsLogic.go b/app/wallet/rpc/internal/logic/searchWalletTransactionsLogic.go new file mode 100644 index 0000000..1246fc5 --- /dev/null +++ b/app/wallet/rpc/internal/logic/searchWalletTransactionsLogic.go @@ -0,0 +1,106 @@ +package logic + +import ( + "context" + "errors" + "strconv" + "time" + + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/shopspring/decimal" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchWalletTransactionsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchWalletTransactionsLogic { + return &SearchWalletTransactionsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchWalletTransactionsLogic) SearchWalletTransactions(in *pb.SearchWalletTransactionsReq) (*pb.SearchWalletTransactionsResp, error) { + if in.Limit <= 0 { + in.Limit = 20 + } + + preds := make([]predicate.WalletTransactions, 0, 8) + if in.Id > 0 { + preds = append(preds, wallettransactions.IDEQ(strconv.FormatInt(in.Id, 10))) + } + if in.UserId != nil { + preds = append(preds, wallettransactions.UserIDEQ(in.GetUserId())) + } + if in.Type != nil && in.GetType() != "" { + preds = append(preds, wallettransactions.TypeEQ(in.GetType())) + } + if in.Amount != nil { + amount, perr := decimal.NewFromString(in.GetAmount()) + if perr != nil { + return nil, errors.New("invalid amount") + } + preds = append(preds, wallettransactions.AmountEQ(amount)) + } + if in.BalanceAfter != nil { + balanceAfter, perr := decimal.NewFromString(in.GetBalanceAfter()) + if perr != nil { + return nil, errors.New("invalid balanceAfter") + } + preds = append(preds, wallettransactions.BalanceAfterEQ(balanceAfter)) + } + if in.OrderId != nil { + preds = append(preds, wallettransactions.OrderIDEQ(in.GetOrderId())) + } + if in.CreatedAt != nil && in.GetCreatedAt() > 0 { + preds = append(preds, wallettransactions.CreatedAtGTE(time.Unix(in.GetCreatedAt(), 0))) + } + if in.SearchText != nil && in.GetSearchText() != "" { + preds = append(preds, wallettransactions.SearchTextContainsFold(in.GetSearchText())) + } + + query := l.svcCtx.WalletModelsRO.WalletTransactions.Query() + if len(preds) > 0 { + query = query.Where(wallettransactions.And(preds...)) + } + + list, err := query. + Offset(int(in.Page * in.Limit)). + Limit(int(in.Limit)). + All(l.ctx) + if err != nil { + return nil, err + } + + result := make([]*pb.WalletTransactions, 0, len(list)) + for _, item := range list { + id, _ := strconv.ParseInt(item.ID, 10, 64) + description := "" + if len(item.Description) > 0 { + description = item.Description[0] + } + result = append(result, &pb.WalletTransactions{ + Id: id, + UserId: item.UserID, + Type: item.Type, + Amount: item.Amount.String(), + BalanceAfter: item.BalanceAfter.String(), + Description: description, + OrderId: item.OrderID, + CreatedAt: item.CreatedAt.Unix(), + SearchText: item.SearchText, + }) + } + + return &pb.SearchWalletTransactionsResp{WalletTransactions: result}, nil +} diff --git a/app/wallet/rpc/internal/logic/searchWalletsLogic.go b/app/wallet/rpc/internal/logic/searchWalletsLogic.go new file mode 100644 index 0000000..6d452aa --- /dev/null +++ b/app/wallet/rpc/internal/logic/searchWalletsLogic.go @@ -0,0 +1,30 @@ +package logic + +import ( + "context" + + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchWalletsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchWalletsLogic { + return &SearchWalletsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchWalletsLogic) SearchWallets(in *pb.SearchWalletsReq) (*pb.SearchWalletsResp, error) { + // todo: add your logic here and delete this line + + return &pb.SearchWalletsResp{}, nil +} diff --git a/app/wallet/rpc/internal/logic/updateWalletTransactionsLogic.go b/app/wallet/rpc/internal/logic/updateWalletTransactionsLogic.go new file mode 100644 index 0000000..8b79de0 --- /dev/null +++ b/app/wallet/rpc/internal/logic/updateWalletTransactionsLogic.go @@ -0,0 +1,30 @@ +package logic + +import ( + "context" + + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateWalletTransactionsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateWalletTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateWalletTransactionsLogic { + return &UpdateWalletTransactionsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateWalletTransactionsLogic) UpdateWalletTransactions(in *pb.UpdateWalletTransactionsReq) (*pb.UpdateWalletTransactionsResp, error) { + // todo: add your logic here and delete this line + + return &pb.UpdateWalletTransactionsResp{}, nil +} diff --git a/app/wallet/rpc/internal/logic/updateWalletsLogic.go b/app/wallet/rpc/internal/logic/updateWalletsLogic.go new file mode 100644 index 0000000..dace6b2 --- /dev/null +++ b/app/wallet/rpc/internal/logic/updateWalletsLogic.go @@ -0,0 +1,89 @@ +package logic + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/shopspring/decimal" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateWalletsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateWalletsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateWalletsLogic { + return &UpdateWalletsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateWalletsLogic) UpdateWallets(in *pb.UpdateWalletsReq) (*pb.UpdateWalletsResp, error) { + if in.Version == nil { + return nil, errors.New("version is required") + } + + tx, err := l.svcCtx.WalletModelsRW.Tx(l.ctx) + if err != nil { + return nil, err + } + + updater := tx.Wallet.Update(). + Where(wallet.UserIDEQ(in.UserId), wallet.VersionEQ(int(in.GetVersion()))). + AddVersion(1) + + if in.Balance != nil { + parsedBalance, perr := decimal.NewFromString(in.GetBalance()) + if perr != nil { + _ = tx.Rollback() + return nil, errors.New("invalid balance") + } + updater = updater.SetBalance(parsedBalance) + } + if in.FrozenBalance != nil { + parsedFrozenBalance, perr := decimal.NewFromString(in.GetFrozenBalance()) + if perr != nil { + _ = tx.Rollback() + return nil, errors.New("invalid frozenBalance") + } + updater = updater.SetFrozenBalance(parsedFrozenBalance) + } + if in.UpdatedAt != nil && in.GetUpdatedAt() > 0 { + updater = updater.SetUpdatedAt(time.Unix(in.GetUpdatedAt(), 0)) + } else { + updater = updater.SetUpdatedAt(time.Now()) + } + + affected, err := updater.Save(l.ctx) + if err != nil { + _ = tx.Rollback() + return nil, err + } + if affected == 0 { + exist, qerr := tx.Wallet.Query().Where(wallet.UserIDEQ(in.UserId)).Exist(l.ctx) + _ = tx.Rollback() + if qerr != nil { + return nil, qerr + } + if !exist { + return nil, errors.New("wallet not found") + } + return nil, errors.New("wallet update conflict") + } + + if err = tx.Commit(); err != nil { + return nil, err + } + + return &pb.UpdateWalletsResp{}, nil +} diff --git a/app/wallet/rpc/internal/models/client.go b/app/wallet/rpc/internal/models/client.go new file mode 100644 index 0000000..45dcfc3 --- /dev/null +++ b/app/wallet/rpc/internal/models/client.go @@ -0,0 +1,484 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "juwan-backend/app/wallet/rpc/internal/models/migrate" + + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Wallet is the client for interacting with the Wallet builders. + Wallet *WalletClient + // WalletTransactions is the client for interacting with the WalletTransactions builders. + WalletTransactions *WalletTransactionsClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Wallet = NewWalletClient(c.config) + c.WalletTransactions = NewWalletTransactionsClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("models: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Wallet: NewWalletClient(cfg), + WalletTransactions: NewWalletTransactionsClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Wallet: NewWalletClient(cfg), + WalletTransactions: NewWalletTransactionsClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Wallet. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Wallet.Use(hooks...) + c.WalletTransactions.Use(hooks...) +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.Wallet.Intercept(interceptors...) + c.WalletTransactions.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *WalletMutation: + return c.Wallet.mutate(ctx, m) + case *WalletTransactionsMutation: + return c.WalletTransactions.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// WalletClient is a client for the Wallet schema. +type WalletClient struct { + config +} + +// NewWalletClient returns a client for the Wallet from the given config. +func NewWalletClient(c config) *WalletClient { + return &WalletClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `wallet.Hooks(f(g(h())))`. +func (c *WalletClient) Use(hooks ...Hook) { + c.hooks.Wallet = append(c.hooks.Wallet, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `wallet.Intercept(f(g(h())))`. +func (c *WalletClient) Intercept(interceptors ...Interceptor) { + c.inters.Wallet = append(c.inters.Wallet, interceptors...) +} + +// Create returns a builder for creating a Wallet entity. +func (c *WalletClient) Create() *WalletCreate { + mutation := newWalletMutation(c.config, OpCreate) + return &WalletCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Wallet entities. +func (c *WalletClient) CreateBulk(builders ...*WalletCreate) *WalletCreateBulk { + return &WalletCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *WalletClient) MapCreateBulk(slice any, setFunc func(*WalletCreate, int)) *WalletCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &WalletCreateBulk{err: fmt.Errorf("calling to WalletClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*WalletCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &WalletCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Wallet. +func (c *WalletClient) Update() *WalletUpdate { + mutation := newWalletMutation(c.config, OpUpdate) + return &WalletUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *WalletClient) UpdateOne(_m *Wallet) *WalletUpdateOne { + mutation := newWalletMutation(c.config, OpUpdateOne, withWallet(_m)) + return &WalletUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *WalletClient) UpdateOneID(id int) *WalletUpdateOne { + mutation := newWalletMutation(c.config, OpUpdateOne, withWalletID(id)) + return &WalletUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Wallet. +func (c *WalletClient) Delete() *WalletDelete { + mutation := newWalletMutation(c.config, OpDelete) + return &WalletDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *WalletClient) DeleteOne(_m *Wallet) *WalletDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *WalletClient) DeleteOneID(id int) *WalletDeleteOne { + builder := c.Delete().Where(wallet.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &WalletDeleteOne{builder} +} + +// Query returns a query builder for Wallet. +func (c *WalletClient) Query() *WalletQuery { + return &WalletQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeWallet}, + inters: c.Interceptors(), + } +} + +// Get returns a Wallet entity by its id. +func (c *WalletClient) Get(ctx context.Context, id int) (*Wallet, error) { + return c.Query().Where(wallet.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *WalletClient) GetX(ctx context.Context, id int) *Wallet { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *WalletClient) Hooks() []Hook { + return c.hooks.Wallet +} + +// Interceptors returns the client interceptors. +func (c *WalletClient) Interceptors() []Interceptor { + return c.inters.Wallet +} + +func (c *WalletClient) mutate(ctx context.Context, m *WalletMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&WalletCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&WalletUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&WalletUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&WalletDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Wallet mutation op: %q", m.Op()) + } +} + +// WalletTransactionsClient is a client for the WalletTransactions schema. +type WalletTransactionsClient struct { + config +} + +// NewWalletTransactionsClient returns a client for the WalletTransactions from the given config. +func NewWalletTransactionsClient(c config) *WalletTransactionsClient { + return &WalletTransactionsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `wallettransactions.Hooks(f(g(h())))`. +func (c *WalletTransactionsClient) Use(hooks ...Hook) { + c.hooks.WalletTransactions = append(c.hooks.WalletTransactions, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `wallettransactions.Intercept(f(g(h())))`. +func (c *WalletTransactionsClient) Intercept(interceptors ...Interceptor) { + c.inters.WalletTransactions = append(c.inters.WalletTransactions, interceptors...) +} + +// Create returns a builder for creating a WalletTransactions entity. +func (c *WalletTransactionsClient) Create() *WalletTransactionsCreate { + mutation := newWalletTransactionsMutation(c.config, OpCreate) + return &WalletTransactionsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of WalletTransactions entities. +func (c *WalletTransactionsClient) CreateBulk(builders ...*WalletTransactionsCreate) *WalletTransactionsCreateBulk { + return &WalletTransactionsCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *WalletTransactionsClient) MapCreateBulk(slice any, setFunc func(*WalletTransactionsCreate, int)) *WalletTransactionsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &WalletTransactionsCreateBulk{err: fmt.Errorf("calling to WalletTransactionsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*WalletTransactionsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &WalletTransactionsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for WalletTransactions. +func (c *WalletTransactionsClient) Update() *WalletTransactionsUpdate { + mutation := newWalletTransactionsMutation(c.config, OpUpdate) + return &WalletTransactionsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *WalletTransactionsClient) UpdateOne(_m *WalletTransactions) *WalletTransactionsUpdateOne { + mutation := newWalletTransactionsMutation(c.config, OpUpdateOne, withWalletTransactions(_m)) + return &WalletTransactionsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *WalletTransactionsClient) UpdateOneID(id string) *WalletTransactionsUpdateOne { + mutation := newWalletTransactionsMutation(c.config, OpUpdateOne, withWalletTransactionsID(id)) + return &WalletTransactionsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for WalletTransactions. +func (c *WalletTransactionsClient) Delete() *WalletTransactionsDelete { + mutation := newWalletTransactionsMutation(c.config, OpDelete) + return &WalletTransactionsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *WalletTransactionsClient) DeleteOne(_m *WalletTransactions) *WalletTransactionsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *WalletTransactionsClient) DeleteOneID(id string) *WalletTransactionsDeleteOne { + builder := c.Delete().Where(wallettransactions.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &WalletTransactionsDeleteOne{builder} +} + +// Query returns a query builder for WalletTransactions. +func (c *WalletTransactionsClient) Query() *WalletTransactionsQuery { + return &WalletTransactionsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeWalletTransactions}, + inters: c.Interceptors(), + } +} + +// Get returns a WalletTransactions entity by its id. +func (c *WalletTransactionsClient) Get(ctx context.Context, id string) (*WalletTransactions, error) { + return c.Query().Where(wallettransactions.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *WalletTransactionsClient) GetX(ctx context.Context, id string) *WalletTransactions { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *WalletTransactionsClient) Hooks() []Hook { + return c.hooks.WalletTransactions +} + +// Interceptors returns the client interceptors. +func (c *WalletTransactionsClient) Interceptors() []Interceptor { + return c.inters.WalletTransactions +} + +func (c *WalletTransactionsClient) mutate(ctx context.Context, m *WalletTransactionsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&WalletTransactionsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&WalletTransactionsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&WalletTransactionsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&WalletTransactionsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown WalletTransactions mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Wallet, WalletTransactions []ent.Hook + } + inters struct { + Wallet, WalletTransactions []ent.Interceptor + } +) diff --git a/app/wallet/rpc/internal/models/ent.go b/app/wallet/rpc/internal/models/ent.go new file mode 100644 index 0000000..a1bb2e5 --- /dev/null +++ b/app/wallet/rpc/internal/models/ent.go @@ -0,0 +1,610 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(t, c string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + wallet.Table: wallet.ValidColumn, + wallettransactions.Table: wallettransactions.ValidColumn, + }) + }) + return columnCheck(t, c) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "models: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "models: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "models: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "models: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("models: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/app/wallet/rpc/internal/models/enttest/enttest.go b/app/wallet/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..fd9b036 --- /dev/null +++ b/app/wallet/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/wallet/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/wallet/rpc/internal/models/runtime" + + "juwan-backend/app/wallet/rpc/internal/models/migrate" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []models.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...models.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls models.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client { + o := newOptions(opts) + c, err := models.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls models.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *models.Client { + o := newOptions(opts) + c := models.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *models.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/app/wallet/rpc/internal/models/hook/hook.go b/app/wallet/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..4a4f111 --- /dev/null +++ b/app/wallet/rpc/internal/models/hook/hook.go @@ -0,0 +1,210 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models" +) + +// The WalletFunc type is an adapter to allow the use of ordinary +// function as Wallet mutator. +type WalletFunc func(context.Context, *models.WalletMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f WalletFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.WalletMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.WalletMutation", m) +} + +// The WalletTransactionsFunc type is an adapter to allow the use of ordinary +// function as WalletTransactions mutator. +type WalletTransactionsFunc func(context.Context, *models.WalletTransactionsMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f WalletTransactionsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.WalletTransactionsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.WalletTransactionsMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, models.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m models.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op models.Op) Condition { + return func(_ context.Context, m models.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m models.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk models.Hook, cond Condition) models.Hook { + return func(next models.Mutator) models.Mutator { + return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, models.Delete|models.Create) +func On(hk models.Hook, op models.Op) models.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, models.Update|models.UpdateOne) +func Unless(hk models.Hook, op models.Op) models.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) models.Hook { + return func(models.Mutator) models.Mutator { + return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []models.Hook { +// return []models.Hook{ +// Reject(models.Delete|models.Update), +// } +// } +func Reject(op models.Op) models.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []models.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...models.Hook) Chain { + return Chain{append([]models.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() models.Hook { + return func(mutator models.Mutator) models.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...models.Hook) Chain { + newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/app/wallet/rpc/internal/models/migrate/migrate.go b/app/wallet/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/wallet/rpc/internal/models/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/app/wallet/rpc/internal/models/migrate/schema.go b/app/wallet/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..f781cac --- /dev/null +++ b/app/wallet/rpc/internal/models/migrate/schema.go @@ -0,0 +1,52 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // WalletsColumns holds the columns for the "wallets" table. + WalletsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "user_id", Type: field.TypeInt64, Unique: true}, + {Name: "balance", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "decimal(12,2)"}}, + {Name: "frozen_balance", Type: field.TypeOther, SchemaType: map[string]string{"postgres": "decimal(12,2)"}}, + {Name: "version", Type: field.TypeInt, Default: 1}, + {Name: "updated_at", Type: field.TypeTime}, + } + // WalletsTable holds the schema information for the "wallets" table. + WalletsTable = &schema.Table{ + Name: "wallets", + Columns: WalletsColumns, + PrimaryKey: []*schema.Column{WalletsColumns[0]}, + } + // WalletTransactionsColumns holds the columns for the "wallet_transactions" table. + WalletTransactionsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true}, + {Name: "user_id", Type: field.TypeInt64, Unique: true}, + {Name: "type", Type: field.TypeString}, + {Name: "amount", Type: field.TypeOther, Unique: true, SchemaType: map[string]string{"postgres": "decimal(12,2"}}, + {Name: "balance_after", Type: field.TypeOther, Unique: true, SchemaType: map[string]string{"postgres": "decimal(12,2)"}}, + {Name: "description", Type: field.TypeJSON}, + {Name: "order_id", Type: field.TypeInt64, Unique: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "search_text", Type: field.TypeString}, + } + // WalletTransactionsTable holds the schema information for the "wallet_transactions" table. + WalletTransactionsTable = &schema.Table{ + Name: "wallet_transactions", + Columns: WalletTransactionsColumns, + PrimaryKey: []*schema.Column{WalletTransactionsColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + WalletsTable, + WalletTransactionsTable, + } +) + +func init() { +} diff --git a/app/wallet/rpc/internal/models/mutation.go b/app/wallet/rpc/internal/models/mutation.go new file mode 100644 index 0000000..c271463 --- /dev/null +++ b/app/wallet/rpc/internal/models/mutation.go @@ -0,0 +1,1437 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeWallet = "Wallet" + TypeWalletTransactions = "WalletTransactions" +) + +// WalletMutation represents an operation that mutates the Wallet nodes in the graph. +type WalletMutation struct { + config + op Op + typ string + id *int + user_id *int64 + adduser_id *int64 + balance *decimal.Decimal + frozen_balance *decimal.Decimal + version *int + addversion *int + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Wallet, error) + predicates []predicate.Wallet +} + +var _ ent.Mutation = (*WalletMutation)(nil) + +// walletOption allows management of the mutation configuration using functional options. +type walletOption func(*WalletMutation) + +// newWalletMutation creates new mutation for the Wallet entity. +func newWalletMutation(c config, op Op, opts ...walletOption) *WalletMutation { + m := &WalletMutation{ + config: c, + op: op, + typ: TypeWallet, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withWalletID sets the ID field of the mutation. +func withWalletID(id int) walletOption { + return func(m *WalletMutation) { + var ( + err error + once sync.Once + value *Wallet + ) + m.oldValue = func(ctx context.Context) (*Wallet, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Wallet.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withWallet sets the old Wallet of the mutation. +func withWallet(node *Wallet) walletOption { + return func(m *WalletMutation) { + m.oldValue = func(context.Context) (*Wallet, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m WalletMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m WalletMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *WalletMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *WalletMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Wallet.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetUserID sets the "user_id" field. +func (m *WalletMutation) SetUserID(i int64) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *WalletMutation) UserID() (r int64, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Wallet entity. +// If the Wallet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletMutation) OldUserID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// AddUserID adds i to the "user_id" field. +func (m *WalletMutation) AddUserID(i int64) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *WalletMutation) AddedUserID() (r int64, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *WalletMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetBalance sets the "balance" field. +func (m *WalletMutation) SetBalance(d decimal.Decimal) { + m.balance = &d +} + +// Balance returns the value of the "balance" field in the mutation. +func (m *WalletMutation) Balance() (r decimal.Decimal, exists bool) { + v := m.balance + if v == nil { + return + } + return *v, true +} + +// OldBalance returns the old "balance" field's value of the Wallet entity. +// If the Wallet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletMutation) OldBalance(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBalance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBalance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBalance: %w", err) + } + return oldValue.Balance, nil +} + +// ResetBalance resets all changes to the "balance" field. +func (m *WalletMutation) ResetBalance() { + m.balance = nil +} + +// SetFrozenBalance sets the "frozen_balance" field. +func (m *WalletMutation) SetFrozenBalance(d decimal.Decimal) { + m.frozen_balance = &d +} + +// FrozenBalance returns the value of the "frozen_balance" field in the mutation. +func (m *WalletMutation) FrozenBalance() (r decimal.Decimal, exists bool) { + v := m.frozen_balance + if v == nil { + return + } + return *v, true +} + +// OldFrozenBalance returns the old "frozen_balance" field's value of the Wallet entity. +// If the Wallet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletMutation) OldFrozenBalance(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFrozenBalance is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFrozenBalance requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFrozenBalance: %w", err) + } + return oldValue.FrozenBalance, nil +} + +// ResetFrozenBalance resets all changes to the "frozen_balance" field. +func (m *WalletMutation) ResetFrozenBalance() { + m.frozen_balance = nil +} + +// SetVersion sets the "version" field. +func (m *WalletMutation) SetVersion(i int) { + m.version = &i + m.addversion = nil +} + +// Version returns the value of the "version" field in the mutation. +func (m *WalletMutation) Version() (r int, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the Wallet entity. +// If the Wallet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletMutation) OldVersion(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil +} + +// AddVersion adds i to the "version" field. +func (m *WalletMutation) AddVersion(i int) { + if m.addversion != nil { + *m.addversion += i + } else { + m.addversion = &i + } +} + +// AddedVersion returns the value that was added to the "version" field in this mutation. +func (m *WalletMutation) AddedVersion() (r int, exists bool) { + v := m.addversion + if v == nil { + return + } + return *v, true +} + +// ResetVersion resets all changes to the "version" field. +func (m *WalletMutation) ResetVersion() { + m.version = nil + m.addversion = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *WalletMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *WalletMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the Wallet entity. +// If the Wallet object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *WalletMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the WalletMutation builder. +func (m *WalletMutation) Where(ps ...predicate.Wallet) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the WalletMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *WalletMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Wallet, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *WalletMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *WalletMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Wallet). +func (m *WalletMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *WalletMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.user_id != nil { + fields = append(fields, wallet.FieldUserID) + } + if m.balance != nil { + fields = append(fields, wallet.FieldBalance) + } + if m.frozen_balance != nil { + fields = append(fields, wallet.FieldFrozenBalance) + } + if m.version != nil { + fields = append(fields, wallet.FieldVersion) + } + if m.updated_at != nil { + fields = append(fields, wallet.FieldUpdatedAt) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *WalletMutation) Field(name string) (ent.Value, bool) { + switch name { + case wallet.FieldUserID: + return m.UserID() + case wallet.FieldBalance: + return m.Balance() + case wallet.FieldFrozenBalance: + return m.FrozenBalance() + case wallet.FieldVersion: + return m.Version() + case wallet.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *WalletMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case wallet.FieldUserID: + return m.OldUserID(ctx) + case wallet.FieldBalance: + return m.OldBalance(ctx) + case wallet.FieldFrozenBalance: + return m.OldFrozenBalance(ctx) + case wallet.FieldVersion: + return m.OldVersion(ctx) + case wallet.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Wallet field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *WalletMutation) SetField(name string, value ent.Value) error { + switch name { + case wallet.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case wallet.FieldBalance: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBalance(v) + return nil + case wallet.FieldFrozenBalance: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFrozenBalance(v) + return nil + case wallet.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case wallet.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Wallet field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *WalletMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, wallet.FieldUserID) + } + if m.addversion != nil { + fields = append(fields, wallet.FieldVersion) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *WalletMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case wallet.FieldUserID: + return m.AddedUserID() + case wallet.FieldVersion: + return m.AddedVersion() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *WalletMutation) AddField(name string, value ent.Value) error { + switch name { + case wallet.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + case wallet.FieldVersion: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddVersion(v) + return nil + } + return fmt.Errorf("unknown Wallet numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *WalletMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *WalletMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *WalletMutation) ClearField(name string) error { + return fmt.Errorf("unknown Wallet nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *WalletMutation) ResetField(name string) error { + switch name { + case wallet.FieldUserID: + m.ResetUserID() + return nil + case wallet.FieldBalance: + m.ResetBalance() + return nil + case wallet.FieldFrozenBalance: + m.ResetFrozenBalance() + return nil + case wallet.FieldVersion: + m.ResetVersion() + return nil + case wallet.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Wallet field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *WalletMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *WalletMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *WalletMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *WalletMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *WalletMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *WalletMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *WalletMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Wallet unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *WalletMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Wallet edge %s", name) +} + +// WalletTransactionsMutation represents an operation that mutates the WalletTransactions nodes in the graph. +type WalletTransactionsMutation struct { + config + op Op + typ string + id *string + user_id *int64 + adduser_id *int64 + _type *string + amount *decimal.Decimal + balance_after *decimal.Decimal + description *[]string + appenddescription []string + order_id *int64 + addorder_id *int64 + created_at *time.Time + search_text *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*WalletTransactions, error) + predicates []predicate.WalletTransactions +} + +var _ ent.Mutation = (*WalletTransactionsMutation)(nil) + +// wallettransactionsOption allows management of the mutation configuration using functional options. +type wallettransactionsOption func(*WalletTransactionsMutation) + +// newWalletTransactionsMutation creates new mutation for the WalletTransactions entity. +func newWalletTransactionsMutation(c config, op Op, opts ...wallettransactionsOption) *WalletTransactionsMutation { + m := &WalletTransactionsMutation{ + config: c, + op: op, + typ: TypeWalletTransactions, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withWalletTransactionsID sets the ID field of the mutation. +func withWalletTransactionsID(id string) wallettransactionsOption { + return func(m *WalletTransactionsMutation) { + var ( + err error + once sync.Once + value *WalletTransactions + ) + m.oldValue = func(ctx context.Context) (*WalletTransactions, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().WalletTransactions.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withWalletTransactions sets the old WalletTransactions of the mutation. +func withWalletTransactions(node *WalletTransactions) wallettransactionsOption { + return func(m *WalletTransactionsMutation) { + m.oldValue = func(context.Context) (*WalletTransactions, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m WalletTransactionsMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m WalletTransactionsMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("models: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of WalletTransactions entities. +func (m *WalletTransactionsMutation) SetID(id string) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *WalletTransactionsMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *WalletTransactionsMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().WalletTransactions.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetUserID sets the "user_id" field. +func (m *WalletTransactionsMutation) SetUserID(i int64) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *WalletTransactionsMutation) UserID() (r int64, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldUserID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// AddUserID adds i to the "user_id" field. +func (m *WalletTransactionsMutation) AddUserID(i int64) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *WalletTransactionsMutation) AddedUserID() (r int64, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *WalletTransactionsMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetType sets the "type" field. +func (m *WalletTransactionsMutation) SetType(s string) { + m._type = &s +} + +// GetType returns the value of the "type" field in the mutation. +func (m *WalletTransactionsMutation) GetType() (r string, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil +} + +// ResetType resets all changes to the "type" field. +func (m *WalletTransactionsMutation) ResetType() { + m._type = nil +} + +// SetAmount sets the "amount" field. +func (m *WalletTransactionsMutation) SetAmount(d decimal.Decimal) { + m.amount = &d +} + +// Amount returns the value of the "amount" field in the mutation. +func (m *WalletTransactionsMutation) Amount() (r decimal.Decimal, exists bool) { + v := m.amount + if v == nil { + return + } + return *v, true +} + +// OldAmount returns the old "amount" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldAmount(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAmount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAmount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAmount: %w", err) + } + return oldValue.Amount, nil +} + +// ResetAmount resets all changes to the "amount" field. +func (m *WalletTransactionsMutation) ResetAmount() { + m.amount = nil +} + +// SetBalanceAfter sets the "balance_after" field. +func (m *WalletTransactionsMutation) SetBalanceAfter(d decimal.Decimal) { + m.balance_after = &d +} + +// BalanceAfter returns the value of the "balance_after" field in the mutation. +func (m *WalletTransactionsMutation) BalanceAfter() (r decimal.Decimal, exists bool) { + v := m.balance_after + if v == nil { + return + } + return *v, true +} + +// OldBalanceAfter returns the old "balance_after" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldBalanceAfter(ctx context.Context) (v decimal.Decimal, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBalanceAfter is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBalanceAfter requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBalanceAfter: %w", err) + } + return oldValue.BalanceAfter, nil +} + +// ResetBalanceAfter resets all changes to the "balance_after" field. +func (m *WalletTransactionsMutation) ResetBalanceAfter() { + m.balance_after = nil +} + +// SetDescription sets the "description" field. +func (m *WalletTransactionsMutation) SetDescription(s []string) { + m.description = &s + m.appenddescription = nil +} + +// Description returns the value of the "description" field in the mutation. +func (m *WalletTransactionsMutation) Description() (r []string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldDescription(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// AppendDescription adds s to the "description" field. +func (m *WalletTransactionsMutation) AppendDescription(s []string) { + m.appenddescription = append(m.appenddescription, s...) +} + +// AppendedDescription returns the list of values that were appended to the "description" field in this mutation. +func (m *WalletTransactionsMutation) AppendedDescription() ([]string, bool) { + if len(m.appenddescription) == 0 { + return nil, false + } + return m.appenddescription, true +} + +// ResetDescription resets all changes to the "description" field. +func (m *WalletTransactionsMutation) ResetDescription() { + m.description = nil + m.appenddescription = nil +} + +// SetOrderID sets the "order_id" field. +func (m *WalletTransactionsMutation) SetOrderID(i int64) { + m.order_id = &i + m.addorder_id = nil +} + +// OrderID returns the value of the "order_id" field in the mutation. +func (m *WalletTransactionsMutation) OrderID() (r int64, exists bool) { + v := m.order_id + if v == nil { + return + } + return *v, true +} + +// OldOrderID returns the old "order_id" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldOrderID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOrderID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOrderID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOrderID: %w", err) + } + return oldValue.OrderID, nil +} + +// AddOrderID adds i to the "order_id" field. +func (m *WalletTransactionsMutation) AddOrderID(i int64) { + if m.addorder_id != nil { + *m.addorder_id += i + } else { + m.addorder_id = &i + } +} + +// AddedOrderID returns the value that was added to the "order_id" field in this mutation. +func (m *WalletTransactionsMutation) AddedOrderID() (r int64, exists bool) { + v := m.addorder_id + if v == nil { + return + } + return *v, true +} + +// ResetOrderID resets all changes to the "order_id" field. +func (m *WalletTransactionsMutation) ResetOrderID() { + m.order_id = nil + m.addorder_id = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *WalletTransactionsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *WalletTransactionsMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *WalletTransactionsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetSearchText sets the "search_text" field. +func (m *WalletTransactionsMutation) SetSearchText(s string) { + m.search_text = &s +} + +// SearchText returns the value of the "search_text" field in the mutation. +func (m *WalletTransactionsMutation) SearchText() (r string, exists bool) { + v := m.search_text + if v == nil { + return + } + return *v, true +} + +// OldSearchText returns the old "search_text" field's value of the WalletTransactions entity. +// If the WalletTransactions object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WalletTransactionsMutation) OldSearchText(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSearchText is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSearchText requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSearchText: %w", err) + } + return oldValue.SearchText, nil +} + +// ResetSearchText resets all changes to the "search_text" field. +func (m *WalletTransactionsMutation) ResetSearchText() { + m.search_text = nil +} + +// Where appends a list predicates to the WalletTransactionsMutation builder. +func (m *WalletTransactionsMutation) Where(ps ...predicate.WalletTransactions) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the WalletTransactionsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *WalletTransactionsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.WalletTransactions, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *WalletTransactionsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *WalletTransactionsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (WalletTransactions). +func (m *WalletTransactionsMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *WalletTransactionsMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.user_id != nil { + fields = append(fields, wallettransactions.FieldUserID) + } + if m._type != nil { + fields = append(fields, wallettransactions.FieldType) + } + if m.amount != nil { + fields = append(fields, wallettransactions.FieldAmount) + } + if m.balance_after != nil { + fields = append(fields, wallettransactions.FieldBalanceAfter) + } + if m.description != nil { + fields = append(fields, wallettransactions.FieldDescription) + } + if m.order_id != nil { + fields = append(fields, wallettransactions.FieldOrderID) + } + if m.created_at != nil { + fields = append(fields, wallettransactions.FieldCreatedAt) + } + if m.search_text != nil { + fields = append(fields, wallettransactions.FieldSearchText) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *WalletTransactionsMutation) Field(name string) (ent.Value, bool) { + switch name { + case wallettransactions.FieldUserID: + return m.UserID() + case wallettransactions.FieldType: + return m.GetType() + case wallettransactions.FieldAmount: + return m.Amount() + case wallettransactions.FieldBalanceAfter: + return m.BalanceAfter() + case wallettransactions.FieldDescription: + return m.Description() + case wallettransactions.FieldOrderID: + return m.OrderID() + case wallettransactions.FieldCreatedAt: + return m.CreatedAt() + case wallettransactions.FieldSearchText: + return m.SearchText() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *WalletTransactionsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case wallettransactions.FieldUserID: + return m.OldUserID(ctx) + case wallettransactions.FieldType: + return m.OldType(ctx) + case wallettransactions.FieldAmount: + return m.OldAmount(ctx) + case wallettransactions.FieldBalanceAfter: + return m.OldBalanceAfter(ctx) + case wallettransactions.FieldDescription: + return m.OldDescription(ctx) + case wallettransactions.FieldOrderID: + return m.OldOrderID(ctx) + case wallettransactions.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case wallettransactions.FieldSearchText: + return m.OldSearchText(ctx) + } + return nil, fmt.Errorf("unknown WalletTransactions field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *WalletTransactionsMutation) SetField(name string, value ent.Value) error { + switch name { + case wallettransactions.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case wallettransactions.FieldType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case wallettransactions.FieldAmount: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAmount(v) + return nil + case wallettransactions.FieldBalanceAfter: + v, ok := value.(decimal.Decimal) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBalanceAfter(v) + return nil + case wallettransactions.FieldDescription: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case wallettransactions.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOrderID(v) + return nil + case wallettransactions.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case wallettransactions.FieldSearchText: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSearchText(v) + return nil + } + return fmt.Errorf("unknown WalletTransactions field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *WalletTransactionsMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, wallettransactions.FieldUserID) + } + if m.addorder_id != nil { + fields = append(fields, wallettransactions.FieldOrderID) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *WalletTransactionsMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case wallettransactions.FieldUserID: + return m.AddedUserID() + case wallettransactions.FieldOrderID: + return m.AddedOrderID() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *WalletTransactionsMutation) AddField(name string, value ent.Value) error { + switch name { + case wallettransactions.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + case wallettransactions.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOrderID(v) + return nil + } + return fmt.Errorf("unknown WalletTransactions numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *WalletTransactionsMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *WalletTransactionsMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *WalletTransactionsMutation) ClearField(name string) error { + return fmt.Errorf("unknown WalletTransactions nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *WalletTransactionsMutation) ResetField(name string) error { + switch name { + case wallettransactions.FieldUserID: + m.ResetUserID() + return nil + case wallettransactions.FieldType: + m.ResetType() + return nil + case wallettransactions.FieldAmount: + m.ResetAmount() + return nil + case wallettransactions.FieldBalanceAfter: + m.ResetBalanceAfter() + return nil + case wallettransactions.FieldDescription: + m.ResetDescription() + return nil + case wallettransactions.FieldOrderID: + m.ResetOrderID() + return nil + case wallettransactions.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case wallettransactions.FieldSearchText: + m.ResetSearchText() + return nil + } + return fmt.Errorf("unknown WalletTransactions field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *WalletTransactionsMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *WalletTransactionsMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *WalletTransactionsMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *WalletTransactionsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *WalletTransactionsMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *WalletTransactionsMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *WalletTransactionsMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown WalletTransactions unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *WalletTransactionsMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown WalletTransactions edge %s", name) +} diff --git a/app/wallet/rpc/internal/models/predicate/predicate.go b/app/wallet/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..8326d24 --- /dev/null +++ b/app/wallet/rpc/internal/models/predicate/predicate.go @@ -0,0 +1,13 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Wallet is the predicate function for wallet builders. +type Wallet func(*sql.Selector) + +// WalletTransactions is the predicate function for wallettransactions builders. +type WalletTransactions func(*sql.Selector) diff --git a/app/wallet/rpc/internal/models/runtime.go b/app/wallet/rpc/internal/models/runtime.go new file mode 100644 index 0000000..dc85cdf --- /dev/null +++ b/app/wallet/rpc/internal/models/runtime.go @@ -0,0 +1,30 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/wallet/rpc/internal/models/schema" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + + "github.com/shopspring/decimal" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + walletFields := schema.Wallet{}.Fields() + _ = walletFields + // walletDescBalance is the schema descriptor for balance field. + walletDescBalance := walletFields[1].Descriptor() + // wallet.DefaultBalance holds the default value on creation for the balance field. + wallet.DefaultBalance = walletDescBalance.Default.(decimal.Decimal) + // walletDescFrozenBalance is the schema descriptor for frozen_balance field. + walletDescFrozenBalance := walletFields[2].Descriptor() + // wallet.DefaultFrozenBalance holds the default value on creation for the frozen_balance field. + wallet.DefaultFrozenBalance = walletDescFrozenBalance.Default.(decimal.Decimal) + // walletDescVersion is the schema descriptor for version field. + walletDescVersion := walletFields[3].Descriptor() + // wallet.DefaultVersion holds the default value on creation for the version field. + wallet.DefaultVersion = walletDescVersion.Default.(int) +} diff --git a/app/wallet/rpc/internal/models/runtime/runtime.go b/app/wallet/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..0ec7a71 --- /dev/null +++ b/app/wallet/rpc/internal/models/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in juwan-backend/app/wallet/rpc/internal/models/runtime.go + +const ( + Version = "v0.14.5" // Version of ent codegen. + Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. +) diff --git a/app/wallet/rpc/internal/models/schema/wallet.go b/app/wallet/rpc/internal/models/schema/wallet.go new file mode 100644 index 0000000..7f770b6 --- /dev/null +++ b/app/wallet/rpc/internal/models/schema/wallet.go @@ -0,0 +1,39 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +var defalutBalance = decimal.RequireFromString("0.00") + +// Wallet holds the schema definition for the Wallet entity. +type Wallet struct { + ent.Schema +} + +// Fields of the Wallet. +func (Wallet) Fields() []ent.Field { + return []ent.Field{ + field.Int64("user_id").Immutable().Unique(), + field.Other("balance", decimal.Decimal{}). + Default(defalutBalance). + SchemaType(map[string]string{ + dialect.Postgres: "decimal(12,2)", + }), + field.Other("frozen_balance", decimal.Decimal{}). + Default(defalutBalance). + SchemaType(map[string]string{ + dialect.Postgres: "decimal(12,2)", + }), + field.Int("version").Default(1), + field.Time("updated_at"), + } +} + +// Edges of the Wallet. +func (Wallet) Edges() []ent.Edge { + return nil +} diff --git a/app/wallet/rpc/internal/models/schema/wallettransactions.go b/app/wallet/rpc/internal/models/schema/wallettransactions.go new file mode 100644 index 0000000..f8b5872 --- /dev/null +++ b/app/wallet/rpc/internal/models/schema/wallettransactions.go @@ -0,0 +1,39 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +// WalletTransactions holds the schema definition for the WalletTransactions entity. +type WalletTransactions struct { + ent.Schema +} + +// Fields of the WalletTransactions. +func (WalletTransactions) Fields() []ent.Field { + return []ent.Field{ + field.String("id").Immutable().Unique(), + field.Int64("user_id").Immutable().Unique(), + field.String("type"), + field.Other("amount", decimal.Decimal{}). + SchemaType(map[string]string{ + dialect.Postgres: "decimal(12,2", + }).Unique().Immutable(), + field.Other("balance_after", decimal.Decimal{}). + SchemaType(map[string]string{ + dialect.Postgres: "decimal(12,2)", + }).Unique().Immutable(), + field.Strings("description"), + field.Int64("order_id").Immutable().Unique(), + field.Time("created_at"), + field.String("search_text"), + } +} + +// Edges of the WalletTransactions. +func (WalletTransactions) Edges() []ent.Edge { + return nil +} diff --git a/app/wallet/rpc/internal/models/tx.go b/app/wallet/rpc/internal/models/tx.go new file mode 100644 index 0000000..52ce91c --- /dev/null +++ b/app/wallet/rpc/internal/models/tx.go @@ -0,0 +1,213 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Wallet is the client for interacting with the Wallet builders. + Wallet *WalletClient + // WalletTransactions is the client for interacting with the WalletTransactions builders. + WalletTransactions *WalletTransactionsClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Wallet = NewWalletClient(tx.config) + tx.WalletTransactions = NewWalletTransactionsClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Wallet.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/app/wallet/rpc/internal/models/wallet.go b/app/wallet/rpc/internal/models/wallet.go new file mode 100644 index 0000000..6f633be --- /dev/null +++ b/app/wallet/rpc/internal/models/wallet.go @@ -0,0 +1,151 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +// Wallet is the model entity for the Wallet schema. +type Wallet struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int64 `json:"user_id,omitempty"` + // Balance holds the value of the "balance" field. + Balance decimal.Decimal `json:"balance,omitempty"` + // FrozenBalance holds the value of the "frozen_balance" field. + FrozenBalance decimal.Decimal `json:"frozen_balance,omitempty"` + // Version holds the value of the "version" field. + Version int `json:"version,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Wallet) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case wallet.FieldBalance, wallet.FieldFrozenBalance: + values[i] = new(decimal.Decimal) + case wallet.FieldID, wallet.FieldUserID, wallet.FieldVersion: + values[i] = new(sql.NullInt64) + case wallet.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Wallet fields. +func (_m *Wallet) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case wallet.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case wallet.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = value.Int64 + } + case wallet.FieldBalance: + if value, ok := values[i].(*decimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field balance", values[i]) + } else if value != nil { + _m.Balance = *value + } + case wallet.FieldFrozenBalance: + if value, ok := values[i].(*decimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field frozen_balance", values[i]) + } else if value != nil { + _m.FrozenBalance = *value + } + case wallet.FieldVersion: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + _m.Version = int(value.Int64) + } + case wallet.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Wallet. +// This includes values selected through modifiers, order, etc. +func (_m *Wallet) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Wallet. +// Note that you need to call Wallet.Unwrap() before calling this method if this Wallet +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Wallet) Update() *WalletUpdateOne { + return NewWalletClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Wallet entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Wallet) Unwrap() *Wallet { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Wallet is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Wallet) String() string { + var builder strings.Builder + builder.WriteString("Wallet(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("balance=") + builder.WriteString(fmt.Sprintf("%v", _m.Balance)) + builder.WriteString(", ") + builder.WriteString("frozen_balance=") + builder.WriteString(fmt.Sprintf("%v", _m.FrozenBalance)) + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(fmt.Sprintf("%v", _m.Version)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// Wallets is a parsable slice of Wallet. +type Wallets []*Wallet diff --git a/app/wallet/rpc/internal/models/wallet/wallet.go b/app/wallet/rpc/internal/models/wallet/wallet.go new file mode 100644 index 0000000..d79f0f0 --- /dev/null +++ b/app/wallet/rpc/internal/models/wallet/wallet.go @@ -0,0 +1,89 @@ +// Code generated by ent, DO NOT EDIT. + +package wallet + +import ( + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +const ( + // Label holds the string label denoting the wallet type in the database. + Label = "wallet" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldBalance holds the string denoting the balance field in the database. + FieldBalance = "balance" + // FieldFrozenBalance holds the string denoting the frozen_balance field in the database. + FieldFrozenBalance = "frozen_balance" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // Table holds the table name of the wallet in the database. + Table = "wallets" +) + +// Columns holds all SQL columns for wallet fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldBalance, + FieldFrozenBalance, + FieldVersion, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultBalance holds the default value on creation for the "balance" field. + DefaultBalance decimal.Decimal + // DefaultFrozenBalance holds the default value on creation for the "frozen_balance" field. + DefaultFrozenBalance decimal.Decimal + // DefaultVersion holds the default value on creation for the "version" field. + DefaultVersion int +) + +// OrderOption defines the ordering options for the Wallet queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByBalance orders the results by the balance field. +func ByBalance(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBalance, opts...).ToFunc() +} + +// ByFrozenBalance orders the results by the frozen_balance field. +func ByFrozenBalance(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFrozenBalance, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} diff --git a/app/wallet/rpc/internal/models/wallet/where.go b/app/wallet/rpc/internal/models/wallet/where.go new file mode 100644 index 0000000..83b527e --- /dev/null +++ b/app/wallet/rpc/internal/models/wallet/where.go @@ -0,0 +1,296 @@ +// Code generated by ent, DO NOT EDIT. + +package wallet + +import ( + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Wallet { + return predicate.Wallet(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Wallet { + return predicate.Wallet(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Wallet { + return predicate.Wallet(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Wallet { + return predicate.Wallet(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Wallet { + return predicate.Wallet(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Wallet { + return predicate.Wallet(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Wallet { + return predicate.Wallet(sql.FieldLTE(FieldID, id)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldUserID, v)) +} + +// Balance applies equality check predicate on the "balance" field. It's identical to BalanceEQ. +func Balance(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldBalance, v)) +} + +// FrozenBalance applies equality check predicate on the "frozen_balance" field. It's identical to FrozenBalanceEQ. +func FrozenBalance(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldFrozenBalance, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v int) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldVersion, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.Wallet { + return predicate.Wallet(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.Wallet { + return predicate.Wallet(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.Wallet { + return predicate.Wallet(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int64) predicate.Wallet { + return predicate.Wallet(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int64) predicate.Wallet { + return predicate.Wallet(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int64) predicate.Wallet { + return predicate.Wallet(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int64) predicate.Wallet { + return predicate.Wallet(sql.FieldLTE(FieldUserID, v)) +} + +// BalanceEQ applies the EQ predicate on the "balance" field. +func BalanceEQ(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldBalance, v)) +} + +// BalanceNEQ applies the NEQ predicate on the "balance" field. +func BalanceNEQ(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldNEQ(FieldBalance, v)) +} + +// BalanceIn applies the In predicate on the "balance" field. +func BalanceIn(vs ...decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldIn(FieldBalance, vs...)) +} + +// BalanceNotIn applies the NotIn predicate on the "balance" field. +func BalanceNotIn(vs ...decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldNotIn(FieldBalance, vs...)) +} + +// BalanceGT applies the GT predicate on the "balance" field. +func BalanceGT(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldGT(FieldBalance, v)) +} + +// BalanceGTE applies the GTE predicate on the "balance" field. +func BalanceGTE(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldGTE(FieldBalance, v)) +} + +// BalanceLT applies the LT predicate on the "balance" field. +func BalanceLT(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldLT(FieldBalance, v)) +} + +// BalanceLTE applies the LTE predicate on the "balance" field. +func BalanceLTE(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldLTE(FieldBalance, v)) +} + +// FrozenBalanceEQ applies the EQ predicate on the "frozen_balance" field. +func FrozenBalanceEQ(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldFrozenBalance, v)) +} + +// FrozenBalanceNEQ applies the NEQ predicate on the "frozen_balance" field. +func FrozenBalanceNEQ(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldNEQ(FieldFrozenBalance, v)) +} + +// FrozenBalanceIn applies the In predicate on the "frozen_balance" field. +func FrozenBalanceIn(vs ...decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldIn(FieldFrozenBalance, vs...)) +} + +// FrozenBalanceNotIn applies the NotIn predicate on the "frozen_balance" field. +func FrozenBalanceNotIn(vs ...decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldNotIn(FieldFrozenBalance, vs...)) +} + +// FrozenBalanceGT applies the GT predicate on the "frozen_balance" field. +func FrozenBalanceGT(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldGT(FieldFrozenBalance, v)) +} + +// FrozenBalanceGTE applies the GTE predicate on the "frozen_balance" field. +func FrozenBalanceGTE(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldGTE(FieldFrozenBalance, v)) +} + +// FrozenBalanceLT applies the LT predicate on the "frozen_balance" field. +func FrozenBalanceLT(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldLT(FieldFrozenBalance, v)) +} + +// FrozenBalanceLTE applies the LTE predicate on the "frozen_balance" field. +func FrozenBalanceLTE(v decimal.Decimal) predicate.Wallet { + return predicate.Wallet(sql.FieldLTE(FieldFrozenBalance, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v int) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v int) predicate.Wallet { + return predicate.Wallet(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...int) predicate.Wallet { + return predicate.Wallet(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...int) predicate.Wallet { + return predicate.Wallet(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v int) predicate.Wallet { + return predicate.Wallet(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v int) predicate.Wallet { + return predicate.Wallet(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v int) predicate.Wallet { + return predicate.Wallet(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v int) predicate.Wallet { + return predicate.Wallet(sql.FieldLTE(FieldVersion, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Wallet { + return predicate.Wallet(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Wallet) predicate.Wallet { + return predicate.Wallet(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Wallet) predicate.Wallet { + return predicate.Wallet(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Wallet) predicate.Wallet { + return predicate.Wallet(sql.NotPredicates(p)) +} diff --git a/app/wallet/rpc/internal/models/wallet_create.go b/app/wallet/rpc/internal/models/wallet_create.go new file mode 100644 index 0000000..943bdb6 --- /dev/null +++ b/app/wallet/rpc/internal/models/wallet_create.go @@ -0,0 +1,279 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +// WalletCreate is the builder for creating a Wallet entity. +type WalletCreate struct { + config + mutation *WalletMutation + hooks []Hook +} + +// SetUserID sets the "user_id" field. +func (_c *WalletCreate) SetUserID(v int64) *WalletCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetBalance sets the "balance" field. +func (_c *WalletCreate) SetBalance(v decimal.Decimal) *WalletCreate { + _c.mutation.SetBalance(v) + return _c +} + +// SetNillableBalance sets the "balance" field if the given value is not nil. +func (_c *WalletCreate) SetNillableBalance(v *decimal.Decimal) *WalletCreate { + if v != nil { + _c.SetBalance(*v) + } + return _c +} + +// SetFrozenBalance sets the "frozen_balance" field. +func (_c *WalletCreate) SetFrozenBalance(v decimal.Decimal) *WalletCreate { + _c.mutation.SetFrozenBalance(v) + return _c +} + +// SetNillableFrozenBalance sets the "frozen_balance" field if the given value is not nil. +func (_c *WalletCreate) SetNillableFrozenBalance(v *decimal.Decimal) *WalletCreate { + if v != nil { + _c.SetFrozenBalance(*v) + } + return _c +} + +// SetVersion sets the "version" field. +func (_c *WalletCreate) SetVersion(v int) *WalletCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_c *WalletCreate) SetNillableVersion(v *int) *WalletCreate { + if v != nil { + _c.SetVersion(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *WalletCreate) SetUpdatedAt(v time.Time) *WalletCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// Mutation returns the WalletMutation object of the builder. +func (_c *WalletCreate) Mutation() *WalletMutation { + return _c.mutation +} + +// Save creates the Wallet in the database. +func (_c *WalletCreate) Save(ctx context.Context) (*Wallet, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *WalletCreate) SaveX(ctx context.Context) *Wallet { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *WalletCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *WalletCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *WalletCreate) defaults() { + if _, ok := _c.mutation.Balance(); !ok { + v := wallet.DefaultBalance + _c.mutation.SetBalance(v) + } + if _, ok := _c.mutation.FrozenBalance(); !ok { + v := wallet.DefaultFrozenBalance + _c.mutation.SetFrozenBalance(v) + } + if _, ok := _c.mutation.Version(); !ok { + v := wallet.DefaultVersion + _c.mutation.SetVersion(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *WalletCreate) check() error { + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "Wallet.user_id"`)} + } + if _, ok := _c.mutation.Balance(); !ok { + return &ValidationError{Name: "balance", err: errors.New(`models: missing required field "Wallet.balance"`)} + } + if _, ok := _c.mutation.FrozenBalance(); !ok { + return &ValidationError{Name: "frozen_balance", err: errors.New(`models: missing required field "Wallet.frozen_balance"`)} + } + if _, ok := _c.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`models: missing required field "Wallet.version"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Wallet.updated_at"`)} + } + return nil +} + +func (_c *WalletCreate) sqlSave(ctx context.Context) (*Wallet, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *WalletCreate) createSpec() (*Wallet, *sqlgraph.CreateSpec) { + var ( + _node = &Wallet{config: _c.config} + _spec = sqlgraph.NewCreateSpec(wallet.Table, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(wallet.FieldUserID, field.TypeInt64, value) + _node.UserID = value + } + if value, ok := _c.mutation.Balance(); ok { + _spec.SetField(wallet.FieldBalance, field.TypeOther, value) + _node.Balance = value + } + if value, ok := _c.mutation.FrozenBalance(); ok { + _spec.SetField(wallet.FieldFrozenBalance, field.TypeOther, value) + _node.FrozenBalance = value + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(wallet.FieldVersion, field.TypeInt, value) + _node.Version = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(wallet.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + return _node, _spec +} + +// WalletCreateBulk is the builder for creating many Wallet entities in bulk. +type WalletCreateBulk struct { + config + err error + builders []*WalletCreate +} + +// Save creates the Wallet entities in the database. +func (_c *WalletCreateBulk) Save(ctx context.Context) ([]*Wallet, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Wallet, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*WalletMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *WalletCreateBulk) SaveX(ctx context.Context) []*Wallet { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *WalletCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *WalletCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/wallet/rpc/internal/models/wallet_delete.go b/app/wallet/rpc/internal/models/wallet_delete.go new file mode 100644 index 0000000..07dc1c1 --- /dev/null +++ b/app/wallet/rpc/internal/models/wallet_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WalletDelete is the builder for deleting a Wallet entity. +type WalletDelete struct { + config + hooks []Hook + mutation *WalletMutation +} + +// Where appends a list predicates to the WalletDelete builder. +func (_d *WalletDelete) Where(ps ...predicate.Wallet) *WalletDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *WalletDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *WalletDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *WalletDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(wallet.Table, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// WalletDeleteOne is the builder for deleting a single Wallet entity. +type WalletDeleteOne struct { + _d *WalletDelete +} + +// Where appends a list predicates to the WalletDelete builder. +func (_d *WalletDeleteOne) Where(ps ...predicate.Wallet) *WalletDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *WalletDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{wallet.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *WalletDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/wallet/rpc/internal/models/wallet_query.go b/app/wallet/rpc/internal/models/wallet_query.go new file mode 100644 index 0000000..3902f0d --- /dev/null +++ b/app/wallet/rpc/internal/models/wallet_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WalletQuery is the builder for querying Wallet entities. +type WalletQuery struct { + config + ctx *QueryContext + order []wallet.OrderOption + inters []Interceptor + predicates []predicate.Wallet + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the WalletQuery builder. +func (_q *WalletQuery) Where(ps ...predicate.Wallet) *WalletQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *WalletQuery) Limit(limit int) *WalletQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *WalletQuery) Offset(offset int) *WalletQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *WalletQuery) Unique(unique bool) *WalletQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *WalletQuery) Order(o ...wallet.OrderOption) *WalletQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Wallet entity from the query. +// Returns a *NotFoundError when no Wallet was found. +func (_q *WalletQuery) First(ctx context.Context) (*Wallet, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{wallet.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *WalletQuery) FirstX(ctx context.Context) *Wallet { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Wallet ID from the query. +// Returns a *NotFoundError when no Wallet ID was found. +func (_q *WalletQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{wallet.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *WalletQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Wallet entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Wallet entity is found. +// Returns a *NotFoundError when no Wallet entities are found. +func (_q *WalletQuery) Only(ctx context.Context) (*Wallet, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{wallet.Label} + default: + return nil, &NotSingularError{wallet.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *WalletQuery) OnlyX(ctx context.Context) *Wallet { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Wallet ID in the query. +// Returns a *NotSingularError when more than one Wallet ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *WalletQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{wallet.Label} + default: + err = &NotSingularError{wallet.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *WalletQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Wallets. +func (_q *WalletQuery) All(ctx context.Context) ([]*Wallet, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Wallet, *WalletQuery]() + return withInterceptors[[]*Wallet](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *WalletQuery) AllX(ctx context.Context) []*Wallet { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Wallet IDs. +func (_q *WalletQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(wallet.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *WalletQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *WalletQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*WalletQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *WalletQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *WalletQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *WalletQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the WalletQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *WalletQuery) Clone() *WalletQuery { + if _q == nil { + return nil + } + return &WalletQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]wallet.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Wallet{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// UserID int64 `json:"user_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Wallet.Query(). +// GroupBy(wallet.FieldUserID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *WalletQuery) GroupBy(field string, fields ...string) *WalletGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &WalletGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = wallet.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// UserID int64 `json:"user_id,omitempty"` +// } +// +// client.Wallet.Query(). +// Select(wallet.FieldUserID). +// Scan(ctx, &v) +func (_q *WalletQuery) Select(fields ...string) *WalletSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &WalletSelect{WalletQuery: _q} + sbuild.label = wallet.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a WalletSelect configured with the given aggregations. +func (_q *WalletQuery) Aggregate(fns ...AggregateFunc) *WalletSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *WalletQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !wallet.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *WalletQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Wallet, error) { + var ( + nodes = []*Wallet{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Wallet).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Wallet{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *WalletQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *WalletQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(wallet.Table, wallet.Columns, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, wallet.FieldID) + for i := range fields { + if fields[i] != wallet.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *WalletQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(wallet.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = wallet.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// WalletGroupBy is the group-by builder for Wallet entities. +type WalletGroupBy struct { + selector + build *WalletQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *WalletGroupBy) Aggregate(fns ...AggregateFunc) *WalletGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *WalletGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WalletQuery, *WalletGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *WalletGroupBy) sqlScan(ctx context.Context, root *WalletQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// WalletSelect is the builder for selecting fields of Wallet entities. +type WalletSelect struct { + *WalletQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *WalletSelect) Aggregate(fns ...AggregateFunc) *WalletSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *WalletSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WalletQuery, *WalletSelect](ctx, _s.WalletQuery, _s, _s.inters, v) +} + +func (_s *WalletSelect) sqlScan(ctx context.Context, root *WalletQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/wallet/rpc/internal/models/wallet_update.go b/app/wallet/rpc/internal/models/wallet_update.go new file mode 100644 index 0000000..8a0a8a1 --- /dev/null +++ b/app/wallet/rpc/internal/models/wallet_update.go @@ -0,0 +1,333 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallet" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +// WalletUpdate is the builder for updating Wallet entities. +type WalletUpdate struct { + config + hooks []Hook + mutation *WalletMutation +} + +// Where appends a list predicates to the WalletUpdate builder. +func (_u *WalletUpdate) Where(ps ...predicate.Wallet) *WalletUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetBalance sets the "balance" field. +func (_u *WalletUpdate) SetBalance(v decimal.Decimal) *WalletUpdate { + _u.mutation.SetBalance(v) + return _u +} + +// SetNillableBalance sets the "balance" field if the given value is not nil. +func (_u *WalletUpdate) SetNillableBalance(v *decimal.Decimal) *WalletUpdate { + if v != nil { + _u.SetBalance(*v) + } + return _u +} + +// SetFrozenBalance sets the "frozen_balance" field. +func (_u *WalletUpdate) SetFrozenBalance(v decimal.Decimal) *WalletUpdate { + _u.mutation.SetFrozenBalance(v) + return _u +} + +// SetNillableFrozenBalance sets the "frozen_balance" field if the given value is not nil. +func (_u *WalletUpdate) SetNillableFrozenBalance(v *decimal.Decimal) *WalletUpdate { + if v != nil { + _u.SetFrozenBalance(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *WalletUpdate) SetVersion(v int) *WalletUpdate { + _u.mutation.ResetVersion() + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *WalletUpdate) SetNillableVersion(v *int) *WalletUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// AddVersion adds value to the "version" field. +func (_u *WalletUpdate) AddVersion(v int) *WalletUpdate { + _u.mutation.AddVersion(v) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *WalletUpdate) SetUpdatedAt(v time.Time) *WalletUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_u *WalletUpdate) SetNillableUpdatedAt(v *time.Time) *WalletUpdate { + if v != nil { + _u.SetUpdatedAt(*v) + } + return _u +} + +// Mutation returns the WalletMutation object of the builder. +func (_u *WalletUpdate) Mutation() *WalletMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *WalletUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *WalletUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *WalletUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *WalletUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *WalletUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(wallet.Table, wallet.Columns, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Balance(); ok { + _spec.SetField(wallet.FieldBalance, field.TypeOther, value) + } + if value, ok := _u.mutation.FrozenBalance(); ok { + _spec.SetField(wallet.FieldFrozenBalance, field.TypeOther, value) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(wallet.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedVersion(); ok { + _spec.AddField(wallet.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(wallet.FieldUpdatedAt, field.TypeTime, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{wallet.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// WalletUpdateOne is the builder for updating a single Wallet entity. +type WalletUpdateOne struct { + config + fields []string + hooks []Hook + mutation *WalletMutation +} + +// SetBalance sets the "balance" field. +func (_u *WalletUpdateOne) SetBalance(v decimal.Decimal) *WalletUpdateOne { + _u.mutation.SetBalance(v) + return _u +} + +// SetNillableBalance sets the "balance" field if the given value is not nil. +func (_u *WalletUpdateOne) SetNillableBalance(v *decimal.Decimal) *WalletUpdateOne { + if v != nil { + _u.SetBalance(*v) + } + return _u +} + +// SetFrozenBalance sets the "frozen_balance" field. +func (_u *WalletUpdateOne) SetFrozenBalance(v decimal.Decimal) *WalletUpdateOne { + _u.mutation.SetFrozenBalance(v) + return _u +} + +// SetNillableFrozenBalance sets the "frozen_balance" field if the given value is not nil. +func (_u *WalletUpdateOne) SetNillableFrozenBalance(v *decimal.Decimal) *WalletUpdateOne { + if v != nil { + _u.SetFrozenBalance(*v) + } + return _u +} + +// SetVersion sets the "version" field. +func (_u *WalletUpdateOne) SetVersion(v int) *WalletUpdateOne { + _u.mutation.ResetVersion() + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *WalletUpdateOne) SetNillableVersion(v *int) *WalletUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// AddVersion adds value to the "version" field. +func (_u *WalletUpdateOne) AddVersion(v int) *WalletUpdateOne { + _u.mutation.AddVersion(v) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *WalletUpdateOne) SetUpdatedAt(v time.Time) *WalletUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_u *WalletUpdateOne) SetNillableUpdatedAt(v *time.Time) *WalletUpdateOne { + if v != nil { + _u.SetUpdatedAt(*v) + } + return _u +} + +// Mutation returns the WalletMutation object of the builder. +func (_u *WalletUpdateOne) Mutation() *WalletMutation { + return _u.mutation +} + +// Where appends a list predicates to the WalletUpdate builder. +func (_u *WalletUpdateOne) Where(ps ...predicate.Wallet) *WalletUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *WalletUpdateOne) Select(field string, fields ...string) *WalletUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Wallet entity. +func (_u *WalletUpdateOne) Save(ctx context.Context) (*Wallet, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *WalletUpdateOne) SaveX(ctx context.Context) *Wallet { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *WalletUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *WalletUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *WalletUpdateOne) sqlSave(ctx context.Context) (_node *Wallet, err error) { + _spec := sqlgraph.NewUpdateSpec(wallet.Table, wallet.Columns, sqlgraph.NewFieldSpec(wallet.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Wallet.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, wallet.FieldID) + for _, f := range fields { + if !wallet.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != wallet.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Balance(); ok { + _spec.SetField(wallet.FieldBalance, field.TypeOther, value) + } + if value, ok := _u.mutation.FrozenBalance(); ok { + _spec.SetField(wallet.FieldFrozenBalance, field.TypeOther, value) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(wallet.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedVersion(); ok { + _spec.AddField(wallet.FieldVersion, field.TypeInt, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(wallet.FieldUpdatedAt, field.TypeTime, value) + } + _node = &Wallet{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{wallet.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/wallet/rpc/internal/models/wallettransactions.go b/app/wallet/rpc/internal/models/wallettransactions.go new file mode 100644 index 0000000..fdf8e3d --- /dev/null +++ b/app/wallet/rpc/internal/models/wallettransactions.go @@ -0,0 +1,191 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +// WalletTransactions is the model entity for the WalletTransactions schema. +type WalletTransactions struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int64 `json:"user_id,omitempty"` + // Type holds the value of the "type" field. + Type string `json:"type,omitempty"` + // Amount holds the value of the "amount" field. + Amount decimal.Decimal `json:"amount,omitempty"` + // BalanceAfter holds the value of the "balance_after" field. + BalanceAfter decimal.Decimal `json:"balance_after,omitempty"` + // Description holds the value of the "description" field. + Description []string `json:"description,omitempty"` + // OrderID holds the value of the "order_id" field. + OrderID int64 `json:"order_id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // SearchText holds the value of the "search_text" field. + SearchText string `json:"search_text,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*WalletTransactions) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case wallettransactions.FieldDescription: + values[i] = new([]byte) + case wallettransactions.FieldAmount, wallettransactions.FieldBalanceAfter: + values[i] = new(decimal.Decimal) + case wallettransactions.FieldUserID, wallettransactions.FieldOrderID: + values[i] = new(sql.NullInt64) + case wallettransactions.FieldID, wallettransactions.FieldType, wallettransactions.FieldSearchText: + values[i] = new(sql.NullString) + case wallettransactions.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the WalletTransactions fields. +func (_m *WalletTransactions) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case wallettransactions.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case wallettransactions.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = value.Int64 + } + case wallettransactions.FieldType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + _m.Type = value.String + } + case wallettransactions.FieldAmount: + if value, ok := values[i].(*decimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field amount", values[i]) + } else if value != nil { + _m.Amount = *value + } + case wallettransactions.FieldBalanceAfter: + if value, ok := values[i].(*decimal.Decimal); !ok { + return fmt.Errorf("unexpected type %T for field balance_after", values[i]) + } else if value != nil { + _m.BalanceAfter = *value + } + case wallettransactions.FieldDescription: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Description); err != nil { + return fmt.Errorf("unmarshal field description: %w", err) + } + } + case wallettransactions.FieldOrderID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field order_id", values[i]) + } else if value.Valid { + _m.OrderID = value.Int64 + } + case wallettransactions.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case wallettransactions.FieldSearchText: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field search_text", values[i]) + } else if value.Valid { + _m.SearchText = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the WalletTransactions. +// This includes values selected through modifiers, order, etc. +func (_m *WalletTransactions) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this WalletTransactions. +// Note that you need to call WalletTransactions.Unwrap() before calling this method if this WalletTransactions +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *WalletTransactions) Update() *WalletTransactionsUpdateOne { + return NewWalletTransactionsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the WalletTransactions entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *WalletTransactions) Unwrap() *WalletTransactions { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: WalletTransactions is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *WalletTransactions) String() string { + var builder strings.Builder + builder.WriteString("WalletTransactions(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(_m.Type) + builder.WriteString(", ") + builder.WriteString("amount=") + builder.WriteString(fmt.Sprintf("%v", _m.Amount)) + builder.WriteString(", ") + builder.WriteString("balance_after=") + builder.WriteString(fmt.Sprintf("%v", _m.BalanceAfter)) + builder.WriteString(", ") + builder.WriteString("description=") + builder.WriteString(fmt.Sprintf("%v", _m.Description)) + builder.WriteString(", ") + builder.WriteString("order_id=") + builder.WriteString(fmt.Sprintf("%v", _m.OrderID)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("search_text=") + builder.WriteString(_m.SearchText) + builder.WriteByte(')') + return builder.String() +} + +// WalletTransactionsSlice is a parsable slice of WalletTransactions. +type WalletTransactionsSlice []*WalletTransactions diff --git a/app/wallet/rpc/internal/models/wallettransactions/wallettransactions.go b/app/wallet/rpc/internal/models/wallettransactions/wallettransactions.go new file mode 100644 index 0000000..1c82a7f --- /dev/null +++ b/app/wallet/rpc/internal/models/wallettransactions/wallettransactions.go @@ -0,0 +1,98 @@ +// Code generated by ent, DO NOT EDIT. + +package wallettransactions + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the wallettransactions type in the database. + Label = "wallet_transactions" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldAmount holds the string denoting the amount field in the database. + FieldAmount = "amount" + // FieldBalanceAfter holds the string denoting the balance_after field in the database. + FieldBalanceAfter = "balance_after" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldOrderID holds the string denoting the order_id field in the database. + FieldOrderID = "order_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldSearchText holds the string denoting the search_text field in the database. + FieldSearchText = "search_text" + // Table holds the table name of the wallettransactions in the database. + Table = "wallet_transactions" +) + +// Columns holds all SQL columns for wallettransactions fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldType, + FieldAmount, + FieldBalanceAfter, + FieldDescription, + FieldOrderID, + FieldCreatedAt, + FieldSearchText, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the WalletTransactions queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByAmount orders the results by the amount field. +func ByAmount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAmount, opts...).ToFunc() +} + +// ByBalanceAfter orders the results by the balance_after field. +func ByBalanceAfter(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBalanceAfter, opts...).ToFunc() +} + +// ByOrderID orders the results by the order_id field. +func ByOrderID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOrderID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// BySearchText orders the results by the search_text field. +func BySearchText(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSearchText, opts...).ToFunc() +} diff --git a/app/wallet/rpc/internal/models/wallettransactions/where.go b/app/wallet/rpc/internal/models/wallettransactions/where.go new file mode 100644 index 0000000..2fab64b --- /dev/null +++ b/app/wallet/rpc/internal/models/wallettransactions/where.go @@ -0,0 +1,446 @@ +// Code generated by ent, DO NOT EDIT. + +package wallettransactions + +import ( + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/shopspring/decimal" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldContainsFold(FieldID, id)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldUserID, v)) +} + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldType, v)) +} + +// Amount applies equality check predicate on the "amount" field. It's identical to AmountEQ. +func Amount(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldAmount, v)) +} + +// BalanceAfter applies equality check predicate on the "balance_after" field. It's identical to BalanceAfterEQ. +func BalanceAfter(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldBalanceAfter, v)) +} + +// OrderID applies equality check predicate on the "order_id" field. It's identical to OrderIDEQ. +func OrderID(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldOrderID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldCreatedAt, v)) +} + +// SearchText applies equality check predicate on the "search_text" field. It's identical to SearchTextEQ. +func SearchText(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldSearchText, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldUserID, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldType, v)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldType, v)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldType, vs...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldType, vs...)) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldType, v)) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldType, v)) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldType, v)) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldType, v)) +} + +// TypeContains applies the Contains predicate on the "type" field. +func TypeContains(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldContains(FieldType, v)) +} + +// TypeHasPrefix applies the HasPrefix predicate on the "type" field. +func TypeHasPrefix(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldHasPrefix(FieldType, v)) +} + +// TypeHasSuffix applies the HasSuffix predicate on the "type" field. +func TypeHasSuffix(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldHasSuffix(FieldType, v)) +} + +// TypeEqualFold applies the EqualFold predicate on the "type" field. +func TypeEqualFold(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEqualFold(FieldType, v)) +} + +// TypeContainsFold applies the ContainsFold predicate on the "type" field. +func TypeContainsFold(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldContainsFold(FieldType, v)) +} + +// AmountEQ applies the EQ predicate on the "amount" field. +func AmountEQ(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldAmount, v)) +} + +// AmountNEQ applies the NEQ predicate on the "amount" field. +func AmountNEQ(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldAmount, v)) +} + +// AmountIn applies the In predicate on the "amount" field. +func AmountIn(vs ...decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldAmount, vs...)) +} + +// AmountNotIn applies the NotIn predicate on the "amount" field. +func AmountNotIn(vs ...decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldAmount, vs...)) +} + +// AmountGT applies the GT predicate on the "amount" field. +func AmountGT(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldAmount, v)) +} + +// AmountGTE applies the GTE predicate on the "amount" field. +func AmountGTE(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldAmount, v)) +} + +// AmountLT applies the LT predicate on the "amount" field. +func AmountLT(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldAmount, v)) +} + +// AmountLTE applies the LTE predicate on the "amount" field. +func AmountLTE(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldAmount, v)) +} + +// BalanceAfterEQ applies the EQ predicate on the "balance_after" field. +func BalanceAfterEQ(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldBalanceAfter, v)) +} + +// BalanceAfterNEQ applies the NEQ predicate on the "balance_after" field. +func BalanceAfterNEQ(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldBalanceAfter, v)) +} + +// BalanceAfterIn applies the In predicate on the "balance_after" field. +func BalanceAfterIn(vs ...decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldBalanceAfter, vs...)) +} + +// BalanceAfterNotIn applies the NotIn predicate on the "balance_after" field. +func BalanceAfterNotIn(vs ...decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldBalanceAfter, vs...)) +} + +// BalanceAfterGT applies the GT predicate on the "balance_after" field. +func BalanceAfterGT(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldBalanceAfter, v)) +} + +// BalanceAfterGTE applies the GTE predicate on the "balance_after" field. +func BalanceAfterGTE(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldBalanceAfter, v)) +} + +// BalanceAfterLT applies the LT predicate on the "balance_after" field. +func BalanceAfterLT(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldBalanceAfter, v)) +} + +// BalanceAfterLTE applies the LTE predicate on the "balance_after" field. +func BalanceAfterLTE(v decimal.Decimal) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldBalanceAfter, v)) +} + +// OrderIDEQ applies the EQ predicate on the "order_id" field. +func OrderIDEQ(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldOrderID, v)) +} + +// OrderIDNEQ applies the NEQ predicate on the "order_id" field. +func OrderIDNEQ(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldOrderID, v)) +} + +// OrderIDIn applies the In predicate on the "order_id" field. +func OrderIDIn(vs ...int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldOrderID, vs...)) +} + +// OrderIDNotIn applies the NotIn predicate on the "order_id" field. +func OrderIDNotIn(vs ...int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldOrderID, vs...)) +} + +// OrderIDGT applies the GT predicate on the "order_id" field. +func OrderIDGT(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldOrderID, v)) +} + +// OrderIDGTE applies the GTE predicate on the "order_id" field. +func OrderIDGTE(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldOrderID, v)) +} + +// OrderIDLT applies the LT predicate on the "order_id" field. +func OrderIDLT(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldOrderID, v)) +} + +// OrderIDLTE applies the LTE predicate on the "order_id" field. +func OrderIDLTE(v int64) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldOrderID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldCreatedAt, v)) +} + +// SearchTextEQ applies the EQ predicate on the "search_text" field. +func SearchTextEQ(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEQ(FieldSearchText, v)) +} + +// SearchTextNEQ applies the NEQ predicate on the "search_text" field. +func SearchTextNEQ(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNEQ(FieldSearchText, v)) +} + +// SearchTextIn applies the In predicate on the "search_text" field. +func SearchTextIn(vs ...string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldIn(FieldSearchText, vs...)) +} + +// SearchTextNotIn applies the NotIn predicate on the "search_text" field. +func SearchTextNotIn(vs ...string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldNotIn(FieldSearchText, vs...)) +} + +// SearchTextGT applies the GT predicate on the "search_text" field. +func SearchTextGT(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGT(FieldSearchText, v)) +} + +// SearchTextGTE applies the GTE predicate on the "search_text" field. +func SearchTextGTE(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldGTE(FieldSearchText, v)) +} + +// SearchTextLT applies the LT predicate on the "search_text" field. +func SearchTextLT(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLT(FieldSearchText, v)) +} + +// SearchTextLTE applies the LTE predicate on the "search_text" field. +func SearchTextLTE(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldLTE(FieldSearchText, v)) +} + +// SearchTextContains applies the Contains predicate on the "search_text" field. +func SearchTextContains(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldContains(FieldSearchText, v)) +} + +// SearchTextHasPrefix applies the HasPrefix predicate on the "search_text" field. +func SearchTextHasPrefix(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldHasPrefix(FieldSearchText, v)) +} + +// SearchTextHasSuffix applies the HasSuffix predicate on the "search_text" field. +func SearchTextHasSuffix(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldHasSuffix(FieldSearchText, v)) +} + +// SearchTextEqualFold applies the EqualFold predicate on the "search_text" field. +func SearchTextEqualFold(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldEqualFold(FieldSearchText, v)) +} + +// SearchTextContainsFold applies the ContainsFold predicate on the "search_text" field. +func SearchTextContainsFold(v string) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.FieldContainsFold(FieldSearchText, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.WalletTransactions) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.WalletTransactions) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.WalletTransactions) predicate.WalletTransactions { + return predicate.WalletTransactions(sql.NotPredicates(p)) +} diff --git a/app/wallet/rpc/internal/models/wallettransactions_create.go b/app/wallet/rpc/internal/models/wallettransactions_create.go new file mode 100644 index 0000000..6391e6b --- /dev/null +++ b/app/wallet/rpc/internal/models/wallettransactions_create.go @@ -0,0 +1,287 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/shopspring/decimal" +) + +// WalletTransactionsCreate is the builder for creating a WalletTransactions entity. +type WalletTransactionsCreate struct { + config + mutation *WalletTransactionsMutation + hooks []Hook +} + +// SetUserID sets the "user_id" field. +func (_c *WalletTransactionsCreate) SetUserID(v int64) *WalletTransactionsCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetType sets the "type" field. +func (_c *WalletTransactionsCreate) SetType(v string) *WalletTransactionsCreate { + _c.mutation.SetType(v) + return _c +} + +// SetAmount sets the "amount" field. +func (_c *WalletTransactionsCreate) SetAmount(v decimal.Decimal) *WalletTransactionsCreate { + _c.mutation.SetAmount(v) + return _c +} + +// SetBalanceAfter sets the "balance_after" field. +func (_c *WalletTransactionsCreate) SetBalanceAfter(v decimal.Decimal) *WalletTransactionsCreate { + _c.mutation.SetBalanceAfter(v) + return _c +} + +// SetDescription sets the "description" field. +func (_c *WalletTransactionsCreate) SetDescription(v []string) *WalletTransactionsCreate { + _c.mutation.SetDescription(v) + return _c +} + +// SetOrderID sets the "order_id" field. +func (_c *WalletTransactionsCreate) SetOrderID(v int64) *WalletTransactionsCreate { + _c.mutation.SetOrderID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *WalletTransactionsCreate) SetCreatedAt(v time.Time) *WalletTransactionsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetSearchText sets the "search_text" field. +func (_c *WalletTransactionsCreate) SetSearchText(v string) *WalletTransactionsCreate { + _c.mutation.SetSearchText(v) + return _c +} + +// SetID sets the "id" field. +func (_c *WalletTransactionsCreate) SetID(v string) *WalletTransactionsCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the WalletTransactionsMutation object of the builder. +func (_c *WalletTransactionsCreate) Mutation() *WalletTransactionsMutation { + return _c.mutation +} + +// Save creates the WalletTransactions in the database. +func (_c *WalletTransactionsCreate) Save(ctx context.Context) (*WalletTransactions, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *WalletTransactionsCreate) SaveX(ctx context.Context) *WalletTransactions { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *WalletTransactionsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *WalletTransactionsCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *WalletTransactionsCreate) check() error { + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "WalletTransactions.user_id"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`models: missing required field "WalletTransactions.type"`)} + } + if _, ok := _c.mutation.Amount(); !ok { + return &ValidationError{Name: "amount", err: errors.New(`models: missing required field "WalletTransactions.amount"`)} + } + if _, ok := _c.mutation.BalanceAfter(); !ok { + return &ValidationError{Name: "balance_after", err: errors.New(`models: missing required field "WalletTransactions.balance_after"`)} + } + if _, ok := _c.mutation.Description(); !ok { + return &ValidationError{Name: "description", err: errors.New(`models: missing required field "WalletTransactions.description"`)} + } + if _, ok := _c.mutation.OrderID(); !ok { + return &ValidationError{Name: "order_id", err: errors.New(`models: missing required field "WalletTransactions.order_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "WalletTransactions.created_at"`)} + } + if _, ok := _c.mutation.SearchText(); !ok { + return &ValidationError{Name: "search_text", err: errors.New(`models: missing required field "WalletTransactions.search_text"`)} + } + return nil +} + +func (_c *WalletTransactionsCreate) sqlSave(ctx context.Context) (*WalletTransactions, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected WalletTransactions.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *WalletTransactionsCreate) createSpec() (*WalletTransactions, *sqlgraph.CreateSpec) { + var ( + _node = &WalletTransactions{config: _c.config} + _spec = sqlgraph.NewCreateSpec(wallettransactions.Table, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(wallettransactions.FieldUserID, field.TypeInt64, value) + _node.UserID = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(wallettransactions.FieldType, field.TypeString, value) + _node.Type = value + } + if value, ok := _c.mutation.Amount(); ok { + _spec.SetField(wallettransactions.FieldAmount, field.TypeOther, value) + _node.Amount = value + } + if value, ok := _c.mutation.BalanceAfter(); ok { + _spec.SetField(wallettransactions.FieldBalanceAfter, field.TypeOther, value) + _node.BalanceAfter = value + } + if value, ok := _c.mutation.Description(); ok { + _spec.SetField(wallettransactions.FieldDescription, field.TypeJSON, value) + _node.Description = value + } + if value, ok := _c.mutation.OrderID(); ok { + _spec.SetField(wallettransactions.FieldOrderID, field.TypeInt64, value) + _node.OrderID = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(wallettransactions.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.SearchText(); ok { + _spec.SetField(wallettransactions.FieldSearchText, field.TypeString, value) + _node.SearchText = value + } + return _node, _spec +} + +// WalletTransactionsCreateBulk is the builder for creating many WalletTransactions entities in bulk. +type WalletTransactionsCreateBulk struct { + config + err error + builders []*WalletTransactionsCreate +} + +// Save creates the WalletTransactions entities in the database. +func (_c *WalletTransactionsCreateBulk) Save(ctx context.Context) ([]*WalletTransactions, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*WalletTransactions, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*WalletTransactionsMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *WalletTransactionsCreateBulk) SaveX(ctx context.Context) []*WalletTransactions { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *WalletTransactionsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *WalletTransactionsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/wallet/rpc/internal/models/wallettransactions_delete.go b/app/wallet/rpc/internal/models/wallettransactions_delete.go new file mode 100644 index 0000000..c5d6131 --- /dev/null +++ b/app/wallet/rpc/internal/models/wallettransactions_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WalletTransactionsDelete is the builder for deleting a WalletTransactions entity. +type WalletTransactionsDelete struct { + config + hooks []Hook + mutation *WalletTransactionsMutation +} + +// Where appends a list predicates to the WalletTransactionsDelete builder. +func (_d *WalletTransactionsDelete) Where(ps ...predicate.WalletTransactions) *WalletTransactionsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *WalletTransactionsDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *WalletTransactionsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *WalletTransactionsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(wallettransactions.Table, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// WalletTransactionsDeleteOne is the builder for deleting a single WalletTransactions entity. +type WalletTransactionsDeleteOne struct { + _d *WalletTransactionsDelete +} + +// Where appends a list predicates to the WalletTransactionsDelete builder. +func (_d *WalletTransactionsDeleteOne) Where(ps ...predicate.WalletTransactions) *WalletTransactionsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *WalletTransactionsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{wallettransactions.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *WalletTransactionsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/wallet/rpc/internal/models/wallettransactions_query.go b/app/wallet/rpc/internal/models/wallettransactions_query.go new file mode 100644 index 0000000..e970373 --- /dev/null +++ b/app/wallet/rpc/internal/models/wallettransactions_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WalletTransactionsQuery is the builder for querying WalletTransactions entities. +type WalletTransactionsQuery struct { + config + ctx *QueryContext + order []wallettransactions.OrderOption + inters []Interceptor + predicates []predicate.WalletTransactions + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the WalletTransactionsQuery builder. +func (_q *WalletTransactionsQuery) Where(ps ...predicate.WalletTransactions) *WalletTransactionsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *WalletTransactionsQuery) Limit(limit int) *WalletTransactionsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *WalletTransactionsQuery) Offset(offset int) *WalletTransactionsQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *WalletTransactionsQuery) Unique(unique bool) *WalletTransactionsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *WalletTransactionsQuery) Order(o ...wallettransactions.OrderOption) *WalletTransactionsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first WalletTransactions entity from the query. +// Returns a *NotFoundError when no WalletTransactions was found. +func (_q *WalletTransactionsQuery) First(ctx context.Context) (*WalletTransactions, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{wallettransactions.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *WalletTransactionsQuery) FirstX(ctx context.Context) *WalletTransactions { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first WalletTransactions ID from the query. +// Returns a *NotFoundError when no WalletTransactions ID was found. +func (_q *WalletTransactionsQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{wallettransactions.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *WalletTransactionsQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single WalletTransactions entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one WalletTransactions entity is found. +// Returns a *NotFoundError when no WalletTransactions entities are found. +func (_q *WalletTransactionsQuery) Only(ctx context.Context) (*WalletTransactions, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{wallettransactions.Label} + default: + return nil, &NotSingularError{wallettransactions.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *WalletTransactionsQuery) OnlyX(ctx context.Context) *WalletTransactions { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only WalletTransactions ID in the query. +// Returns a *NotSingularError when more than one WalletTransactions ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *WalletTransactionsQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{wallettransactions.Label} + default: + err = &NotSingularError{wallettransactions.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *WalletTransactionsQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of WalletTransactionsSlice. +func (_q *WalletTransactionsQuery) All(ctx context.Context) ([]*WalletTransactions, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*WalletTransactions, *WalletTransactionsQuery]() + return withInterceptors[[]*WalletTransactions](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *WalletTransactionsQuery) AllX(ctx context.Context) []*WalletTransactions { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of WalletTransactions IDs. +func (_q *WalletTransactionsQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(wallettransactions.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *WalletTransactionsQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *WalletTransactionsQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*WalletTransactionsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *WalletTransactionsQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *WalletTransactionsQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("models: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *WalletTransactionsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the WalletTransactionsQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *WalletTransactionsQuery) Clone() *WalletTransactionsQuery { + if _q == nil { + return nil + } + return &WalletTransactionsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]wallettransactions.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.WalletTransactions{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// UserID int64 `json:"user_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.WalletTransactions.Query(). +// GroupBy(wallettransactions.FieldUserID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *WalletTransactionsQuery) GroupBy(field string, fields ...string) *WalletTransactionsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &WalletTransactionsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = wallettransactions.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// UserID int64 `json:"user_id,omitempty"` +// } +// +// client.WalletTransactions.Query(). +// Select(wallettransactions.FieldUserID). +// Scan(ctx, &v) +func (_q *WalletTransactionsQuery) Select(fields ...string) *WalletTransactionsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &WalletTransactionsSelect{WalletTransactionsQuery: _q} + sbuild.label = wallettransactions.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a WalletTransactionsSelect configured with the given aggregations. +func (_q *WalletTransactionsQuery) Aggregate(fns ...AggregateFunc) *WalletTransactionsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *WalletTransactionsQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !wallettransactions.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *WalletTransactionsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WalletTransactions, error) { + var ( + nodes = []*WalletTransactions{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*WalletTransactions).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &WalletTransactions{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *WalletTransactionsQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *WalletTransactionsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(wallettransactions.Table, wallettransactions.Columns, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, wallettransactions.FieldID) + for i := range fields { + if fields[i] != wallettransactions.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *WalletTransactionsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(wallettransactions.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = wallettransactions.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// WalletTransactionsGroupBy is the group-by builder for WalletTransactions entities. +type WalletTransactionsGroupBy struct { + selector + build *WalletTransactionsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *WalletTransactionsGroupBy) Aggregate(fns ...AggregateFunc) *WalletTransactionsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *WalletTransactionsGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WalletTransactionsQuery, *WalletTransactionsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *WalletTransactionsGroupBy) sqlScan(ctx context.Context, root *WalletTransactionsQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// WalletTransactionsSelect is the builder for selecting fields of WalletTransactions entities. +type WalletTransactionsSelect struct { + *WalletTransactionsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *WalletTransactionsSelect) Aggregate(fns ...AggregateFunc) *WalletTransactionsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *WalletTransactionsSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WalletTransactionsQuery, *WalletTransactionsSelect](ctx, _s.WalletTransactionsQuery, _s, _s.inters, v) +} + +func (_s *WalletTransactionsSelect) sqlScan(ctx context.Context, root *WalletTransactionsQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/app/wallet/rpc/internal/models/wallettransactions_update.go b/app/wallet/rpc/internal/models/wallettransactions_update.go new file mode 100644 index 0000000..96fed77 --- /dev/null +++ b/app/wallet/rpc/internal/models/wallettransactions_update.go @@ -0,0 +1,319 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/wallet/rpc/internal/models/predicate" + "juwan-backend/app/wallet/rpc/internal/models/wallettransactions" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" + "entgo.io/ent/schema/field" +) + +// WalletTransactionsUpdate is the builder for updating WalletTransactions entities. +type WalletTransactionsUpdate struct { + config + hooks []Hook + mutation *WalletTransactionsMutation +} + +// Where appends a list predicates to the WalletTransactionsUpdate builder. +func (_u *WalletTransactionsUpdate) Where(ps ...predicate.WalletTransactions) *WalletTransactionsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetType sets the "type" field. +func (_u *WalletTransactionsUpdate) SetType(v string) *WalletTransactionsUpdate { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *WalletTransactionsUpdate) SetNillableType(v *string) *WalletTransactionsUpdate { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *WalletTransactionsUpdate) SetDescription(v []string) *WalletTransactionsUpdate { + _u.mutation.SetDescription(v) + return _u +} + +// AppendDescription appends value to the "description" field. +func (_u *WalletTransactionsUpdate) AppendDescription(v []string) *WalletTransactionsUpdate { + _u.mutation.AppendDescription(v) + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *WalletTransactionsUpdate) SetCreatedAt(v time.Time) *WalletTransactionsUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *WalletTransactionsUpdate) SetNillableCreatedAt(v *time.Time) *WalletTransactionsUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetSearchText sets the "search_text" field. +func (_u *WalletTransactionsUpdate) SetSearchText(v string) *WalletTransactionsUpdate { + _u.mutation.SetSearchText(v) + return _u +} + +// SetNillableSearchText sets the "search_text" field if the given value is not nil. +func (_u *WalletTransactionsUpdate) SetNillableSearchText(v *string) *WalletTransactionsUpdate { + if v != nil { + _u.SetSearchText(*v) + } + return _u +} + +// Mutation returns the WalletTransactionsMutation object of the builder. +func (_u *WalletTransactionsUpdate) Mutation() *WalletTransactionsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *WalletTransactionsUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *WalletTransactionsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *WalletTransactionsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *WalletTransactionsUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *WalletTransactionsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(wallettransactions.Table, wallettransactions.Columns, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(wallettransactions.FieldType, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(wallettransactions.FieldDescription, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedDescription(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, wallettransactions.FieldDescription, value) + }) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(wallettransactions.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.SearchText(); ok { + _spec.SetField(wallettransactions.FieldSearchText, field.TypeString, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{wallettransactions.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// WalletTransactionsUpdateOne is the builder for updating a single WalletTransactions entity. +type WalletTransactionsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *WalletTransactionsMutation +} + +// SetType sets the "type" field. +func (_u *WalletTransactionsUpdateOne) SetType(v string) *WalletTransactionsUpdateOne { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *WalletTransactionsUpdateOne) SetNillableType(v *string) *WalletTransactionsUpdateOne { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetDescription sets the "description" field. +func (_u *WalletTransactionsUpdateOne) SetDescription(v []string) *WalletTransactionsUpdateOne { + _u.mutation.SetDescription(v) + return _u +} + +// AppendDescription appends value to the "description" field. +func (_u *WalletTransactionsUpdateOne) AppendDescription(v []string) *WalletTransactionsUpdateOne { + _u.mutation.AppendDescription(v) + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *WalletTransactionsUpdateOne) SetCreatedAt(v time.Time) *WalletTransactionsUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *WalletTransactionsUpdateOne) SetNillableCreatedAt(v *time.Time) *WalletTransactionsUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetSearchText sets the "search_text" field. +func (_u *WalletTransactionsUpdateOne) SetSearchText(v string) *WalletTransactionsUpdateOne { + _u.mutation.SetSearchText(v) + return _u +} + +// SetNillableSearchText sets the "search_text" field if the given value is not nil. +func (_u *WalletTransactionsUpdateOne) SetNillableSearchText(v *string) *WalletTransactionsUpdateOne { + if v != nil { + _u.SetSearchText(*v) + } + return _u +} + +// Mutation returns the WalletTransactionsMutation object of the builder. +func (_u *WalletTransactionsUpdateOne) Mutation() *WalletTransactionsMutation { + return _u.mutation +} + +// Where appends a list predicates to the WalletTransactionsUpdate builder. +func (_u *WalletTransactionsUpdateOne) Where(ps ...predicate.WalletTransactions) *WalletTransactionsUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *WalletTransactionsUpdateOne) Select(field string, fields ...string) *WalletTransactionsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated WalletTransactions entity. +func (_u *WalletTransactionsUpdateOne) Save(ctx context.Context) (*WalletTransactions, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *WalletTransactionsUpdateOne) SaveX(ctx context.Context) *WalletTransactions { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *WalletTransactionsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *WalletTransactionsUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *WalletTransactionsUpdateOne) sqlSave(ctx context.Context) (_node *WalletTransactions, err error) { + _spec := sqlgraph.NewUpdateSpec(wallettransactions.Table, wallettransactions.Columns, sqlgraph.NewFieldSpec(wallettransactions.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "WalletTransactions.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, wallettransactions.FieldID) + for _, f := range fields { + if !wallettransactions.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != wallettransactions.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(wallettransactions.FieldType, field.TypeString, value) + } + if value, ok := _u.mutation.Description(); ok { + _spec.SetField(wallettransactions.FieldDescription, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedDescription(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, wallettransactions.FieldDescription, value) + }) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(wallettransactions.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.SearchText(); ok { + _spec.SetField(wallettransactions.FieldSearchText, field.TypeString, value) + } + _node = &WalletTransactions{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{wallettransactions.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/wallet/rpc/internal/server/walletServiceServer.go b/app/wallet/rpc/internal/server/walletServiceServer.go new file mode 100644 index 0000000..6ad63d6 --- /dev/null +++ b/app/wallet/rpc/internal/server/walletServiceServer.go @@ -0,0 +1,76 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 +// Source: wallet.proto + +package server + +import ( + "context" + + "juwan-backend/app/wallet/rpc/internal/logic" + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" +) + +type WalletServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedWalletServiceServer +} + +func NewWalletServiceServer(svcCtx *svc.ServiceContext) *WalletServiceServer { + return &WalletServiceServer{ + svcCtx: svcCtx, + } +} + +// -----------------------walletTransactions----------------------- +func (s *WalletServiceServer) AddWalletTransactions(ctx context.Context, in *pb.AddWalletTransactionsReq) (*pb.AddWalletTransactionsResp, error) { + l := logic.NewAddWalletTransactionsLogic(ctx, s.svcCtx) + return l.AddWalletTransactions(in) +} + +func (s *WalletServiceServer) UpdateWalletTransactions(ctx context.Context, in *pb.UpdateWalletTransactionsReq) (*pb.UpdateWalletTransactionsResp, error) { + l := logic.NewUpdateWalletTransactionsLogic(ctx, s.svcCtx) + return l.UpdateWalletTransactions(in) +} + +func (s *WalletServiceServer) DelWalletTransactions(ctx context.Context, in *pb.DelWalletTransactionsReq) (*pb.DelWalletTransactionsResp, error) { + l := logic.NewDelWalletTransactionsLogic(ctx, s.svcCtx) + return l.DelWalletTransactions(in) +} + +func (s *WalletServiceServer) GetWalletTransactionsById(ctx context.Context, in *pb.GetWalletTransactionsByIdReq) (*pb.GetWalletTransactionsByIdResp, error) { + l := logic.NewGetWalletTransactionsByIdLogic(ctx, s.svcCtx) + return l.GetWalletTransactionsById(in) +} + +func (s *WalletServiceServer) SearchWalletTransactions(ctx context.Context, in *pb.SearchWalletTransactionsReq) (*pb.SearchWalletTransactionsResp, error) { + l := logic.NewSearchWalletTransactionsLogic(ctx, s.svcCtx) + return l.SearchWalletTransactions(in) +} + +// -----------------------wallets----------------------- +func (s *WalletServiceServer) AddWallets(ctx context.Context, in *pb.AddWalletsReq) (*pb.AddWalletsResp, error) { + l := logic.NewAddWalletsLogic(ctx, s.svcCtx) + return l.AddWallets(in) +} + +func (s *WalletServiceServer) UpdateWallets(ctx context.Context, in *pb.UpdateWalletsReq) (*pb.UpdateWalletsResp, error) { + l := logic.NewUpdateWalletsLogic(ctx, s.svcCtx) + return l.UpdateWallets(in) +} + +func (s *WalletServiceServer) DelWallets(ctx context.Context, in *pb.DelWalletsReq) (*pb.DelWalletsResp, error) { + l := logic.NewDelWalletsLogic(ctx, s.svcCtx) + return l.DelWallets(in) +} + +func (s *WalletServiceServer) GetWalletsById(ctx context.Context, in *pb.GetWalletsByIdReq) (*pb.GetWalletsByIdResp, error) { + l := logic.NewGetWalletsByIdLogic(ctx, s.svcCtx) + return l.GetWalletsById(in) +} + +func (s *WalletServiceServer) SearchWallets(ctx context.Context, in *pb.SearchWalletsReq) (*pb.SearchWalletsResp, error) { + l := logic.NewSearchWalletsLogic(ctx, s.svcCtx) + return l.SearchWallets(in) +} diff --git a/app/wallet/rpc/internal/svc/serviceContext.go b/app/wallet/rpc/internal/svc/serviceContext.go new file mode 100644 index 0000000..d43deec --- /dev/null +++ b/app/wallet/rpc/internal/svc/serviceContext.go @@ -0,0 +1,63 @@ +package svc + +import ( + "fmt" + "juwan-backend/app/snowflake/rpc/snowflake" + "juwan-backend/app/wallet/rpc/internal/config" + "juwan-backend/app/wallet/rpc/internal/models" + "juwan-backend/common/redisx" + "juwan-backend/common/snowflakex" + "juwan-backend/pkg/adapter" + "strings" + "time" + + "ariga.io/entcache" + "entgo.io/ent/dialect/sql" + _ "github.com/jackc/pgx/v5/stdlib" + "github.com/zeromicro/go-zero/core/logx" +) + +type ServiceContext struct { + Config config.Config + Snowflake snowflake.SnowflakeServiceClient + WalletModelsRW *models.Client + WalletModelsRO *models.Client +} + +func NewServiceContext(c config.Config) *ServiceContext { + RWConn, err := sql.Open("pgx", c.DB.Master) + if err != nil { + panic(err) + } + ROConn, err := sql.Open("pgx", c.DB.Slaves) + if err != nil { + panic(err) + } + + redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second) + if redisCluster == nil || err != nil { + logx.Errorf("failed to connect to Redis cluster: %v", err) + panic(err) + } + + RWDrv := entcache.NewDriver(RWConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) + RODrv := entcache.NewDriver(ROConn, entcache.TTL(30*time.Second), entcache.Levels(adapter.NewRedisCache(redisCluster.Client))) + + entLogFn := func(v ...any) { + logx.Infof("[ent][wallet] %s", fmt.Sprint(v...)) + } + + modelOpts := []models.Option{models.Driver(RWDrv), models.Log(entLogFn)} + roModelOpts := []models.Option{models.Driver(RODrv), models.Log(entLogFn)} + if strings.EqualFold(c.Log.Level, "debug") { + modelOpts = append(modelOpts, models.Debug()) + roModelOpts = append(roModelOpts, models.Debug()) + } + + return &ServiceContext{ + Config: c, + Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), + WalletModelsRW: models.NewClient(modelOpts...), + WalletModelsRO: models.NewClient(roModelOpts...), + } +} diff --git a/app/wallet/rpc/pb.go b/app/wallet/rpc/pb.go new file mode 100644 index 0000000..a325f3e --- /dev/null +++ b/app/wallet/rpc/pb.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/wallet/rpc/internal/config" + "juwan-backend/app/wallet/rpc/internal/server" + "juwan-backend/app/wallet/rpc/internal/svc" + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/core/service" + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" + "google.golang.org/grpc/reflection" +) + +var configFile = flag.String("f", "etc/pb.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c, conf.UseEnv()) + ctx := svc.NewServiceContext(c) + + s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { + pb.RegisterWalletServiceServer(grpcServer, server.NewWalletServiceServer(ctx)) + + if c.Mode == service.DevMode || c.Mode == service.TestMode { + reflection.Register(grpcServer) + } + }) + defer s.Stop() + + fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) + s.Start() +} diff --git a/app/wallet/rpc/pb/wallet.pb.go b/app/wallet/rpc/pb/wallet.pb.go new file mode 100644 index 0000000..746135b --- /dev/null +++ b/app/wallet/rpc/pb/wallet.pb.go @@ -0,0 +1,1580 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v5.29.6 +// source: wallet.proto + +package pb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// --------------------------------walletTransactions-------------------------------- +type WalletTransactions struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId + Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` //type + Amount string `protobuf:"bytes,4,opt,name=amount,proto3" json:"amount,omitempty"` //amount + BalanceAfter string `protobuf:"bytes,5,opt,name=balanceAfter,proto3" json:"balanceAfter,omitempty"` //balanceAfter + Description string `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"` //description + OrderId int64 `protobuf:"varint,7,opt,name=orderId,proto3" json:"orderId,omitempty"` //orderId + CreatedAt int64 `protobuf:"varint,8,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + SearchText string `protobuf:"bytes,9,opt,name=searchText,proto3" json:"searchText,omitempty"` //searchText + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WalletTransactions) Reset() { + *x = WalletTransactions{} + mi := &file_wallet_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WalletTransactions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WalletTransactions) ProtoMessage() {} + +func (x *WalletTransactions) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WalletTransactions.ProtoReflect.Descriptor instead. +func (*WalletTransactions) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{0} +} + +func (x *WalletTransactions) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *WalletTransactions) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *WalletTransactions) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *WalletTransactions) GetAmount() string { + if x != nil { + return x.Amount + } + return "" +} + +func (x *WalletTransactions) GetBalanceAfter() string { + if x != nil { + return x.BalanceAfter + } + return "" +} + +func (x *WalletTransactions) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *WalletTransactions) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *WalletTransactions) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *WalletTransactions) GetSearchText() string { + if x != nil { + return x.SearchText + } + return "" +} + +type AddWalletTransactionsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId int64 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"` //userId + Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` //type + Amount string `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount,omitempty"` //amount + BalanceAfter string `protobuf:"bytes,4,opt,name=balanceAfter,proto3" json:"balanceAfter,omitempty"` //balanceAfter + Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"` //description + OrderId int64 `protobuf:"varint,6,opt,name=orderId,proto3" json:"orderId,omitempty"` //orderId + CreatedAt int64 `protobuf:"varint,7,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + SearchText string `protobuf:"bytes,8,opt,name=searchText,proto3" json:"searchText,omitempty"` //searchText + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddWalletTransactionsReq) Reset() { + *x = AddWalletTransactionsReq{} + mi := &file_wallet_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddWalletTransactionsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddWalletTransactionsReq) ProtoMessage() {} + +func (x *AddWalletTransactionsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddWalletTransactionsReq.ProtoReflect.Descriptor instead. +func (*AddWalletTransactionsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{1} +} + +func (x *AddWalletTransactionsReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *AddWalletTransactionsReq) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *AddWalletTransactionsReq) GetAmount() string { + if x != nil { + return x.Amount + } + return "" +} + +func (x *AddWalletTransactionsReq) GetBalanceAfter() string { + if x != nil { + return x.BalanceAfter + } + return "" +} + +func (x *AddWalletTransactionsReq) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *AddWalletTransactionsReq) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *AddWalletTransactionsReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *AddWalletTransactionsReq) GetSearchText() string { + if x != nil { + return x.SearchText + } + return "" +} + +type AddWalletTransactionsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddWalletTransactionsResp) Reset() { + *x = AddWalletTransactionsResp{} + mi := &file_wallet_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddWalletTransactionsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddWalletTransactionsResp) ProtoMessage() {} + +func (x *AddWalletTransactionsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddWalletTransactionsResp.ProtoReflect.Descriptor instead. +func (*AddWalletTransactionsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{2} +} + +type UpdateWalletTransactionsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + UserId *int64 `protobuf:"varint,2,opt,name=userId,proto3,oneof" json:"userId,omitempty"` //userId + Type *string `protobuf:"bytes,3,opt,name=type,proto3,oneof" json:"type,omitempty"` //type + Amount *string `protobuf:"bytes,4,opt,name=amount,proto3,oneof" json:"amount,omitempty"` //amount + BalanceAfter *string `protobuf:"bytes,5,opt,name=balanceAfter,proto3,oneof" json:"balanceAfter,omitempty"` //balanceAfter + Description *string `protobuf:"bytes,6,opt,name=description,proto3,oneof" json:"description,omitempty"` //description + OrderId *int64 `protobuf:"varint,7,opt,name=orderId,proto3,oneof" json:"orderId,omitempty"` //orderId + CreatedAt *int64 `protobuf:"varint,8,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + SearchText *string `protobuf:"bytes,9,opt,name=searchText,proto3,oneof" json:"searchText,omitempty"` //searchText + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateWalletTransactionsReq) Reset() { + *x = UpdateWalletTransactionsReq{} + mi := &file_wallet_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateWalletTransactionsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateWalletTransactionsReq) ProtoMessage() {} + +func (x *UpdateWalletTransactionsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateWalletTransactionsReq.ProtoReflect.Descriptor instead. +func (*UpdateWalletTransactionsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{3} +} + +func (x *UpdateWalletTransactionsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateWalletTransactionsReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +func (x *UpdateWalletTransactionsReq) GetType() string { + if x != nil && x.Type != nil { + return *x.Type + } + return "" +} + +func (x *UpdateWalletTransactionsReq) GetAmount() string { + if x != nil && x.Amount != nil { + return *x.Amount + } + return "" +} + +func (x *UpdateWalletTransactionsReq) GetBalanceAfter() string { + if x != nil && x.BalanceAfter != nil { + return *x.BalanceAfter + } + return "" +} + +func (x *UpdateWalletTransactionsReq) GetDescription() string { + if x != nil && x.Description != nil { + return *x.Description + } + return "" +} + +func (x *UpdateWalletTransactionsReq) GetOrderId() int64 { + if x != nil && x.OrderId != nil { + return *x.OrderId + } + return 0 +} + +func (x *UpdateWalletTransactionsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *UpdateWalletTransactionsReq) GetSearchText() string { + if x != nil && x.SearchText != nil { + return *x.SearchText + } + return "" +} + +type UpdateWalletTransactionsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateWalletTransactionsResp) Reset() { + *x = UpdateWalletTransactionsResp{} + mi := &file_wallet_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateWalletTransactionsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateWalletTransactionsResp) ProtoMessage() {} + +func (x *UpdateWalletTransactionsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateWalletTransactionsResp.ProtoReflect.Descriptor instead. +func (*UpdateWalletTransactionsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{4} +} + +type DelWalletTransactionsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelWalletTransactionsReq) Reset() { + *x = DelWalletTransactionsReq{} + mi := &file_wallet_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelWalletTransactionsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelWalletTransactionsReq) ProtoMessage() {} + +func (x *DelWalletTransactionsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelWalletTransactionsReq.ProtoReflect.Descriptor instead. +func (*DelWalletTransactionsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{5} +} + +func (x *DelWalletTransactionsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelWalletTransactionsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelWalletTransactionsResp) Reset() { + *x = DelWalletTransactionsResp{} + mi := &file_wallet_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelWalletTransactionsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelWalletTransactionsResp) ProtoMessage() {} + +func (x *DelWalletTransactionsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelWalletTransactionsResp.ProtoReflect.Descriptor instead. +func (*DelWalletTransactionsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{6} +} + +type GetWalletTransactionsByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetWalletTransactionsByIdReq) Reset() { + *x = GetWalletTransactionsByIdReq{} + mi := &file_wallet_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetWalletTransactionsByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetWalletTransactionsByIdReq) ProtoMessage() {} + +func (x *GetWalletTransactionsByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetWalletTransactionsByIdReq.ProtoReflect.Descriptor instead. +func (*GetWalletTransactionsByIdReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{7} +} + +func (x *GetWalletTransactionsByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetWalletTransactionsByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + WalletTransactions *WalletTransactions `protobuf:"bytes,1,opt,name=walletTransactions,proto3" json:"walletTransactions,omitempty"` //walletTransactions + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetWalletTransactionsByIdResp) Reset() { + *x = GetWalletTransactionsByIdResp{} + mi := &file_wallet_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetWalletTransactionsByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetWalletTransactionsByIdResp) ProtoMessage() {} + +func (x *GetWalletTransactionsByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetWalletTransactionsByIdResp.ProtoReflect.Descriptor instead. +func (*GetWalletTransactionsByIdResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{8} +} + +func (x *GetWalletTransactionsByIdResp) GetWalletTransactions() *WalletTransactions { + if x != nil { + return x.WalletTransactions + } + return nil +} + +type SearchWalletTransactionsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + Id int64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` //id + UserId *int64 `protobuf:"varint,4,opt,name=userId,proto3,oneof" json:"userId,omitempty"` //userId + Type *string `protobuf:"bytes,5,opt,name=type,proto3,oneof" json:"type,omitempty"` //type + Amount *string `protobuf:"bytes,6,opt,name=amount,proto3,oneof" json:"amount,omitempty"` //amount + BalanceAfter *string `protobuf:"bytes,7,opt,name=balanceAfter,proto3,oneof" json:"balanceAfter,omitempty"` //balanceAfter + Description *string `protobuf:"bytes,8,opt,name=description,proto3,oneof" json:"description,omitempty"` //description + OrderId *int64 `protobuf:"varint,9,opt,name=orderId,proto3,oneof" json:"orderId,omitempty"` //orderId + CreatedAt *int64 `protobuf:"varint,10,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + SearchText *string `protobuf:"bytes,11,opt,name=searchText,proto3,oneof" json:"searchText,omitempty"` //searchText + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchWalletTransactionsReq) Reset() { + *x = SearchWalletTransactionsReq{} + mi := &file_wallet_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchWalletTransactionsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchWalletTransactionsReq) ProtoMessage() {} + +func (x *SearchWalletTransactionsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchWalletTransactionsReq.ProtoReflect.Descriptor instead. +func (*SearchWalletTransactionsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{9} +} + +func (x *SearchWalletTransactionsReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchWalletTransactionsReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchWalletTransactionsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *SearchWalletTransactionsReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +func (x *SearchWalletTransactionsReq) GetType() string { + if x != nil && x.Type != nil { + return *x.Type + } + return "" +} + +func (x *SearchWalletTransactionsReq) GetAmount() string { + if x != nil && x.Amount != nil { + return *x.Amount + } + return "" +} + +func (x *SearchWalletTransactionsReq) GetBalanceAfter() string { + if x != nil && x.BalanceAfter != nil { + return *x.BalanceAfter + } + return "" +} + +func (x *SearchWalletTransactionsReq) GetDescription() string { + if x != nil && x.Description != nil { + return *x.Description + } + return "" +} + +func (x *SearchWalletTransactionsReq) GetOrderId() int64 { + if x != nil && x.OrderId != nil { + return *x.OrderId + } + return 0 +} + +func (x *SearchWalletTransactionsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *SearchWalletTransactionsReq) GetSearchText() string { + if x != nil && x.SearchText != nil { + return *x.SearchText + } + return "" +} + +type SearchWalletTransactionsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + WalletTransactions []*WalletTransactions `protobuf:"bytes,1,rep,name=walletTransactions,proto3" json:"walletTransactions,omitempty"` //walletTransactions + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchWalletTransactionsResp) Reset() { + *x = SearchWalletTransactionsResp{} + mi := &file_wallet_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchWalletTransactionsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchWalletTransactionsResp) ProtoMessage() {} + +func (x *SearchWalletTransactionsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchWalletTransactionsResp.ProtoReflect.Descriptor instead. +func (*SearchWalletTransactionsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{10} +} + +func (x *SearchWalletTransactionsResp) GetWalletTransactions() []*WalletTransactions { + if x != nil { + return x.WalletTransactions + } + return nil +} + +// --------------------------------wallets-------------------------------- +type Wallets struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId int64 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"` //userId + Balance string `protobuf:"bytes,2,opt,name=balance,proto3" json:"balance,omitempty"` //balance + FrozenBalance string `protobuf:"bytes,3,opt,name=frozenBalance,proto3" json:"frozenBalance,omitempty"` //frozenBalance + UpdatedAt int64 `protobuf:"varint,4,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt + Version int64 `protobuf:"varint,5,opt,name=version,proto3" json:"version,omitempty"` //version + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Wallets) Reset() { + *x = Wallets{} + mi := &file_wallet_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Wallets) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Wallets) ProtoMessage() {} + +func (x *Wallets) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Wallets.ProtoReflect.Descriptor instead. +func (*Wallets) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{11} +} + +func (x *Wallets) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *Wallets) GetBalance() string { + if x != nil { + return x.Balance + } + return "" +} + +func (x *Wallets) GetFrozenBalance() string { + if x != nil { + return x.FrozenBalance + } + return "" +} + +func (x *Wallets) GetUpdatedAt() int64 { + if x != nil { + return x.UpdatedAt + } + return 0 +} + +func (x *Wallets) GetVersion() int64 { + if x != nil { + return x.Version + } + return 0 +} + +type AddWalletsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId int64 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"` //userId + Balance string `protobuf:"bytes,2,opt,name=balance,proto3" json:"balance,omitempty"` //balance + FrozenBalance string `protobuf:"bytes,3,opt,name=frozenBalance,proto3" json:"frozenBalance,omitempty"` //frozenBalance + UpdatedAt int64 `protobuf:"varint,4,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddWalletsReq) Reset() { + *x = AddWalletsReq{} + mi := &file_wallet_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddWalletsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddWalletsReq) ProtoMessage() {} + +func (x *AddWalletsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddWalletsReq.ProtoReflect.Descriptor instead. +func (*AddWalletsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{12} +} + +func (x *AddWalletsReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *AddWalletsReq) GetBalance() string { + if x != nil { + return x.Balance + } + return "" +} + +func (x *AddWalletsReq) GetFrozenBalance() string { + if x != nil { + return x.FrozenBalance + } + return "" +} + +func (x *AddWalletsReq) GetUpdatedAt() int64 { + if x != nil { + return x.UpdatedAt + } + return 0 +} + +type AddWalletsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddWalletsResp) Reset() { + *x = AddWalletsResp{} + mi := &file_wallet_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddWalletsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddWalletsResp) ProtoMessage() {} + +func (x *AddWalletsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddWalletsResp.ProtoReflect.Descriptor instead. +func (*AddWalletsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{13} +} + +type UpdateWalletsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId int64 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"` //userId + Balance *string `protobuf:"bytes,2,opt,name=balance,proto3,oneof" json:"balance,omitempty"` //balance + FrozenBalance *string `protobuf:"bytes,3,opt,name=frozenBalance,proto3,oneof" json:"frozenBalance,omitempty"` //frozenBalance + UpdatedAt *int64 `protobuf:"varint,4,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt + Version *int64 `protobuf:"varint,5,opt,name=version,proto3,oneof" json:"version,omitempty"` //version + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateWalletsReq) Reset() { + *x = UpdateWalletsReq{} + mi := &file_wallet_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateWalletsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateWalletsReq) ProtoMessage() {} + +func (x *UpdateWalletsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateWalletsReq.ProtoReflect.Descriptor instead. +func (*UpdateWalletsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{14} +} + +func (x *UpdateWalletsReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *UpdateWalletsReq) GetBalance() string { + if x != nil && x.Balance != nil { + return *x.Balance + } + return "" +} + +func (x *UpdateWalletsReq) GetFrozenBalance() string { + if x != nil && x.FrozenBalance != nil { + return *x.FrozenBalance + } + return "" +} + +func (x *UpdateWalletsReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +func (x *UpdateWalletsReq) GetVersion() int64 { + if x != nil && x.Version != nil { + return *x.Version + } + return 0 +} + +type UpdateWalletsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateWalletsResp) Reset() { + *x = UpdateWalletsResp{} + mi := &file_wallet_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateWalletsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateWalletsResp) ProtoMessage() {} + +func (x *UpdateWalletsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[15] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateWalletsResp.ProtoReflect.Descriptor instead. +func (*UpdateWalletsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{15} +} + +type DelWalletsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelWalletsReq) Reset() { + *x = DelWalletsReq{} + mi := &file_wallet_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelWalletsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelWalletsReq) ProtoMessage() {} + +func (x *DelWalletsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[16] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelWalletsReq.ProtoReflect.Descriptor instead. +func (*DelWalletsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{16} +} + +func (x *DelWalletsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelWalletsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelWalletsResp) Reset() { + *x = DelWalletsResp{} + mi := &file_wallet_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelWalletsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelWalletsResp) ProtoMessage() {} + +func (x *DelWalletsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DelWalletsResp.ProtoReflect.Descriptor instead. +func (*DelWalletsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{17} +} + +type GetWalletsByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetWalletsByIdReq) Reset() { + *x = GetWalletsByIdReq{} + mi := &file_wallet_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetWalletsByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetWalletsByIdReq) ProtoMessage() {} + +func (x *GetWalletsByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetWalletsByIdReq.ProtoReflect.Descriptor instead. +func (*GetWalletsByIdReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{18} +} + +func (x *GetWalletsByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetWalletsByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Wallets *Wallets `protobuf:"bytes,1,opt,name=wallets,proto3" json:"wallets,omitempty"` //wallets + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetWalletsByIdResp) Reset() { + *x = GetWalletsByIdResp{} + mi := &file_wallet_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetWalletsByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetWalletsByIdResp) ProtoMessage() {} + +func (x *GetWalletsByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetWalletsByIdResp.ProtoReflect.Descriptor instead. +func (*GetWalletsByIdResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{19} +} + +func (x *GetWalletsByIdResp) GetWallets() *Wallets { + if x != nil { + return x.Wallets + } + return nil +} + +type SearchWalletsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit + UserId int64 `protobuf:"varint,3,opt,name=userId,proto3" json:"userId,omitempty"` //userId + Balance *string `protobuf:"bytes,4,opt,name=balance,proto3,oneof" json:"balance,omitempty"` //balance + FrozenBalance *string `protobuf:"bytes,5,opt,name=frozenBalance,proto3,oneof" json:"frozenBalance,omitempty"` //frozenBalance + UpdatedAt *int64 `protobuf:"varint,6,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` //updatedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchWalletsReq) Reset() { + *x = SearchWalletsReq{} + mi := &file_wallet_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchWalletsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchWalletsReq) ProtoMessage() {} + +func (x *SearchWalletsReq) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[20] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchWalletsReq.ProtoReflect.Descriptor instead. +func (*SearchWalletsReq) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{20} +} + +func (x *SearchWalletsReq) GetPage() int64 { + if x != nil { + return x.Page + } + return 0 +} + +func (x *SearchWalletsReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchWalletsReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *SearchWalletsReq) GetBalance() string { + if x != nil && x.Balance != nil { + return *x.Balance + } + return "" +} + +func (x *SearchWalletsReq) GetFrozenBalance() string { + if x != nil && x.FrozenBalance != nil { + return *x.FrozenBalance + } + return "" +} + +func (x *SearchWalletsReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +type SearchWalletsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Wallets []*Wallets `protobuf:"bytes,1,rep,name=wallets,proto3" json:"wallets,omitempty"` //wallets + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchWalletsResp) Reset() { + *x = SearchWalletsResp{} + mi := &file_wallet_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchWalletsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchWalletsResp) ProtoMessage() {} + +func (x *SearchWalletsResp) ProtoReflect() protoreflect.Message { + mi := &file_wallet_proto_msgTypes[21] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchWalletsResp.ProtoReflect.Descriptor instead. +func (*SearchWalletsResp) Descriptor() ([]byte, []int) { + return file_wallet_proto_rawDescGZIP(), []int{21} +} + +func (x *SearchWalletsResp) GetWallets() []*Wallets { + if x != nil { + return x.Wallets + } + return nil +} + +var File_wallet_proto protoreflect.FileDescriptor + +const file_wallet_proto_rawDesc = "" + + "\n" + + "\fwallet.proto\x12\x02pb\"\x86\x02\n" + + "\x12WalletTransactions\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x16\n" + + "\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x12\n" + + "\x04type\x18\x03 \x01(\tR\x04type\x12\x16\n" + + "\x06amount\x18\x04 \x01(\tR\x06amount\x12\"\n" + + "\fbalanceAfter\x18\x05 \x01(\tR\fbalanceAfter\x12 \n" + + "\vdescription\x18\x06 \x01(\tR\vdescription\x12\x18\n" + + "\aorderId\x18\a \x01(\x03R\aorderId\x12\x1c\n" + + "\tcreatedAt\x18\b \x01(\x03R\tcreatedAt\x12\x1e\n" + + "\n" + + "searchText\x18\t \x01(\tR\n" + + "searchText\"\xfc\x01\n" + + "\x18AddWalletTransactionsReq\x12\x16\n" + + "\x06userId\x18\x01 \x01(\x03R\x06userId\x12\x12\n" + + "\x04type\x18\x02 \x01(\tR\x04type\x12\x16\n" + + "\x06amount\x18\x03 \x01(\tR\x06amount\x12\"\n" + + "\fbalanceAfter\x18\x04 \x01(\tR\fbalanceAfter\x12 \n" + + "\vdescription\x18\x05 \x01(\tR\vdescription\x12\x18\n" + + "\aorderId\x18\x06 \x01(\x03R\aorderId\x12\x1c\n" + + "\tcreatedAt\x18\a \x01(\x03R\tcreatedAt\x12\x1e\n" + + "\n" + + "searchText\x18\b \x01(\tR\n" + + "searchText\"\x1b\n" + + "\x19AddWalletTransactionsResp\"\xa0\x03\n" + + "\x1bUpdateWalletTransactionsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1b\n" + + "\x06userId\x18\x02 \x01(\x03H\x00R\x06userId\x88\x01\x01\x12\x17\n" + + "\x04type\x18\x03 \x01(\tH\x01R\x04type\x88\x01\x01\x12\x1b\n" + + "\x06amount\x18\x04 \x01(\tH\x02R\x06amount\x88\x01\x01\x12'\n" + + "\fbalanceAfter\x18\x05 \x01(\tH\x03R\fbalanceAfter\x88\x01\x01\x12%\n" + + "\vdescription\x18\x06 \x01(\tH\x04R\vdescription\x88\x01\x01\x12\x1d\n" + + "\aorderId\x18\a \x01(\x03H\x05R\aorderId\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\b \x01(\x03H\x06R\tcreatedAt\x88\x01\x01\x12#\n" + + "\n" + + "searchText\x18\t \x01(\tH\aR\n" + + "searchText\x88\x01\x01B\t\n" + + "\a_userIdB\a\n" + + "\x05_typeB\t\n" + + "\a_amountB\x0f\n" + + "\r_balanceAfterB\x0e\n" + + "\f_descriptionB\n" + + "\n" + + "\b_orderIdB\f\n" + + "\n" + + "_createdAtB\r\n" + + "\v_searchText\"\x1e\n" + + "\x1cUpdateWalletTransactionsResp\"*\n" + + "\x18DelWalletTransactionsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x1b\n" + + "\x19DelWalletTransactionsResp\".\n" + + "\x1cGetWalletTransactionsByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"g\n" + + "\x1dGetWalletTransactionsByIdResp\x12F\n" + + "\x12walletTransactions\x18\x01 \x01(\v2\x16.pb.WalletTransactionsR\x12walletTransactions\"\xca\x03\n" + + "\x1bSearchWalletTransactionsReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x0e\n" + + "\x02id\x18\x03 \x01(\x03R\x02id\x12\x1b\n" + + "\x06userId\x18\x04 \x01(\x03H\x00R\x06userId\x88\x01\x01\x12\x17\n" + + "\x04type\x18\x05 \x01(\tH\x01R\x04type\x88\x01\x01\x12\x1b\n" + + "\x06amount\x18\x06 \x01(\tH\x02R\x06amount\x88\x01\x01\x12'\n" + + "\fbalanceAfter\x18\a \x01(\tH\x03R\fbalanceAfter\x88\x01\x01\x12%\n" + + "\vdescription\x18\b \x01(\tH\x04R\vdescription\x88\x01\x01\x12\x1d\n" + + "\aorderId\x18\t \x01(\x03H\x05R\aorderId\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\n" + + " \x01(\x03H\x06R\tcreatedAt\x88\x01\x01\x12#\n" + + "\n" + + "searchText\x18\v \x01(\tH\aR\n" + + "searchText\x88\x01\x01B\t\n" + + "\a_userIdB\a\n" + + "\x05_typeB\t\n" + + "\a_amountB\x0f\n" + + "\r_balanceAfterB\x0e\n" + + "\f_descriptionB\n" + + "\n" + + "\b_orderIdB\f\n" + + "\n" + + "_createdAtB\r\n" + + "\v_searchText\"f\n" + + "\x1cSearchWalletTransactionsResp\x12F\n" + + "\x12walletTransactions\x18\x01 \x03(\v2\x16.pb.WalletTransactionsR\x12walletTransactions\"\x99\x01\n" + + "\aWallets\x12\x16\n" + + "\x06userId\x18\x01 \x01(\x03R\x06userId\x12\x18\n" + + "\abalance\x18\x02 \x01(\tR\abalance\x12$\n" + + "\rfrozenBalance\x18\x03 \x01(\tR\rfrozenBalance\x12\x1c\n" + + "\tupdatedAt\x18\x04 \x01(\x03R\tupdatedAt\x12\x18\n" + + "\aversion\x18\x05 \x01(\x03R\aversion\"\x85\x01\n" + + "\rAddWalletsReq\x12\x16\n" + + "\x06userId\x18\x01 \x01(\x03R\x06userId\x12\x18\n" + + "\abalance\x18\x02 \x01(\tR\abalance\x12$\n" + + "\rfrozenBalance\x18\x03 \x01(\tR\rfrozenBalance\x12\x1c\n" + + "\tupdatedAt\x18\x04 \x01(\x03R\tupdatedAt\"\x10\n" + + "\x0eAddWalletsResp\"\xee\x01\n" + + "\x10UpdateWalletsReq\x12\x16\n" + + "\x06userId\x18\x01 \x01(\x03R\x06userId\x12\x1d\n" + + "\abalance\x18\x02 \x01(\tH\x00R\abalance\x88\x01\x01\x12)\n" + + "\rfrozenBalance\x18\x03 \x01(\tH\x01R\rfrozenBalance\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\x04 \x01(\x03H\x02R\tupdatedAt\x88\x01\x01\x12\x1d\n" + + "\aversion\x18\x05 \x01(\x03H\x03R\aversion\x88\x01\x01B\n" + + "\n" + + "\b_balanceB\x10\n" + + "\x0e_frozenBalanceB\f\n" + + "\n" + + "_updatedAtB\n" + + "\n" + + "\b_version\"\x13\n" + + "\x11UpdateWalletsResp\"\x1f\n" + + "\rDelWalletsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x10\n" + + "\x0eDelWalletsResp\"#\n" + + "\x11GetWalletsByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\";\n" + + "\x12GetWalletsByIdResp\x12%\n" + + "\awallets\x18\x01 \x01(\v2\v.pb.WalletsR\awallets\"\xed\x01\n" + + "\x10SearchWalletsReq\x12\x12\n" + + "\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x16\n" + + "\x06userId\x18\x03 \x01(\x03R\x06userId\x12\x1d\n" + + "\abalance\x18\x04 \x01(\tH\x00R\abalance\x88\x01\x01\x12)\n" + + "\rfrozenBalance\x18\x05 \x01(\tH\x01R\rfrozenBalance\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\x06 \x01(\x03H\x02R\tupdatedAt\x88\x01\x01B\n" + + "\n" + + "\b_balanceB\x10\n" + + "\x0e_frozenBalanceB\f\n" + + "\n" + + "_updatedAt\":\n" + + "\x11SearchWalletsResp\x12%\n" + + "\awallets\x18\x01 \x03(\v2\v.pb.WalletsR\awallets2\x82\x06\n" + + "\rwalletService\x12T\n" + + "\x15AddWalletTransactions\x12\x1c.pb.AddWalletTransactionsReq\x1a\x1d.pb.AddWalletTransactionsResp\x12]\n" + + "\x18UpdateWalletTransactions\x12\x1f.pb.UpdateWalletTransactionsReq\x1a .pb.UpdateWalletTransactionsResp\x12T\n" + + "\x15DelWalletTransactions\x12\x1c.pb.DelWalletTransactionsReq\x1a\x1d.pb.DelWalletTransactionsResp\x12`\n" + + "\x19GetWalletTransactionsById\x12 .pb.GetWalletTransactionsByIdReq\x1a!.pb.GetWalletTransactionsByIdResp\x12]\n" + + "\x18SearchWalletTransactions\x12\x1f.pb.SearchWalletTransactionsReq\x1a .pb.SearchWalletTransactionsResp\x123\n" + + "\n" + + "AddWallets\x12\x11.pb.AddWalletsReq\x1a\x12.pb.AddWalletsResp\x12<\n" + + "\rUpdateWallets\x12\x14.pb.UpdateWalletsReq\x1a\x15.pb.UpdateWalletsResp\x123\n" + + "\n" + + "DelWallets\x12\x11.pb.DelWalletsReq\x1a\x12.pb.DelWalletsResp\x12?\n" + + "\x0eGetWalletsById\x12\x15.pb.GetWalletsByIdReq\x1a\x16.pb.GetWalletsByIdResp\x12<\n" + + "\rSearchWallets\x12\x14.pb.SearchWalletsReq\x1a\x15.pb.SearchWalletsRespB\x06Z\x04./pbb\x06proto3" + +var ( + file_wallet_proto_rawDescOnce sync.Once + file_wallet_proto_rawDescData []byte +) + +func file_wallet_proto_rawDescGZIP() []byte { + file_wallet_proto_rawDescOnce.Do(func() { + file_wallet_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_wallet_proto_rawDesc), len(file_wallet_proto_rawDesc))) + }) + return file_wallet_proto_rawDescData +} + +var file_wallet_proto_msgTypes = make([]protoimpl.MessageInfo, 22) +var file_wallet_proto_goTypes = []any{ + (*WalletTransactions)(nil), // 0: pb.WalletTransactions + (*AddWalletTransactionsReq)(nil), // 1: pb.AddWalletTransactionsReq + (*AddWalletTransactionsResp)(nil), // 2: pb.AddWalletTransactionsResp + (*UpdateWalletTransactionsReq)(nil), // 3: pb.UpdateWalletTransactionsReq + (*UpdateWalletTransactionsResp)(nil), // 4: pb.UpdateWalletTransactionsResp + (*DelWalletTransactionsReq)(nil), // 5: pb.DelWalletTransactionsReq + (*DelWalletTransactionsResp)(nil), // 6: pb.DelWalletTransactionsResp + (*GetWalletTransactionsByIdReq)(nil), // 7: pb.GetWalletTransactionsByIdReq + (*GetWalletTransactionsByIdResp)(nil), // 8: pb.GetWalletTransactionsByIdResp + (*SearchWalletTransactionsReq)(nil), // 9: pb.SearchWalletTransactionsReq + (*SearchWalletTransactionsResp)(nil), // 10: pb.SearchWalletTransactionsResp + (*Wallets)(nil), // 11: pb.Wallets + (*AddWalletsReq)(nil), // 12: pb.AddWalletsReq + (*AddWalletsResp)(nil), // 13: pb.AddWalletsResp + (*UpdateWalletsReq)(nil), // 14: pb.UpdateWalletsReq + (*UpdateWalletsResp)(nil), // 15: pb.UpdateWalletsResp + (*DelWalletsReq)(nil), // 16: pb.DelWalletsReq + (*DelWalletsResp)(nil), // 17: pb.DelWalletsResp + (*GetWalletsByIdReq)(nil), // 18: pb.GetWalletsByIdReq + (*GetWalletsByIdResp)(nil), // 19: pb.GetWalletsByIdResp + (*SearchWalletsReq)(nil), // 20: pb.SearchWalletsReq + (*SearchWalletsResp)(nil), // 21: pb.SearchWalletsResp +} +var file_wallet_proto_depIdxs = []int32{ + 0, // 0: pb.GetWalletTransactionsByIdResp.walletTransactions:type_name -> pb.WalletTransactions + 0, // 1: pb.SearchWalletTransactionsResp.walletTransactions:type_name -> pb.WalletTransactions + 11, // 2: pb.GetWalletsByIdResp.wallets:type_name -> pb.Wallets + 11, // 3: pb.SearchWalletsResp.wallets:type_name -> pb.Wallets + 1, // 4: pb.walletService.AddWalletTransactions:input_type -> pb.AddWalletTransactionsReq + 3, // 5: pb.walletService.UpdateWalletTransactions:input_type -> pb.UpdateWalletTransactionsReq + 5, // 6: pb.walletService.DelWalletTransactions:input_type -> pb.DelWalletTransactionsReq + 7, // 7: pb.walletService.GetWalletTransactionsById:input_type -> pb.GetWalletTransactionsByIdReq + 9, // 8: pb.walletService.SearchWalletTransactions:input_type -> pb.SearchWalletTransactionsReq + 12, // 9: pb.walletService.AddWallets:input_type -> pb.AddWalletsReq + 14, // 10: pb.walletService.UpdateWallets:input_type -> pb.UpdateWalletsReq + 16, // 11: pb.walletService.DelWallets:input_type -> pb.DelWalletsReq + 18, // 12: pb.walletService.GetWalletsById:input_type -> pb.GetWalletsByIdReq + 20, // 13: pb.walletService.SearchWallets:input_type -> pb.SearchWalletsReq + 2, // 14: pb.walletService.AddWalletTransactions:output_type -> pb.AddWalletTransactionsResp + 4, // 15: pb.walletService.UpdateWalletTransactions:output_type -> pb.UpdateWalletTransactionsResp + 6, // 16: pb.walletService.DelWalletTransactions:output_type -> pb.DelWalletTransactionsResp + 8, // 17: pb.walletService.GetWalletTransactionsById:output_type -> pb.GetWalletTransactionsByIdResp + 10, // 18: pb.walletService.SearchWalletTransactions:output_type -> pb.SearchWalletTransactionsResp + 13, // 19: pb.walletService.AddWallets:output_type -> pb.AddWalletsResp + 15, // 20: pb.walletService.UpdateWallets:output_type -> pb.UpdateWalletsResp + 17, // 21: pb.walletService.DelWallets:output_type -> pb.DelWalletsResp + 19, // 22: pb.walletService.GetWalletsById:output_type -> pb.GetWalletsByIdResp + 21, // 23: pb.walletService.SearchWallets:output_type -> pb.SearchWalletsResp + 14, // [14:24] is the sub-list for method output_type + 4, // [4:14] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name +} + +func init() { file_wallet_proto_init() } +func file_wallet_proto_init() { + if File_wallet_proto != nil { + return + } + file_wallet_proto_msgTypes[3].OneofWrappers = []any{} + file_wallet_proto_msgTypes[9].OneofWrappers = []any{} + file_wallet_proto_msgTypes[14].OneofWrappers = []any{} + file_wallet_proto_msgTypes[20].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_wallet_proto_rawDesc), len(file_wallet_proto_rawDesc)), + NumEnums: 0, + NumMessages: 22, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_wallet_proto_goTypes, + DependencyIndexes: file_wallet_proto_depIdxs, + MessageInfos: file_wallet_proto_msgTypes, + }.Build() + File_wallet_proto = out.File + file_wallet_proto_goTypes = nil + file_wallet_proto_depIdxs = nil +} diff --git a/app/wallet/rpc/pb/wallet_grpc.pb.go b/app/wallet/rpc/pb/wallet_grpc.pb.go new file mode 100644 index 0000000..1bd6317 --- /dev/null +++ b/app/wallet/rpc/pb/wallet_grpc.pb.go @@ -0,0 +1,467 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v5.29.6 +// source: wallet.proto + +package pb + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + WalletService_AddWalletTransactions_FullMethodName = "/pb.walletService/AddWalletTransactions" + WalletService_UpdateWalletTransactions_FullMethodName = "/pb.walletService/UpdateWalletTransactions" + WalletService_DelWalletTransactions_FullMethodName = "/pb.walletService/DelWalletTransactions" + WalletService_GetWalletTransactionsById_FullMethodName = "/pb.walletService/GetWalletTransactionsById" + WalletService_SearchWalletTransactions_FullMethodName = "/pb.walletService/SearchWalletTransactions" + WalletService_AddWallets_FullMethodName = "/pb.walletService/AddWallets" + WalletService_UpdateWallets_FullMethodName = "/pb.walletService/UpdateWallets" + WalletService_DelWallets_FullMethodName = "/pb.walletService/DelWallets" + WalletService_GetWalletsById_FullMethodName = "/pb.walletService/GetWalletsById" + WalletService_SearchWallets_FullMethodName = "/pb.walletService/SearchWallets" +) + +// WalletServiceClient is the client API for WalletService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type WalletServiceClient interface { + // -----------------------walletTransactions----------------------- + AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error) + UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error) + DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error) + GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error) + SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error) + // -----------------------wallets----------------------- + AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error) + UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error) + DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error) + GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error) + SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error) +} + +type walletServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewWalletServiceClient(cc grpc.ClientConnInterface) WalletServiceClient { + return &walletServiceClient{cc} +} + +func (c *walletServiceClient) AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddWalletTransactionsResp) + err := c.cc.Invoke(ctx, WalletService_AddWalletTransactions_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateWalletTransactionsResp) + err := c.cc.Invoke(ctx, WalletService_UpdateWalletTransactions_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelWalletTransactionsResp) + err := c.cc.Invoke(ctx, WalletService_DelWalletTransactions_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetWalletTransactionsByIdResp) + err := c.cc.Invoke(ctx, WalletService_GetWalletTransactionsById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchWalletTransactionsResp) + err := c.cc.Invoke(ctx, WalletService_SearchWalletTransactions_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddWalletsResp) + err := c.cc.Invoke(ctx, WalletService_AddWallets_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateWalletsResp) + err := c.cc.Invoke(ctx, WalletService_UpdateWallets_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelWalletsResp) + err := c.cc.Invoke(ctx, WalletService_DelWallets_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetWalletsByIdResp) + err := c.cc.Invoke(ctx, WalletService_GetWalletsById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *walletServiceClient) SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchWalletsResp) + err := c.cc.Invoke(ctx, WalletService_SearchWallets_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// WalletServiceServer is the server API for WalletService service. +// All implementations must embed UnimplementedWalletServiceServer +// for forward compatibility. +type WalletServiceServer interface { + // -----------------------walletTransactions----------------------- + AddWalletTransactions(context.Context, *AddWalletTransactionsReq) (*AddWalletTransactionsResp, error) + UpdateWalletTransactions(context.Context, *UpdateWalletTransactionsReq) (*UpdateWalletTransactionsResp, error) + DelWalletTransactions(context.Context, *DelWalletTransactionsReq) (*DelWalletTransactionsResp, error) + GetWalletTransactionsById(context.Context, *GetWalletTransactionsByIdReq) (*GetWalletTransactionsByIdResp, error) + SearchWalletTransactions(context.Context, *SearchWalletTransactionsReq) (*SearchWalletTransactionsResp, error) + // -----------------------wallets----------------------- + AddWallets(context.Context, *AddWalletsReq) (*AddWalletsResp, error) + UpdateWallets(context.Context, *UpdateWalletsReq) (*UpdateWalletsResp, error) + DelWallets(context.Context, *DelWalletsReq) (*DelWalletsResp, error) + GetWalletsById(context.Context, *GetWalletsByIdReq) (*GetWalletsByIdResp, error) + SearchWallets(context.Context, *SearchWalletsReq) (*SearchWalletsResp, error) + mustEmbedUnimplementedWalletServiceServer() +} + +// UnimplementedWalletServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedWalletServiceServer struct{} + +func (UnimplementedWalletServiceServer) AddWalletTransactions(context.Context, *AddWalletTransactionsReq) (*AddWalletTransactionsResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddWalletTransactions not implemented") +} +func (UnimplementedWalletServiceServer) UpdateWalletTransactions(context.Context, *UpdateWalletTransactionsReq) (*UpdateWalletTransactionsResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateWalletTransactions not implemented") +} +func (UnimplementedWalletServiceServer) DelWalletTransactions(context.Context, *DelWalletTransactionsReq) (*DelWalletTransactionsResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelWalletTransactions not implemented") +} +func (UnimplementedWalletServiceServer) GetWalletTransactionsById(context.Context, *GetWalletTransactionsByIdReq) (*GetWalletTransactionsByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetWalletTransactionsById not implemented") +} +func (UnimplementedWalletServiceServer) SearchWalletTransactions(context.Context, *SearchWalletTransactionsReq) (*SearchWalletTransactionsResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchWalletTransactions not implemented") +} +func (UnimplementedWalletServiceServer) AddWallets(context.Context, *AddWalletsReq) (*AddWalletsResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddWallets not implemented") +} +func (UnimplementedWalletServiceServer) UpdateWallets(context.Context, *UpdateWalletsReq) (*UpdateWalletsResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateWallets not implemented") +} +func (UnimplementedWalletServiceServer) DelWallets(context.Context, *DelWalletsReq) (*DelWalletsResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelWallets not implemented") +} +func (UnimplementedWalletServiceServer) GetWalletsById(context.Context, *GetWalletsByIdReq) (*GetWalletsByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetWalletsById not implemented") +} +func (UnimplementedWalletServiceServer) SearchWallets(context.Context, *SearchWalletsReq) (*SearchWalletsResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchWallets not implemented") +} +func (UnimplementedWalletServiceServer) mustEmbedUnimplementedWalletServiceServer() {} +func (UnimplementedWalletServiceServer) testEmbeddedByValue() {} + +// UnsafeWalletServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to WalletServiceServer will +// result in compilation errors. +type UnsafeWalletServiceServer interface { + mustEmbedUnimplementedWalletServiceServer() +} + +func RegisterWalletServiceServer(s grpc.ServiceRegistrar, srv WalletServiceServer) { + // If the following call panics, it indicates UnimplementedWalletServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&WalletService_ServiceDesc, srv) +} + +func _WalletService_AddWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddWalletTransactionsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).AddWalletTransactions(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_AddWalletTransactions_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).AddWalletTransactions(ctx, req.(*AddWalletTransactionsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_UpdateWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateWalletTransactionsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).UpdateWalletTransactions(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_UpdateWalletTransactions_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).UpdateWalletTransactions(ctx, req.(*UpdateWalletTransactionsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_DelWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelWalletTransactionsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).DelWalletTransactions(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_DelWalletTransactions_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).DelWalletTransactions(ctx, req.(*DelWalletTransactionsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_GetWalletTransactionsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetWalletTransactionsByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).GetWalletTransactionsById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_GetWalletTransactionsById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).GetWalletTransactionsById(ctx, req.(*GetWalletTransactionsByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_SearchWalletTransactions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchWalletTransactionsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).SearchWalletTransactions(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_SearchWalletTransactions_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).SearchWalletTransactions(ctx, req.(*SearchWalletTransactionsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_AddWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddWalletsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).AddWallets(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_AddWallets_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).AddWallets(ctx, req.(*AddWalletsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_UpdateWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateWalletsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).UpdateWallets(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_UpdateWallets_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).UpdateWallets(ctx, req.(*UpdateWalletsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_DelWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelWalletsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).DelWallets(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_DelWallets_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).DelWallets(ctx, req.(*DelWalletsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_GetWalletsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetWalletsByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).GetWalletsById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_GetWalletsById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).GetWalletsById(ctx, req.(*GetWalletsByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _WalletService_SearchWallets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchWalletsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).SearchWallets(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_SearchWallets_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).SearchWallets(ctx, req.(*SearchWalletsReq)) + } + return interceptor(ctx, in, info, handler) +} + +// WalletService_ServiceDesc is the grpc.ServiceDesc for WalletService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var WalletService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.walletService", + HandlerType: (*WalletServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "AddWalletTransactions", + Handler: _WalletService_AddWalletTransactions_Handler, + }, + { + MethodName: "UpdateWalletTransactions", + Handler: _WalletService_UpdateWalletTransactions_Handler, + }, + { + MethodName: "DelWalletTransactions", + Handler: _WalletService_DelWalletTransactions_Handler, + }, + { + MethodName: "GetWalletTransactionsById", + Handler: _WalletService_GetWalletTransactionsById_Handler, + }, + { + MethodName: "SearchWalletTransactions", + Handler: _WalletService_SearchWalletTransactions_Handler, + }, + { + MethodName: "AddWallets", + Handler: _WalletService_AddWallets_Handler, + }, + { + MethodName: "UpdateWallets", + Handler: _WalletService_UpdateWallets_Handler, + }, + { + MethodName: "DelWallets", + Handler: _WalletService_DelWallets_Handler, + }, + { + MethodName: "GetWalletsById", + Handler: _WalletService_GetWalletsById_Handler, + }, + { + MethodName: "SearchWallets", + Handler: _WalletService_SearchWallets_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "wallet.proto", +} diff --git a/app/wallet/rpc/walletservice/walletService.go b/app/wallet/rpc/walletservice/walletService.go new file mode 100644 index 0000000..8fa305c --- /dev/null +++ b/app/wallet/rpc/walletservice/walletService.go @@ -0,0 +1,116 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.9.2 +// Source: wallet.proto + +package walletservice + +import ( + "context" + + "juwan-backend/app/wallet/rpc/pb" + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + AddWalletTransactionsReq = pb.AddWalletTransactionsReq + AddWalletTransactionsResp = pb.AddWalletTransactionsResp + AddWalletsReq = pb.AddWalletsReq + AddWalletsResp = pb.AddWalletsResp + DelWalletTransactionsReq = pb.DelWalletTransactionsReq + DelWalletTransactionsResp = pb.DelWalletTransactionsResp + DelWalletsReq = pb.DelWalletsReq + DelWalletsResp = pb.DelWalletsResp + GetWalletTransactionsByIdReq = pb.GetWalletTransactionsByIdReq + GetWalletTransactionsByIdResp = pb.GetWalletTransactionsByIdResp + GetWalletsByIdReq = pb.GetWalletsByIdReq + GetWalletsByIdResp = pb.GetWalletsByIdResp + SearchWalletTransactionsReq = pb.SearchWalletTransactionsReq + SearchWalletTransactionsResp = pb.SearchWalletTransactionsResp + SearchWalletsReq = pb.SearchWalletsReq + SearchWalletsResp = pb.SearchWalletsResp + UpdateWalletTransactionsReq = pb.UpdateWalletTransactionsReq + UpdateWalletTransactionsResp = pb.UpdateWalletTransactionsResp + UpdateWalletsReq = pb.UpdateWalletsReq + UpdateWalletsResp = pb.UpdateWalletsResp + WalletTransactions = pb.WalletTransactions + Wallets = pb.Wallets + + WalletService interface { + // -----------------------walletTransactions----------------------- + AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error) + UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error) + DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error) + GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error) + SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error) + // -----------------------wallets----------------------- + AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error) + UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error) + DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error) + GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error) + SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error) + } + + defaultWalletService struct { + cli zrpc.Client + } +) + +func NewWalletService(cli zrpc.Client) WalletService { + return &defaultWalletService{ + cli: cli, + } +} + +// -----------------------walletTransactions----------------------- +func (m *defaultWalletService) AddWalletTransactions(ctx context.Context, in *AddWalletTransactionsReq, opts ...grpc.CallOption) (*AddWalletTransactionsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.AddWalletTransactions(ctx, in, opts...) +} + +func (m *defaultWalletService) UpdateWalletTransactions(ctx context.Context, in *UpdateWalletTransactionsReq, opts ...grpc.CallOption) (*UpdateWalletTransactionsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.UpdateWalletTransactions(ctx, in, opts...) +} + +func (m *defaultWalletService) DelWalletTransactions(ctx context.Context, in *DelWalletTransactionsReq, opts ...grpc.CallOption) (*DelWalletTransactionsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.DelWalletTransactions(ctx, in, opts...) +} + +func (m *defaultWalletService) GetWalletTransactionsById(ctx context.Context, in *GetWalletTransactionsByIdReq, opts ...grpc.CallOption) (*GetWalletTransactionsByIdResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.GetWalletTransactionsById(ctx, in, opts...) +} + +func (m *defaultWalletService) SearchWalletTransactions(ctx context.Context, in *SearchWalletTransactionsReq, opts ...grpc.CallOption) (*SearchWalletTransactionsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.SearchWalletTransactions(ctx, in, opts...) +} + +// -----------------------wallets----------------------- +func (m *defaultWalletService) AddWallets(ctx context.Context, in *AddWalletsReq, opts ...grpc.CallOption) (*AddWalletsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.AddWallets(ctx, in, opts...) +} + +func (m *defaultWalletService) UpdateWallets(ctx context.Context, in *UpdateWalletsReq, opts ...grpc.CallOption) (*UpdateWalletsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.UpdateWallets(ctx, in, opts...) +} + +func (m *defaultWalletService) DelWallets(ctx context.Context, in *DelWalletsReq, opts ...grpc.CallOption) (*DelWalletsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.DelWallets(ctx, in, opts...) +} + +func (m *defaultWalletService) GetWalletsById(ctx context.Context, in *GetWalletsByIdReq, opts ...grpc.CallOption) (*GetWalletsByIdResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.GetWalletsById(ctx, in, opts...) +} + +func (m *defaultWalletService) SearchWallets(ctx context.Context, in *SearchWalletsReq, opts ...grpc.CallOption) (*SearchWalletsResp, error) { + client := pb.NewWalletServiceClient(m.cli.Conn()) + return client.SearchWallets(ctx, in, opts...) +} diff --git a/deploy/k8s/postgreSql.yaml b/backup/postgreSql.yaml similarity index 95% rename from deploy/k8s/postgreSql.yaml rename to backup/postgreSql.yaml index ba1f0cc..16dcd63 100644 --- a/deploy/k8s/postgreSql.yaml +++ b/backup/postgreSql.yaml @@ -1,22 +1,22 @@ -apiVersion: postgresql.cnpg.io/v1 -kind: Cluster -metadata: - namespace: juwan - name: cluster-example -spec: - instances: 3 - backup: - barmanObjectStore: - destinationPath: s3://juwan-dev-pg-backups-zj/pg-data/ - endpointURL: https://cn-nb1.rains3.com - s3Credentials: - accessKeyId: - name: rc-creds - key: ACCESS_KEY_ID - secretAccessKey: - name: rc-creds - key: SECRET_ACCESS_KEY - wal: - compression: gzip - storage: - size: 1Gi +apiVersion: postgresql.cnpg.io/v1 +kind: Cluster +metadata: + namespace: juwan + name: cluster-example +spec: + instances: 3 + backup: + barmanObjectStore: + destinationPath: s3://juwan-dev-pg-backups-zj/pg-data/ + endpointURL: https://cn-nb1.rains3.com + s3Credentials: + accessKeyId: + name: rc-creds + key: ACCESS_KEY_ID + secretAccessKey: + name: rc-creds + key: SECRET_ACCESS_KEY + wal: + compression: gzip + storage: + size: 1Gi diff --git a/common/utils/contextx/contextx.go b/common/utils/contextj/contextx.go similarity index 99% rename from common/utils/contextx/contextx.go rename to common/utils/contextj/contextx.go index 9b9d29c..cdb8c43 100644 --- a/common/utils/contextx/contextx.go +++ b/common/utils/contextj/contextx.go @@ -1,4 +1,4 @@ -package contextx +package contextj import ( "context" diff --git a/common/utils/httpx/httpx.go b/common/utils/httpj/httpx.go similarity index 97% rename from common/utils/httpx/httpx.go rename to common/utils/httpj/httpx.go index 8d480f6..b1a319f 100644 --- a/common/utils/httpx/httpx.go +++ b/common/utils/httpj/httpx.go @@ -1,4 +1,4 @@ -package httpx +package httpj import ( "net/http" diff --git a/deploy/docker/.env.example b/deploy/docker/.env.example new file mode 100644 index 0000000..152e774 --- /dev/null +++ b/deploy/docker/.env.example @@ -0,0 +1,4 @@ +HARBOR_REGISTRY=harbor.example.com +HARBOR_PROJECT=juwan +IMAGE_NAME=st-1-example +IMAGE_TAG=latest diff --git a/deploy/docker/README.md b/deploy/docker/README.md new file mode 100644 index 0000000..7d8bbc2 --- /dev/null +++ b/deploy/docker/README.md @@ -0,0 +1,48 @@ +# Docker 服务器部署方案(Gitea Actions) + +本方案替代 Jenkins: + +1. `push` 代码后由 Gitea Actions 构建镜像并推送 Harbor。 +2. 同一工作流通过 SSH 连接服务器,执行 `docker compose pull && docker compose up -d` 完成更新。 + +## 1) 服务器准备 + +在目标服务器安装: + +- Docker Engine +- Docker Compose 插件(`docker compose version` 可用) + +并确保部署用户有 docker 权限: + +```bash +sudo usermod -aG docker +``` + +## 2) Gitea 仓库 Secrets + +在仓库中配置以下 Secrets: + +- `HARBOR_REGISTRY`:例如 `harbor.example.com` +- `HARBOR_PROJECT`:例如 `juwan` +- `HARBOR_USERNAME` +- `HARBOR_PASSWORD` +- `DEPLOY_HOST`:服务器地址 +- `DEPLOY_PORT`:可选,默认 `22` +- `DEPLOY_USER`:服务器 SSH 用户 +- `DEPLOY_SSH_KEY`:私钥内容(PEM) +- `DEPLOY_PATH`:可选,默认 `/opt/st-1-example` + +## 3) 触发规则 + +- 构建推送:`main/master/dev/feature/**` +- 自动部署:仅 `main/master` + +如需改分支规则,编辑: + +- `.gitea/workflows/build-push-harbor.yml` + +## 4) 端口与服务 + +Compose 文件:`deploy/docker/docker-compose.yml` + +默认映射:`8888:8888`,服务名:`st-example`。 diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml new file mode 100644 index 0000000..17888ef --- /dev/null +++ b/deploy/docker/docker-compose.yml @@ -0,0 +1,9 @@ +services: + st-example: + image: ${HARBOR_REGISTRY}/${HARBOR_PROJECT}/${IMAGE_NAME}:${IMAGE_TAG:-latest} + container_name: st-example + restart: always + ports: + - "8888:8888" + environment: + TZ: Asia/Shanghai diff --git a/deploy/k8s/envoy/envoy.yaml b/deploy/k8s/envoy/envoy.yaml index 113708a..757807c 100644 --- a/deploy/k8s/envoy/envoy.yaml +++ b/deploy/k8s/envoy/envoy.yaml @@ -131,11 +131,21 @@ data: timeout: 30s # ===== 未来按服务拆分路由(服务未落地前先注释) ===== - # - match: - # prefix: /api/v1/games - # route: - # cluster: game_api_cluster - # timeout: 30s + - match: + prefix: /api/v1/games + route: + cluster: game_api_cluster + timeout: 30s + - match: + prefix: /api/v1/players + route: + cluster: player_api_cluster + timeout: 30s + # - match: + # prefix: /api/v1/shop + # route: + # cluster: player_api_cluster + # timeout: 30s # - match: # prefix: /api/v1/orders # route: @@ -551,35 +561,93 @@ data: socket_address: address: email-api-svc.juwan.svc.cluster.local port_value: 8888 - + + - name: player_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: player_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: player-api-svc.juwan.svc.cluster.local + port_value: 8888 + + - name: game_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: game_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: game-api-svc.juwan.svc.cluster.local + port_value: 8888 + + - name: objectstory_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: objectstory_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: objectstory-api-svc.juwan.svc.cluster.local + port_value: 8888 + + - name: wallet_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: wallet_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: wallet-api-svc.juwan.svc.cluster.local + port_value: 8888 + + - name: shop_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: shop_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: shop-api-svc.juwan.svc.cluster.local + port_value: 8888 + + - name: community_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: community_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: community-api-svc.juwan.svc.cluster.local + port_value: 8888 + # ===== 未来服务集群预留(当前未实现,先注释) ===== - # - name: game_api_cluster - # connect_timeout: 2s - # type: STRICT_DNS - # lb_policy: ROUND_ROBIN - # load_assignment: - # cluster_name: game_api_cluster - # endpoints: - # - lb_endpoints: - # - endpoint: - # address: - # socket_address: - # address: game-api-svc.juwan.svc.cluster.local - # port_value: 8888 # - # - name: objectstory_api_cluster - # connect_timeout: 2s - # type: STRICT_DNS - # lb_policy: ROUND_ROBIN - # load_assignment: - # cluster_name: objectstory_api_cluster - # endpoints: - # - lb_endpoints: - # - endpoint: - # address: - # socket_address: - # address: objectstory-api-svc.juwan.svc.cluster.local - # port_value: 8888 # # - name: order_api_cluster # connect_timeout: 2s @@ -595,19 +663,6 @@ data: # address: order-api-svc.juwan.svc.cluster.local # port_value: 8888 # - # - name: player_api_cluster - # connect_timeout: 2s - # type: STRICT_DNS - # lb_policy: ROUND_ROBIN - # load_assignment: - # cluster_name: player_api_cluster - # endpoints: - # - lb_endpoints: - # - endpoint: - # address: - # socket_address: - # address: player-api-svc.juwan.svc.cluster.local - # port_value: 8888 # # - name: shop_api_cluster # connect_timeout: 2s diff --git a/deploy/k8s/service/game/game-api.yaml b/deploy/k8s/service/game/game-api.yaml new file mode 100644 index 0000000..8fc8195 --- /dev/null +++ b/deploy/k8s/service/game/game-api.yaml @@ -0,0 +1,121 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: game-api + namespace: juwan + labels: + app: game-api +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: game-api + template: + metadata: + labels: + app: game-api + spec: + serviceAccountName: find-endpoints + containers: + - name: game-api + image: game-api:latest + imagePullPolicy: Always + ports: + - containerPort: 8888 + - containerPort: 4001 # 暴露端口 + readinessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: game-api-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8888 + targetPort: 8888 + selector: + app: game-api + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: game-api-hpa-c + namespace: juwan + labels: + app: game-api-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: game-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: game-api-hpa-m + namespace: juwan + labels: + app: game-api-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: game-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + diff --git a/deploy/k8s/service/game/game-rpc.yaml b/deploy/k8s/service/game/game-rpc.yaml new file mode 100644 index 0000000..e39b453 --- /dev/null +++ b/deploy/k8s/service/game/game-rpc.yaml @@ -0,0 +1,254 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: game-rpc + namespace: juwan + labels: + app: game-rpc +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: game-rpc + template: + metadata: + labels: + app: game-rpc + spec: + serviceAccountName: find-endpoints + containers: + - name: game-rpc + image: game-rpc:latest + imagePullPolicy: Always + ports: + - containerPort: 8080 + - containerPort: 4001 # 暴露端口 + env: + - name: DB_PORT + valueFrom: + secretKeyRef: + name: user-db-app + key: port + - name: DB_PASSWORD + valueFrom: + secretKeyRef: + name: user-db-app + key: password + - name: PD_USERNAME + valueFrom: + secretKeyRef: + name: user-db-app + key: username + - name: DB_NAME + valueFrom: + secretKeyRef: + name: user-db-app + key: dbname + - name: REDIS_M_HOST + value: "user-redis-master.juwan:6379" + - name: REDIS_S_HOST + value: "user-redis-replica.juwan:6379" + - name: REDIS_PASSWORD + valueFrom: + secretKeyRef: + name: user-redis + key: password + readinessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: game-rpc-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8080 + targetPort: 8080 + selector: + app: game-rpc + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: game-rpc-hpa-c + namespace: juwan + labels: + app: game-rpc-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: game-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: game-rpc-hpa-m + namespace: juwan + labels: + app: game-rpc-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: game-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + +#--- +## Redis 主从复制 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisReplication +#metadata: +# name: game-redis +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# redisSecret: # 记得创建密码 +# name: game-redis +# key: password +# +# redisExporter: +# enabled: true +# image: quay.io/opstree/redis-exporter:latest +# imagePullPolicy: Always +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# storage: +# volumeClaimTemplate: +# spec: +# accessModes: ["ReadWriteOnce"] +# resources: +# requests: +# storage: 1Gi +# +#--- +## Sentinel 监控 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisSentinel +#metadata: +# name: game-rpc-redis-sentinel +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis-sentinel:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# redisSentinelConfig: +# redisReplicationName: game-redis +# masterGroupName: mymaster +# redisPort: "6379" +# quorum: "2" +# downAfterMilliseconds: "5000" +# failoverTimeout: "10000" +# parallelSyncs: "1" +# +#--- +## PostgreSQL 集群 +#apiVersion: postgresql.cnpg.io/v1 +#kind: Cluster +#metadata: +# namespace: juwan +# name: game-db +#spec: +# instances: 3 +# primaryUpdateStrategy: unsupervised +# bootstrap: +# initdb: +# database: app +# owner: app +# # 只在 PVC 为空时初始化 +# postInitSQL: +# - CREATE EXTENSION IF NOT EXISTS pg_stat_statements; +# backup: +# barmanObjectStore: +# destinationPath: s3://juwan-dev-pg-backups-zj/pg-data/ +# endpointURL: https://cn-nb1.rains3.com +# s3Credentials: +# accessKeyId: +# name: rc-creds +# key: ACCESS_KEY_ID +# secretAccessKey: +# name: rc-creds +# key: SECRET_ACCESS_KEY +# wal: +# compression: gzip +# storage: +# size: 1Gi +# monitoring: +# enablePodMonitor: true diff --git a/deploy/k8s/service/objectStorge/s3storge-api.yaml b/deploy/k8s/service/objectStorge/s3storge-api.yaml new file mode 100644 index 0000000..e44aa40 --- /dev/null +++ b/deploy/k8s/service/objectStorge/s3storge-api.yaml @@ -0,0 +1,120 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: s3storge-api + namespace: juwan + labels: + app: s3storge-api +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: s3storge-api + template: + metadata: + labels: + app: s3storge-api + spec: + serviceAccountName: find-endpoints + containers: + - name: s3storge-api + image: s3storge-api:latest + ports: + - containerPort: 8888 + - containerPort: 4001 # 暴露端口 + readinessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: s3storge-api-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8888 + targetPort: 8888 + selector: + app: s3storge-api + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: s3storge-api-hpa-c + namespace: juwan + labels: + app: s3storge-api-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: s3storge-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: s3storge-api-hpa-m + namespace: juwan + labels: + app: s3storge-api-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: s3storge-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + diff --git a/deploy/k8s/service/objectStorge/s3storge-rpc.yaml b/deploy/k8s/service/objectStorge/s3storge-rpc.yaml new file mode 100644 index 0000000..950675b --- /dev/null +++ b/deploy/k8s/service/objectStorge/s3storge-rpc.yaml @@ -0,0 +1,119 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: s3storge-rpc + namespace: juwan + labels: + app: s3storge-rpc +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: s3storge-rpc + template: + metadata: + labels: + app: s3storge-rpc + spec: + serviceAccountName: find-endpoints + containers: + - name: s3storge-rpc + image: s3storge-rpc:latest + ports: + - containerPort: 8080 + - containerPort: 4001 # 暴露端口 + readinessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: s3storge-rpc-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - port: 8080 + targetPort: 8080 + selector: + app: s3storge-rpc + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: s3storge-rpc-hpa-c + namespace: juwan + labels: + app: s3storge-rpc-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: s3storge-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: s3storge-rpc-hpa-m + namespace: juwan + labels: + app: s3storge-rpc-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: s3storge-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + diff --git a/deploy/k8s/service/player/player-api.yaml b/deploy/k8s/service/player/player-api.yaml new file mode 100644 index 0000000..a315f43 --- /dev/null +++ b/deploy/k8s/service/player/player-api.yaml @@ -0,0 +1,116 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: player-api + namespace: juwan + labels: + app: player-api +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: player-api + template: + metadata: + labels: + app: player-api + spec: + serviceAccountName: find-endpoints + containers: + - name: player-api + image: player-api:latest + ports: + - containerPort: 8888 + - containerPort: 4001 # 暴露端口 + readinessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- +apiVersion: v1 +kind: Service +metadata: + name: player-api-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8888 + targetPort: 8888 + selector: + app: player-api + +--- +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: player-api-hpa-c + namespace: juwan + labels: + app: player-api-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: player-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: player-api-hpa-m + namespace: juwan + labels: + app: player-api-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: player-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 diff --git a/deploy/k8s/service/player/player-rpc.yaml b/deploy/k8s/service/player/player-rpc.yaml new file mode 100644 index 0000000..fa5b04a --- /dev/null +++ b/deploy/k8s/service/player/player-rpc.yaml @@ -0,0 +1,254 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: player-rpc + namespace: juwan + labels: + app: player-rpc +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: player-rpc + template: + metadata: + labels: + app: player-rpc + spec: + serviceAccountName: find-endpoints + containers: + - name: player-rpc + image: player-rpc:latest + imagePullPolicy: Always + ports: + - containerPort: 8080 + - containerPort: 4001 # 暴露端口 + env: + - name: DB_PORT + valueFrom: + secretKeyRef: + name: user-db-app + key: port + - name: DB_PASSWORD + valueFrom: + secretKeyRef: + name: user-db-app + key: password + - name: PD_USERNAME + valueFrom: + secretKeyRef: + name: user-db-app + key: username + - name: DB_NAME + valueFrom: + secretKeyRef: + name: user-db-app + key: dbname + - name: REDIS_M_HOST + value: "user-redis-master.juwan:6379" + - name: REDIS_S_HOST + value: "user-redis-replica.juwan:6379" + - name: REDIS_PASSWORD + valueFrom: + secretKeyRef: + name: user-redis + key: password + readinessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: player-rpc-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8080 + targetPort: 8080 + selector: + app: player-rpc + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: player-rpc-hpa-c + namespace: juwan + labels: + app: player-rpc-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: player-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: player-rpc-hpa-m + namespace: juwan + labels: + app: player-rpc-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: player-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + +#--- +## Redis 主从复制 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisReplication +#metadata: +# name: player-rpc-redis +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# redisSecret: # 记得创建密码 +# name: player-rpc-redis +# key: password +# +# redisExporter: +# enabled: true +# image: quay.io/opstree/redis-exporter:latest +# imagePullPolicy: Always +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# storage: +# volumeClaimTemplate: +# spec: +# accessModes: ["ReadWriteOnce"] +# resources: +# requests: +# storage: 1Gi +# +#--- +## Sentinel 监控 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisSentinel +#metadata: +# name: player-rpc-redis-sentinel +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis-sentinel:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# redisSentinelConfig: +# redisReplicationName: player-rpc-redis +# masterGroupName: mymaster +# redisPort: "6379" +# quorum: "2" +# downAfterMilliseconds: "5000" +# failoverTimeout: "10000" +# parallelSyncs: "1" +# +#--- +## PostgreSQL 集群 +#apiVersion: postgresql.cnpg.io/v1 +#kind: Cluster +#metadata: +# namespace: juwan +# name: player-rpc-db +#spec: +# instances: 3 +# primaryUpdateStrategy: unsupervised +# bootstrap: +# initdb: +# database: app +# owner: app +# # 只在 PVC 为空时初始化 +# postInitSQL: +# - CREATE EXTENSION IF NOT EXISTS pg_stat_statements; +# backup: +# barmanObjectStore: +# destinationPath: s3://juwan-dev-pg-backups-zj/pg-data/ +# endpointURL: https://cn-nb1.rains3.com +# s3Credentials: +# accessKeyId: +# name: rc-creds +# key: ACCESS_KEY_ID +# secretAccessKey: +# name: rc-creds +# key: SECRET_ACCESS_KEY +# wal: +# compression: gzip +# storage: +# size: 1Gi +# monitoring: +# enablePodMonitor: true diff --git a/deploy/k8s/service/shop/shop-api.yaml b/deploy/k8s/service/shop/shop-api.yaml new file mode 100644 index 0000000..c824993 --- /dev/null +++ b/deploy/k8s/service/shop/shop-api.yaml @@ -0,0 +1,120 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: shop-api + namespace: juwan + labels: + app: shop-api +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: shop-api + template: + metadata: + labels: + app: shop-api + spec: + serviceAccountName: find-endpoints + containers: + - name: shop-api + image: shop-api:latest + ports: + - containerPort: 8888 + - containerPort: 4001 # 暴露端口 + readinessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: shop-api-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8888 + targetPort: 8888 + selector: + app: shop-api + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: shop-api-hpa-c + namespace: juwan + labels: + app: shop-api-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: shop-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: shop-api-hpa-m + namespace: juwan + labels: + app: shop-api-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: shop-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + diff --git a/deploy/k8s/service/shop/shop-rpc.yaml b/deploy/k8s/service/shop/shop-rpc.yaml new file mode 100644 index 0000000..535847f --- /dev/null +++ b/deploy/k8s/service/shop/shop-rpc.yaml @@ -0,0 +1,253 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: shop-rpc + namespace: juwan + labels: + app: shop-rpc +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: shop-rpc + template: + metadata: + labels: + app: shop-rpc + spec: + serviceAccountName: find-endpoints + containers: + - name: shop-rpc + image: shop-rpc:latest + ports: + - containerPort: 8080 + - containerPort: 4001 # 暴露端口 + env: + - name: DB_PORT + valueFrom: + secretKeyRef: + name: user-db-app + key: port + - name: DB_PASSWORD + valueFrom: + secretKeyRef: + name: user-db-app + key: password + - name: PD_USERNAME + valueFrom: + secretKeyRef: + name: user-db-app + key: username + - name: DB_NAME + valueFrom: + secretKeyRef: + name: user-db-app + key: dbname + - name: REDIS_M_HOST + value: "user-redis-master.juwan:6379" + - name: REDIS_S_HOST + value: "user-redis-replica.juwan:6379" + - name: REDIS_PASSWORD + valueFrom: + secretKeyRef: + name: user-redis + key: password + readinessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: shop-rpc-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8080 + targetPort: 8080 + selector: + app: shop-rpc + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: shop-rpc-hpa-c + namespace: juwan + labels: + app: shop-rpc-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: shop-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: shop-rpc-hpa-m + namespace: juwan + labels: + app: shop-rpc-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: shop-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + +#--- +## Redis 主从复制 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisReplication +#metadata: +# name: shop-rpc-redis +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# redisSecret: # 记得创建密码 +# name: shop-rpc-redis +# key: password +# +# redisExporter: +# enabled: true +# image: quay.io/opstree/redis-exporter:latest +# imagePullPolicy: Always +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# storage: +# volumeClaimTemplate: +# spec: +# accessModes: ["ReadWriteOnce"] +# resources: +# requests: +# storage: 1Gi +# +#--- +## Sentinel 监控 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisSentinel +#metadata: +# name: shop-rpc-redis-sentinel +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis-sentinel:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# redisSentinelConfig: +# redisReplicationName: shop-rpc-redis +# masterGroupName: mymaster +# redisPort: "6379" +# quorum: "2" +# downAfterMilliseconds: "5000" +# failoverTimeout: "10000" +# parallelSyncs: "1" +# +#--- +## PostgreSQL 集群 +#apiVersion: postgresql.cnpg.io/v1 +#kind: Cluster +#metadata: +# namespace: juwan +# name: shop-rpc-db +#spec: +# instances: 3 +# primaryUpdateStrategy: unsupervised +# bootstrap: +# initdb: +# database: app +# owner: app +# # 只在 PVC 为空时初始化 +# postInitSQL: +# - CREATE EXTENSION IF NOT EXISTS pg_stat_statements; +# backup: +# barmanObjectStore: +# destinationPath: s3://juwan-dev-pg-backups-zj/pg-data/ +# endpointURL: https://cn-nb1.rains3.com +# s3Credentials: +# accessKeyId: +# name: rc-creds +# key: ACCESS_KEY_ID +# secretAccessKey: +# name: rc-creds +# key: SECRET_ACCESS_KEY +# wal: +# compression: gzip +# storage: +# size: 1Gi +# monitoring: +# enablePodMonitor: true diff --git a/deploy/k8s/service/wallet/wallet-api.yaml b/deploy/k8s/service/wallet/wallet-api.yaml new file mode 100644 index 0000000..b098003 --- /dev/null +++ b/deploy/k8s/service/wallet/wallet-api.yaml @@ -0,0 +1,120 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: wallet-api + namespace: juwan + labels: + app: wallet-api +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: wallet-api + template: + metadata: + labels: + app: wallet-api + spec: + serviceAccountName: find-endpoints + containers: + - name: wallet-api + image: wallet-api:latest + ports: + - containerPort: 8888 + - containerPort: 4001 # 暴露端口 + readinessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8888 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: wallet-api-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8888 + targetPort: 8888 + selector: + app: wallet-api + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: wallet-api-hpa-c + namespace: juwan + labels: + app: wallet-api-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: wallet-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: wallet-api-hpa-m + namespace: juwan + labels: + app: wallet-api-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: wallet-api + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + \ No newline at end of file diff --git a/deploy/k8s/service/wallet/wallet-rpc.yaml b/deploy/k8s/service/wallet/wallet-rpc.yaml new file mode 100644 index 0000000..10a4ef3 --- /dev/null +++ b/deploy/k8s/service/wallet/wallet-rpc.yaml @@ -0,0 +1,253 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: wallet-rpc + namespace: juwan + labels: + app: wallet-rpc +spec: + replicas: 3 + revisionHistoryLimit: 5 + selector: + matchLabels: + app: wallet-rpc + template: + metadata: + labels: + app: wallet-rpc + spec: + serviceAccountName: find-endpoints + containers: + - name: wallet-rpc + image: wallet-rpc:latest + ports: + - containerPort: 8080 + - containerPort: 4001 # 暴露端口 + env: + - name: DB_PORT + valueFrom: + secretKeyRef: + name: user-db-app + key: port + - name: DB_PASSWORD + valueFrom: + secretKeyRef: + name: user-db-app + key: password + - name: PD_USERNAME + valueFrom: + secretKeyRef: + name: user-db-app + key: username + - name: DB_NAME + valueFrom: + secretKeyRef: + name: user-db-app + key: dbname + - name: REDIS_M_HOST + value: "user-redis-master.juwan:6379" + - name: REDIS_S_HOST + value: "user-redis-replica.juwan:6379" + - name: REDIS_PASSWORD + valueFrom: + secretKeyRef: + name: user-redis + key: password + readinessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 1000m + memory: 1024Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: wallet-rpc-svc + namespace: juwan + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "4001" + prometheus.io/path: "/metrics" +spec: + ports: + - name: metrics + port: 4001 + targetPort: 4001 + - name: http + port: 8080 + targetPort: 8080 + selector: + app: wallet-rpc + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: wallet-rpc-hpa-c + namespace: juwan + labels: + app: wallet-rpc-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: wallet-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: wallet-rpc-hpa-m + namespace: juwan + labels: + app: wallet-rpc-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: wallet-rpc + minReplicas: 3 + maxReplicas: 10 + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 + +#--- +## Redis 主从复制 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisReplication +#metadata: +# name: wallet-rpc-redis +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# redisSecret: # 记得创建密码 +# name: wallet-rpc-redis +# key: password +# +# redisExporter: +# enabled: true +# image: quay.io/opstree/redis-exporter:latest +# imagePullPolicy: Always +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# storage: +# volumeClaimTemplate: +# spec: +# accessModes: ["ReadWriteOnce"] +# resources: +# requests: +# storage: 1Gi +# +#--- +## Sentinel 监控 +#apiVersion: redis.redis.opstreelabs.in/v1beta2 +#kind: RedisSentinel +#metadata: +# name: wallet-rpc-redis-sentinel +# namespace: juwan +#spec: +# clusterSize: 3 +# kubernetesConfig: +# image: quay.io/opstree/redis-sentinel:v7.0.12 +# imagePullPolicy: IfNotPresent +# resources: +# requests: +# cpu: 100m +# memory: 128Mi +# limits: +# cpu: 500m +# memory: 512Mi +# podSecurityContext: +# runAsUser: 1000 +# fsGroup: 1000 +# redisSentinelConfig: +# redisReplicationName: wallet-rpc-redis +# masterGroupName: mymaster +# redisPort: "6379" +# quorum: "2" +# downAfterMilliseconds: "5000" +# failoverTimeout: "10000" +# parallelSyncs: "1" +# +#--- +## PostgreSQL 集群 +#apiVersion: postgresql.cnpg.io/v1 +#kind: Cluster +#metadata: +# namespace: juwan +# name: wallet-rpc-db +#spec: +# instances: 3 +# primaryUpdateStrategy: unsupervised +# bootstrap: +# initdb: +# database: app +# owner: app +# # 只在 PVC 为空时初始化 +# postInitSQL: +# - CREATE EXTENSION IF NOT EXISTS pg_stat_statements; +# backup: +# barmanObjectStore: +# destinationPath: s3://juwan-dev-pg-backups-zj/pg-data/ +# endpointURL: https://cn-nb1.rains3.com +# s3Credentials: +# accessKeyId: +# name: rc-creds +# key: ACCESS_KEY_ID +# secretAccessKey: +# name: rc-creds +# key: SECRET_ACCESS_KEY +# wal: +# compression: gzip +# storage: +# size: 1Gi +# monitoring: +# enablePodMonitor: true diff --git a/desc/api/chat.api b/desc/api/chat.api index 7896132..05dec40 100644 --- a/desc/api/chat.api +++ b/desc/api/chat.api @@ -50,7 +50,7 @@ type ( prefix: api/v1/chat group: chat ) -service juwan-api { +service chat-api { @doc "获取会话列表" @handler ListSessions get /sessions (PageReq) returns (ChatSessionListResp) diff --git a/desc/api/community.api b/desc/api/community.api index e99e803..9b8e3a1 100644 --- a/desc/api/community.api +++ b/desc/api/community.api @@ -1,121 +1,117 @@ syntax = "v1" + import "common.api" type ( - PathId { - Id int64 `path:"id"` - } - Post { - Id int64 `json:"id"` - Title string `json:"title"` - Content string `json:"content"` - Images []string `json:"images"` - Tags []string `json:"tags"` - LikeCount int64 `json:"likeCount"` - CommentCount int64 `json:"commentCount"` - Liked bool `json:"liked"` - Author UserProfile `json:"author"` - CreatedAt string `json:"createdAt"` - } - - CreatePostReq { - Title string `json:"title"` - Content string `json:"content"` - Images []string `json:"images"` - Tags []string `json:"tags"` - LinkedOrderId string `json:"linkedOrderId,optional"` - } - - PostListReq { - PageReq - Tags string `form:"tags,optional"` - SortBy string `form:"sortBy,optional"` - } - - PostListResp { - Items []Post `json:"items"` - Meta PageMeta `json:"meta"` - } - - Comment { - Id int64 `json:"id"` - Content string `json:"content"` - Author UserProfile `json:"author"` - LikeCount int64 `json:"likeCount"` - Liked bool `json:"liked"` - CreatedAt string `json:"createdAt"` - } - - CommentListResp { - Items []Comment `json:"items"` - Meta PageMeta `json:"meta"` - } - - CreateCommentReq { - Content string `json:"content"` - } - ListCommentsReq { - PathId - PageReq - } + PathId { + Id int64 `path:"id"` + } + Post { + Id int64 `json:"id"` + Title string `json:"title"` + Content string `json:"content"` + Images []string `json:"images"` + Tags []string `json:"tags"` + LikeCount int64 `json:"likeCount"` + CommentCount int64 `json:"commentCount"` + Liked bool `json:"liked"` + Author UserProfile `json:"author"` + CreatedAt string `json:"createdAt"` + } + CreatePostReq { + Title string `json:"title"` + Content string `json:"content"` + Images []string `json:"images"` + Tags []string `json:"tags"` + LinkedOrderId string `json:"linkedOrderId,optional"` + } + PostListReq { + PageReq + Tags string `form:"tags,optional"` + SortBy string `form:"sortBy,optional"` + } + PostListResp { + Items []Post `json:"items"` + Meta PageMeta `json:"meta"` + } + Comment { + Id int64 `json:"id"` + Content string `json:"content"` + Author UserProfile `json:"author"` + LikeCount int64 `json:"likeCount"` + Liked bool `json:"liked"` + CreatedAt string `json:"createdAt"` + } + CommentListResp { + Items []Comment `json:"items"` + Meta PageMeta `json:"meta"` + } + CreateCommentReq { + Content string `json:"content"` + } + ListCommentsReq { + PathId + PageReq + } ) -@server( - prefix: api/v1 - group: community +@server ( + prefix: api/v1 + group: community ) -service juwan-api { - @doc "获取帖子列表" - @handler ListPosts - get /posts (PostListReq) returns (PostListResp) +service community-api { + @doc "获取帖子列表" + @handler ListPosts + get /posts (PostListReq) returns (PostListResp) - @doc "获取帖子详情" - @handler GetPost - get /posts/:id (PathId) returns (Post) + @doc "获取帖子详情" + @handler GetPost + get /posts/:id (PathId) returns (Post) - @doc "获取帖子评论" - @handler ListComments - get /posts/:id/comments (ListCommentsReq ) returns (CommentListResp) + @doc "获取帖子评论" + @handler ListComments + get /posts/:id/comments (ListCommentsReq) returns (CommentListResp) - @doc "获取用户帖子" - @handler ListUserPosts - get /users/:id/posts (ListCommentsReq ) returns (PostListResp) + @doc "获取用户帖子" + @handler ListUserPosts + get /users/:id/posts (ListCommentsReq) returns (PostListResp) } -@server( - prefix: api/v1 - group: community +@server ( + prefix: api/v1 + group: community ) -service juwan-api { - @doc "发布帖子" - @handler CreatePost - post /posts (CreatePostReq) returns (Post) +service community-api { + @doc "发布帖子" + @handler CreatePost + post /posts (CreatePostReq) returns (Post) - @doc "点赞帖子" - @handler LikePost - post /posts/:id/like (PathId) returns (EmptyResp) + @doc "点赞帖子" + @handler LikePost + post /posts/:id/like (PathId) returns (EmptyResp) - @doc "取消点赞帖子" - @handler UnlikePost - delete /posts/:id/like (PathId) returns (EmptyResp) + @doc "取消点赞帖子" + @handler UnlikePost + delete /posts/:id/like (PathId) returns (EmptyResp) - @doc "置顶帖子" - @handler PinPost - post /posts/:id/pin (PathId) returns (EmptyResp) + @doc "置顶帖子" + @handler PinPost + post /posts/:id/pin (PathId) returns (EmptyResp) - @doc "取消置顶" - @handler UnpinPost - delete /posts/:id/pin (PathId) returns (EmptyResp) + @doc "取消置顶" + @handler UnpinPost + delete /posts/:id/pin (PathId) returns (EmptyResp) - @doc "发表评论" - @handler CreateComment - post /posts/:id/comments (CreateCommentReq) returns (Comment) + @doc "发表评论" + @handler CreateComment + post /posts/:id/comments (CreateCommentReq) returns (Comment) - @doc "点赞评论" - @handler LikeComment - post /comments/:id/like (PathId) returns (EmptyResp) + @doc "点赞评论" + @handler LikeComment + post /comments/:id/like (PathId) returns (EmptyResp) + + @doc "取消点赞评论" + @handler UnlikeComment + delete /comments/:id/like (PathId) returns (EmptyResp) +} - @doc "取消点赞评论" - @handler UnlikeComment - delete /comments/:id/like (PathId) returns (EmptyResp) -} \ No newline at end of file diff --git a/desc/api/dispute.api b/desc/api/dispute.api index e7e94af..c20463d 100644 --- a/desc/api/dispute.api +++ b/desc/api/dispute.api @@ -42,7 +42,7 @@ type ( prefix: api/v1 group: dispute ) -service juwan-api { +service dispute-api { @doc "获取争议列表" @handler ListDisputes get /disputes (PageReq) returns (DisputeListResp) diff --git a/desc/api/notification.api b/desc/api/notification.api index 089d20d..6d30e48 100644 --- a/desc/api/notification.api +++ b/desc/api/notification.api @@ -25,7 +25,7 @@ type ( prefix: api/v1 group: notification ) -service juwan-api { +service notifi-api { @doc "获取通知列表" @handler ListNotifications get /notifications (PageReq) returns (NotificationListResp) diff --git a/desc/api/order.api b/desc/api/order.api index 0262c87..7ec7929 100644 --- a/desc/api/order.api +++ b/desc/api/order.api @@ -1,6 +1,5 @@ syntax = "v1" import "common.api" -import "player.api" // 为了使用 PlayerService 定义 type ( PathId { @@ -52,7 +51,7 @@ type ( prefix: api/v1/orders group: order ) -service juwan-api { +service order-api { @doc "获取订单列表" @handler ListOrders get / (OrderListReq) returns (OrderListResp) diff --git a/desc/api/player.api b/desc/api/player.api index 915055c..0685f33 100644 --- a/desc/api/player.api +++ b/desc/api/player.api @@ -83,7 +83,7 @@ type ( prefix: api/v1 group: player ) -service juwan-api { +service player-api { @doc "获取打手列表" @handler ListPlayers get /players (PlayerListReq) returns (PlayerListResp) @@ -115,7 +115,7 @@ type ( prefix: api/v1 group: player ) -service juwan-api { +service player-api { @doc "更新接单状态" @handler UpdatePlayerStatus put /players/me/status (UpdatePlayerStatusReq) returns (EmptyResp) diff --git a/desc/api/review.api b/desc/api/review.api index ad842de..b3ccf7a 100644 --- a/desc/api/review.api +++ b/desc/api/review.api @@ -42,7 +42,7 @@ service juwan-api { prefix: api/v1 group: review ) -service juwan-api { +service review-api { @doc "获取公开评价列表" @handler ListReviews get /reviews (PageReq) returns (ReviewListResp) diff --git a/desc/api/search.api b/desc/api/search.api index dbe1908..5af3e78 100644 --- a/desc/api/search.api +++ b/desc/api/search.api @@ -53,7 +53,7 @@ service juwan-api { prefix: api/v1 group: favorites ) -service juwan-api { +service search-api { @doc "获取收藏列表" @handler ListFavorites get /favorites (PageReq) returns (SearchResp) diff --git a/desc/api/shop.api b/desc/api/shop.api index 66c51d1..f381e14 100644 --- a/desc/api/shop.api +++ b/desc/api/shop.api @@ -9,11 +9,11 @@ type ( Name string `json:"name"` Banner string `json:"banner,optional"` Description string `json:"description"` - Rating float64 `json:"rating"` + Rating string `json:"rating"` TotalOrders int64 `json:"totalOrders"` PlayerCount int64 `json:"playerCount"` CommissionType string `json:"commissionType"` - CommissionValue float64 `json:"commissionValue"` + CommissionValue string `json:"commissionValue"` Announcements []string `json:"announcements"` TemplateConfig interface{} `json:"templateConfig"` } @@ -22,20 +22,20 @@ type ( Meta PageMeta `json:"meta"` } CreateShopReq { - Name string `json:"name"` - Description string `json:"description"` - CommissionType string `json:"commissionType"` - CommissionValue float64 `json:"commissionValue"` + Name string `json:"name"` + Description string `json:"description"` + CommissionType string `json:"commissionType"` + CommissionValue string `json:"commissionValue"` } UpdateShopReq { - Id int64 `path:"id"` - Name string `json:"name,optional"` - Description string `json:"description,optional"` - CommissionType string `json:"commissionType,optional"` - CommissionValue float64 `json:"commissionValue,optional"` - AllowMultiShop bool `json:"allowMultiShop,optional"` - AllowIndependentOrders bool `json:"allowIndependentOrders,optional"` - DispatchMode string `json:"dispatchMode,optional"` + Id int64 `path:"id"` + Name string `json:"name,optional"` + Description string `json:"description,optional"` + CommissionType string `json:"commissionType,optional"` + CommissionValue string `json:"commissionValue,optional"` + AllowMultiShop bool `json:"allowMultiShop,optional"` + AllowIndependentOrders bool `json:"allowIndependentOrders,optional"` + DispatchMode string `json:"dispatchMode,optional"` } UpdateTemplateReq { Id int64 `path:"id"` @@ -46,11 +46,11 @@ type ( Content string `json:"content"` } IncomeStatsResp { - MonthlyIncome float64 `json:"monthlyIncome"` - PendingSettlement float64 `json:"pendingSettlement"` - TotalWithdrawn float64 `json:"totalWithdrawn"` - TotalOrders int64 `json:"totalOrders"` - CompletedOrders int64 `json:"completedOrders"` + MonthlyIncome string `json:"monthlyIncome"` + PendingSettlement string `json:"pendingSettlement"` + TotalWithdrawn string `json:"totalWithdrawn"` + TotalOrders int64 `json:"totalOrders"` + CompletedOrders int64 `json:"completedOrders"` } InvitationReq { Id int64 `path:"id"` @@ -71,7 +71,7 @@ type ( prefix: api/v1 group: shop ) -service juwan-api { +service shop-api { @doc "获取店铺列表" @handler ListShops get /shops (PageReq) returns (ShopListResp) @@ -99,7 +99,7 @@ type ( prefix: api/v1 group: shop ) -service juwan-api { +service shop-api { @doc "创建店铺" @handler CreateShop post /shops (CreateShopReq) returns (ShopProfile) diff --git a/desc/api/users.api b/desc/api/users.api index 0dee23e..ac77e96 100644 --- a/desc/api/users.api +++ b/desc/api/users.api @@ -70,8 +70,8 @@ type ( Role string `json:"role"` // consumer, player, owner, admin VerifiedRoles []string `json:"verifiedRoles"` // e.g. ["consumer", "player"] VerificationStatus map[string]string `json:"verificationStatus"` // e.g. {"player": "approved"} - Phone string `json:"phone,omitempty"` - Bio string `json:"bio,omitempty"` + Phone string `json:"phone,omitempty,optional "` + Bio string `json:"bio,omitempty,optional "` CreatedAt string `json:"createdAt"` // ISO 8601 } ) @@ -81,8 +81,8 @@ type ( // ================================================================================= type ( RegisterReq { - Phone string `json:"phone,omitempty"` - Email string `json:"email,omitempty"` + Phone string `json:"phone,omitempty,optional"` + Email string `json:"email,omitempty,"` Username string `json:"username"` Password string `json:"password"` Vcode string `json:"vcode,omitempty"` // 验证码 @@ -93,7 +93,7 @@ type ( User User `json:"user"` } LoginReq { - Phone string `json:"phone,omitempty"` // 手机号登录 + Phone string `json:"phone,omitempty,optional"` // 手机号登录 Username string `json:"username,omitempty"` // 或用户名登录 Password string `json:"password"` Remember bool `json:"remember,optional"` diff --git a/desc/api/wallet.api b/desc/api/wallet.api index bb4031c..6194cab 100644 --- a/desc/api/wallet.api +++ b/desc/api/wallet.api @@ -1,50 +1,49 @@ syntax = "v1" + import "common.api" type ( - WalletBalance { - Balance float64 `json:"balance"` - FrozenBalance float64 `json:"frozenBalance"` - } - - Transaction { - Id int64 `json:"id"` - Type string `json:"type"` - Amount float64 `json:"amount"` - Description string `json:"description"` - OrderId string `json:"orderId,optional"` - CreatedAt string `json:"createdAt"` - } - - TransactionListResp { - Items []Transaction `json:"items"` - Meta PageMeta `json:"meta"` - } - - TopupReq { - Amount float64 `json:"amount"` - Method string `json:"method"` - } + WalletBalance { + Balance string `json:"balance"` + FrozenBalance string `json:"frozenBalance"` + } + Transaction { + Id int64 `json:"id"` + Type string `json:"type"` + Amount string `json:"amount"` + Description string `json:"description"` + OrderId string `json:"orderId,optional"` + CreatedAt string `json:"createdAt"` + } + TransactionListResp { + Items []Transaction `json:"items"` + Meta PageMeta `json:"meta"` + } + TopupReq { + Amount string `json:"amount"` + Method string `json:"method"` + } ) -@server( - prefix: api/v1/wallet - group: wallet +@server ( + prefix: api/v1/wallet + group: wallet ) -service juwan-api { - @doc "获取余额" - @handler GetBalance - get /balance (EmptyResp) returns (WalletBalance) +service wallet-api { + @doc "获取余额" + @handler GetBalance + get /balance (EmptyResp) returns (WalletBalance) - @doc "获取流水" - @handler ListTransactions - get /transactions (PageReq) returns (TransactionListResp) + @doc "获取流水" + @handler ListTransactions + get /transactions (PageReq) returns (TransactionListResp) - @doc "充值" - @handler Topup - post /topup (TopupReq) returns (EmptyResp) + @doc "充值" + @handler Topup + post /topup (TopupReq) returns (EmptyResp) + + @doc "提现" + @handler Withdraw + post /withdraw (TopupReq) returns (EmptyResp) +} - @doc "提现" - @handler Withdraw - post /withdraw (TopupReq) returns (EmptyResp) -} \ No newline at end of file diff --git a/desc/rpc/community.proto b/desc/rpc/community.proto new file mode 100644 index 0000000..5716531 --- /dev/null +++ b/desc/rpc/community.proto @@ -0,0 +1,320 @@ +syntax = "proto3"; + +option go_package ="./pb"; + +package pb; + +// ------------------------------------ +// Messages +// ------------------------------------ + +//--------------------------------commentLikes-------------------------------- +message CommentLikes { + int64 commentId = 1; //commentId + int64 userId = 2; //userId + int64 createdAt = 3; //createdAt +} + +message AddCommentLikesReq { + int64 commentId = 1; //commentId + int64 userId = 2; //userId + int64 createdAt = 3; //createdAt +} + +message AddCommentLikesResp { +} + +message UpdateCommentLikesReq { + int64 commentId = 1; //commentId + int64 userId = 2; //userId + int64 createdAt = 3; //createdAt +} + +message UpdateCommentLikesResp { +} + +message DelCommentLikesReq { + int64 id = 1; //id + optional int64 userId = 2; //userId +} + +message DelCommentLikesResp { +} + +message GetCommentLikesByIdReq { + int64 id = 1; //id +} + +message GetCommentLikesByIdResp { + CommentLikes commentLikes = 1; //commentLikes +} + +message SearchCommentLikesReq { + int64 page = 1; //page + int64 limit = 2; //limit + int64 commentId = 3; //commentId + int64 userId = 4; //userId + int64 createdAt = 5; //createdAt +} + +message SearchCommentLikesResp { + repeated CommentLikes commentLikes = 1; //commentLikes +} + +//--------------------------------comments-------------------------------- +message Comments { + int64 id = 1; //id + int64 postId = 2; //postId + int64 authorId = 3; //authorId + string content = 4; //content + int64 likeCount = 5; //likeCount + int64 createdAt = 6; //createdAt + int64 deletedAt = 7; //deletedAt +} + +message AddCommentsReq { + int64 postId = 1; //postId + int64 authorId = 2; //authorId + string content = 3; //content + int64 likeCount = 4; //likeCount + int64 createdAt = 5; //createdAt + int64 deletedAt = 6; //deletedAt +} + +message AddCommentsResp { +} + +message UpdateCommentsReq { + int64 id = 1; //id + int64 postId = 2; //postId + int64 authorId = 3; //authorId + string content = 4; //content + int64 likeCount = 5; //likeCount + int64 createdAt = 6; //createdAt + int64 deletedAt = 7; //deletedAt +} + +message UpdateCommentsResp { +} + +message DelCommentsReq { + int64 id = 1; //id +} + +message DelCommentsResp { +} + +message GetCommentsByIdReq { + int64 id = 1; //id +} + +message GetCommentsByIdResp { + Comments comments = 1; //comments +} + +message SearchCommentsReq { + int64 page = 1; //page + int64 limit = 2; //limit + int64 id = 3; //id + int64 postId = 4; //postId + int64 authorId = 5; //authorId + optional string content = 6; //content + optional int64 likeCount = 7; //likeCount + int64 createdAt = 8; //createdAt + int64 deletedAt = 9; //deletedAt +} + +message SearchCommentsResp { + repeated Comments comments = 1; //comments +} + +//--------------------------------postLikes-------------------------------- +message PostLikes { + int64 postId = 1; //postId + int64 userId = 2; //userId + int64 createdAt = 3; //createdAt +} + +message AddPostLikesReq { + int64 postId = 1; //postId + int64 userId = 2; //userId + int64 createdAt = 3; //createdAt +} + +message AddPostLikesResp { +} + +message UpdatePostLikesReq { + optional int64 postId = 1; //postId + optional int64 userId = 2; //userId + int64 createdAt = 3; //createdAt +} + +message UpdatePostLikesResp { +} + +message DelPostLikesReq { + int64 id = 1; //id + optional int64 userId = 2; //userId +} + +message DelPostLikesResp { +} + +message GetPostLikesByIdReq { + int64 id = 1; //id +} + +message GetPostLikesByIdResp { + PostLikes postLikes = 1; //postLikes +} + +message SearchPostLikesReq { + int64 page = 1; //page + int64 limit = 2; //limit + optional int64 postId = 3; //postId + optional int64 userId = 4; //userId + int64 createdAt = 5; //createdAt +} + +message SearchPostLikesResp { + repeated PostLikes postLikes = 1; //postLikes +} + +//--------------------------------posts-------------------------------- +message Posts { + int64 id = 1; //id + int64 authorId = 2; //authorId + string authorRole = 3; //authorRole + string title = 4; //title + string content = 5; //content + repeated string images = 6; //images + repeated string tags = 7; //tags + int64 linkedOrderId = 8; //linkedOrderId + int64 quotedPostId = 9; //quotedPostId + int64 likeCount = 10; //likeCount + int64 commentCount = 11; //commentCount + bool pinned = 12; //pinned + string searchText = 13; //searchText + int64 createdAt = 14; //createdAt + int64 updatedAt = 15; //updatedAt + int64 deletedAt = 16; //deletedAt +} + +message AddPostsReq { + int64 authorId = 1; //authorId + string authorRole = 2; //authorRole + string title = 3; //title + string content = 4; //content + repeated string images = 5; //images + repeated string tags = 6; //tags + int64 linkedOrderId = 7; //linkedOrderId + int64 quotedPostId = 8; //quotedPostId + int64 likeCount = 9; //likeCount + int64 commentCount = 10; //commentCount + bool pinned = 11; //pinned + string searchText = 12; //searchText + int64 createdAt = 13; //createdAt + int64 updatedAt = 14; //updatedAt + int64 deletedAt = 15; //deletedAt +} + +message AddPostsResp { +} + +message UpdatePostsReq { + int64 id = 1; //id + optional int64 authorId = 2; //authorId + optional string authorRole = 3; //authorRole + optional string title = 4; //title + optional string content = 5; //content + repeated string images = 6; //images + repeated string tags = 7; //tags + optional int64 linkedOrderId = 8; //linkedOrderId + optional int64 quotedPostId = 9; //quotedPostId + optional int64 likeCount = 10; //likeCount + optional int64 commentCount = 11; //commentCount + optional bool pinned = 12; //pinned + optional string searchText = 13; //searchText + optional int64 createdAt = 14; //createdAt + optional int64 updatedAt = 15; //updatedAt + optional int64 deletedAt = 16; //deletedAt +} + +message UpdatePostsResp { +} + +message DelPostsReq { + int64 id = 1; //id +} + +message DelPostsResp { +} + +message GetPostsByIdReq { + int64 id = 1; //id +} + +message GetPostsByIdResp { + Posts posts = 1; //posts +} + +message SearchPostsReq { + int64 page = 1; //page + int64 limit = 2; //limit + int64 id = 3; //id + optional int64 authorId = 4; //authorId + optional string authorRole = 5; //authorRole + optional string title = 6; //title + optional string content = 7; //content + repeated string images = 8; //images + repeated string tags = 9; //tags + optional int64 linkedOrderId = 10; //linkedOrderId + optional int64 quotedPostId = 11; //quotedPostId + optional int64 likeCount = 12; //likeCount + optional int64 commentCount = 13; //commentCount + optional bool pinned = 14; //pinned + optional string searchText = 15; //searchText + optional int64 createdAt = 16; //createdAt + optional int64 updatedAt = 17; //updatedAt + optional int64 deletedAt = 18; //deletedAt +} + +message SearchPostsResp { + repeated Posts posts = 1; //posts +} + + + +// ------------------------------------ +// Rpc Func +// ------------------------------------ + +service communityService{ + + //-----------------------commentLikes----------------------- + rpc AddCommentLikes(AddCommentLikesReq) returns (AddCommentLikesResp); + rpc UpdateCommentLikes(UpdateCommentLikesReq) returns (UpdateCommentLikesResp); + rpc DelCommentLikes(DelCommentLikesReq) returns (DelCommentLikesResp); + rpc GetCommentLikesById(GetCommentLikesByIdReq) returns (GetCommentLikesByIdResp); + rpc SearchCommentLikes(SearchCommentLikesReq) returns (SearchCommentLikesResp); + //-----------------------comments----------------------- + rpc AddComments(AddCommentsReq) returns (AddCommentsResp); + rpc UpdateComments(UpdateCommentsReq) returns (UpdateCommentsResp); + rpc DelComments(DelCommentsReq) returns (DelCommentsResp); + rpc GetCommentsById(GetCommentsByIdReq) returns (GetCommentsByIdResp); + rpc SearchComments(SearchCommentsReq) returns (SearchCommentsResp); + //-----------------------postLikes----------------------- + rpc AddPostLikes(AddPostLikesReq) returns (AddPostLikesResp); + rpc UpdatePostLikes(UpdatePostLikesReq) returns (UpdatePostLikesResp); + rpc DelPostLikes(DelPostLikesReq) returns (DelPostLikesResp); + rpc GetPostLikesById(GetPostLikesByIdReq) returns (GetPostLikesByIdResp); + rpc SearchPostLikes(SearchPostLikesReq) returns (SearchPostLikesResp); + //-----------------------posts----------------------- + rpc AddPosts(AddPostsReq) returns (AddPostsResp); + rpc UpdatePosts(UpdatePostsReq) returns (UpdatePostsResp); + rpc DelPosts(DelPostsReq) returns (DelPostsResp); + rpc GetPostsById(GetPostsByIdReq) returns (GetPostsByIdResp); + rpc SearchPosts(SearchPostsReq) returns (SearchPostsResp); + +} diff --git a/desc/rpc/game.proto b/desc/rpc/game.proto index 6d9751a..b687e2c 100644 --- a/desc/rpc/game.proto +++ b/desc/rpc/game.proto @@ -66,13 +66,13 @@ message SearchGamesReq { int64 page = 1; //page int64 limit = 2; //limit int64 id = 3; //id - string name = 4; //name - string icon = 5; //icon - string category = 6; //category - int64 sortOrder = 7; //sortOrder - bool isActive = 8; //isActive - int64 createdAt = 9; //createdAt - int64 updatedAt = 10; //updatedAt + optional string name = 4; //name + optional string icon = 5; //icon + optional string category = 6; //category + optional int64 sortOrder = 7; //sortOrder + optional bool isActive = 8; //isActive + optional int64 createdAt = 9; //createdAt + optional int64 updatedAt = 10; //updatedAt } message SearchGamesResp { @@ -85,7 +85,7 @@ message SearchGamesResp { // Rpc Func // ------------------------------------ -service public{ +service GameService { //-----------------------games----------------------- rpc AddGames(AddGamesReq) returns (AddGamesResp); diff --git a/desc/rpc/order.proto b/desc/rpc/order.proto new file mode 100644 index 0000000..0057e03 --- /dev/null +++ b/desc/rpc/order.proto @@ -0,0 +1,225 @@ +syntax = "proto3"; + +option go_package ="./pb"; + +package pb; + +// ------------------------------------ +// Messages +// ------------------------------------ + +//--------------------------------orders-------------------------------- +message Orders { + int64 id = 1; //id + int64 consumerId = 2; //consumerId + string consumerName = 3; //consumerName + int64 playerId = 4; //playerId + string playerName = 5; //playerName + optional int64 shopId = 6; //shopId + optional string shopName = 7; //shopName + string serviceSnapshot = 8; //serviceSnapshot + string status = 9; //status + string totalPrice = 10; //totalPrice + optional string note = 11; //note + int64 version = 12; //version + optional string timeoutJobId = 13; //timeoutJobId + string searchText = 14; //searchText + int64 createdAt = 15; //createdAt + optional int64 acceptedAt = 16; //acceptedAt + optional int64 closedAt = 17; //closedAt + optional int64 completedAt = 18; //completedAt + optional int64 cancelledAt = 19; //cancelledAt + int64 updatedAt = 20; //updatedAt +} + +message AddOrdersReq { + int64 id = 1; //id + int64 consumerId = 2; //consumerId + string consumerName = 3; //consumerName + int64 playerId = 4; //playerId + string playerName = 5; //playerName + optional int64 shopId = 6; //shopId + optional string shopName = 7; //shopName + string serviceSnapshot = 8; //serviceSnapshot + optional string status = 9; //status + string totalPrice = 10; //totalPrice + optional string note = 11; //note + optional int64 version = 12; //version + optional string timeoutJobId = 13; //timeoutJobId + optional string searchText = 14; //searchText + optional int64 createdAt = 15; //createdAt + optional int64 acceptedAt = 16; //acceptedAt + optional int64 closedAt = 17; //closedAt + optional int64 completedAt = 18; //completedAt + optional int64 cancelledAt = 19; //cancelledAt + optional int64 updatedAt = 20; //updatedAt +} + +message AddOrdersResp { +} + +message UpdateOrdersReq { + int64 id = 1; //id + optional int64 consumerId = 2; //consumerId + optional string consumerName = 3; //consumerName + optional int64 playerId = 4; //playerId + optional string playerName = 5; //playerName + optional int64 shopId = 6; //shopId + optional string shopName = 7; //shopName + optional string serviceSnapshot = 8; //serviceSnapshot + optional string status = 9; //status + optional string totalPrice = 10; //totalPrice + optional string note = 11; //note + optional int64 version = 12; //version + optional string timeoutJobId = 13; //timeoutJobId + optional string searchText = 14; //searchText + optional int64 createdAt = 15; //createdAt + optional int64 acceptedAt = 16; //acceptedAt + optional int64 closedAt = 17; //closedAt + optional int64 completedAt = 18; //completedAt + optional int64 cancelledAt = 19; //cancelledAt + optional int64 updatedAt = 20; //updatedAt +} + +message UpdateOrdersResp { +} + +message DelOrdersReq { + int64 id = 1; //id +} + +message DelOrdersResp { +} + +message GetOrdersByIdReq { + int64 id = 1; //id +} + +message GetOrdersByIdResp { + Orders orders = 1; //orders +} + +message SearchOrdersReq { + int64 page = 1; //page + int64 limit = 2; //limit + optional int64 id = 3; //id + optional int64 consumerId = 4; //consumerId + optional string consumerName = 5; //consumerName + optional int64 playerId = 6; //playerId + optional string playerName = 7; //playerName + optional int64 shopId = 8; //shopId + optional string shopName = 9; //shopName + optional string serviceSnapshot = 10; //serviceSnapshot + optional string status = 11; //status + optional string totalPrice = 12; //totalPrice + optional string note = 13; //note + optional int64 version = 14; //version + optional string timeoutJobId = 15; //timeoutJobId + optional string searchText = 16; //searchText + optional int64 createdAt = 17; //createdAt + optional int64 acceptedAt = 18; //acceptedAt + optional int64 closedAt = 19; //closedAt + optional int64 completedAt = 20; //completedAt + optional int64 cancelledAt = 21; //cancelledAt + optional int64 updatedAt = 22; //updatedAt +} + +message SearchOrdersResp { + repeated Orders orders = 1; //orders +} + +//--------------------------------orderStateLogs-------------------------------- +message OrderStateLogs { + int64 id = 1; //id + int64 orderId = 2; //orderId + optional string fromStatus = 3; //fromStatus + string toStatus = 4; //toStatus + string action = 5; //action + int64 actorId = 6; //actorId + string actorRole = 7; //actorRole + optional string metadata = 8; //metadata + int64 createdAt = 9; //createdAt +} + +message AddOrderStateLogsReq { + int64 id = 1; //id + int64 orderId = 2; //orderId + optional string fromStatus = 3; //fromStatus + string toStatus = 4; //toStatus + string action = 5; //action + int64 actorId = 6; //actorId + string actorRole = 7; //actorRole + optional string metadata = 8; //metadata + optional int64 createdAt = 9; //createdAt +} + +message AddOrderStateLogsResp { +} + +message UpdateOrderStateLogsReq { + int64 id = 1; //id + optional int64 orderId = 2; //orderId + optional string fromStatus = 3; //fromStatus + optional string toStatus = 4; //toStatus + optional string action = 5; //action + optional int64 actorId = 6; //actorId + optional string actorRole = 7; //actorRole + optional string metadata = 8; //metadata + optional int64 createdAt = 9; //createdAt +} + +message UpdateOrderStateLogsResp { +} + +message DelOrderStateLogsReq { + int64 id = 1; //id +} + +message DelOrderStateLogsResp { +} + +message GetOrderStateLogsByIdReq { + int64 id = 1; //id +} + +message GetOrderStateLogsByIdResp { + OrderStateLogs orderStateLogs = 1; //orderStateLogs +} + +message SearchOrderStateLogsReq { + int64 page = 1; //page + int64 limit = 2; //limit + optional int64 id = 3; //id + optional int64 orderId = 4; //orderId + optional string fromStatus = 5; //fromStatus + optional string toStatus = 6; //toStatus + optional string action = 7; //action + optional int64 actorId = 8; //actorId + optional string actorRole = 9; //actorRole + optional string metadata = 10; //metadata + optional int64 createdAt = 11; //createdAt +} + +message SearchOrderStateLogsResp { + repeated OrderStateLogs orderStateLogs = 1; //orderStateLogs +} + +// ------------------------------------ +// Rpc Func +// ------------------------------------ + +service orderService { + //-----------------------orders----------------------- + rpc AddOrders(AddOrdersReq) returns (AddOrdersResp); + rpc UpdateOrders(UpdateOrdersReq) returns (UpdateOrdersResp); + rpc DelOrders(DelOrdersReq) returns (DelOrdersResp); + rpc GetOrdersById(GetOrdersByIdReq) returns (GetOrdersByIdResp); + rpc SearchOrders(SearchOrdersReq) returns (SearchOrdersResp); + + //-----------------------orderStateLogs----------------------- + rpc AddOrderStateLogs(AddOrderStateLogsReq) returns (AddOrderStateLogsResp); + rpc UpdateOrderStateLogs(UpdateOrderStateLogsReq) returns (UpdateOrderStateLogsResp); + rpc DelOrderStateLogs(DelOrderStateLogsReq) returns (DelOrderStateLogsResp); + rpc GetOrderStateLogsById(GetOrderStateLogsByIdReq) returns (GetOrderStateLogsByIdResp); + rpc SearchOrderStateLogs(SearchOrderStateLogsReq) returns (SearchOrderStateLogsResp); +} diff --git a/desc/rpc/shop.proto b/desc/rpc/shop.proto index d7959da..bee7351 100644 --- a/desc/rpc/shop.proto +++ b/desc/rpc/shop.proto @@ -42,6 +42,7 @@ message UpdateShopInvitationsReq { } message UpdateShopInvitationsResp { + ShopInvitations shopInvitations = 1; } message DelShopInvitationsReq { @@ -142,11 +143,11 @@ message Shops { string name = 3; //name string banner = 4; //banner string description = 5; //description - double rating = 6; //rating + string rating = 6; //rating int64 totalOrders = 7; //totalOrders int64 playerCount = 8; //playerCount string commissionType = 9; //commissionType - double commissionValue = 10; //commissionValue + string commissionValue = 10; //commissionValue bool allowMultiShop = 11; //allowMultiShop bool allowIndependentOrders = 12; //allowIndependentOrders string dispatchMode = 13; //dispatchMode @@ -161,11 +162,11 @@ message AddShopsReq { string name = 2; //name string banner = 3; //banner string description = 4; //description - double rating = 5; //rating + string rating = 5; //rating int64 totalOrders = 6; //totalOrders int64 playerCount = 7; //playerCount string commissionType = 8; //commissionType - double commissionValue = 9; //commissionValue + string commissionValue = 9; //commissionValue bool allowMultiShop = 10; //allowMultiShop bool allowIndependentOrders = 11; //allowIndependentOrders string dispatchMode = 12; //dispatchMode @@ -184,11 +185,11 @@ message UpdateShopsReq { string name = 3; //name string banner = 4; //banner string description = 5; //description - double rating = 6; //rating + string rating = 6; //rating int64 totalOrders = 7; //totalOrders int64 playerCount = 8; //playerCount string commissionType = 9; //commissionType - double commissionValue = 10; //commissionValue + string commissionValue = 10; //commissionValue bool allowMultiShop = 11; //allowMultiShop bool allowIndependentOrders = 12; //allowIndependentOrders string dispatchMode = 13; //dispatchMode @@ -224,11 +225,11 @@ message SearchShopsReq { string name = 5; //name string banner = 6; //banner string description = 7; //description - double rating = 8; //rating + string rating = 8; //rating int64 totalOrders = 9; //totalOrders int64 playerCount = 10; //playerCount string commissionType = 11; //commissionType - double commissionValue = 12; //commissionValue + string commissionValue = 12; //commissionValue bool allowMultiShop = 13; //allowMultiShop bool allowIndependentOrders = 14; //allowIndependentOrders string dispatchMode = 15; //dispatchMode diff --git a/desc/rpc/wallet.proto b/desc/rpc/wallet.proto new file mode 100644 index 0000000..cd62766 --- /dev/null +++ b/desc/rpc/wallet.proto @@ -0,0 +1,165 @@ +syntax = "proto3"; + +option go_package ="./pb"; + +package pb; + +// ------------------------------------ +// Messages +// ------------------------------------ + +//--------------------------------walletTransactions-------------------------------- +message WalletTransactions { + int64 id = 1; //id + int64 userId = 2; //userId + string type = 3; //type + string amount = 4; //amount + string balanceAfter = 5; //balanceAfter + string description = 6; //description + int64 orderId = 7; //orderId + int64 createdAt = 8; //createdAt + string searchText = 9; //searchText +} + +message AddWalletTransactionsReq { + int64 userId = 1; //userId + string type = 2; //type + string amount = 3; //amount + string balanceAfter = 4; //balanceAfter + string description = 5; //description + int64 orderId = 6; //orderId + int64 createdAt = 7; //createdAt + string searchText = 8; //searchText +} + +message AddWalletTransactionsResp { +} + +message UpdateWalletTransactionsReq { + int64 id = 1; //id + optional int64 userId = 2; //userId + optional string type = 3; //type + optional string amount = 4; //amount + optional string balanceAfter = 5; //balanceAfter + optional string description = 6; //description + optional int64 orderId = 7; //orderId + optional int64 createdAt = 8; //createdAt + optional string searchText = 9; //searchText +} + +message UpdateWalletTransactionsResp { +} + +message DelWalletTransactionsReq { + int64 id = 1; //id +} + +message DelWalletTransactionsResp { +} + +message GetWalletTransactionsByIdReq { + int64 id = 1; //id +} + +message GetWalletTransactionsByIdResp { + WalletTransactions walletTransactions = 1; //walletTransactions +} + +message SearchWalletTransactionsReq { + int64 page = 1; //page + int64 limit = 2; //limit + int64 id = 3; //id + optional int64 userId = 4; //userId + optional string type = 5; //type + optional string amount = 6; //amount + optional string balanceAfter = 7; //balanceAfter + optional string description = 8; //description + optional int64 orderId = 9; //orderId + optional int64 createdAt = 10; //createdAt + optional string searchText = 11; //searchText +} + +message SearchWalletTransactionsResp { + repeated WalletTransactions walletTransactions = 1; //walletTransactions +} + +//--------------------------------wallets-------------------------------- +message Wallets { + int64 userId = 1; //userId + string balance = 2; //balance + string frozenBalance = 3; //frozenBalance + int64 updatedAt = 4; //updatedAt + int64 version = 5; //version +} + +message AddWalletsReq { + int64 userId = 1; //userId + string balance = 2; //balance + string frozenBalance = 3; //frozenBalance + int64 updatedAt = 4; //updatedAt +} + +message AddWalletsResp { +} + +message UpdateWalletsReq { + int64 userId = 1; //userId + optional string balance = 2; //balance + optional string frozenBalance = 3; //frozenBalance + optional int64 updatedAt = 4; //updatedAt + optional int64 version = 5; //version +} + +message UpdateWalletsResp { +} + +message DelWalletsReq { + int64 id = 1; //id +} + +message DelWalletsResp { +} + +message GetWalletsByIdReq { + int64 id = 1; //id +} + +message GetWalletsByIdResp { + Wallets wallets = 1; //wallets +} + +message SearchWalletsReq { + int64 page = 1; //page + int64 limit = 2; //limit + int64 userId = 3; //userId + optional string balance = 4; //balance + optional string frozenBalance = 5; //frozenBalance + optional int64 updatedAt = 6; //updatedAt +} + +message SearchWalletsResp { + repeated Wallets wallets = 1; //wallets +} + + + +// ------------------------------------ +// Rpc Func +// ------------------------------------ + +service walletService{ + + //-----------------------walletTransactions----------------------- + rpc AddWalletTransactions(AddWalletTransactionsReq) returns (AddWalletTransactionsResp); + rpc UpdateWalletTransactions(UpdateWalletTransactionsReq) returns (UpdateWalletTransactionsResp); + rpc DelWalletTransactions(DelWalletTransactionsReq) returns (DelWalletTransactionsResp); + rpc GetWalletTransactionsById(GetWalletTransactionsByIdReq) returns (GetWalletTransactionsByIdResp); + rpc SearchWalletTransactions(SearchWalletTransactionsReq) returns (SearchWalletTransactionsResp); + //-----------------------wallets----------------------- + rpc AddWallets(AddWalletsReq) returns (AddWalletsResp); + rpc UpdateWallets(UpdateWalletsReq) returns (UpdateWalletsResp); + rpc DelWallets(DelWalletsReq) returns (DelWalletsResp); + rpc GetWalletsById(GetWalletsByIdReq) returns (GetWalletsByIdResp); + rpc SearchWallets(SearchWalletsReq) returns (SearchWalletsResp); + +} diff --git a/desc/sql/community/comment_likes.sql b/desc/sql/community/comment_likes.sql index 9318be7..9849ebc 100644 --- a/desc/sql/community/comment_likes.sql +++ b/desc/sql/community/comment_likes.sql @@ -1,9 +1,10 @@ -CREATE TABLE comment_likes ( - comment_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), +CREATE TABLE comment_likes +( + comment_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (comment_id, user_id) + PRIMARY KEY (comment_id, user_id) ); -CREATE INDEX idx_comment_likes_lookup ON comment_likes(user_id, comment_id); \ No newline at end of file +CREATE INDEX idx_comment_likes_lookup ON comment_likes (user_id, comment_id); \ No newline at end of file diff --git a/desc/sql/community/comments.sql b/desc/sql/community/comments.sql index 3e7d90e..c3fc997 100644 --- a/desc/sql/community/comments.sql +++ b/desc/sql/community/comments.sql @@ -1,21 +1,22 @@ -CREATE TABLE comments ( - id BIGINT PRIMARY KEY, - post_id BIGINT NOT NULL REFERENCES posts(id), - author_id BIGINT NOT NULL, - content TEXT NOT NULL, - like_count INT DEFAULT 0, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - deleted_at TIMESTAMPTZ +CREATE TABLE comments +( + id BIGINT PRIMARY KEY, + post_id BIGINT NOT NULL REFERENCES posts (id), + author_id BIGINT NOT NULL, + content TEXT NOT NULL, + like_count INT DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ ); -- 基础索引 -CREATE INDEX idx_comments_post ON comments(post_id, created_at) WHERE deleted_at IS NULL; -CREATE INDEX idx_comments_author ON comments(author_id, created_at DESC) WHERE deleted_at IS NULL; +CREATE INDEX idx_comments_post ON comments (post_id, created_at) WHERE deleted_at IS NULL; +CREATE INDEX idx_comments_author ON comments (author_id, created_at DESC) WHERE deleted_at IS NULL; -- 三元组索引用于评论内容搜索 -CREATE INDEX idx_comments_content_trgm ON comments USING gin(content gin_trgm_ops) +CREATE INDEX idx_comments_content_trgm ON comments USING gin (content gin_trgm_ops) WHERE deleted_at IS NULL; -- 热门评论索引 -CREATE INDEX idx_comments_post_likes ON comments(post_id, like_count DESC, created_at) +CREATE INDEX idx_comments_post_likes ON comments (post_id, like_count DESC, created_at) WHERE deleted_at IS NULL; \ No newline at end of file diff --git a/desc/sql/community/post_likes.sql b/desc/sql/community/post_likes.sql index 10e5110..a7faf0d 100644 --- a/desc/sql/community/post_likes.sql +++ b/desc/sql/community/post_likes.sql @@ -1,14 +1,15 @@ -CREATE TABLE post_likes ( - post_id BIGINT NOT NULL, - user_id BIGINT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), +CREATE TABLE post_likes +( + post_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), -- 复合主键,防止重复点赞 - PRIMARY KEY (post_id, user_id) + PRIMARY KEY (post_id, user_id) ); -- [核心索引] 优化 "feed流中判断我是否已赞" (user_id = ? AND post_id IN (...)) -CREATE INDEX idx_post_likes_lookup ON post_likes(user_id, post_id); +CREATE INDEX idx_post_likes_lookup ON post_likes (user_id, post_id); -- [核心索引] 优化 "我赞过的帖子" 列表 -CREATE INDEX idx_post_likes_user_timeline ON post_likes(user_id, created_at DESC); \ No newline at end of file +CREATE INDEX idx_post_likes_user_timeline ON post_likes (user_id, created_at DESC); \ No newline at end of file diff --git a/desc/sql/dispute/dispute_timeline.sql b/desc/sql/dispute/dispute_timeline.sql index b3a8f37..f94e215 100644 --- a/desc/sql/dispute/dispute_timeline.sql +++ b/desc/sql/dispute/dispute_timeline.sql @@ -1,17 +1,16 @@ -CREATE TABLE dispute_timeline ( - id BIGINT PRIMARY KEY, - dispute_id BIGINT NOT NULL REFERENCES disputes(id), - event_type VARCHAR(30) NOT NULL, - actor_id BIGINT, - actor_name VARCHAR(100), - details JSONB, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), +CREATE TABLE dispute_timeline +( + id BIGINT PRIMARY KEY, + dispute_id BIGINT NOT NULL REFERENCES disputes (id), + event_type VARCHAR(30) NOT NULL, + actor_id BIGINT, + actor_name VARCHAR(100), + details JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - CONSTRAINT chk_event_type CHECK (event_type IN ( - 'created', 'response', 'reviewing', 'resolved', 'appealed' - )) + CONSTRAINT chk_event_type CHECK (event_type IN ('created', 'response', 'reviewing', 'resolved', 'appealed')) ); -CREATE INDEX idx_timeline_dispute ON dispute_timeline(dispute_id, created_at); -CREATE INDEX idx_timeline_dispute_created ON dispute_timeline(dispute_id, created_at); +CREATE INDEX idx_timeline_dispute ON dispute_timeline (dispute_id, created_at); +CREATE INDEX idx_timeline_dispute_created ON dispute_timeline (dispute_id, created_at); CREATE INDEX idx_timeline_details ON dispute_timeline USING gin(details); \ No newline at end of file diff --git a/desc/sql/dispute/disputes.sql b/desc/sql/dispute/disputes.sql index 7d511f8..85df8b0 100644 --- a/desc/sql/dispute/disputes.sql +++ b/desc/sql/dispute/disputes.sql @@ -1,49 +1,51 @@ -CREATE TABLE disputes ( - id BIGINT PRIMARY KEY, - order_id BIGINT NOT NULL UNIQUE, - initiator_id BIGINT NOT NULL, - initiator_name VARCHAR(100) NOT NULL, - respondent_id BIGINT NOT NULL, - reason TEXT NOT NULL, - evidence TEXT[] DEFAULT ARRAY[]::TEXT[], - status VARCHAR(20) NOT NULL DEFAULT 'open', - result VARCHAR(30), - respondent_reason TEXT, - respondent_evidence TEXT[] DEFAULT ARRAY[]::TEXT[], - appeal_reason TEXT, - appealed_at TIMESTAMPTZ, - resolved_by BIGINT, - resolved_at TIMESTAMPTZ, - search_text TEXT GENERATED ALWAYS AS ( - initiator_name || ' ' || reason || ' ' || coalesce(respondent_reason, '') || ' ' || coalesce(appeal_reason, '') - ) STORED, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), +CREATE TABLE disputes +( + id BIGINT PRIMARY KEY, + order_id BIGINT NOT NULL UNIQUE, + initiator_id BIGINT NOT NULL, + initiator_name VARCHAR(100) NOT NULL, + respondent_id BIGINT NOT NULL, + reason TEXT NOT NULL, + evidence TEXT[] DEFAULT ARRAY[]::TEXT[], + status VARCHAR(20) NOT NULL DEFAULT 'open', + result VARCHAR(30), + respondent_reason TEXT, + respondent_evidence TEXT[] DEFAULT ARRAY[]::TEXT[], + appeal_reason TEXT, + appealed_at TIMESTAMPTZ, + resolved_by BIGINT, + resolved_at TIMESTAMPTZ, + search_text TEXT GENERATED ALWAYS AS (initiator_name || ' ' || reason || ' ' || + coalesce(respondent_reason, '') || ' ' || + coalesce(appeal_reason, '')) STORED, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - CONSTRAINT chk_dispute_status CHECK (status IN ('open', 'reviewing', 'resolved', 'appealed')), - CONSTRAINT chk_dispute_result CHECK (result IS NULL OR result IN ('full_refund', 'full_payment', 'partial_refund')) + CONSTRAINT chk_dispute_status CHECK (status IN ('open', 'reviewing', 'resolved', 'appealed')), + CONSTRAINT chk_dispute_result CHECK (result IS NULL OR result IN ('full_refund', 'full_payment', 'partial_refund')) ); -- 基础索引 -CREATE INDEX idx_disputes_order ON disputes(order_id); -CREATE INDEX idx_disputes_status ON disputes(status, created_at DESC); -CREATE INDEX idx_disputes_initiator ON disputes(initiator_id); +CREATE INDEX idx_disputes_order ON disputes (order_id); +CREATE INDEX idx_disputes_status ON disputes (status, created_at DESC); +CREATE INDEX idx_disputes_initiator ON disputes (initiator_id); -- 三元组索引用于争议内容搜索 CREATE INDEX idx_disputes_search_trgm ON disputes USING gin(search_text gin_trgm_ops); -- 复合索引优化状态查询 -CREATE INDEX idx_disputes_status_created ON disputes(status, created_at DESC); +CREATE INDEX idx_disputes_status_created ON disputes (status, created_at DESC); -- 参与者索引 -CREATE INDEX idx_disputes_initiator_status ON disputes(initiator_id, status, created_at DESC); -CREATE INDEX idx_disputes_respondent_status ON disputes(respondent_id, status, created_at DESC); +CREATE INDEX idx_disputes_initiator_status ON disputes (initiator_id, status, created_at DESC); +CREATE INDEX idx_disputes_respondent_status ON disputes (respondent_id, status, created_at DESC); -- 数组索引优化证据查询 CREATE INDEX idx_disputes_evidence ON disputes USING gin(evidence); CREATE INDEX idx_disputes_respondent_evidence ON disputes USING gin(respondent_evidence); CREATE TRIGGER trigger_disputes_updated_at - BEFORE UPDATE ON disputes + BEFORE UPDATE + ON disputes FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); \ No newline at end of file diff --git a/desc/sql/review/reviews.sql b/desc/sql/review/reviews.sql index 616ddd3..7a71d52 100644 --- a/desc/sql/review/reviews.sql +++ b/desc/sql/review/reviews.sql @@ -1,37 +1,37 @@ -CREATE TABLE reviews ( - id BIGINT PRIMARY KEY, - order_id BIGINT NOT NULL, - from_user_id BIGINT NOT NULL, - from_user_name VARCHAR(100) NOT NULL, - from_user_avatar TEXT, - to_user_id BIGINT NOT NULL, - rating SMALLINT NOT NULL, - content TEXT, - sealed BOOLEAN DEFAULT TRUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - unsealed_at TIMESTAMPTZ, - - CONSTRAINT chk_rating_range CHECK (rating >= 1 AND rating <= 5), - UNIQUE(order_id, from_user_id) +CREATE TABLE reviews +( + id BIGINT PRIMARY KEY, + order_id BIGINT NOT NULL, + from_user_id BIGINT NOT NULL, + from_user_name VARCHAR(100) NOT NULL, + from_user_avatar TEXT, + to_user_id BIGINT NOT NULL, + rating SMALLINT NOT NULL, + content TEXT, + sealed BOOLEAN DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + unsealed_at TIMESTAMPTZ, + CONSTRAINT chk_rating_range CHECK (rating >= 1 AND rating <= 5), + UNIQUE (order_id, from_user_id) ); -- 基础索引 -CREATE INDEX idx_reviews_order ON reviews(order_id); -CREATE INDEX idx_reviews_to_user ON reviews(to_user_id, created_at - - CREATE INDEX idx_reviews_to_user ON reviews(to_user_id, created_at DESC) WHERE sealed = FALSE; -CREATE INDEX idx_reviews_from_user ON reviews(from_user_id); +CREATE INDEX idx_reviews_order ON reviews (order_id); +CREATE INDEX idx_reviews_to_user ON reviews (to_user_id, created_at + CREATE INDEX idx_reviews_to_user ON reviews(to_user_id, created_at DESC) + WHERE sealed = FALSE; +CREATE INDEX idx_reviews_from_user ON reviews (from_user_id); -- 三元组索引用于评价内容搜索 -CREATE INDEX idx_reviews_content_trgm ON reviews USING gin(content gin_trgm_ops) +CREATE INDEX idx_reviews_content_trgm ON reviews USING gin (content gin_trgm_ops) WHERE sealed = FALSE AND content IS NOT NULL; -- 复合索引优化用户评价列表 -CREATE INDEX idx_reviews_to_user_rating ON reviews(to_user_id, rating DESC, created_at DESC) +CREATE INDEX idx_reviews_to_user_rating ON reviews (to_user_id, rating DESC, created_at DESC) WHERE sealed = FALSE; -- 复合索引优化订单评价查询 -CREATE INDEX idx_reviews_order_sealed ON reviews(order_id, sealed); +CREATE INDEX idx_reviews_order_sealed ON reviews (order_id, sealed); -- 评分统计索引 -CREATE INDEX idx_reviews_rating_created ON reviews(rating, created_at DESC) WHERE sealed = FALSE; \ No newline at end of file +CREATE INDEX idx_reviews_rating_created ON reviews (rating, created_at DESC) WHERE sealed = FALSE; \ No newline at end of file diff --git a/desc/sql/wallet/wallet_transactions.sql b/desc/sql/wallet/wallet_transactions.sql index 9a307e7..c1019f4 100644 --- a/desc/sql/wallet/wallet_transactions.sql +++ b/desc/sql/wallet/wallet_transactions.sql @@ -1,33 +1,33 @@ -CREATE TABLE wallet_transactions ( - id BIGINT PRIMARY KEY, - user_id BIGINT NOT NULL, - type VARCHAR(20) NOT NULL, - amount DECIMAL(12,2) NOT NULL, - balance_after DECIMAL(12,2) NOT NULL, - description VARCHAR(500) NOT NULL, - order_id BIGINT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - search_text TEXT GENERATED ALWAYS AS ( - type || ' ' || description - ) STORED, +CREATE TABLE wallet_transactions +( + id BIGINT PRIMARY KEY, + user_id BIGINT NOT NULL, + type VARCHAR(20) NOT NULL, + amount DECIMAL(12, 2) NOT NULL, + balance_after DECIMAL(12, 2) NOT NULL, + description VARCHAR(500) NOT NULL, + order_id BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + search_text TEXT GENERATED ALWAYS AS ( + type || ' ' || description + ) STORED, - CONSTRAINT chk_transaction_type CHECK (type IN ('topup', 'payment', 'income', 'withdrawal', 'refund')) + CONSTRAINT chk_transaction_type CHECK (type IN ('topup', 'payment', 'income', 'withdrawal', 'refund')) ); -- 基础索引 -CREATE INDEX idx_transactions_user ON wallet_transactions(user_id, created_at DESC); -CREATE INDEX idx_transactions_order ON wallet_transactions(order_id) WHERE order_id IS NOT NULL; -CREATE INDEX idx_transactions_type ON wallet_transactions(user_id, type, created_at DESC); +CREATE INDEX idx_transactions_user ON wallet_transactions (user_id, created_at DESC); +CREATE INDEX idx_transactions_order ON wallet_transactions (order_id) WHERE order_id IS NOT NULL; +CREATE INDEX idx_transactions_type ON wallet_transactions (user_id, type, created_at DESC); -- 三元组索引用于交易描述搜索 CREATE INDEX idx_transactions_search_trgm ON wallet_transactions USING gin(search_text gin_trgm_ops); -- 复合索引优化用户交易查询 -CREATE INDEX idx_transactions_user_type_created ON wallet_transactions(user_id, type, created_at DESC); +CREATE INDEX idx_transactions_user_type_created ON wallet_transactions (user_id, type, created_at DESC); -- 时间范围索引 (用于统计) -CREATE INDEX idx_transactions_created_amount ON wallet_transactions(created_at DESC, amount); +CREATE INDEX idx_transactions_created_amount ON wallet_transactions (created_at DESC, amount); -- 订单关联索引 -CREATE INDEX idx_transactions_order_type ON wallet_transactions(order_id, type) - WHERE order_id IS NOT NULL; \ No newline at end of file +CREATE INDEX idx_transactions_order_type ON wallet_transactions (order_id, type) WHERE order_id IS NOT NULL; \ No newline at end of file diff --git a/desc/sql/wallet/wallets.sql b/desc/sql/wallet/wallets.sql index a2427c9..0732c05 100644 --- a/desc/sql/wallet/wallets.sql +++ b/desc/sql/wallet/wallets.sql @@ -1,17 +1,19 @@ -CREATE TABLE wallets ( - user_id BIGINT PRIMARY KEY, - balance DECIMAL(12,2) NOT NULL DEFAULT 0.00, - frozen_balance DECIMAL(12,2) NOT NULL DEFAULT 0.00, - version INT NOT NULL DEFAULT 1, -- 必须使用乐观锁 - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), +CREATE TABLE wallets +( + user_id BIGINT PRIMARY KEY, + balance DECIMAL(12, 2) NOT NULL DEFAULT 0.00, + frozen_balance DECIMAL(12, 2) NOT NULL DEFAULT 0.00, + version INT NOT NULL DEFAULT 1, -- 必须使用乐观锁 + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - CONSTRAINT chk_balance_non_negative CHECK (balance >= 0), - CONSTRAINT chk_frozen_non_negative CHECK (frozen_balance >= 0) + CONSTRAINT chk_balance_non_negative CHECK (balance >= 0), + CONSTRAINT chk_frozen_non_negative CHECK (frozen_balance >= 0) ); -CREATE INDEX idx_wallets_updated ON wallets(updated_at DESC); +CREATE INDEX idx_wallets_updated ON wallets (updated_at DESC); CREATE TRIGGER trigger_wallets_updated_at - BEFORE UPDATE ON wallets + BEFORE UPDATE + ON wallets FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); \ No newline at end of file diff --git a/go.mod b/go.mod index 88e5826..6ba6e61 100644 --- a/go.mod +++ b/go.mod @@ -72,6 +72,10 @@ require ( github.com/grafana/pyroscope-go/godeltaprof v0.1.9 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect github.com/hashicorp/hcl/v2 v2.18.1 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.8.0 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jinzhu/copier v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect @@ -120,6 +124,7 @@ require ( golang.org/x/mod v0.30.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/oauth2 v0.34.0 // indirect + golang.org/x/sync v0.19.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/term v0.38.0 // indirect golang.org/x/text v0.32.0 // indirect diff --git a/go.sum b/go.sum index 4404b19..5c27214 100644 --- a/go.sum +++ b/go.sum @@ -161,6 +161,14 @@ github.com/hashicorp/hcl/v2 v2.18.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+J github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo= +github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8= github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= @@ -267,6 +275,7 @@ github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=