diff --git a/app/community/rpc/internal/logic/helpers.go b/app/community/rpc/internal/logic/helpers.go index d134634..09d672f 100644 --- a/app/community/rpc/internal/logic/helpers.go +++ b/app/community/rpc/internal/logic/helpers.go @@ -10,7 +10,7 @@ import ( func toTextArray(s []string) types.TextArray { if len(s) == 0 { - return types.TextArray{Valid: true} + return types.TextArray{Elements: []string{}, Valid: true} } return types.TextArray{ Elements: s, diff --git a/app/dispute/api/dispute.go b/app/dispute/api/dispute.go new file mode 100644 index 0000000..bc735fb --- /dev/null +++ b/app/dispute/api/dispute.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/dispute/api/internal/config" + "juwan-backend/app/dispute/api/internal/handler" + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/common/middlewares" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/dispute-api.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + server.Use(middlewares.NewHeaderExtractorMiddleware().Handle) + 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/dispute/api/etc/dispute-api.yaml b/app/dispute/api/etc/dispute-api.yaml new file mode 100644 index 0000000..abecb24 --- /dev/null +++ b/app/dispute/api/etc/dispute-api.yaml @@ -0,0 +1,16 @@ +Name: dispute-api +Host: 0.0.0.0 +Port: 8888 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONFIG ===== +DisputeRpcConf: + Endpoints: + - dispute-rpc:8080 +OrderRpcConf: + Endpoints: + - order-rpc:8080 diff --git a/app/dispute/api/internal/config/config.go b/app/dispute/api/internal/config/config.go new file mode 100644 index 0000000..cc4fc3b --- /dev/null +++ b/app/dispute/api/internal/config/config.go @@ -0,0 +1,12 @@ +package config + +import ( + "github.com/zeromicro/go-zero/rest" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + rest.RestConf + DisputeRpcConf zrpc.RpcClientConf + OrderRpcConf zrpc.RpcClientConf +} diff --git a/app/dispute/api/internal/handler/dispute/appealDisputeHandler.go b/app/dispute/api/internal/handler/dispute/appealDisputeHandler.go new file mode 100644 index 0000000..63bf40c --- /dev/null +++ b/app/dispute/api/internal/handler/dispute/appealDisputeHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/dispute/api/internal/logic/dispute" + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" +) + +// 申诉 +func AppealDisputeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.AppealReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := dispute.NewAppealDisputeLogic(r.Context(), svcCtx) + resp, err := l.AppealDispute(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/dispute/api/internal/handler/dispute/createDisputeHandler.go b/app/dispute/api/internal/handler/dispute/createDisputeHandler.go new file mode 100644 index 0000000..b53e91b --- /dev/null +++ b/app/dispute/api/internal/handler/dispute/createDisputeHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/dispute/api/internal/logic/dispute" + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" +) + +// 发起争议 +func CreateDisputeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.CreateDisputeReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := dispute.NewCreateDisputeLogic(r.Context(), svcCtx) + resp, err := l.CreateDispute(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/dispute/api/internal/handler/dispute/getOrderDisputeHandler.go b/app/dispute/api/internal/handler/dispute/getOrderDisputeHandler.go new file mode 100644 index 0000000..09ffc02 --- /dev/null +++ b/app/dispute/api/internal/handler/dispute/getOrderDisputeHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/dispute/api/internal/logic/dispute" + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" +) + +// 获取订单争议 +func GetOrderDisputeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.DisputePathId + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := dispute.NewGetOrderDisputeLogic(r.Context(), svcCtx) + resp, err := l.GetOrderDispute(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/dispute/api/internal/handler/dispute/listDisputesHandler.go b/app/dispute/api/internal/handler/dispute/listDisputesHandler.go new file mode 100644 index 0000000..d75a5d6 --- /dev/null +++ b/app/dispute/api/internal/handler/dispute/listDisputesHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/dispute/api/internal/logic/dispute" + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" +) + +// 获取争议列表 +func ListDisputesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.DisputeListReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := dispute.NewListDisputesLogic(r.Context(), svcCtx) + resp, err := l.ListDisputes(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/dispute/api/internal/handler/dispute/respondDisputeHandler.go b/app/dispute/api/internal/handler/dispute/respondDisputeHandler.go new file mode 100644 index 0000000..3f6eab7 --- /dev/null +++ b/app/dispute/api/internal/handler/dispute/respondDisputeHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/dispute/api/internal/logic/dispute" + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" +) + +// 回应争议 +func RespondDisputeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.DisputeResponseReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := dispute.NewRespondDisputeLogic(r.Context(), svcCtx) + resp, err := l.RespondDispute(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/dispute/api/internal/handler/routes.go b/app/dispute/api/internal/handler/routes.go new file mode 100644 index 0000000..65e6e12 --- /dev/null +++ b/app/dispute/api/internal/handler/routes.go @@ -0,0 +1,51 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package handler + +import ( + "net/http" + + dispute "juwan-backend/app/dispute/api/internal/handler/dispute" + "juwan-backend/app/dispute/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: "/disputes", + Handler: dispute.ListDisputesHandler(serverCtx), + }, + { + // 申诉 + Method: http.MethodPost, + Path: "/disputes/:id/appeal", + Handler: dispute.AppealDisputeHandler(serverCtx), + }, + { + // 回应争议 + Method: http.MethodPost, + Path: "/disputes/:id/response", + Handler: dispute.RespondDisputeHandler(serverCtx), + }, + { + // 获取订单争议 + Method: http.MethodGet, + Path: "/orders/:id/dispute", + Handler: dispute.GetOrderDisputeHandler(serverCtx), + }, + { + // 发起争议 + Method: http.MethodPost, + Path: "/orders/:id/dispute", + Handler: dispute.CreateDisputeHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) +} diff --git a/app/dispute/api/internal/logic/dispute/appealDisputeLogic.go b/app/dispute/api/internal/logic/dispute/appealDisputeLogic.go new file mode 100644 index 0000000..4076b5f --- /dev/null +++ b/app/dispute/api/internal/logic/dispute/appealDisputeLogic.go @@ -0,0 +1,82 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" + "juwan-backend/app/dispute/rpc/disputeservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AppealDisputeLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 申诉 +func NewAppealDisputeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AppealDisputeLogic { + return &AppealDisputeLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *AppealDisputeLogic) AppealDispute(req *types.AppealReq) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + if req.Reason == "" { + return nil, errors.New("reason is required") + } + + disputeResp, err := l.svcCtx.DisputeRpc.GetDisputesById(l.ctx, &disputeservice.GetDisputesByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + d := disputeResp.GetDisputes() + if d == nil { + return nil, errors.New("dispute not found") + } + if uid != d.GetInitiatorId() && uid != d.GetRespondentId() { + return nil, errors.New("not a participant of this dispute") + } + if d.GetStatus() != "resolved" { + return nil, errors.New("dispute status does not allow appeal") + } + + status := "appealed" + now := time.Now().Unix() + _, err = l.svcCtx.DisputeRpc.UpdateDisputes(l.ctx, &disputeservice.UpdateDisputesReq{ + Id: req.Id, + Status: &status, + AppealReason: &req.Reason, + AppealedAt: &now, + }) + if err != nil { + return nil, err + } + + _, err = l.svcCtx.DisputeRpc.AddDisputeTimeline(l.ctx, &disputeservice.AddDisputeTimelineReq{ + DisputeId: req.Id, + EventType: "appealed", + ActorId: uid, + ActorName: actorName(uid), + Details: detailsJSON(map[string]any{"reason": req.Reason}), + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/dispute/api/internal/logic/dispute/createDisputeLogic.go b/app/dispute/api/internal/logic/dispute/createDisputeLogic.go new file mode 100644 index 0000000..33e5a81 --- /dev/null +++ b/app/dispute/api/internal/logic/dispute/createDisputeLogic.go @@ -0,0 +1,128 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" + "juwan-backend/app/dispute/rpc/disputeservice" + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CreateDisputeLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 发起争议 +func NewCreateDisputeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateDisputeLogic { + return &CreateDisputeLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CreateDisputeLogic) CreateDispute(req *types.CreateDisputeReq) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + if req.Reason == "" { + return nil, errors.New("reason is required") + } + + orderResp, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + order := orderResp.GetOrders() + if order == nil { + return nil, errors.New("order not found") + } + if order.GetStatus() != "in_progress" && order.GetStatus() != "pending_close" { + return nil, errors.New("order status does not allow disputes") + } + + var respondentID int64 + if uid == order.GetConsumerId() { + respondentID = order.GetPlayerId() + } else if uid == order.GetPlayerId() { + respondentID = order.GetConsumerId() + } else { + return nil, errors.New("not a participant of this order") + } + + existing, err := l.svcCtx.DisputeRpc.SearchDisputes(l.ctx, &disputeservice.SearchDisputesReq{ + Offset: 0, + Limit: 1, + OrderId: &req.Id, + }) + if err != nil { + return nil, err + } + if len(existing.GetDisputes()) > 0 { + return nil, errors.New("dispute already exists") + } + + created, err := l.svcCtx.DisputeRpc.AddDisputes(l.ctx, &disputeservice.AddDisputesReq{ + OrderId: req.Id, + InitiatorId: uid, + InitiatorName: actorName(uid), + RespondentId: respondentID, + Reason: req.Reason, + Evidence: req.Evidence, + Status: "open", + }) + if err != nil { + return nil, err + } + + _, err = l.svcCtx.DisputeRpc.AddDisputeTimeline(l.ctx, &disputeservice.AddDisputeTimelineReq{ + DisputeId: created.GetId(), + EventType: "created", + ActorId: uid, + ActorName: actorName(uid), + Details: detailsJSON(map[string]any{"reason": req.Reason, "evidence": req.Evidence}), + }) + if err != nil { + return nil, err + } + + now := time.Now().Unix() + status := "disputed" + oldStatus := order.GetStatus() + metadata := detailsJSON(map[string]any{"disputeId": created.GetId()}) + _, err = l.svcCtx.OrderRpc.UpdateOrders(l.ctx, &orderservice.UpdateOrdersReq{ + Id: req.Id, + Status: &status, + UpdatedAt: &now, + }) + if err != nil { + return nil, err + } + _, err = l.svcCtx.OrderRpc.AddOrderStateLogs(l.ctx, &orderservice.AddOrderStateLogsReq{ + OrderId: req.Id, + FromStatus: &oldStatus, + ToStatus: status, + Action: "open_dispute", + ActorId: uid, + ActorRole: "user", + Metadata: &metadata, + CreatedAt: &now, + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/dispute/api/internal/logic/dispute/getOrderDisputeLogic.go b/app/dispute/api/internal/logic/dispute/getOrderDisputeLogic.go new file mode 100644 index 0000000..18344b5 --- /dev/null +++ b/app/dispute/api/internal/logic/dispute/getOrderDisputeLogic.go @@ -0,0 +1,65 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "context" + "errors" + + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" + "juwan-backend/app/dispute/rpc/disputeservice" + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetOrderDisputeLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取订单争议 +func NewGetOrderDisputeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderDisputeLogic { + return &GetOrderDisputeLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetOrderDisputeLogic) GetOrderDispute(req *types.DisputePathId) (resp *types.Dispute, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + orderResp, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + order := orderResp.GetOrders() + if order == nil { + return nil, errors.New("order not found") + } + if uid != order.GetConsumerId() && uid != order.GetPlayerId() { + return nil, errors.New("not a participant of this order") + } + + out, err := l.svcCtx.DisputeRpc.SearchDisputes(l.ctx, &disputeservice.SearchDisputesReq{ + Offset: 0, + Limit: 1, + OrderId: &req.Id, + }) + if err != nil { + return nil, err + } + if len(out.GetDisputes()) == 0 { + return nil, errors.New("dispute not found") + } + dispute := toAPIDispute(out.GetDisputes()[0]) + + return &dispute, nil +} diff --git a/app/dispute/api/internal/logic/dispute/helpers.go b/app/dispute/api/internal/logic/dispute/helpers.go new file mode 100644 index 0000000..27c29b6 --- /dev/null +++ b/app/dispute/api/internal/logic/dispute/helpers.go @@ -0,0 +1,97 @@ +package dispute + +import ( + "encoding/json" + "sort" + "strconv" + "time" + + "juwan-backend/app/dispute/api/internal/types" + "juwan-backend/app/dispute/rpc/disputeservice" +) + +func formatUnix(ts int64) string { + if ts <= 0 { + return "" + } + return time.Unix(ts, 0).UTC().Format(time.RFC3339) +} + +func toAPIDispute(d *disputeservice.Disputes) types.Dispute { + return types.Dispute{ + Id: d.GetId(), + OrderId: d.GetOrderId(), + InitiatorId: d.GetInitiatorId(), + InitiatorName: d.GetInitiatorName(), + RespondentId: d.GetRespondentId(), + Reason: d.GetReason(), + Evidence: d.GetEvidence(), + Status: d.GetStatus(), + Result: d.GetResult(), + RespondentReason: d.GetRespondentReason(), + RespondentEvidence: d.GetRespondentEvidence(), + AppealReason: d.GetAppealReason(), + AppealedAt: formatUnix(d.GetAppealedAt()), + ResolvedBy: d.GetResolvedBy(), + ResolvedAt: formatUnix(d.GetResolvedAt()), + CreatedAt: formatUnix(d.GetCreatedAt()), + UpdatedAt: formatUnix(d.GetUpdatedAt()), + } +} + +func mergeDisputes(groups ...[]*disputeservice.Disputes) []*disputeservice.Disputes { + seen := make(map[int64]struct{}) + items := make([]*disputeservice.Disputes, 0) + for _, group := range groups { + for _, item := range group { + if item == nil { + continue + } + if _, ok := seen[item.GetId()]; ok { + continue + } + seen[item.GetId()] = struct{}{} + items = append(items, item) + } + } + sort.Slice(items, func(i, j int) bool { + if items[i].GetCreatedAt() == items[j].GetCreatedAt() { + return items[i].GetId() > items[j].GetId() + } + return items[i].GetCreatedAt() > items[j].GetCreatedAt() + }) + return items +} + +func paginateDisputes(items []*disputeservice.Disputes, offset int64, limit int64) []*disputeservice.Disputes { + if offset < 0 { + offset = 0 + } + if limit <= 0 { + limit = 20 + } + start := int(offset) + if start >= len(items) { + return []*disputeservice.Disputes{} + } + end := start + int(limit) + if end > len(items) { + end = len(items) + } + return items[start:end] +} + +func actorName(uid int64) string { + return strconv.FormatInt(uid, 10) +} + +func detailsJSON(values map[string]any) string { + if len(values) == 0 { + return "{}" + } + b, err := json.Marshal(values) + if err != nil { + return "{}" + } + return string(b) +} diff --git a/app/dispute/api/internal/logic/dispute/listDisputesLogic.go b/app/dispute/api/internal/logic/dispute/listDisputesLogic.go new file mode 100644 index 0000000..3ffa88c --- /dev/null +++ b/app/dispute/api/internal/logic/dispute/listDisputesLogic.go @@ -0,0 +1,80 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "context" + + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" + "juwan-backend/app/dispute/rpc/disputeservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListDisputesLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取争议列表 +func NewListDisputesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListDisputesLogic { + return &ListDisputesLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListDisputesLogic) ListDisputes(req *types.DisputeListReq) (resp *types.DisputeListResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + limit := req.Limit + if limit <= 0 { + limit = 20 + } + var status *string + if req.Status != "" { + status = &req.Status + } + + initiated, err := l.svcCtx.DisputeRpc.SearchDisputes(l.ctx, &disputeservice.SearchDisputesReq{ + Offset: 0, + Limit: 100, + InitiatorId: &uid, + Status: status, + }) + if err != nil { + return nil, err + } + responded, err := l.svcCtx.DisputeRpc.SearchDisputes(l.ctx, &disputeservice.SearchDisputesReq{ + Offset: 0, + Limit: 100, + RespondentId: &uid, + Status: status, + }) + if err != nil { + return nil, err + } + + items := mergeDisputes(initiated.GetDisputes(), responded.GetDisputes()) + page := paginateDisputes(items, req.Offset, limit) + out := make([]types.Dispute, 0, len(page)) + for _, item := range page { + out = append(out, toAPIDispute(item)) + } + + return &types.DisputeListResp{ + Items: out, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: limit, + }, + }, nil +} diff --git a/app/dispute/api/internal/logic/dispute/respondDisputeLogic.go b/app/dispute/api/internal/logic/dispute/respondDisputeLogic.go new file mode 100644 index 0000000..7182c5a --- /dev/null +++ b/app/dispute/api/internal/logic/dispute/respondDisputeLogic.go @@ -0,0 +1,80 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package dispute + +import ( + "context" + "errors" + + "juwan-backend/app/dispute/api/internal/svc" + "juwan-backend/app/dispute/api/internal/types" + "juwan-backend/app/dispute/rpc/disputeservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type RespondDisputeLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 回应争议 +func NewRespondDisputeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RespondDisputeLogic { + return &RespondDisputeLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *RespondDisputeLogic) RespondDispute(req *types.DisputeResponseReq) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + if req.Reason == "" { + return nil, errors.New("reason is required") + } + + disputeResp, err := l.svcCtx.DisputeRpc.GetDisputesById(l.ctx, &disputeservice.GetDisputesByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + d := disputeResp.GetDisputes() + if d == nil { + return nil, errors.New("dispute not found") + } + if uid != d.GetRespondentId() { + return nil, errors.New("not the respondent of this dispute") + } + if d.GetStatus() != "open" { + return nil, errors.New("dispute status does not allow response") + } + + status := "reviewing" + _, err = l.svcCtx.DisputeRpc.UpdateDisputes(l.ctx, &disputeservice.UpdateDisputesReq{ + Id: req.Id, + Status: &status, + RespondentReason: &req.Reason, + RespondentEvidence: req.Evidence, + }) + if err != nil { + return nil, err + } + + _, err = l.svcCtx.DisputeRpc.AddDisputeTimeline(l.ctx, &disputeservice.AddDisputeTimelineReq{ + DisputeId: req.Id, + EventType: "response", + ActorId: uid, + ActorName: actorName(uid), + Details: detailsJSON(map[string]any{"reason": req.Reason, "evidence": req.Evidence}), + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/dispute/api/internal/svc/serviceContext.go b/app/dispute/api/internal/svc/serviceContext.go new file mode 100644 index 0000000..c160ccb --- /dev/null +++ b/app/dispute/api/internal/svc/serviceContext.go @@ -0,0 +1,23 @@ +package svc + +import ( + "juwan-backend/app/dispute/api/internal/config" + "juwan-backend/app/dispute/rpc/disputeservice" + "juwan-backend/app/order/rpc/orderservice" + + "github.com/zeromicro/go-zero/zrpc" +) + +type ServiceContext struct { + Config config.Config + DisputeRpc disputeservice.DisputeService + OrderRpc orderservice.OrderService +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + DisputeRpc: disputeservice.NewDisputeService(zrpc.MustNewClient(c.DisputeRpcConf)), + OrderRpc: orderservice.NewOrderService(zrpc.MustNewClient(c.OrderRpcConf)), + } +} diff --git a/app/dispute/api/internal/types/types.go b/app/dispute/api/internal/types/types.go new file mode 100644 index 0000000..db505c5 --- /dev/null +++ b/app/dispute/api/internal/types/types.go @@ -0,0 +1,88 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package types + +type AppealReq struct { + DisputePathId + Reason string `json:"reason"` +} + +type CreateDisputeReq struct { + DisputePathId + Reason string `json:"reason"` + Evidence []string `json:"evidence"` +} + +type Dispute struct { + Id int64 `json:"id"` + OrderId int64 `json:"orderId"` + InitiatorId int64 `json:"initiatorId"` + InitiatorName string `json:"initiatorName"` + RespondentId int64 `json:"respondentId"` + Reason string `json:"reason"` + Evidence []string `json:"evidence"` + Status string `json:"status"` + Result string `json:"result,optional"` + RespondentReason string `json:"respondentReason,optional"` + RespondentEvidence []string `json:"respondentEvidence"` + AppealReason string `json:"appealReason,optional"` + AppealedAt string `json:"appealedAt,optional"` + ResolvedBy int64 `json:"resolvedBy,optional"` + ResolvedAt string `json:"resolvedAt,optional"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` +} + +type DisputeListReq struct { + PageReq + Status string `form:"status,optional"` +} + +type DisputeListResp struct { + Items []Dispute `json:"items"` + Meta PageMeta `json:"meta"` +} + +type DisputePathId struct { + Id int64 `path:"id"` +} + +type DisputeResponseReq struct { + DisputePathId + Reason string `json:"reason"` + Evidence []string `json:"evidence"` +} + +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 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/dispute/rpc/disputeservice/disputeService.go b/app/dispute/rpc/disputeservice/disputeService.go new file mode 100644 index 0000000..9fc25bd --- /dev/null +++ b/app/dispute/rpc/disputeservice/disputeService.go @@ -0,0 +1,92 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: dispute.proto + +package disputeservice + +import ( + "context" + + "juwan-backend/app/dispute/rpc/pb" + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + AddDisputeTimelineReq = pb.AddDisputeTimelineReq + AddDisputeTimelineResp = pb.AddDisputeTimelineResp + AddDisputesReq = pb.AddDisputesReq + AddDisputesResp = pb.AddDisputesResp + DelDisputesReq = pb.DelDisputesReq + DelDisputesResp = pb.DelDisputesResp + DisputeTimeline = pb.DisputeTimeline + Disputes = pb.Disputes + GetDisputesByIdReq = pb.GetDisputesByIdReq + GetDisputesByIdResp = pb.GetDisputesByIdResp + SearchDisputeTimelineReq = pb.SearchDisputeTimelineReq + SearchDisputeTimelineResp = pb.SearchDisputeTimelineResp + SearchDisputesReq = pb.SearchDisputesReq + SearchDisputesResp = pb.SearchDisputesResp + UpdateDisputesReq = pb.UpdateDisputesReq + UpdateDisputesResp = pb.UpdateDisputesResp + + DisputeService interface { + // -----------------------disputes----------------------- + AddDisputes(ctx context.Context, in *AddDisputesReq, opts ...grpc.CallOption) (*AddDisputesResp, error) + UpdateDisputes(ctx context.Context, in *UpdateDisputesReq, opts ...grpc.CallOption) (*UpdateDisputesResp, error) + DelDisputes(ctx context.Context, in *DelDisputesReq, opts ...grpc.CallOption) (*DelDisputesResp, error) + GetDisputesById(ctx context.Context, in *GetDisputesByIdReq, opts ...grpc.CallOption) (*GetDisputesByIdResp, error) + SearchDisputes(ctx context.Context, in *SearchDisputesReq, opts ...grpc.CallOption) (*SearchDisputesResp, error) + // -----------------------disputeTimeline----------------------- + AddDisputeTimeline(ctx context.Context, in *AddDisputeTimelineReq, opts ...grpc.CallOption) (*AddDisputeTimelineResp, error) + SearchDisputeTimeline(ctx context.Context, in *SearchDisputeTimelineReq, opts ...grpc.CallOption) (*SearchDisputeTimelineResp, error) + } + + defaultDisputeService struct { + cli zrpc.Client + } +) + +func NewDisputeService(cli zrpc.Client) DisputeService { + return &defaultDisputeService{ + cli: cli, + } +} + +// -----------------------disputes----------------------- +func (m *defaultDisputeService) AddDisputes(ctx context.Context, in *AddDisputesReq, opts ...grpc.CallOption) (*AddDisputesResp, error) { + client := pb.NewDisputeServiceClient(m.cli.Conn()) + return client.AddDisputes(ctx, in, opts...) +} + +func (m *defaultDisputeService) UpdateDisputes(ctx context.Context, in *UpdateDisputesReq, opts ...grpc.CallOption) (*UpdateDisputesResp, error) { + client := pb.NewDisputeServiceClient(m.cli.Conn()) + return client.UpdateDisputes(ctx, in, opts...) +} + +func (m *defaultDisputeService) DelDisputes(ctx context.Context, in *DelDisputesReq, opts ...grpc.CallOption) (*DelDisputesResp, error) { + client := pb.NewDisputeServiceClient(m.cli.Conn()) + return client.DelDisputes(ctx, in, opts...) +} + +func (m *defaultDisputeService) GetDisputesById(ctx context.Context, in *GetDisputesByIdReq, opts ...grpc.CallOption) (*GetDisputesByIdResp, error) { + client := pb.NewDisputeServiceClient(m.cli.Conn()) + return client.GetDisputesById(ctx, in, opts...) +} + +func (m *defaultDisputeService) SearchDisputes(ctx context.Context, in *SearchDisputesReq, opts ...grpc.CallOption) (*SearchDisputesResp, error) { + client := pb.NewDisputeServiceClient(m.cli.Conn()) + return client.SearchDisputes(ctx, in, opts...) +} + +// -----------------------disputeTimeline----------------------- +func (m *defaultDisputeService) AddDisputeTimeline(ctx context.Context, in *AddDisputeTimelineReq, opts ...grpc.CallOption) (*AddDisputeTimelineResp, error) { + client := pb.NewDisputeServiceClient(m.cli.Conn()) + return client.AddDisputeTimeline(ctx, in, opts...) +} + +func (m *defaultDisputeService) SearchDisputeTimeline(ctx context.Context, in *SearchDisputeTimelineReq, opts ...grpc.CallOption) (*SearchDisputeTimelineResp, error) { + client := pb.NewDisputeServiceClient(m.cli.Conn()) + return client.SearchDisputeTimeline(ctx, in, opts...) +} diff --git a/app/dispute/rpc/etc/pb.yaml b/app/dispute/rpc/etc/pb.yaml new file mode 100644 index 0000000..0bbfacb --- /dev/null +++ b/app/dispute/rpc/etc/pb.yaml @@ -0,0 +1,23 @@ +Name: pb.rpc +ListenOn: 0.0.0.0:8080 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONF ===== +SnowflakeRpcConf: + Endpoints: + - snowflake:8080 + +DB: + Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + +CacheConf: + - Host: "${REDIS_HOST}:${REDIS_PORT}" + Type: node + +Log: + Level: debug diff --git a/app/dispute/rpc/internal/config/config.go b/app/dispute/rpc/internal/config/config.go new file mode 100644 index 0000000..f4107e8 --- /dev/null +++ b/app/dispute/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/dispute/rpc/internal/logic/addDisputeTimelineLogic.go b/app/dispute/rpc/internal/logic/addDisputeTimelineLogic.go new file mode 100644 index 0000000..c9d2df7 --- /dev/null +++ b/app/dispute/rpc/internal/logic/addDisputeTimelineLogic.go @@ -0,0 +1,60 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddDisputeTimelineLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddDisputeTimelineLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDisputeTimelineLogic { + return &AddDisputeTimelineLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------disputeTimeline----------------------- +func (l *AddDisputeTimelineLogic) AddDisputeTimeline(in *pb.AddDisputeTimelineReq) (*pb.AddDisputeTimelineResp, error) { + if in.GetDisputeId() <= 0 { + return nil, errors.New("disputeId is required") + } + if in.GetEventType() == "" { + return nil, errors.New("eventType is required") + } + + details, err := parseJSONMap(in.GetDetails()) + if err != nil { + return nil, err + } + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create dispute timeline id failed") + } + + _, err = l.svcCtx.DisputeModelRW.DisputeTimeline.Create(). + SetID(idResp.Id). + SetDisputeID(in.GetDisputeId()). + SetEventType(in.GetEventType()). + SetActorID(in.GetActorId()). + SetActorName(in.GetActorName()). + SetDetails(details). + Save(l.ctx) + if err != nil { + logx.Errorf("addDisputeTimeline err: %v", err) + return nil, errors.New("add dispute timeline failed") + } + + return &pb.AddDisputeTimelineResp{}, nil +} diff --git a/app/dispute/rpc/internal/logic/addDisputesLogic.go b/app/dispute/rpc/internal/logic/addDisputesLogic.go new file mode 100644 index 0000000..fd5abd8 --- /dev/null +++ b/app/dispute/rpc/internal/logic/addDisputesLogic.go @@ -0,0 +1,69 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddDisputesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddDisputesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDisputesLogic { + return &AddDisputesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// -----------------------disputes----------------------- +func (l *AddDisputesLogic) AddDisputes(in *pb.AddDisputesReq) (*pb.AddDisputesResp, error) { + if in.GetOrderId() <= 0 { + return nil, errors.New("orderId is required") + } + if in.GetInitiatorId() <= 0 { + return nil, errors.New("initiatorId is required") + } + if in.GetRespondentId() <= 0 { + return nil, errors.New("respondentId is required") + } + if in.GetReason() == "" { + return nil, errors.New("reason is required") + } + + status := in.GetStatus() + if status == "" { + status = "open" + } + + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create dispute id failed") + } + + created, err := l.svcCtx.DisputeModelRW.Disputes.Create(). + SetID(idResp.Id). + SetOrderID(in.GetOrderId()). + SetInitiatorID(in.GetInitiatorId()). + SetInitiatorName(in.GetInitiatorName()). + SetRespondentID(in.GetRespondentId()). + SetReason(in.GetReason()). + SetEvidence(toTextArray(in.GetEvidence())). + SetStatus(status). + Save(l.ctx) + if err != nil { + logx.Errorf("addDisputes err: %v", err) + return nil, errors.New("add dispute failed") + } + + return &pb.AddDisputesResp{Id: created.ID}, nil +} diff --git a/app/dispute/rpc/internal/logic/delDisputesLogic.go b/app/dispute/rpc/internal/logic/delDisputesLogic.go new file mode 100644 index 0000000..cd783dc --- /dev/null +++ b/app/dispute/rpc/internal/logic/delDisputesLogic.go @@ -0,0 +1,34 @@ +package logic + +import ( + "context" + + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelDisputesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelDisputesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelDisputesLogic { + return &DelDisputesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelDisputesLogic) DelDisputes(in *pb.DelDisputesReq) (*pb.DelDisputesResp, error) { + err := l.svcCtx.DisputeModelRW.Disputes.DeleteOneID(in.GetId()).Exec(l.ctx) + if err != nil { + logx.Errorf("delDisputes err: %v", err) + return nil, err + } + + return &pb.DelDisputesResp{}, nil +} diff --git a/app/dispute/rpc/internal/logic/getDisputesByIdLogic.go b/app/dispute/rpc/internal/logic/getDisputesByIdLogic.go new file mode 100644 index 0000000..2a1e5db --- /dev/null +++ b/app/dispute/rpc/internal/logic/getDisputesByIdLogic.go @@ -0,0 +1,33 @@ +package logic + +import ( + "context" + + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetDisputesByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetDisputesByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDisputesByIdLogic { + return &GetDisputesByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetDisputesByIdLogic) GetDisputesById(in *pb.GetDisputesByIdReq) (*pb.GetDisputesByIdResp, error) { + d, err := l.svcCtx.DisputeModelRO.Disputes.Get(l.ctx, in.GetId()) + if err != nil { + return nil, err + } + + return &pb.GetDisputesByIdResp{Disputes: entDisputeToPb(d)}, nil +} diff --git a/app/dispute/rpc/internal/logic/helpers.go b/app/dispute/rpc/internal/logic/helpers.go new file mode 100644 index 0000000..d7f28e3 --- /dev/null +++ b/app/dispute/rpc/internal/logic/helpers.go @@ -0,0 +1,90 @@ +package logic + +import ( + "encoding/json" + "errors" + + "juwan-backend/app/dispute/rpc/internal/models" + "juwan-backend/app/dispute/rpc/pb" + "juwan-backend/pkg/types" + + "github.com/jackc/pgx/v5/pgtype" +) + +func toTextArray(s []string) types.TextArray { + if len(s) == 0 { + return types.TextArray{Valid: true} + } + return types.TextArray{ + Elements: s, + Dims: []pgtype.ArrayDimension{{Length: int32(len(s)), LowerBound: 1}}, + Valid: true, + } +} + +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 entDisputeToPb(d *models.Disputes) *pb.Disputes { + out := &pb.Disputes{ + Id: d.ID, + OrderId: d.OrderID, + InitiatorId: d.InitiatorID, + InitiatorName: d.InitiatorName, + RespondentId: d.RespondentID, + Reason: d.Reason, + Evidence: d.Evidence.Elements, + Status: d.Status, + RespondentEvidence: d.RespondentEvidence.Elements, + CreatedAt: d.CreatedAt.Unix(), + UpdatedAt: d.UpdatedAt.Unix(), + } + if d.Result != nil { + out.Result = *d.Result + } + if d.RespondentReason != nil { + out.RespondentReason = *d.RespondentReason + } + if d.AppealReason != nil { + out.AppealReason = *d.AppealReason + } + if d.AppealedAt != nil { + out.AppealedAt = d.AppealedAt.Unix() + } + if d.ResolvedBy != nil { + out.ResolvedBy = *d.ResolvedBy + } + if d.ResolvedAt != nil { + out.ResolvedAt = d.ResolvedAt.Unix() + } + return out +} + +func entDisputeTimelineToPb(t *models.DisputeTimeline) *pb.DisputeTimeline { + details := "{}" + if t.Details != nil { + if b, err := json.Marshal(t.Details); err == nil { + details = string(b) + } + } + return &pb.DisputeTimeline{ + Id: t.ID, + DisputeId: t.DisputeID, + EventType: t.EventType, + ActorId: t.ActorID, + ActorName: t.ActorName, + Details: details, + CreatedAt: t.CreatedAt.Unix(), + } +} diff --git a/app/dispute/rpc/internal/logic/searchDisputeTimelineLogic.go b/app/dispute/rpc/internal/logic/searchDisputeTimelineLogic.go new file mode 100644 index 0000000..9c11a83 --- /dev/null +++ b/app/dispute/rpc/internal/logic/searchDisputeTimelineLogic.go @@ -0,0 +1,63 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" + + "entgo.io/ent/dialect/sql" + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchDisputeTimelineLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchDisputeTimelineLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchDisputeTimelineLogic { + return &SearchDisputeTimelineLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchDisputeTimelineLogic) SearchDisputeTimeline(in *pb.SearchDisputeTimelineReq) (*pb.SearchDisputeTimelineResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + if limit > 100 { + return nil, errors.New("limit too large") + } + offset := in.GetOffset() + if offset < 0 { + offset = 0 + } + + query := l.svcCtx.DisputeModelRO.DisputeTimeline.Query() + if in.DisputeId != nil { + query = query.Where(disputetimeline.DisputeIDEQ(in.GetDisputeId())) + } + + list, err := query. + Order(disputetimeline.ByCreatedAt(sql.OrderAsc()), disputetimeline.ByID(sql.OrderAsc())). + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchDisputeTimeline err: %v", err) + return nil, errors.New("search dispute timeline failed") + } + + out := make([]*pb.DisputeTimeline, len(list)) + for i, item := range list { + out[i] = entDisputeTimelineToPb(item) + } + + return &pb.SearchDisputeTimelineResp{Timeline: out}, nil +} diff --git a/app/dispute/rpc/internal/logic/searchDisputesLogic.go b/app/dispute/rpc/internal/logic/searchDisputesLogic.go new file mode 100644 index 0000000..5ca0368 --- /dev/null +++ b/app/dispute/rpc/internal/logic/searchDisputesLogic.go @@ -0,0 +1,75 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" + + "entgo.io/ent/dialect/sql" + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchDisputesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchDisputesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchDisputesLogic { + return &SearchDisputesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchDisputesLogic) SearchDisputes(in *pb.SearchDisputesReq) (*pb.SearchDisputesResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + if limit > 100 { + return nil, errors.New("limit too large") + } + offset := in.GetOffset() + if offset < 0 { + offset = 0 + } + + query := l.svcCtx.DisputeModelRO.Disputes.Query() + if in.Id != nil { + query = query.Where(disputes.IDEQ(in.GetId())) + } + if in.OrderId != nil { + query = query.Where(disputes.OrderIDEQ(in.GetOrderId())) + } + if in.InitiatorId != nil { + query = query.Where(disputes.InitiatorIDEQ(in.GetInitiatorId())) + } + if in.RespondentId != nil { + query = query.Where(disputes.RespondentIDEQ(in.GetRespondentId())) + } + if in.Status != nil { + query = query.Where(disputes.StatusEQ(in.GetStatus())) + } + + list, err := query. + Order(disputes.ByCreatedAt(sql.OrderDesc()), disputes.ByID(sql.OrderDesc())). + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchDisputes err: %v", err) + return nil, errors.New("search disputes failed") + } + + out := make([]*pb.Disputes, len(list)) + for i, d := range list { + out[i] = entDisputeToPb(d) + } + + return &pb.SearchDisputesResp{Disputes: out}, nil +} diff --git a/app/dispute/rpc/internal/logic/updateDisputesLogic.go b/app/dispute/rpc/internal/logic/updateDisputesLogic.go new file mode 100644 index 0000000..756050d --- /dev/null +++ b/app/dispute/rpc/internal/logic/updateDisputesLogic.go @@ -0,0 +1,62 @@ +package logic + +import ( + "context" + "time" + + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateDisputesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateDisputesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateDisputesLogic { + return &UpdateDisputesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateDisputesLogic) UpdateDisputes(in *pb.UpdateDisputesReq) (*pb.UpdateDisputesResp, error) { + updater := l.svcCtx.DisputeModelRW.Disputes.UpdateOneID(in.GetId()) + + if in.Status != nil { + updater = updater.SetStatus(in.GetStatus()) + } + if in.Result != nil { + updater = updater.SetResult(in.GetResult()) + } + if in.RespondentReason != nil { + updater = updater.SetRespondentReason(in.GetRespondentReason()) + } + if len(in.GetRespondentEvidence()) > 0 { + updater = updater.SetRespondentEvidence(toTextArray(in.GetRespondentEvidence())) + } + if in.AppealReason != nil { + updater = updater.SetAppealReason(in.GetAppealReason()) + } + if in.AppealedAt != nil { + updater = updater.SetAppealedAt(time.Unix(in.GetAppealedAt(), 0)) + } + if in.ResolvedBy != nil { + updater = updater.SetResolvedBy(in.GetResolvedBy()) + } + if in.ResolvedAt != nil { + updater = updater.SetResolvedAt(time.Unix(in.GetResolvedAt(), 0)) + } + + _, err := updater.Save(l.ctx) + if err != nil { + logx.Errorf("updateDisputes err: %v", err) + return nil, err + } + + return &pb.UpdateDisputesResp{}, nil +} diff --git a/app/dispute/rpc/internal/models/client.go b/app/dispute/rpc/internal/models/client.go new file mode 100644 index 0000000..cfd28bc --- /dev/null +++ b/app/dispute/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/dispute/rpc/internal/models/migrate" + + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + + "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 + // DisputeTimeline is the client for interacting with the DisputeTimeline builders. + DisputeTimeline *DisputeTimelineClient + // Disputes is the client for interacting with the Disputes builders. + Disputes *DisputesClient +} + +// 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.DisputeTimeline = NewDisputeTimelineClient(c.config) + c.Disputes = NewDisputesClient(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, + DisputeTimeline: NewDisputeTimelineClient(cfg), + Disputes: NewDisputesClient(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, + DisputeTimeline: NewDisputeTimelineClient(cfg), + Disputes: NewDisputesClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// DisputeTimeline. +// 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.DisputeTimeline.Use(hooks...) + c.Disputes.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.DisputeTimeline.Intercept(interceptors...) + c.Disputes.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *DisputeTimelineMutation: + return c.DisputeTimeline.mutate(ctx, m) + case *DisputesMutation: + return c.Disputes.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// DisputeTimelineClient is a client for the DisputeTimeline schema. +type DisputeTimelineClient struct { + config +} + +// NewDisputeTimelineClient returns a client for the DisputeTimeline from the given config. +func NewDisputeTimelineClient(c config) *DisputeTimelineClient { + return &DisputeTimelineClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `disputetimeline.Hooks(f(g(h())))`. +func (c *DisputeTimelineClient) Use(hooks ...Hook) { + c.hooks.DisputeTimeline = append(c.hooks.DisputeTimeline, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `disputetimeline.Intercept(f(g(h())))`. +func (c *DisputeTimelineClient) Intercept(interceptors ...Interceptor) { + c.inters.DisputeTimeline = append(c.inters.DisputeTimeline, interceptors...) +} + +// Create returns a builder for creating a DisputeTimeline entity. +func (c *DisputeTimelineClient) Create() *DisputeTimelineCreate { + mutation := newDisputeTimelineMutation(c.config, OpCreate) + return &DisputeTimelineCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of DisputeTimeline entities. +func (c *DisputeTimelineClient) CreateBulk(builders ...*DisputeTimelineCreate) *DisputeTimelineCreateBulk { + return &DisputeTimelineCreateBulk{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 *DisputeTimelineClient) MapCreateBulk(slice any, setFunc func(*DisputeTimelineCreate, int)) *DisputeTimelineCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &DisputeTimelineCreateBulk{err: fmt.Errorf("calling to DisputeTimelineClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*DisputeTimelineCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &DisputeTimelineCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for DisputeTimeline. +func (c *DisputeTimelineClient) Update() *DisputeTimelineUpdate { + mutation := newDisputeTimelineMutation(c.config, OpUpdate) + return &DisputeTimelineUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *DisputeTimelineClient) UpdateOne(_m *DisputeTimeline) *DisputeTimelineUpdateOne { + mutation := newDisputeTimelineMutation(c.config, OpUpdateOne, withDisputeTimeline(_m)) + return &DisputeTimelineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *DisputeTimelineClient) UpdateOneID(id int64) *DisputeTimelineUpdateOne { + mutation := newDisputeTimelineMutation(c.config, OpUpdateOne, withDisputeTimelineID(id)) + return &DisputeTimelineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for DisputeTimeline. +func (c *DisputeTimelineClient) Delete() *DisputeTimelineDelete { + mutation := newDisputeTimelineMutation(c.config, OpDelete) + return &DisputeTimelineDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *DisputeTimelineClient) DeleteOne(_m *DisputeTimeline) *DisputeTimelineDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *DisputeTimelineClient) DeleteOneID(id int64) *DisputeTimelineDeleteOne { + builder := c.Delete().Where(disputetimeline.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &DisputeTimelineDeleteOne{builder} +} + +// Query returns a query builder for DisputeTimeline. +func (c *DisputeTimelineClient) Query() *DisputeTimelineQuery { + return &DisputeTimelineQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeDisputeTimeline}, + inters: c.Interceptors(), + } +} + +// Get returns a DisputeTimeline entity by its id. +func (c *DisputeTimelineClient) Get(ctx context.Context, id int64) (*DisputeTimeline, error) { + return c.Query().Where(disputetimeline.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *DisputeTimelineClient) GetX(ctx context.Context, id int64) *DisputeTimeline { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *DisputeTimelineClient) Hooks() []Hook { + return c.hooks.DisputeTimeline +} + +// Interceptors returns the client interceptors. +func (c *DisputeTimelineClient) Interceptors() []Interceptor { + return c.inters.DisputeTimeline +} + +func (c *DisputeTimelineClient) mutate(ctx context.Context, m *DisputeTimelineMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&DisputeTimelineCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&DisputeTimelineUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&DisputeTimelineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&DisputeTimelineDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown DisputeTimeline mutation op: %q", m.Op()) + } +} + +// DisputesClient is a client for the Disputes schema. +type DisputesClient struct { + config +} + +// NewDisputesClient returns a client for the Disputes from the given config. +func NewDisputesClient(c config) *DisputesClient { + return &DisputesClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `disputes.Hooks(f(g(h())))`. +func (c *DisputesClient) Use(hooks ...Hook) { + c.hooks.Disputes = append(c.hooks.Disputes, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `disputes.Intercept(f(g(h())))`. +func (c *DisputesClient) Intercept(interceptors ...Interceptor) { + c.inters.Disputes = append(c.inters.Disputes, interceptors...) +} + +// Create returns a builder for creating a Disputes entity. +func (c *DisputesClient) Create() *DisputesCreate { + mutation := newDisputesMutation(c.config, OpCreate) + return &DisputesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Disputes entities. +func (c *DisputesClient) CreateBulk(builders ...*DisputesCreate) *DisputesCreateBulk { + return &DisputesCreateBulk{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 *DisputesClient) MapCreateBulk(slice any, setFunc func(*DisputesCreate, int)) *DisputesCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &DisputesCreateBulk{err: fmt.Errorf("calling to DisputesClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*DisputesCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &DisputesCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Disputes. +func (c *DisputesClient) Update() *DisputesUpdate { + mutation := newDisputesMutation(c.config, OpUpdate) + return &DisputesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *DisputesClient) UpdateOne(_m *Disputes) *DisputesUpdateOne { + mutation := newDisputesMutation(c.config, OpUpdateOne, withDisputes(_m)) + return &DisputesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *DisputesClient) UpdateOneID(id int64) *DisputesUpdateOne { + mutation := newDisputesMutation(c.config, OpUpdateOne, withDisputesID(id)) + return &DisputesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Disputes. +func (c *DisputesClient) Delete() *DisputesDelete { + mutation := newDisputesMutation(c.config, OpDelete) + return &DisputesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *DisputesClient) DeleteOne(_m *Disputes) *DisputesDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *DisputesClient) DeleteOneID(id int64) *DisputesDeleteOne { + builder := c.Delete().Where(disputes.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &DisputesDeleteOne{builder} +} + +// Query returns a query builder for Disputes. +func (c *DisputesClient) Query() *DisputesQuery { + return &DisputesQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeDisputes}, + inters: c.Interceptors(), + } +} + +// Get returns a Disputes entity by its id. +func (c *DisputesClient) Get(ctx context.Context, id int64) (*Disputes, error) { + return c.Query().Where(disputes.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *DisputesClient) GetX(ctx context.Context, id int64) *Disputes { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *DisputesClient) Hooks() []Hook { + return c.hooks.Disputes +} + +// Interceptors returns the client interceptors. +func (c *DisputesClient) Interceptors() []Interceptor { + return c.inters.Disputes +} + +func (c *DisputesClient) mutate(ctx context.Context, m *DisputesMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&DisputesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&DisputesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&DisputesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&DisputesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Disputes mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + DisputeTimeline, Disputes []ent.Hook + } + inters struct { + DisputeTimeline, Disputes []ent.Interceptor + } +) diff --git a/app/dispute/rpc/internal/models/disputes.go b/app/dispute/rpc/internal/models/disputes.go new file mode 100644 index 0000000..9e2f4d8 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputes.go @@ -0,0 +1,292 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/pkg/types" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Disputes is the model entity for the Disputes schema. +type Disputes 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"` + // InitiatorID holds the value of the "initiator_id" field. + InitiatorID int64 `json:"initiator_id,omitempty"` + // InitiatorName holds the value of the "initiator_name" field. + InitiatorName string `json:"initiator_name,omitempty"` + // RespondentID holds the value of the "respondent_id" field. + RespondentID int64 `json:"respondent_id,omitempty"` + // Reason holds the value of the "reason" field. + Reason string `json:"reason,omitempty"` + // Evidence holds the value of the "evidence" field. + Evidence types.TextArray `json:"evidence,omitempty"` + // Status holds the value of the "status" field. + Status string `json:"status,omitempty"` + // Result holds the value of the "result" field. + Result *string `json:"result,omitempty"` + // RespondentReason holds the value of the "respondent_reason" field. + RespondentReason *string `json:"respondent_reason,omitempty"` + // RespondentEvidence holds the value of the "respondent_evidence" field. + RespondentEvidence types.TextArray `json:"respondent_evidence,omitempty"` + // AppealReason holds the value of the "appeal_reason" field. + AppealReason *string `json:"appeal_reason,omitempty"` + // AppealedAt holds the value of the "appealed_at" field. + AppealedAt *time.Time `json:"appealed_at,omitempty"` + // ResolvedBy holds the value of the "resolved_by" field. + ResolvedBy *int64 `json:"resolved_by,omitempty"` + // ResolvedAt holds the value of the "resolved_at" field. + ResolvedAt *time.Time `json:"resolved_at,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 (*Disputes) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case disputes.FieldID, disputes.FieldOrderID, disputes.FieldInitiatorID, disputes.FieldRespondentID, disputes.FieldResolvedBy: + values[i] = new(sql.NullInt64) + case disputes.FieldInitiatorName, disputes.FieldReason, disputes.FieldStatus, disputes.FieldResult, disputes.FieldRespondentReason, disputes.FieldAppealReason: + values[i] = new(sql.NullString) + case disputes.FieldAppealedAt, disputes.FieldResolvedAt, disputes.FieldCreatedAt, disputes.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case disputes.FieldEvidence, disputes.FieldRespondentEvidence: + values[i] = new(types.TextArray) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Disputes fields. +func (_m *Disputes) 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 disputes.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 disputes.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 disputes.FieldInitiatorID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field initiator_id", values[i]) + } else if value.Valid { + _m.InitiatorID = value.Int64 + } + case disputes.FieldInitiatorName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field initiator_name", values[i]) + } else if value.Valid { + _m.InitiatorName = value.String + } + case disputes.FieldRespondentID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field respondent_id", values[i]) + } else if value.Valid { + _m.RespondentID = value.Int64 + } + case disputes.FieldReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field reason", values[i]) + } else if value.Valid { + _m.Reason = value.String + } + case disputes.FieldEvidence: + if value, ok := values[i].(*types.TextArray); !ok { + return fmt.Errorf("unexpected type %T for field evidence", values[i]) + } else if value != nil { + _m.Evidence = *value + } + case disputes.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 disputes.FieldResult: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field result", values[i]) + } else if value.Valid { + _m.Result = new(string) + *_m.Result = value.String + } + case disputes.FieldRespondentReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field respondent_reason", values[i]) + } else if value.Valid { + _m.RespondentReason = new(string) + *_m.RespondentReason = value.String + } + case disputes.FieldRespondentEvidence: + if value, ok := values[i].(*types.TextArray); !ok { + return fmt.Errorf("unexpected type %T for field respondent_evidence", values[i]) + } else if value != nil { + _m.RespondentEvidence = *value + } + case disputes.FieldAppealReason: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field appeal_reason", values[i]) + } else if value.Valid { + _m.AppealReason = new(string) + *_m.AppealReason = value.String + } + case disputes.FieldAppealedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field appealed_at", values[i]) + } else if value.Valid { + _m.AppealedAt = new(time.Time) + *_m.AppealedAt = value.Time + } + case disputes.FieldResolvedBy: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field resolved_by", values[i]) + } else if value.Valid { + _m.ResolvedBy = new(int64) + *_m.ResolvedBy = value.Int64 + } + case disputes.FieldResolvedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field resolved_at", values[i]) + } else if value.Valid { + _m.ResolvedAt = new(time.Time) + *_m.ResolvedAt = value.Time + } + case disputes.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 disputes.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 Disputes. +// This includes values selected through modifiers, order, etc. +func (_m *Disputes) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Disputes. +// Note that you need to call Disputes.Unwrap() before calling this method if this Disputes +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Disputes) Update() *DisputesUpdateOne { + return NewDisputesClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Disputes 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 *Disputes) Unwrap() *Disputes { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Disputes is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Disputes) String() string { + var builder strings.Builder + builder.WriteString("Disputes(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("order_id=") + builder.WriteString(fmt.Sprintf("%v", _m.OrderID)) + builder.WriteString(", ") + builder.WriteString("initiator_id=") + builder.WriteString(fmt.Sprintf("%v", _m.InitiatorID)) + builder.WriteString(", ") + builder.WriteString("initiator_name=") + builder.WriteString(_m.InitiatorName) + builder.WriteString(", ") + builder.WriteString("respondent_id=") + builder.WriteString(fmt.Sprintf("%v", _m.RespondentID)) + builder.WriteString(", ") + builder.WriteString("reason=") + builder.WriteString(_m.Reason) + builder.WriteString(", ") + builder.WriteString("evidence=") + builder.WriteString(fmt.Sprintf("%v", _m.Evidence)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(_m.Status) + builder.WriteString(", ") + if v := _m.Result; v != nil { + builder.WriteString("result=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.RespondentReason; v != nil { + builder.WriteString("respondent_reason=") + builder.WriteString(*v) + } + builder.WriteString(", ") + builder.WriteString("respondent_evidence=") + builder.WriteString(fmt.Sprintf("%v", _m.RespondentEvidence)) + builder.WriteString(", ") + if v := _m.AppealReason; v != nil { + builder.WriteString("appeal_reason=") + builder.WriteString(*v) + } + builder.WriteString(", ") + if v := _m.AppealedAt; v != nil { + builder.WriteString("appealed_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteString(", ") + if v := _m.ResolvedBy; v != nil { + builder.WriteString("resolved_by=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteString(", ") + if v := _m.ResolvedAt; v != nil { + builder.WriteString("resolved_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + 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() +} + +// DisputesSlice is a parsable slice of Disputes. +type DisputesSlice []*Disputes diff --git a/app/dispute/rpc/internal/models/disputes/disputes.go b/app/dispute/rpc/internal/models/disputes/disputes.go new file mode 100644 index 0000000..7e59e65 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputes/disputes.go @@ -0,0 +1,186 @@ +// Code generated by ent, DO NOT EDIT. + +package disputes + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the disputes type in the database. + Label = "disputes" + // 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" + // FieldInitiatorID holds the string denoting the initiator_id field in the database. + FieldInitiatorID = "initiator_id" + // FieldInitiatorName holds the string denoting the initiator_name field in the database. + FieldInitiatorName = "initiator_name" + // FieldRespondentID holds the string denoting the respondent_id field in the database. + FieldRespondentID = "respondent_id" + // FieldReason holds the string denoting the reason field in the database. + FieldReason = "reason" + // FieldEvidence holds the string denoting the evidence field in the database. + FieldEvidence = "evidence" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldResult holds the string denoting the result field in the database. + FieldResult = "result" + // FieldRespondentReason holds the string denoting the respondent_reason field in the database. + FieldRespondentReason = "respondent_reason" + // FieldRespondentEvidence holds the string denoting the respondent_evidence field in the database. + FieldRespondentEvidence = "respondent_evidence" + // FieldAppealReason holds the string denoting the appeal_reason field in the database. + FieldAppealReason = "appeal_reason" + // FieldAppealedAt holds the string denoting the appealed_at field in the database. + FieldAppealedAt = "appealed_at" + // FieldResolvedBy holds the string denoting the resolved_by field in the database. + FieldResolvedBy = "resolved_by" + // FieldResolvedAt holds the string denoting the resolved_at field in the database. + FieldResolvedAt = "resolved_at" + // 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 disputes in the database. + Table = "disputes" +) + +// Columns holds all SQL columns for disputes fields. +var Columns = []string{ + FieldID, + FieldOrderID, + FieldInitiatorID, + FieldInitiatorName, + FieldRespondentID, + FieldReason, + FieldEvidence, + FieldStatus, + FieldResult, + FieldRespondentReason, + FieldRespondentEvidence, + FieldAppealReason, + FieldAppealedAt, + FieldResolvedBy, + FieldResolvedAt, + 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 ( + // InitiatorNameValidator is a validator for the "initiator_name" field. It is called by the builders before save. + InitiatorNameValidator 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 + // ResultValidator is a validator for the "result" field. It is called by the builders before save. + ResultValidator 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 Disputes 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() +} + +// ByInitiatorID orders the results by the initiator_id field. +func ByInitiatorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInitiatorID, opts...).ToFunc() +} + +// ByInitiatorName orders the results by the initiator_name field. +func ByInitiatorName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInitiatorName, opts...).ToFunc() +} + +// ByRespondentID orders the results by the respondent_id field. +func ByRespondentID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRespondentID, opts...).ToFunc() +} + +// ByReason orders the results by the reason field. +func ByReason(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReason, opts...).ToFunc() +} + +// ByEvidence orders the results by the evidence field. +func ByEvidence(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEvidence, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByResult orders the results by the result field. +func ByResult(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResult, opts...).ToFunc() +} + +// ByRespondentReason orders the results by the respondent_reason field. +func ByRespondentReason(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRespondentReason, opts...).ToFunc() +} + +// ByRespondentEvidence orders the results by the respondent_evidence field. +func ByRespondentEvidence(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRespondentEvidence, opts...).ToFunc() +} + +// ByAppealReason orders the results by the appeal_reason field. +func ByAppealReason(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAppealReason, opts...).ToFunc() +} + +// ByAppealedAt orders the results by the appealed_at field. +func ByAppealedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAppealedAt, opts...).ToFunc() +} + +// ByResolvedBy orders the results by the resolved_by field. +func ByResolvedBy(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResolvedBy, opts...).ToFunc() +} + +// ByResolvedAt orders the results by the resolved_at field. +func ByResolvedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldResolvedAt, 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/dispute/rpc/internal/models/disputes/where.go b/app/dispute/rpc/internal/models/disputes/where.go new file mode 100644 index 0000000..ad4829a --- /dev/null +++ b/app/dispute/rpc/internal/models/disputes/where.go @@ -0,0 +1,1021 @@ +// Code generated by ent, DO NOT EDIT. + +package disputes + +import ( + "juwan-backend/app/dispute/rpc/internal/models/predicate" + "juwan-backend/pkg/types" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldID, id)) +} + +// OrderID applies equality check predicate on the "order_id" field. It's identical to OrderIDEQ. +func OrderID(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldOrderID, v)) +} + +// InitiatorID applies equality check predicate on the "initiator_id" field. It's identical to InitiatorIDEQ. +func InitiatorID(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldInitiatorID, v)) +} + +// InitiatorName applies equality check predicate on the "initiator_name" field. It's identical to InitiatorNameEQ. +func InitiatorName(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldInitiatorName, v)) +} + +// RespondentID applies equality check predicate on the "respondent_id" field. It's identical to RespondentIDEQ. +func RespondentID(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldRespondentID, v)) +} + +// Reason applies equality check predicate on the "reason" field. It's identical to ReasonEQ. +func Reason(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldReason, v)) +} + +// Evidence applies equality check predicate on the "evidence" field. It's identical to EvidenceEQ. +func Evidence(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldEvidence, v)) +} + +// Status applies equality check predicate on the "status" field. It's identical to StatusEQ. +func Status(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldStatus, v)) +} + +// Result applies equality check predicate on the "result" field. It's identical to ResultEQ. +func Result(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldResult, v)) +} + +// RespondentReason applies equality check predicate on the "respondent_reason" field. It's identical to RespondentReasonEQ. +func RespondentReason(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldRespondentReason, v)) +} + +// RespondentEvidence applies equality check predicate on the "respondent_evidence" field. It's identical to RespondentEvidenceEQ. +func RespondentEvidence(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldRespondentEvidence, v)) +} + +// AppealReason applies equality check predicate on the "appeal_reason" field. It's identical to AppealReasonEQ. +func AppealReason(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldAppealReason, v)) +} + +// AppealedAt applies equality check predicate on the "appealed_at" field. It's identical to AppealedAtEQ. +func AppealedAt(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldAppealedAt, v)) +} + +// ResolvedBy applies equality check predicate on the "resolved_by" field. It's identical to ResolvedByEQ. +func ResolvedBy(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldResolvedBy, v)) +} + +// ResolvedAt applies equality check predicate on the "resolved_at" field. It's identical to ResolvedAtEQ. +func ResolvedAt(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldResolvedAt, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Disputes { + return predicate.Disputes(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.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// OrderIDEQ applies the EQ predicate on the "order_id" field. +func OrderIDEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldOrderID, v)) +} + +// OrderIDNEQ applies the NEQ predicate on the "order_id" field. +func OrderIDNEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldOrderID, v)) +} + +// OrderIDIn applies the In predicate on the "order_id" field. +func OrderIDIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldOrderID, vs...)) +} + +// OrderIDNotIn applies the NotIn predicate on the "order_id" field. +func OrderIDNotIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldOrderID, vs...)) +} + +// OrderIDGT applies the GT predicate on the "order_id" field. +func OrderIDGT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldOrderID, v)) +} + +// OrderIDGTE applies the GTE predicate on the "order_id" field. +func OrderIDGTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldOrderID, v)) +} + +// OrderIDLT applies the LT predicate on the "order_id" field. +func OrderIDLT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldOrderID, v)) +} + +// OrderIDLTE applies the LTE predicate on the "order_id" field. +func OrderIDLTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldOrderID, v)) +} + +// InitiatorIDEQ applies the EQ predicate on the "initiator_id" field. +func InitiatorIDEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldInitiatorID, v)) +} + +// InitiatorIDNEQ applies the NEQ predicate on the "initiator_id" field. +func InitiatorIDNEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldInitiatorID, v)) +} + +// InitiatorIDIn applies the In predicate on the "initiator_id" field. +func InitiatorIDIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldInitiatorID, vs...)) +} + +// InitiatorIDNotIn applies the NotIn predicate on the "initiator_id" field. +func InitiatorIDNotIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldInitiatorID, vs...)) +} + +// InitiatorIDGT applies the GT predicate on the "initiator_id" field. +func InitiatorIDGT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldInitiatorID, v)) +} + +// InitiatorIDGTE applies the GTE predicate on the "initiator_id" field. +func InitiatorIDGTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldInitiatorID, v)) +} + +// InitiatorIDLT applies the LT predicate on the "initiator_id" field. +func InitiatorIDLT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldInitiatorID, v)) +} + +// InitiatorIDLTE applies the LTE predicate on the "initiator_id" field. +func InitiatorIDLTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldInitiatorID, v)) +} + +// InitiatorNameEQ applies the EQ predicate on the "initiator_name" field. +func InitiatorNameEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldInitiatorName, v)) +} + +// InitiatorNameNEQ applies the NEQ predicate on the "initiator_name" field. +func InitiatorNameNEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldInitiatorName, v)) +} + +// InitiatorNameIn applies the In predicate on the "initiator_name" field. +func InitiatorNameIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldInitiatorName, vs...)) +} + +// InitiatorNameNotIn applies the NotIn predicate on the "initiator_name" field. +func InitiatorNameNotIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldInitiatorName, vs...)) +} + +// InitiatorNameGT applies the GT predicate on the "initiator_name" field. +func InitiatorNameGT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldInitiatorName, v)) +} + +// InitiatorNameGTE applies the GTE predicate on the "initiator_name" field. +func InitiatorNameGTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldInitiatorName, v)) +} + +// InitiatorNameLT applies the LT predicate on the "initiator_name" field. +func InitiatorNameLT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldInitiatorName, v)) +} + +// InitiatorNameLTE applies the LTE predicate on the "initiator_name" field. +func InitiatorNameLTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldInitiatorName, v)) +} + +// InitiatorNameContains applies the Contains predicate on the "initiator_name" field. +func InitiatorNameContains(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContains(FieldInitiatorName, v)) +} + +// InitiatorNameHasPrefix applies the HasPrefix predicate on the "initiator_name" field. +func InitiatorNameHasPrefix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasPrefix(FieldInitiatorName, v)) +} + +// InitiatorNameHasSuffix applies the HasSuffix predicate on the "initiator_name" field. +func InitiatorNameHasSuffix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasSuffix(FieldInitiatorName, v)) +} + +// InitiatorNameEqualFold applies the EqualFold predicate on the "initiator_name" field. +func InitiatorNameEqualFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEqualFold(FieldInitiatorName, v)) +} + +// InitiatorNameContainsFold applies the ContainsFold predicate on the "initiator_name" field. +func InitiatorNameContainsFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContainsFold(FieldInitiatorName, v)) +} + +// RespondentIDEQ applies the EQ predicate on the "respondent_id" field. +func RespondentIDEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldRespondentID, v)) +} + +// RespondentIDNEQ applies the NEQ predicate on the "respondent_id" field. +func RespondentIDNEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldRespondentID, v)) +} + +// RespondentIDIn applies the In predicate on the "respondent_id" field. +func RespondentIDIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldRespondentID, vs...)) +} + +// RespondentIDNotIn applies the NotIn predicate on the "respondent_id" field. +func RespondentIDNotIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldRespondentID, vs...)) +} + +// RespondentIDGT applies the GT predicate on the "respondent_id" field. +func RespondentIDGT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldRespondentID, v)) +} + +// RespondentIDGTE applies the GTE predicate on the "respondent_id" field. +func RespondentIDGTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldRespondentID, v)) +} + +// RespondentIDLT applies the LT predicate on the "respondent_id" field. +func RespondentIDLT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldRespondentID, v)) +} + +// RespondentIDLTE applies the LTE predicate on the "respondent_id" field. +func RespondentIDLTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldRespondentID, v)) +} + +// ReasonEQ applies the EQ predicate on the "reason" field. +func ReasonEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldReason, v)) +} + +// ReasonNEQ applies the NEQ predicate on the "reason" field. +func ReasonNEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldReason, v)) +} + +// ReasonIn applies the In predicate on the "reason" field. +func ReasonIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldReason, vs...)) +} + +// ReasonNotIn applies the NotIn predicate on the "reason" field. +func ReasonNotIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldReason, vs...)) +} + +// ReasonGT applies the GT predicate on the "reason" field. +func ReasonGT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldReason, v)) +} + +// ReasonGTE applies the GTE predicate on the "reason" field. +func ReasonGTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldReason, v)) +} + +// ReasonLT applies the LT predicate on the "reason" field. +func ReasonLT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldReason, v)) +} + +// ReasonLTE applies the LTE predicate on the "reason" field. +func ReasonLTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldReason, v)) +} + +// ReasonContains applies the Contains predicate on the "reason" field. +func ReasonContains(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContains(FieldReason, v)) +} + +// ReasonHasPrefix applies the HasPrefix predicate on the "reason" field. +func ReasonHasPrefix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasPrefix(FieldReason, v)) +} + +// ReasonHasSuffix applies the HasSuffix predicate on the "reason" field. +func ReasonHasSuffix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasSuffix(FieldReason, v)) +} + +// ReasonEqualFold applies the EqualFold predicate on the "reason" field. +func ReasonEqualFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEqualFold(FieldReason, v)) +} + +// ReasonContainsFold applies the ContainsFold predicate on the "reason" field. +func ReasonContainsFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContainsFold(FieldReason, v)) +} + +// EvidenceEQ applies the EQ predicate on the "evidence" field. +func EvidenceEQ(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldEvidence, v)) +} + +// EvidenceNEQ applies the NEQ predicate on the "evidence" field. +func EvidenceNEQ(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldEvidence, v)) +} + +// EvidenceIn applies the In predicate on the "evidence" field. +func EvidenceIn(vs ...types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldEvidence, vs...)) +} + +// EvidenceNotIn applies the NotIn predicate on the "evidence" field. +func EvidenceNotIn(vs ...types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldEvidence, vs...)) +} + +// EvidenceGT applies the GT predicate on the "evidence" field. +func EvidenceGT(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldEvidence, v)) +} + +// EvidenceGTE applies the GTE predicate on the "evidence" field. +func EvidenceGTE(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldEvidence, v)) +} + +// EvidenceLT applies the LT predicate on the "evidence" field. +func EvidenceLT(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldEvidence, v)) +} + +// EvidenceLTE applies the LTE predicate on the "evidence" field. +func EvidenceLTE(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldEvidence, v)) +} + +// EvidenceIsNil applies the IsNil predicate on the "evidence" field. +func EvidenceIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldEvidence)) +} + +// EvidenceNotNil applies the NotNil predicate on the "evidence" field. +func EvidenceNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldEvidence)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldStatus, vs...)) +} + +// StatusGT applies the GT predicate on the "status" field. +func StatusGT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldStatus, v)) +} + +// StatusGTE applies the GTE predicate on the "status" field. +func StatusGTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldStatus, v)) +} + +// StatusLT applies the LT predicate on the "status" field. +func StatusLT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldStatus, v)) +} + +// StatusLTE applies the LTE predicate on the "status" field. +func StatusLTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldStatus, v)) +} + +// StatusContains applies the Contains predicate on the "status" field. +func StatusContains(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContains(FieldStatus, v)) +} + +// StatusHasPrefix applies the HasPrefix predicate on the "status" field. +func StatusHasPrefix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasPrefix(FieldStatus, v)) +} + +// StatusHasSuffix applies the HasSuffix predicate on the "status" field. +func StatusHasSuffix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasSuffix(FieldStatus, v)) +} + +// StatusEqualFold applies the EqualFold predicate on the "status" field. +func StatusEqualFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEqualFold(FieldStatus, v)) +} + +// StatusContainsFold applies the ContainsFold predicate on the "status" field. +func StatusContainsFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContainsFold(FieldStatus, v)) +} + +// ResultEQ applies the EQ predicate on the "result" field. +func ResultEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldResult, v)) +} + +// ResultNEQ applies the NEQ predicate on the "result" field. +func ResultNEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldResult, v)) +} + +// ResultIn applies the In predicate on the "result" field. +func ResultIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldResult, vs...)) +} + +// ResultNotIn applies the NotIn predicate on the "result" field. +func ResultNotIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldResult, vs...)) +} + +// ResultGT applies the GT predicate on the "result" field. +func ResultGT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldResult, v)) +} + +// ResultGTE applies the GTE predicate on the "result" field. +func ResultGTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldResult, v)) +} + +// ResultLT applies the LT predicate on the "result" field. +func ResultLT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldResult, v)) +} + +// ResultLTE applies the LTE predicate on the "result" field. +func ResultLTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldResult, v)) +} + +// ResultContains applies the Contains predicate on the "result" field. +func ResultContains(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContains(FieldResult, v)) +} + +// ResultHasPrefix applies the HasPrefix predicate on the "result" field. +func ResultHasPrefix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasPrefix(FieldResult, v)) +} + +// ResultHasSuffix applies the HasSuffix predicate on the "result" field. +func ResultHasSuffix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasSuffix(FieldResult, v)) +} + +// ResultIsNil applies the IsNil predicate on the "result" field. +func ResultIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldResult)) +} + +// ResultNotNil applies the NotNil predicate on the "result" field. +func ResultNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldResult)) +} + +// ResultEqualFold applies the EqualFold predicate on the "result" field. +func ResultEqualFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEqualFold(FieldResult, v)) +} + +// ResultContainsFold applies the ContainsFold predicate on the "result" field. +func ResultContainsFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContainsFold(FieldResult, v)) +} + +// RespondentReasonEQ applies the EQ predicate on the "respondent_reason" field. +func RespondentReasonEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldRespondentReason, v)) +} + +// RespondentReasonNEQ applies the NEQ predicate on the "respondent_reason" field. +func RespondentReasonNEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldRespondentReason, v)) +} + +// RespondentReasonIn applies the In predicate on the "respondent_reason" field. +func RespondentReasonIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldRespondentReason, vs...)) +} + +// RespondentReasonNotIn applies the NotIn predicate on the "respondent_reason" field. +func RespondentReasonNotIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldRespondentReason, vs...)) +} + +// RespondentReasonGT applies the GT predicate on the "respondent_reason" field. +func RespondentReasonGT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldRespondentReason, v)) +} + +// RespondentReasonGTE applies the GTE predicate on the "respondent_reason" field. +func RespondentReasonGTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldRespondentReason, v)) +} + +// RespondentReasonLT applies the LT predicate on the "respondent_reason" field. +func RespondentReasonLT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldRespondentReason, v)) +} + +// RespondentReasonLTE applies the LTE predicate on the "respondent_reason" field. +func RespondentReasonLTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldRespondentReason, v)) +} + +// RespondentReasonContains applies the Contains predicate on the "respondent_reason" field. +func RespondentReasonContains(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContains(FieldRespondentReason, v)) +} + +// RespondentReasonHasPrefix applies the HasPrefix predicate on the "respondent_reason" field. +func RespondentReasonHasPrefix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasPrefix(FieldRespondentReason, v)) +} + +// RespondentReasonHasSuffix applies the HasSuffix predicate on the "respondent_reason" field. +func RespondentReasonHasSuffix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasSuffix(FieldRespondentReason, v)) +} + +// RespondentReasonIsNil applies the IsNil predicate on the "respondent_reason" field. +func RespondentReasonIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldRespondentReason)) +} + +// RespondentReasonNotNil applies the NotNil predicate on the "respondent_reason" field. +func RespondentReasonNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldRespondentReason)) +} + +// RespondentReasonEqualFold applies the EqualFold predicate on the "respondent_reason" field. +func RespondentReasonEqualFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEqualFold(FieldRespondentReason, v)) +} + +// RespondentReasonContainsFold applies the ContainsFold predicate on the "respondent_reason" field. +func RespondentReasonContainsFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContainsFold(FieldRespondentReason, v)) +} + +// RespondentEvidenceEQ applies the EQ predicate on the "respondent_evidence" field. +func RespondentEvidenceEQ(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldRespondentEvidence, v)) +} + +// RespondentEvidenceNEQ applies the NEQ predicate on the "respondent_evidence" field. +func RespondentEvidenceNEQ(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldRespondentEvidence, v)) +} + +// RespondentEvidenceIn applies the In predicate on the "respondent_evidence" field. +func RespondentEvidenceIn(vs ...types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldRespondentEvidence, vs...)) +} + +// RespondentEvidenceNotIn applies the NotIn predicate on the "respondent_evidence" field. +func RespondentEvidenceNotIn(vs ...types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldRespondentEvidence, vs...)) +} + +// RespondentEvidenceGT applies the GT predicate on the "respondent_evidence" field. +func RespondentEvidenceGT(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldRespondentEvidence, v)) +} + +// RespondentEvidenceGTE applies the GTE predicate on the "respondent_evidence" field. +func RespondentEvidenceGTE(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldRespondentEvidence, v)) +} + +// RespondentEvidenceLT applies the LT predicate on the "respondent_evidence" field. +func RespondentEvidenceLT(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldRespondentEvidence, v)) +} + +// RespondentEvidenceLTE applies the LTE predicate on the "respondent_evidence" field. +func RespondentEvidenceLTE(v types.TextArray) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldRespondentEvidence, v)) +} + +// RespondentEvidenceIsNil applies the IsNil predicate on the "respondent_evidence" field. +func RespondentEvidenceIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldRespondentEvidence)) +} + +// RespondentEvidenceNotNil applies the NotNil predicate on the "respondent_evidence" field. +func RespondentEvidenceNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldRespondentEvidence)) +} + +// AppealReasonEQ applies the EQ predicate on the "appeal_reason" field. +func AppealReasonEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldAppealReason, v)) +} + +// AppealReasonNEQ applies the NEQ predicate on the "appeal_reason" field. +func AppealReasonNEQ(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldAppealReason, v)) +} + +// AppealReasonIn applies the In predicate on the "appeal_reason" field. +func AppealReasonIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldAppealReason, vs...)) +} + +// AppealReasonNotIn applies the NotIn predicate on the "appeal_reason" field. +func AppealReasonNotIn(vs ...string) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldAppealReason, vs...)) +} + +// AppealReasonGT applies the GT predicate on the "appeal_reason" field. +func AppealReasonGT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldAppealReason, v)) +} + +// AppealReasonGTE applies the GTE predicate on the "appeal_reason" field. +func AppealReasonGTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldAppealReason, v)) +} + +// AppealReasonLT applies the LT predicate on the "appeal_reason" field. +func AppealReasonLT(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldAppealReason, v)) +} + +// AppealReasonLTE applies the LTE predicate on the "appeal_reason" field. +func AppealReasonLTE(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldAppealReason, v)) +} + +// AppealReasonContains applies the Contains predicate on the "appeal_reason" field. +func AppealReasonContains(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContains(FieldAppealReason, v)) +} + +// AppealReasonHasPrefix applies the HasPrefix predicate on the "appeal_reason" field. +func AppealReasonHasPrefix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasPrefix(FieldAppealReason, v)) +} + +// AppealReasonHasSuffix applies the HasSuffix predicate on the "appeal_reason" field. +func AppealReasonHasSuffix(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldHasSuffix(FieldAppealReason, v)) +} + +// AppealReasonIsNil applies the IsNil predicate on the "appeal_reason" field. +func AppealReasonIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldAppealReason)) +} + +// AppealReasonNotNil applies the NotNil predicate on the "appeal_reason" field. +func AppealReasonNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldAppealReason)) +} + +// AppealReasonEqualFold applies the EqualFold predicate on the "appeal_reason" field. +func AppealReasonEqualFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldEqualFold(FieldAppealReason, v)) +} + +// AppealReasonContainsFold applies the ContainsFold predicate on the "appeal_reason" field. +func AppealReasonContainsFold(v string) predicate.Disputes { + return predicate.Disputes(sql.FieldContainsFold(FieldAppealReason, v)) +} + +// AppealedAtEQ applies the EQ predicate on the "appealed_at" field. +func AppealedAtEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldAppealedAt, v)) +} + +// AppealedAtNEQ applies the NEQ predicate on the "appealed_at" field. +func AppealedAtNEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldAppealedAt, v)) +} + +// AppealedAtIn applies the In predicate on the "appealed_at" field. +func AppealedAtIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldAppealedAt, vs...)) +} + +// AppealedAtNotIn applies the NotIn predicate on the "appealed_at" field. +func AppealedAtNotIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldAppealedAt, vs...)) +} + +// AppealedAtGT applies the GT predicate on the "appealed_at" field. +func AppealedAtGT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldAppealedAt, v)) +} + +// AppealedAtGTE applies the GTE predicate on the "appealed_at" field. +func AppealedAtGTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldAppealedAt, v)) +} + +// AppealedAtLT applies the LT predicate on the "appealed_at" field. +func AppealedAtLT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldAppealedAt, v)) +} + +// AppealedAtLTE applies the LTE predicate on the "appealed_at" field. +func AppealedAtLTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldAppealedAt, v)) +} + +// AppealedAtIsNil applies the IsNil predicate on the "appealed_at" field. +func AppealedAtIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldAppealedAt)) +} + +// AppealedAtNotNil applies the NotNil predicate on the "appealed_at" field. +func AppealedAtNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldAppealedAt)) +} + +// ResolvedByEQ applies the EQ predicate on the "resolved_by" field. +func ResolvedByEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldResolvedBy, v)) +} + +// ResolvedByNEQ applies the NEQ predicate on the "resolved_by" field. +func ResolvedByNEQ(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldResolvedBy, v)) +} + +// ResolvedByIn applies the In predicate on the "resolved_by" field. +func ResolvedByIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldResolvedBy, vs...)) +} + +// ResolvedByNotIn applies the NotIn predicate on the "resolved_by" field. +func ResolvedByNotIn(vs ...int64) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldResolvedBy, vs...)) +} + +// ResolvedByGT applies the GT predicate on the "resolved_by" field. +func ResolvedByGT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldResolvedBy, v)) +} + +// ResolvedByGTE applies the GTE predicate on the "resolved_by" field. +func ResolvedByGTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldResolvedBy, v)) +} + +// ResolvedByLT applies the LT predicate on the "resolved_by" field. +func ResolvedByLT(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldResolvedBy, v)) +} + +// ResolvedByLTE applies the LTE predicate on the "resolved_by" field. +func ResolvedByLTE(v int64) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldResolvedBy, v)) +} + +// ResolvedByIsNil applies the IsNil predicate on the "resolved_by" field. +func ResolvedByIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldResolvedBy)) +} + +// ResolvedByNotNil applies the NotNil predicate on the "resolved_by" field. +func ResolvedByNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldResolvedBy)) +} + +// ResolvedAtEQ applies the EQ predicate on the "resolved_at" field. +func ResolvedAtEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldResolvedAt, v)) +} + +// ResolvedAtNEQ applies the NEQ predicate on the "resolved_at" field. +func ResolvedAtNEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldResolvedAt, v)) +} + +// ResolvedAtIn applies the In predicate on the "resolved_at" field. +func ResolvedAtIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldResolvedAt, vs...)) +} + +// ResolvedAtNotIn applies the NotIn predicate on the "resolved_at" field. +func ResolvedAtNotIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldResolvedAt, vs...)) +} + +// ResolvedAtGT applies the GT predicate on the "resolved_at" field. +func ResolvedAtGT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldResolvedAt, v)) +} + +// ResolvedAtGTE applies the GTE predicate on the "resolved_at" field. +func ResolvedAtGTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldResolvedAt, v)) +} + +// ResolvedAtLT applies the LT predicate on the "resolved_at" field. +func ResolvedAtLT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldResolvedAt, v)) +} + +// ResolvedAtLTE applies the LTE predicate on the "resolved_at" field. +func ResolvedAtLTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldResolvedAt, v)) +} + +// ResolvedAtIsNil applies the IsNil predicate on the "resolved_at" field. +func ResolvedAtIsNil() predicate.Disputes { + return predicate.Disputes(sql.FieldIsNull(FieldResolvedAt)) +} + +// ResolvedAtNotNil applies the NotNil predicate on the "resolved_at" field. +func ResolvedAtNotNil() predicate.Disputes { + return predicate.Disputes(sql.FieldNotNull(FieldResolvedAt)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Disputes { + return predicate.Disputes(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Disputes) predicate.Disputes { + return predicate.Disputes(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Disputes) predicate.Disputes { + return predicate.Disputes(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Disputes) predicate.Disputes { + return predicate.Disputes(sql.NotPredicates(p)) +} diff --git a/app/dispute/rpc/internal/models/disputes_create.go b/app/dispute/rpc/internal/models/disputes_create.go new file mode 100644 index 0000000..a49ee31 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputes_create.go @@ -0,0 +1,489 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/pkg/types" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputesCreate is the builder for creating a Disputes entity. +type DisputesCreate struct { + config + mutation *DisputesMutation + hooks []Hook +} + +// SetOrderID sets the "order_id" field. +func (_c *DisputesCreate) SetOrderID(v int64) *DisputesCreate { + _c.mutation.SetOrderID(v) + return _c +} + +// SetInitiatorID sets the "initiator_id" field. +func (_c *DisputesCreate) SetInitiatorID(v int64) *DisputesCreate { + _c.mutation.SetInitiatorID(v) + return _c +} + +// SetInitiatorName sets the "initiator_name" field. +func (_c *DisputesCreate) SetInitiatorName(v string) *DisputesCreate { + _c.mutation.SetInitiatorName(v) + return _c +} + +// SetRespondentID sets the "respondent_id" field. +func (_c *DisputesCreate) SetRespondentID(v int64) *DisputesCreate { + _c.mutation.SetRespondentID(v) + return _c +} + +// SetReason sets the "reason" field. +func (_c *DisputesCreate) SetReason(v string) *DisputesCreate { + _c.mutation.SetReason(v) + return _c +} + +// SetEvidence sets the "evidence" field. +func (_c *DisputesCreate) SetEvidence(v types.TextArray) *DisputesCreate { + _c.mutation.SetEvidence(v) + return _c +} + +// SetNillableEvidence sets the "evidence" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableEvidence(v *types.TextArray) *DisputesCreate { + if v != nil { + _c.SetEvidence(*v) + } + return _c +} + +// SetStatus sets the "status" field. +func (_c *DisputesCreate) SetStatus(v string) *DisputesCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableStatus(v *string) *DisputesCreate { + if v != nil { + _c.SetStatus(*v) + } + return _c +} + +// SetResult sets the "result" field. +func (_c *DisputesCreate) SetResult(v string) *DisputesCreate { + _c.mutation.SetResult(v) + return _c +} + +// SetNillableResult sets the "result" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableResult(v *string) *DisputesCreate { + if v != nil { + _c.SetResult(*v) + } + return _c +} + +// SetRespondentReason sets the "respondent_reason" field. +func (_c *DisputesCreate) SetRespondentReason(v string) *DisputesCreate { + _c.mutation.SetRespondentReason(v) + return _c +} + +// SetNillableRespondentReason sets the "respondent_reason" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableRespondentReason(v *string) *DisputesCreate { + if v != nil { + _c.SetRespondentReason(*v) + } + return _c +} + +// SetRespondentEvidence sets the "respondent_evidence" field. +func (_c *DisputesCreate) SetRespondentEvidence(v types.TextArray) *DisputesCreate { + _c.mutation.SetRespondentEvidence(v) + return _c +} + +// SetNillableRespondentEvidence sets the "respondent_evidence" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableRespondentEvidence(v *types.TextArray) *DisputesCreate { + if v != nil { + _c.SetRespondentEvidence(*v) + } + return _c +} + +// SetAppealReason sets the "appeal_reason" field. +func (_c *DisputesCreate) SetAppealReason(v string) *DisputesCreate { + _c.mutation.SetAppealReason(v) + return _c +} + +// SetNillableAppealReason sets the "appeal_reason" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableAppealReason(v *string) *DisputesCreate { + if v != nil { + _c.SetAppealReason(*v) + } + return _c +} + +// SetAppealedAt sets the "appealed_at" field. +func (_c *DisputesCreate) SetAppealedAt(v time.Time) *DisputesCreate { + _c.mutation.SetAppealedAt(v) + return _c +} + +// SetNillableAppealedAt sets the "appealed_at" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableAppealedAt(v *time.Time) *DisputesCreate { + if v != nil { + _c.SetAppealedAt(*v) + } + return _c +} + +// SetResolvedBy sets the "resolved_by" field. +func (_c *DisputesCreate) SetResolvedBy(v int64) *DisputesCreate { + _c.mutation.SetResolvedBy(v) + return _c +} + +// SetNillableResolvedBy sets the "resolved_by" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableResolvedBy(v *int64) *DisputesCreate { + if v != nil { + _c.SetResolvedBy(*v) + } + return _c +} + +// SetResolvedAt sets the "resolved_at" field. +func (_c *DisputesCreate) SetResolvedAt(v time.Time) *DisputesCreate { + _c.mutation.SetResolvedAt(v) + return _c +} + +// SetNillableResolvedAt sets the "resolved_at" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableResolvedAt(v *time.Time) *DisputesCreate { + if v != nil { + _c.SetResolvedAt(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *DisputesCreate) SetCreatedAt(v time.Time) *DisputesCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableCreatedAt(v *time.Time) *DisputesCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *DisputesCreate) SetUpdatedAt(v time.Time) *DisputesCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *DisputesCreate) SetNillableUpdatedAt(v *time.Time) *DisputesCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *DisputesCreate) SetID(v int64) *DisputesCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the DisputesMutation object of the builder. +func (_c *DisputesCreate) Mutation() *DisputesMutation { + return _c.mutation +} + +// Save creates the Disputes in the database. +func (_c *DisputesCreate) Save(ctx context.Context) (*Disputes, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *DisputesCreate) SaveX(ctx context.Context) *Disputes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *DisputesCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *DisputesCreate) 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 *DisputesCreate) defaults() { + if _, ok := _c.mutation.Status(); !ok { + v := disputes.DefaultStatus + _c.mutation.SetStatus(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := disputes.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := disputes.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *DisputesCreate) check() error { + if _, ok := _c.mutation.OrderID(); !ok { + return &ValidationError{Name: "order_id", err: errors.New(`models: missing required field "Disputes.order_id"`)} + } + if _, ok := _c.mutation.InitiatorID(); !ok { + return &ValidationError{Name: "initiator_id", err: errors.New(`models: missing required field "Disputes.initiator_id"`)} + } + if _, ok := _c.mutation.InitiatorName(); !ok { + return &ValidationError{Name: "initiator_name", err: errors.New(`models: missing required field "Disputes.initiator_name"`)} + } + if v, ok := _c.mutation.InitiatorName(); ok { + if err := disputes.InitiatorNameValidator(v); err != nil { + return &ValidationError{Name: "initiator_name", err: fmt.Errorf(`models: validator failed for field "Disputes.initiator_name": %w`, err)} + } + } + if _, ok := _c.mutation.RespondentID(); !ok { + return &ValidationError{Name: "respondent_id", err: errors.New(`models: missing required field "Disputes.respondent_id"`)} + } + if _, ok := _c.mutation.Reason(); !ok { + return &ValidationError{Name: "reason", err: errors.New(`models: missing required field "Disputes.reason"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`models: missing required field "Disputes.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := disputes.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Disputes.status": %w`, err)} + } + } + if v, ok := _c.mutation.Result(); ok { + if err := disputes.ResultValidator(v); err != nil { + return &ValidationError{Name: "result", err: fmt.Errorf(`models: validator failed for field "Disputes.result": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Disputes.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Disputes.updated_at"`)} + } + return nil +} + +func (_c *DisputesCreate) sqlSave(ctx context.Context) (*Disputes, 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 *DisputesCreate) createSpec() (*Disputes, *sqlgraph.CreateSpec) { + var ( + _node = &Disputes{config: _c.config} + _spec = sqlgraph.NewCreateSpec(disputes.Table, sqlgraph.NewFieldSpec(disputes.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(disputes.FieldOrderID, field.TypeInt64, value) + _node.OrderID = value + } + if value, ok := _c.mutation.InitiatorID(); ok { + _spec.SetField(disputes.FieldInitiatorID, field.TypeInt64, value) + _node.InitiatorID = value + } + if value, ok := _c.mutation.InitiatorName(); ok { + _spec.SetField(disputes.FieldInitiatorName, field.TypeString, value) + _node.InitiatorName = value + } + if value, ok := _c.mutation.RespondentID(); ok { + _spec.SetField(disputes.FieldRespondentID, field.TypeInt64, value) + _node.RespondentID = value + } + if value, ok := _c.mutation.Reason(); ok { + _spec.SetField(disputes.FieldReason, field.TypeString, value) + _node.Reason = value + } + if value, ok := _c.mutation.Evidence(); ok { + _spec.SetField(disputes.FieldEvidence, field.TypeOther, value) + _node.Evidence = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(disputes.FieldStatus, field.TypeString, value) + _node.Status = value + } + if value, ok := _c.mutation.Result(); ok { + _spec.SetField(disputes.FieldResult, field.TypeString, value) + _node.Result = &value + } + if value, ok := _c.mutation.RespondentReason(); ok { + _spec.SetField(disputes.FieldRespondentReason, field.TypeString, value) + _node.RespondentReason = &value + } + if value, ok := _c.mutation.RespondentEvidence(); ok { + _spec.SetField(disputes.FieldRespondentEvidence, field.TypeOther, value) + _node.RespondentEvidence = value + } + if value, ok := _c.mutation.AppealReason(); ok { + _spec.SetField(disputes.FieldAppealReason, field.TypeString, value) + _node.AppealReason = &value + } + if value, ok := _c.mutation.AppealedAt(); ok { + _spec.SetField(disputes.FieldAppealedAt, field.TypeTime, value) + _node.AppealedAt = &value + } + if value, ok := _c.mutation.ResolvedBy(); ok { + _spec.SetField(disputes.FieldResolvedBy, field.TypeInt64, value) + _node.ResolvedBy = &value + } + if value, ok := _c.mutation.ResolvedAt(); ok { + _spec.SetField(disputes.FieldResolvedAt, field.TypeTime, value) + _node.ResolvedAt = &value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(disputes.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(disputes.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + return _node, _spec +} + +// DisputesCreateBulk is the builder for creating many Disputes entities in bulk. +type DisputesCreateBulk struct { + config + err error + builders []*DisputesCreate +} + +// Save creates the Disputes entities in the database. +func (_c *DisputesCreateBulk) Save(ctx context.Context) ([]*Disputes, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Disputes, 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.(*DisputesMutation) + 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 *DisputesCreateBulk) SaveX(ctx context.Context) []*Disputes { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *DisputesCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *DisputesCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/dispute/rpc/internal/models/disputes_delete.go b/app/dispute/rpc/internal/models/disputes_delete.go new file mode 100644 index 0000000..8d4459a --- /dev/null +++ b/app/dispute/rpc/internal/models/disputes_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputesDelete is the builder for deleting a Disputes entity. +type DisputesDelete struct { + config + hooks []Hook + mutation *DisputesMutation +} + +// Where appends a list predicates to the DisputesDelete builder. +func (_d *DisputesDelete) Where(ps ...predicate.Disputes) *DisputesDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *DisputesDelete) 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 *DisputesDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *DisputesDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(disputes.Table, sqlgraph.NewFieldSpec(disputes.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 +} + +// DisputesDeleteOne is the builder for deleting a single Disputes entity. +type DisputesDeleteOne struct { + _d *DisputesDelete +} + +// Where appends a list predicates to the DisputesDelete builder. +func (_d *DisputesDeleteOne) Where(ps ...predicate.Disputes) *DisputesDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *DisputesDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{disputes.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *DisputesDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/dispute/rpc/internal/models/disputes_query.go b/app/dispute/rpc/internal/models/disputes_query.go new file mode 100644 index 0000000..66e1cff --- /dev/null +++ b/app/dispute/rpc/internal/models/disputes_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputesQuery is the builder for querying Disputes entities. +type DisputesQuery struct { + config + ctx *QueryContext + order []disputes.OrderOption + inters []Interceptor + predicates []predicate.Disputes + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the DisputesQuery builder. +func (_q *DisputesQuery) Where(ps ...predicate.Disputes) *DisputesQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *DisputesQuery) Limit(limit int) *DisputesQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *DisputesQuery) Offset(offset int) *DisputesQuery { + _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 *DisputesQuery) Unique(unique bool) *DisputesQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *DisputesQuery) Order(o ...disputes.OrderOption) *DisputesQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Disputes entity from the query. +// Returns a *NotFoundError when no Disputes was found. +func (_q *DisputesQuery) First(ctx context.Context) (*Disputes, 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{disputes.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *DisputesQuery) FirstX(ctx context.Context) *Disputes { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Disputes ID from the query. +// Returns a *NotFoundError when no Disputes ID was found. +func (_q *DisputesQuery) 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{disputes.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *DisputesQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Disputes entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Disputes entity is found. +// Returns a *NotFoundError when no Disputes entities are found. +func (_q *DisputesQuery) Only(ctx context.Context) (*Disputes, 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{disputes.Label} + default: + return nil, &NotSingularError{disputes.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *DisputesQuery) OnlyX(ctx context.Context) *Disputes { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Disputes ID in the query. +// Returns a *NotSingularError when more than one Disputes ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *DisputesQuery) 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{disputes.Label} + default: + err = &NotSingularError{disputes.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *DisputesQuery) 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 DisputesSlice. +func (_q *DisputesQuery) All(ctx context.Context) ([]*Disputes, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Disputes, *DisputesQuery]() + return withInterceptors[[]*Disputes](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *DisputesQuery) AllX(ctx context.Context) []*Disputes { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Disputes IDs. +func (_q *DisputesQuery) 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(disputes.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *DisputesQuery) 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 *DisputesQuery) 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[*DisputesQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *DisputesQuery) 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 *DisputesQuery) 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 *DisputesQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the DisputesQuery 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 *DisputesQuery) Clone() *DisputesQuery { + if _q == nil { + return nil + } + return &DisputesQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]disputes.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Disputes{}, _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.Disputes.Query(). +// GroupBy(disputes.FieldOrderID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *DisputesQuery) GroupBy(field string, fields ...string) *DisputesGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &DisputesGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = disputes.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.Disputes.Query(). +// Select(disputes.FieldOrderID). +// Scan(ctx, &v) +func (_q *DisputesQuery) Select(fields ...string) *DisputesSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &DisputesSelect{DisputesQuery: _q} + sbuild.label = disputes.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a DisputesSelect configured with the given aggregations. +func (_q *DisputesQuery) Aggregate(fns ...AggregateFunc) *DisputesSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *DisputesQuery) 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 !disputes.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 *DisputesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Disputes, error) { + var ( + nodes = []*Disputes{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Disputes).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Disputes{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 *DisputesQuery) 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 *DisputesQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(disputes.Table, disputes.Columns, sqlgraph.NewFieldSpec(disputes.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, disputes.FieldID) + for i := range fields { + if fields[i] != disputes.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 *DisputesQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(disputes.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = disputes.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 +} + +// DisputesGroupBy is the group-by builder for Disputes entities. +type DisputesGroupBy struct { + selector + build *DisputesQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *DisputesGroupBy) Aggregate(fns ...AggregateFunc) *DisputesGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *DisputesGroupBy) 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[*DisputesQuery, *DisputesGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *DisputesGroupBy) sqlScan(ctx context.Context, root *DisputesQuery, 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) +} + +// DisputesSelect is the builder for selecting fields of Disputes entities. +type DisputesSelect struct { + *DisputesQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *DisputesSelect) Aggregate(fns ...AggregateFunc) *DisputesSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *DisputesSelect) 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[*DisputesQuery, *DisputesSelect](ctx, _s.DisputesQuery, _s, _s.inters, v) +} + +func (_s *DisputesSelect) sqlScan(ctx context.Context, root *DisputesQuery, 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/dispute/rpc/internal/models/disputes_update.go b/app/dispute/rpc/internal/models/disputes_update.go new file mode 100644 index 0000000..6fce6ca --- /dev/null +++ b/app/dispute/rpc/internal/models/disputes_update.go @@ -0,0 +1,959 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/models/predicate" + "juwan-backend/pkg/types" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputesUpdate is the builder for updating Disputes entities. +type DisputesUpdate struct { + config + hooks []Hook + mutation *DisputesMutation +} + +// Where appends a list predicates to the DisputesUpdate builder. +func (_u *DisputesUpdate) Where(ps ...predicate.Disputes) *DisputesUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetOrderID sets the "order_id" field. +func (_u *DisputesUpdate) SetOrderID(v int64) *DisputesUpdate { + _u.mutation.ResetOrderID() + _u.mutation.SetOrderID(v) + return _u +} + +// SetNillableOrderID sets the "order_id" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableOrderID(v *int64) *DisputesUpdate { + if v != nil { + _u.SetOrderID(*v) + } + return _u +} + +// AddOrderID adds value to the "order_id" field. +func (_u *DisputesUpdate) AddOrderID(v int64) *DisputesUpdate { + _u.mutation.AddOrderID(v) + return _u +} + +// SetInitiatorID sets the "initiator_id" field. +func (_u *DisputesUpdate) SetInitiatorID(v int64) *DisputesUpdate { + _u.mutation.ResetInitiatorID() + _u.mutation.SetInitiatorID(v) + return _u +} + +// SetNillableInitiatorID sets the "initiator_id" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableInitiatorID(v *int64) *DisputesUpdate { + if v != nil { + _u.SetInitiatorID(*v) + } + return _u +} + +// AddInitiatorID adds value to the "initiator_id" field. +func (_u *DisputesUpdate) AddInitiatorID(v int64) *DisputesUpdate { + _u.mutation.AddInitiatorID(v) + return _u +} + +// SetInitiatorName sets the "initiator_name" field. +func (_u *DisputesUpdate) SetInitiatorName(v string) *DisputesUpdate { + _u.mutation.SetInitiatorName(v) + return _u +} + +// SetNillableInitiatorName sets the "initiator_name" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableInitiatorName(v *string) *DisputesUpdate { + if v != nil { + _u.SetInitiatorName(*v) + } + return _u +} + +// SetRespondentID sets the "respondent_id" field. +func (_u *DisputesUpdate) SetRespondentID(v int64) *DisputesUpdate { + _u.mutation.ResetRespondentID() + _u.mutation.SetRespondentID(v) + return _u +} + +// SetNillableRespondentID sets the "respondent_id" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableRespondentID(v *int64) *DisputesUpdate { + if v != nil { + _u.SetRespondentID(*v) + } + return _u +} + +// AddRespondentID adds value to the "respondent_id" field. +func (_u *DisputesUpdate) AddRespondentID(v int64) *DisputesUpdate { + _u.mutation.AddRespondentID(v) + return _u +} + +// SetReason sets the "reason" field. +func (_u *DisputesUpdate) SetReason(v string) *DisputesUpdate { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableReason(v *string) *DisputesUpdate { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetEvidence sets the "evidence" field. +func (_u *DisputesUpdate) SetEvidence(v types.TextArray) *DisputesUpdate { + _u.mutation.SetEvidence(v) + return _u +} + +// SetNillableEvidence sets the "evidence" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableEvidence(v *types.TextArray) *DisputesUpdate { + if v != nil { + _u.SetEvidence(*v) + } + return _u +} + +// ClearEvidence clears the value of the "evidence" field. +func (_u *DisputesUpdate) ClearEvidence() *DisputesUpdate { + _u.mutation.ClearEvidence() + return _u +} + +// SetStatus sets the "status" field. +func (_u *DisputesUpdate) SetStatus(v string) *DisputesUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableStatus(v *string) *DisputesUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetResult sets the "result" field. +func (_u *DisputesUpdate) SetResult(v string) *DisputesUpdate { + _u.mutation.SetResult(v) + return _u +} + +// SetNillableResult sets the "result" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableResult(v *string) *DisputesUpdate { + if v != nil { + _u.SetResult(*v) + } + return _u +} + +// ClearResult clears the value of the "result" field. +func (_u *DisputesUpdate) ClearResult() *DisputesUpdate { + _u.mutation.ClearResult() + return _u +} + +// SetRespondentReason sets the "respondent_reason" field. +func (_u *DisputesUpdate) SetRespondentReason(v string) *DisputesUpdate { + _u.mutation.SetRespondentReason(v) + return _u +} + +// SetNillableRespondentReason sets the "respondent_reason" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableRespondentReason(v *string) *DisputesUpdate { + if v != nil { + _u.SetRespondentReason(*v) + } + return _u +} + +// ClearRespondentReason clears the value of the "respondent_reason" field. +func (_u *DisputesUpdate) ClearRespondentReason() *DisputesUpdate { + _u.mutation.ClearRespondentReason() + return _u +} + +// SetRespondentEvidence sets the "respondent_evidence" field. +func (_u *DisputesUpdate) SetRespondentEvidence(v types.TextArray) *DisputesUpdate { + _u.mutation.SetRespondentEvidence(v) + return _u +} + +// SetNillableRespondentEvidence sets the "respondent_evidence" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableRespondentEvidence(v *types.TextArray) *DisputesUpdate { + if v != nil { + _u.SetRespondentEvidence(*v) + } + return _u +} + +// ClearRespondentEvidence clears the value of the "respondent_evidence" field. +func (_u *DisputesUpdate) ClearRespondentEvidence() *DisputesUpdate { + _u.mutation.ClearRespondentEvidence() + return _u +} + +// SetAppealReason sets the "appeal_reason" field. +func (_u *DisputesUpdate) SetAppealReason(v string) *DisputesUpdate { + _u.mutation.SetAppealReason(v) + return _u +} + +// SetNillableAppealReason sets the "appeal_reason" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableAppealReason(v *string) *DisputesUpdate { + if v != nil { + _u.SetAppealReason(*v) + } + return _u +} + +// ClearAppealReason clears the value of the "appeal_reason" field. +func (_u *DisputesUpdate) ClearAppealReason() *DisputesUpdate { + _u.mutation.ClearAppealReason() + return _u +} + +// SetAppealedAt sets the "appealed_at" field. +func (_u *DisputesUpdate) SetAppealedAt(v time.Time) *DisputesUpdate { + _u.mutation.SetAppealedAt(v) + return _u +} + +// SetNillableAppealedAt sets the "appealed_at" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableAppealedAt(v *time.Time) *DisputesUpdate { + if v != nil { + _u.SetAppealedAt(*v) + } + return _u +} + +// ClearAppealedAt clears the value of the "appealed_at" field. +func (_u *DisputesUpdate) ClearAppealedAt() *DisputesUpdate { + _u.mutation.ClearAppealedAt() + return _u +} + +// SetResolvedBy sets the "resolved_by" field. +func (_u *DisputesUpdate) SetResolvedBy(v int64) *DisputesUpdate { + _u.mutation.ResetResolvedBy() + _u.mutation.SetResolvedBy(v) + return _u +} + +// SetNillableResolvedBy sets the "resolved_by" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableResolvedBy(v *int64) *DisputesUpdate { + if v != nil { + _u.SetResolvedBy(*v) + } + return _u +} + +// AddResolvedBy adds value to the "resolved_by" field. +func (_u *DisputesUpdate) AddResolvedBy(v int64) *DisputesUpdate { + _u.mutation.AddResolvedBy(v) + return _u +} + +// ClearResolvedBy clears the value of the "resolved_by" field. +func (_u *DisputesUpdate) ClearResolvedBy() *DisputesUpdate { + _u.mutation.ClearResolvedBy() + return _u +} + +// SetResolvedAt sets the "resolved_at" field. +func (_u *DisputesUpdate) SetResolvedAt(v time.Time) *DisputesUpdate { + _u.mutation.SetResolvedAt(v) + return _u +} + +// SetNillableResolvedAt sets the "resolved_at" field if the given value is not nil. +func (_u *DisputesUpdate) SetNillableResolvedAt(v *time.Time) *DisputesUpdate { + if v != nil { + _u.SetResolvedAt(*v) + } + return _u +} + +// ClearResolvedAt clears the value of the "resolved_at" field. +func (_u *DisputesUpdate) ClearResolvedAt() *DisputesUpdate { + _u.mutation.ClearResolvedAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *DisputesUpdate) SetUpdatedAt(v time.Time) *DisputesUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the DisputesMutation object of the builder. +func (_u *DisputesUpdate) Mutation() *DisputesMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *DisputesUpdate) 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 *DisputesUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *DisputesUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *DisputesUpdate) 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 *DisputesUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := disputes.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *DisputesUpdate) check() error { + if v, ok := _u.mutation.InitiatorName(); ok { + if err := disputes.InitiatorNameValidator(v); err != nil { + return &ValidationError{Name: "initiator_name", err: fmt.Errorf(`models: validator failed for field "Disputes.initiator_name": %w`, err)} + } + } + if v, ok := _u.mutation.Status(); ok { + if err := disputes.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Disputes.status": %w`, err)} + } + } + if v, ok := _u.mutation.Result(); ok { + if err := disputes.ResultValidator(v); err != nil { + return &ValidationError{Name: "result", err: fmt.Errorf(`models: validator failed for field "Disputes.result": %w`, err)} + } + } + return nil +} + +func (_u *DisputesUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(disputes.Table, disputes.Columns, sqlgraph.NewFieldSpec(disputes.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(disputes.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedOrderID(); ok { + _spec.AddField(disputes.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.InitiatorID(); ok { + _spec.SetField(disputes.FieldInitiatorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedInitiatorID(); ok { + _spec.AddField(disputes.FieldInitiatorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.InitiatorName(); ok { + _spec.SetField(disputes.FieldInitiatorName, field.TypeString, value) + } + if value, ok := _u.mutation.RespondentID(); ok { + _spec.SetField(disputes.FieldRespondentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRespondentID(); ok { + _spec.AddField(disputes.FieldRespondentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(disputes.FieldReason, field.TypeString, value) + } + if value, ok := _u.mutation.Evidence(); ok { + _spec.SetField(disputes.FieldEvidence, field.TypeOther, value) + } + if _u.mutation.EvidenceCleared() { + _spec.ClearField(disputes.FieldEvidence, field.TypeOther) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(disputes.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Result(); ok { + _spec.SetField(disputes.FieldResult, field.TypeString, value) + } + if _u.mutation.ResultCleared() { + _spec.ClearField(disputes.FieldResult, field.TypeString) + } + if value, ok := _u.mutation.RespondentReason(); ok { + _spec.SetField(disputes.FieldRespondentReason, field.TypeString, value) + } + if _u.mutation.RespondentReasonCleared() { + _spec.ClearField(disputes.FieldRespondentReason, field.TypeString) + } + if value, ok := _u.mutation.RespondentEvidence(); ok { + _spec.SetField(disputes.FieldRespondentEvidence, field.TypeOther, value) + } + if _u.mutation.RespondentEvidenceCleared() { + _spec.ClearField(disputes.FieldRespondentEvidence, field.TypeOther) + } + if value, ok := _u.mutation.AppealReason(); ok { + _spec.SetField(disputes.FieldAppealReason, field.TypeString, value) + } + if _u.mutation.AppealReasonCleared() { + _spec.ClearField(disputes.FieldAppealReason, field.TypeString) + } + if value, ok := _u.mutation.AppealedAt(); ok { + _spec.SetField(disputes.FieldAppealedAt, field.TypeTime, value) + } + if _u.mutation.AppealedAtCleared() { + _spec.ClearField(disputes.FieldAppealedAt, field.TypeTime) + } + if value, ok := _u.mutation.ResolvedBy(); ok { + _spec.SetField(disputes.FieldResolvedBy, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedResolvedBy(); ok { + _spec.AddField(disputes.FieldResolvedBy, field.TypeInt64, value) + } + if _u.mutation.ResolvedByCleared() { + _spec.ClearField(disputes.FieldResolvedBy, field.TypeInt64) + } + if value, ok := _u.mutation.ResolvedAt(); ok { + _spec.SetField(disputes.FieldResolvedAt, field.TypeTime, value) + } + if _u.mutation.ResolvedAtCleared() { + _spec.ClearField(disputes.FieldResolvedAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(disputes.FieldUpdatedAt, field.TypeTime, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{disputes.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// DisputesUpdateOne is the builder for updating a single Disputes entity. +type DisputesUpdateOne struct { + config + fields []string + hooks []Hook + mutation *DisputesMutation +} + +// SetOrderID sets the "order_id" field. +func (_u *DisputesUpdateOne) SetOrderID(v int64) *DisputesUpdateOne { + _u.mutation.ResetOrderID() + _u.mutation.SetOrderID(v) + return _u +} + +// SetNillableOrderID sets the "order_id" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableOrderID(v *int64) *DisputesUpdateOne { + if v != nil { + _u.SetOrderID(*v) + } + return _u +} + +// AddOrderID adds value to the "order_id" field. +func (_u *DisputesUpdateOne) AddOrderID(v int64) *DisputesUpdateOne { + _u.mutation.AddOrderID(v) + return _u +} + +// SetInitiatorID sets the "initiator_id" field. +func (_u *DisputesUpdateOne) SetInitiatorID(v int64) *DisputesUpdateOne { + _u.mutation.ResetInitiatorID() + _u.mutation.SetInitiatorID(v) + return _u +} + +// SetNillableInitiatorID sets the "initiator_id" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableInitiatorID(v *int64) *DisputesUpdateOne { + if v != nil { + _u.SetInitiatorID(*v) + } + return _u +} + +// AddInitiatorID adds value to the "initiator_id" field. +func (_u *DisputesUpdateOne) AddInitiatorID(v int64) *DisputesUpdateOne { + _u.mutation.AddInitiatorID(v) + return _u +} + +// SetInitiatorName sets the "initiator_name" field. +func (_u *DisputesUpdateOne) SetInitiatorName(v string) *DisputesUpdateOne { + _u.mutation.SetInitiatorName(v) + return _u +} + +// SetNillableInitiatorName sets the "initiator_name" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableInitiatorName(v *string) *DisputesUpdateOne { + if v != nil { + _u.SetInitiatorName(*v) + } + return _u +} + +// SetRespondentID sets the "respondent_id" field. +func (_u *DisputesUpdateOne) SetRespondentID(v int64) *DisputesUpdateOne { + _u.mutation.ResetRespondentID() + _u.mutation.SetRespondentID(v) + return _u +} + +// SetNillableRespondentID sets the "respondent_id" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableRespondentID(v *int64) *DisputesUpdateOne { + if v != nil { + _u.SetRespondentID(*v) + } + return _u +} + +// AddRespondentID adds value to the "respondent_id" field. +func (_u *DisputesUpdateOne) AddRespondentID(v int64) *DisputesUpdateOne { + _u.mutation.AddRespondentID(v) + return _u +} + +// SetReason sets the "reason" field. +func (_u *DisputesUpdateOne) SetReason(v string) *DisputesUpdateOne { + _u.mutation.SetReason(v) + return _u +} + +// SetNillableReason sets the "reason" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableReason(v *string) *DisputesUpdateOne { + if v != nil { + _u.SetReason(*v) + } + return _u +} + +// SetEvidence sets the "evidence" field. +func (_u *DisputesUpdateOne) SetEvidence(v types.TextArray) *DisputesUpdateOne { + _u.mutation.SetEvidence(v) + return _u +} + +// SetNillableEvidence sets the "evidence" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableEvidence(v *types.TextArray) *DisputesUpdateOne { + if v != nil { + _u.SetEvidence(*v) + } + return _u +} + +// ClearEvidence clears the value of the "evidence" field. +func (_u *DisputesUpdateOne) ClearEvidence() *DisputesUpdateOne { + _u.mutation.ClearEvidence() + return _u +} + +// SetStatus sets the "status" field. +func (_u *DisputesUpdateOne) SetStatus(v string) *DisputesUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableStatus(v *string) *DisputesUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetResult sets the "result" field. +func (_u *DisputesUpdateOne) SetResult(v string) *DisputesUpdateOne { + _u.mutation.SetResult(v) + return _u +} + +// SetNillableResult sets the "result" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableResult(v *string) *DisputesUpdateOne { + if v != nil { + _u.SetResult(*v) + } + return _u +} + +// ClearResult clears the value of the "result" field. +func (_u *DisputesUpdateOne) ClearResult() *DisputesUpdateOne { + _u.mutation.ClearResult() + return _u +} + +// SetRespondentReason sets the "respondent_reason" field. +func (_u *DisputesUpdateOne) SetRespondentReason(v string) *DisputesUpdateOne { + _u.mutation.SetRespondentReason(v) + return _u +} + +// SetNillableRespondentReason sets the "respondent_reason" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableRespondentReason(v *string) *DisputesUpdateOne { + if v != nil { + _u.SetRespondentReason(*v) + } + return _u +} + +// ClearRespondentReason clears the value of the "respondent_reason" field. +func (_u *DisputesUpdateOne) ClearRespondentReason() *DisputesUpdateOne { + _u.mutation.ClearRespondentReason() + return _u +} + +// SetRespondentEvidence sets the "respondent_evidence" field. +func (_u *DisputesUpdateOne) SetRespondentEvidence(v types.TextArray) *DisputesUpdateOne { + _u.mutation.SetRespondentEvidence(v) + return _u +} + +// SetNillableRespondentEvidence sets the "respondent_evidence" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableRespondentEvidence(v *types.TextArray) *DisputesUpdateOne { + if v != nil { + _u.SetRespondentEvidence(*v) + } + return _u +} + +// ClearRespondentEvidence clears the value of the "respondent_evidence" field. +func (_u *DisputesUpdateOne) ClearRespondentEvidence() *DisputesUpdateOne { + _u.mutation.ClearRespondentEvidence() + return _u +} + +// SetAppealReason sets the "appeal_reason" field. +func (_u *DisputesUpdateOne) SetAppealReason(v string) *DisputesUpdateOne { + _u.mutation.SetAppealReason(v) + return _u +} + +// SetNillableAppealReason sets the "appeal_reason" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableAppealReason(v *string) *DisputesUpdateOne { + if v != nil { + _u.SetAppealReason(*v) + } + return _u +} + +// ClearAppealReason clears the value of the "appeal_reason" field. +func (_u *DisputesUpdateOne) ClearAppealReason() *DisputesUpdateOne { + _u.mutation.ClearAppealReason() + return _u +} + +// SetAppealedAt sets the "appealed_at" field. +func (_u *DisputesUpdateOne) SetAppealedAt(v time.Time) *DisputesUpdateOne { + _u.mutation.SetAppealedAt(v) + return _u +} + +// SetNillableAppealedAt sets the "appealed_at" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableAppealedAt(v *time.Time) *DisputesUpdateOne { + if v != nil { + _u.SetAppealedAt(*v) + } + return _u +} + +// ClearAppealedAt clears the value of the "appealed_at" field. +func (_u *DisputesUpdateOne) ClearAppealedAt() *DisputesUpdateOne { + _u.mutation.ClearAppealedAt() + return _u +} + +// SetResolvedBy sets the "resolved_by" field. +func (_u *DisputesUpdateOne) SetResolvedBy(v int64) *DisputesUpdateOne { + _u.mutation.ResetResolvedBy() + _u.mutation.SetResolvedBy(v) + return _u +} + +// SetNillableResolvedBy sets the "resolved_by" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableResolvedBy(v *int64) *DisputesUpdateOne { + if v != nil { + _u.SetResolvedBy(*v) + } + return _u +} + +// AddResolvedBy adds value to the "resolved_by" field. +func (_u *DisputesUpdateOne) AddResolvedBy(v int64) *DisputesUpdateOne { + _u.mutation.AddResolvedBy(v) + return _u +} + +// ClearResolvedBy clears the value of the "resolved_by" field. +func (_u *DisputesUpdateOne) ClearResolvedBy() *DisputesUpdateOne { + _u.mutation.ClearResolvedBy() + return _u +} + +// SetResolvedAt sets the "resolved_at" field. +func (_u *DisputesUpdateOne) SetResolvedAt(v time.Time) *DisputesUpdateOne { + _u.mutation.SetResolvedAt(v) + return _u +} + +// SetNillableResolvedAt sets the "resolved_at" field if the given value is not nil. +func (_u *DisputesUpdateOne) SetNillableResolvedAt(v *time.Time) *DisputesUpdateOne { + if v != nil { + _u.SetResolvedAt(*v) + } + return _u +} + +// ClearResolvedAt clears the value of the "resolved_at" field. +func (_u *DisputesUpdateOne) ClearResolvedAt() *DisputesUpdateOne { + _u.mutation.ClearResolvedAt() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *DisputesUpdateOne) SetUpdatedAt(v time.Time) *DisputesUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the DisputesMutation object of the builder. +func (_u *DisputesUpdateOne) Mutation() *DisputesMutation { + return _u.mutation +} + +// Where appends a list predicates to the DisputesUpdate builder. +func (_u *DisputesUpdateOne) Where(ps ...predicate.Disputes) *DisputesUpdateOne { + _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 *DisputesUpdateOne) Select(field string, fields ...string) *DisputesUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Disputes entity. +func (_u *DisputesUpdateOne) Save(ctx context.Context) (*Disputes, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *DisputesUpdateOne) SaveX(ctx context.Context) *Disputes { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *DisputesUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *DisputesUpdateOne) 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 *DisputesUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := disputes.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *DisputesUpdateOne) check() error { + if v, ok := _u.mutation.InitiatorName(); ok { + if err := disputes.InitiatorNameValidator(v); err != nil { + return &ValidationError{Name: "initiator_name", err: fmt.Errorf(`models: validator failed for field "Disputes.initiator_name": %w`, err)} + } + } + if v, ok := _u.mutation.Status(); ok { + if err := disputes.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`models: validator failed for field "Disputes.status": %w`, err)} + } + } + if v, ok := _u.mutation.Result(); ok { + if err := disputes.ResultValidator(v); err != nil { + return &ValidationError{Name: "result", err: fmt.Errorf(`models: validator failed for field "Disputes.result": %w`, err)} + } + } + return nil +} + +func (_u *DisputesUpdateOne) sqlSave(ctx context.Context) (_node *Disputes, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(disputes.Table, disputes.Columns, sqlgraph.NewFieldSpec(disputes.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Disputes.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, disputes.FieldID) + for _, f := range fields { + if !disputes.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != disputes.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(disputes.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedOrderID(); ok { + _spec.AddField(disputes.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.InitiatorID(); ok { + _spec.SetField(disputes.FieldInitiatorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedInitiatorID(); ok { + _spec.AddField(disputes.FieldInitiatorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.InitiatorName(); ok { + _spec.SetField(disputes.FieldInitiatorName, field.TypeString, value) + } + if value, ok := _u.mutation.RespondentID(); ok { + _spec.SetField(disputes.FieldRespondentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRespondentID(); ok { + _spec.AddField(disputes.FieldRespondentID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Reason(); ok { + _spec.SetField(disputes.FieldReason, field.TypeString, value) + } + if value, ok := _u.mutation.Evidence(); ok { + _spec.SetField(disputes.FieldEvidence, field.TypeOther, value) + } + if _u.mutation.EvidenceCleared() { + _spec.ClearField(disputes.FieldEvidence, field.TypeOther) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(disputes.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Result(); ok { + _spec.SetField(disputes.FieldResult, field.TypeString, value) + } + if _u.mutation.ResultCleared() { + _spec.ClearField(disputes.FieldResult, field.TypeString) + } + if value, ok := _u.mutation.RespondentReason(); ok { + _spec.SetField(disputes.FieldRespondentReason, field.TypeString, value) + } + if _u.mutation.RespondentReasonCleared() { + _spec.ClearField(disputes.FieldRespondentReason, field.TypeString) + } + if value, ok := _u.mutation.RespondentEvidence(); ok { + _spec.SetField(disputes.FieldRespondentEvidence, field.TypeOther, value) + } + if _u.mutation.RespondentEvidenceCleared() { + _spec.ClearField(disputes.FieldRespondentEvidence, field.TypeOther) + } + if value, ok := _u.mutation.AppealReason(); ok { + _spec.SetField(disputes.FieldAppealReason, field.TypeString, value) + } + if _u.mutation.AppealReasonCleared() { + _spec.ClearField(disputes.FieldAppealReason, field.TypeString) + } + if value, ok := _u.mutation.AppealedAt(); ok { + _spec.SetField(disputes.FieldAppealedAt, field.TypeTime, value) + } + if _u.mutation.AppealedAtCleared() { + _spec.ClearField(disputes.FieldAppealedAt, field.TypeTime) + } + if value, ok := _u.mutation.ResolvedBy(); ok { + _spec.SetField(disputes.FieldResolvedBy, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedResolvedBy(); ok { + _spec.AddField(disputes.FieldResolvedBy, field.TypeInt64, value) + } + if _u.mutation.ResolvedByCleared() { + _spec.ClearField(disputes.FieldResolvedBy, field.TypeInt64) + } + if value, ok := _u.mutation.ResolvedAt(); ok { + _spec.SetField(disputes.FieldResolvedAt, field.TypeTime, value) + } + if _u.mutation.ResolvedAtCleared() { + _spec.ClearField(disputes.FieldResolvedAt, field.TypeTime) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(disputes.FieldUpdatedAt, field.TypeTime, value) + } + _node = &Disputes{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{disputes.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/dispute/rpc/internal/models/disputetimeline.go b/app/dispute/rpc/internal/models/disputetimeline.go new file mode 100644 index 0000000..17ec922 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputetimeline.go @@ -0,0 +1,166 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "encoding/json" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// DisputeTimeline is the model entity for the DisputeTimeline schema. +type DisputeTimeline struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // DisputeID holds the value of the "dispute_id" field. + DisputeID int64 `json:"dispute_id,omitempty"` + // EventType holds the value of the "event_type" field. + EventType string `json:"event_type,omitempty"` + // ActorID holds the value of the "actor_id" field. + ActorID int64 `json:"actor_id,omitempty"` + // ActorName holds the value of the "actor_name" field. + ActorName string `json:"actor_name,omitempty"` + // Details holds the value of the "details" field. + Details map[string]interface{} `json:"details,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 (*DisputeTimeline) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case disputetimeline.FieldDetails: + values[i] = new([]byte) + case disputetimeline.FieldID, disputetimeline.FieldDisputeID, disputetimeline.FieldActorID: + values[i] = new(sql.NullInt64) + case disputetimeline.FieldEventType, disputetimeline.FieldActorName: + values[i] = new(sql.NullString) + case disputetimeline.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 DisputeTimeline fields. +func (_m *DisputeTimeline) 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 disputetimeline.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 disputetimeline.FieldDisputeID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field dispute_id", values[i]) + } else if value.Valid { + _m.DisputeID = value.Int64 + } + case disputetimeline.FieldEventType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field event_type", values[i]) + } else if value.Valid { + _m.EventType = value.String + } + case disputetimeline.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 disputetimeline.FieldActorName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field actor_name", values[i]) + } else if value.Valid { + _m.ActorName = value.String + } + case disputetimeline.FieldDetails: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field details", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Details); err != nil { + return fmt.Errorf("unmarshal field details: %w", err) + } + } + case disputetimeline.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 DisputeTimeline. +// This includes values selected through modifiers, order, etc. +func (_m *DisputeTimeline) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this DisputeTimeline. +// Note that you need to call DisputeTimeline.Unwrap() before calling this method if this DisputeTimeline +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *DisputeTimeline) Update() *DisputeTimelineUpdateOne { + return NewDisputeTimelineClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the DisputeTimeline 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 *DisputeTimeline) Unwrap() *DisputeTimeline { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: DisputeTimeline is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *DisputeTimeline) String() string { + var builder strings.Builder + builder.WriteString("DisputeTimeline(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("dispute_id=") + builder.WriteString(fmt.Sprintf("%v", _m.DisputeID)) + builder.WriteString(", ") + builder.WriteString("event_type=") + builder.WriteString(_m.EventType) + builder.WriteString(", ") + builder.WriteString("actor_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ActorID)) + builder.WriteString(", ") + builder.WriteString("actor_name=") + builder.WriteString(_m.ActorName) + builder.WriteString(", ") + builder.WriteString("details=") + builder.WriteString(fmt.Sprintf("%v", _m.Details)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// DisputeTimelines is a parsable slice of DisputeTimeline. +type DisputeTimelines []*DisputeTimeline diff --git a/app/dispute/rpc/internal/models/disputetimeline/disputetimeline.go b/app/dispute/rpc/internal/models/disputetimeline/disputetimeline.go new file mode 100644 index 0000000..f2db391 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputetimeline/disputetimeline.go @@ -0,0 +1,93 @@ +// Code generated by ent, DO NOT EDIT. + +package disputetimeline + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the disputetimeline type in the database. + Label = "dispute_timeline" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldDisputeID holds the string denoting the dispute_id field in the database. + FieldDisputeID = "dispute_id" + // FieldEventType holds the string denoting the event_type field in the database. + FieldEventType = "event_type" + // FieldActorID holds the string denoting the actor_id field in the database. + FieldActorID = "actor_id" + // FieldActorName holds the string denoting the actor_name field in the database. + FieldActorName = "actor_name" + // FieldDetails holds the string denoting the details field in the database. + FieldDetails = "details" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // Table holds the table name of the disputetimeline in the database. + Table = "dispute_timeline" +) + +// Columns holds all SQL columns for disputetimeline fields. +var Columns = []string{ + FieldID, + FieldDisputeID, + FieldEventType, + FieldActorID, + FieldActorName, + FieldDetails, + 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 ( + // EventTypeValidator is a validator for the "event_type" field. It is called by the builders before save. + EventTypeValidator func(string) error + // ActorNameValidator is a validator for the "actor_name" field. It is called by the builders before save. + ActorNameValidator 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 DisputeTimeline 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() +} + +// ByDisputeID orders the results by the dispute_id field. +func ByDisputeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDisputeID, opts...).ToFunc() +} + +// ByEventType orders the results by the event_type field. +func ByEventType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEventType, opts...).ToFunc() +} + +// ByActorID orders the results by the actor_id field. +func ByActorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActorID, opts...).ToFunc() +} + +// ByActorName orders the results by the actor_name field. +func ByActorName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldActorName, 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/dispute/rpc/internal/models/disputetimeline/where.go b/app/dispute/rpc/internal/models/disputetimeline/where.go new file mode 100644 index 0000000..6d1a99a --- /dev/null +++ b/app/dispute/rpc/internal/models/disputetimeline/where.go @@ -0,0 +1,375 @@ +// Code generated by ent, DO NOT EDIT. + +package disputetimeline + +import ( + "juwan-backend/app/dispute/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLTE(FieldID, id)) +} + +// DisputeID applies equality check predicate on the "dispute_id" field. It's identical to DisputeIDEQ. +func DisputeID(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldDisputeID, v)) +} + +// EventType applies equality check predicate on the "event_type" field. It's identical to EventTypeEQ. +func EventType(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldEventType, v)) +} + +// ActorID applies equality check predicate on the "actor_id" field. It's identical to ActorIDEQ. +func ActorID(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldActorID, v)) +} + +// ActorName applies equality check predicate on the "actor_name" field. It's identical to ActorNameEQ. +func ActorName(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldActorName, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldCreatedAt, v)) +} + +// DisputeIDEQ applies the EQ predicate on the "dispute_id" field. +func DisputeIDEQ(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldDisputeID, v)) +} + +// DisputeIDNEQ applies the NEQ predicate on the "dispute_id" field. +func DisputeIDNEQ(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNEQ(FieldDisputeID, v)) +} + +// DisputeIDIn applies the In predicate on the "dispute_id" field. +func DisputeIDIn(vs ...int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIn(FieldDisputeID, vs...)) +} + +// DisputeIDNotIn applies the NotIn predicate on the "dispute_id" field. +func DisputeIDNotIn(vs ...int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotIn(FieldDisputeID, vs...)) +} + +// DisputeIDGT applies the GT predicate on the "dispute_id" field. +func DisputeIDGT(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGT(FieldDisputeID, v)) +} + +// DisputeIDGTE applies the GTE predicate on the "dispute_id" field. +func DisputeIDGTE(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGTE(FieldDisputeID, v)) +} + +// DisputeIDLT applies the LT predicate on the "dispute_id" field. +func DisputeIDLT(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLT(FieldDisputeID, v)) +} + +// DisputeIDLTE applies the LTE predicate on the "dispute_id" field. +func DisputeIDLTE(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLTE(FieldDisputeID, v)) +} + +// EventTypeEQ applies the EQ predicate on the "event_type" field. +func EventTypeEQ(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldEventType, v)) +} + +// EventTypeNEQ applies the NEQ predicate on the "event_type" field. +func EventTypeNEQ(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNEQ(FieldEventType, v)) +} + +// EventTypeIn applies the In predicate on the "event_type" field. +func EventTypeIn(vs ...string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIn(FieldEventType, vs...)) +} + +// EventTypeNotIn applies the NotIn predicate on the "event_type" field. +func EventTypeNotIn(vs ...string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotIn(FieldEventType, vs...)) +} + +// EventTypeGT applies the GT predicate on the "event_type" field. +func EventTypeGT(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGT(FieldEventType, v)) +} + +// EventTypeGTE applies the GTE predicate on the "event_type" field. +func EventTypeGTE(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGTE(FieldEventType, v)) +} + +// EventTypeLT applies the LT predicate on the "event_type" field. +func EventTypeLT(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLT(FieldEventType, v)) +} + +// EventTypeLTE applies the LTE predicate on the "event_type" field. +func EventTypeLTE(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLTE(FieldEventType, v)) +} + +// EventTypeContains applies the Contains predicate on the "event_type" field. +func EventTypeContains(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldContains(FieldEventType, v)) +} + +// EventTypeHasPrefix applies the HasPrefix predicate on the "event_type" field. +func EventTypeHasPrefix(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldHasPrefix(FieldEventType, v)) +} + +// EventTypeHasSuffix applies the HasSuffix predicate on the "event_type" field. +func EventTypeHasSuffix(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldHasSuffix(FieldEventType, v)) +} + +// EventTypeEqualFold applies the EqualFold predicate on the "event_type" field. +func EventTypeEqualFold(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEqualFold(FieldEventType, v)) +} + +// EventTypeContainsFold applies the ContainsFold predicate on the "event_type" field. +func EventTypeContainsFold(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldContainsFold(FieldEventType, v)) +} + +// ActorIDEQ applies the EQ predicate on the "actor_id" field. +func ActorIDEQ(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldActorID, v)) +} + +// ActorIDNEQ applies the NEQ predicate on the "actor_id" field. +func ActorIDNEQ(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNEQ(FieldActorID, v)) +} + +// ActorIDIn applies the In predicate on the "actor_id" field. +func ActorIDIn(vs ...int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIn(FieldActorID, vs...)) +} + +// ActorIDNotIn applies the NotIn predicate on the "actor_id" field. +func ActorIDNotIn(vs ...int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotIn(FieldActorID, vs...)) +} + +// ActorIDGT applies the GT predicate on the "actor_id" field. +func ActorIDGT(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGT(FieldActorID, v)) +} + +// ActorIDGTE applies the GTE predicate on the "actor_id" field. +func ActorIDGTE(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGTE(FieldActorID, v)) +} + +// ActorIDLT applies the LT predicate on the "actor_id" field. +func ActorIDLT(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLT(FieldActorID, v)) +} + +// ActorIDLTE applies the LTE predicate on the "actor_id" field. +func ActorIDLTE(v int64) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLTE(FieldActorID, v)) +} + +// ActorIDIsNil applies the IsNil predicate on the "actor_id" field. +func ActorIDIsNil() predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIsNull(FieldActorID)) +} + +// ActorIDNotNil applies the NotNil predicate on the "actor_id" field. +func ActorIDNotNil() predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotNull(FieldActorID)) +} + +// ActorNameEQ applies the EQ predicate on the "actor_name" field. +func ActorNameEQ(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldActorName, v)) +} + +// ActorNameNEQ applies the NEQ predicate on the "actor_name" field. +func ActorNameNEQ(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNEQ(FieldActorName, v)) +} + +// ActorNameIn applies the In predicate on the "actor_name" field. +func ActorNameIn(vs ...string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIn(FieldActorName, vs...)) +} + +// ActorNameNotIn applies the NotIn predicate on the "actor_name" field. +func ActorNameNotIn(vs ...string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotIn(FieldActorName, vs...)) +} + +// ActorNameGT applies the GT predicate on the "actor_name" field. +func ActorNameGT(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGT(FieldActorName, v)) +} + +// ActorNameGTE applies the GTE predicate on the "actor_name" field. +func ActorNameGTE(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGTE(FieldActorName, v)) +} + +// ActorNameLT applies the LT predicate on the "actor_name" field. +func ActorNameLT(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLT(FieldActorName, v)) +} + +// ActorNameLTE applies the LTE predicate on the "actor_name" field. +func ActorNameLTE(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLTE(FieldActorName, v)) +} + +// ActorNameContains applies the Contains predicate on the "actor_name" field. +func ActorNameContains(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldContains(FieldActorName, v)) +} + +// ActorNameHasPrefix applies the HasPrefix predicate on the "actor_name" field. +func ActorNameHasPrefix(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldHasPrefix(FieldActorName, v)) +} + +// ActorNameHasSuffix applies the HasSuffix predicate on the "actor_name" field. +func ActorNameHasSuffix(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldHasSuffix(FieldActorName, v)) +} + +// ActorNameIsNil applies the IsNil predicate on the "actor_name" field. +func ActorNameIsNil() predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIsNull(FieldActorName)) +} + +// ActorNameNotNil applies the NotNil predicate on the "actor_name" field. +func ActorNameNotNil() predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotNull(FieldActorName)) +} + +// ActorNameEqualFold applies the EqualFold predicate on the "actor_name" field. +func ActorNameEqualFold(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEqualFold(FieldActorName, v)) +} + +// ActorNameContainsFold applies the ContainsFold predicate on the "actor_name" field. +func ActorNameContainsFold(v string) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldContainsFold(FieldActorName, v)) +} + +// DetailsIsNil applies the IsNil predicate on the "details" field. +func DetailsIsNil() predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIsNull(FieldDetails)) +} + +// DetailsNotNil applies the NotNil predicate on the "details" field. +func DetailsNotNil() predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotNull(FieldDetails)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.FieldLTE(FieldCreatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.DisputeTimeline) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.DisputeTimeline) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.DisputeTimeline) predicate.DisputeTimeline { + return predicate.DisputeTimeline(sql.NotPredicates(p)) +} diff --git a/app/dispute/rpc/internal/models/disputetimeline_create.go b/app/dispute/rpc/internal/models/disputetimeline_create.go new file mode 100644 index 0000000..5d1fdd3 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputetimeline_create.go @@ -0,0 +1,296 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputeTimelineCreate is the builder for creating a DisputeTimeline entity. +type DisputeTimelineCreate struct { + config + mutation *DisputeTimelineMutation + hooks []Hook +} + +// SetDisputeID sets the "dispute_id" field. +func (_c *DisputeTimelineCreate) SetDisputeID(v int64) *DisputeTimelineCreate { + _c.mutation.SetDisputeID(v) + return _c +} + +// SetEventType sets the "event_type" field. +func (_c *DisputeTimelineCreate) SetEventType(v string) *DisputeTimelineCreate { + _c.mutation.SetEventType(v) + return _c +} + +// SetActorID sets the "actor_id" field. +func (_c *DisputeTimelineCreate) SetActorID(v int64) *DisputeTimelineCreate { + _c.mutation.SetActorID(v) + return _c +} + +// SetNillableActorID sets the "actor_id" field if the given value is not nil. +func (_c *DisputeTimelineCreate) SetNillableActorID(v *int64) *DisputeTimelineCreate { + if v != nil { + _c.SetActorID(*v) + } + return _c +} + +// SetActorName sets the "actor_name" field. +func (_c *DisputeTimelineCreate) SetActorName(v string) *DisputeTimelineCreate { + _c.mutation.SetActorName(v) + return _c +} + +// SetNillableActorName sets the "actor_name" field if the given value is not nil. +func (_c *DisputeTimelineCreate) SetNillableActorName(v *string) *DisputeTimelineCreate { + if v != nil { + _c.SetActorName(*v) + } + return _c +} + +// SetDetails sets the "details" field. +func (_c *DisputeTimelineCreate) SetDetails(v map[string]interface{}) *DisputeTimelineCreate { + _c.mutation.SetDetails(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *DisputeTimelineCreate) SetCreatedAt(v time.Time) *DisputeTimelineCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *DisputeTimelineCreate) SetNillableCreatedAt(v *time.Time) *DisputeTimelineCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *DisputeTimelineCreate) SetID(v int64) *DisputeTimelineCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the DisputeTimelineMutation object of the builder. +func (_c *DisputeTimelineCreate) Mutation() *DisputeTimelineMutation { + return _c.mutation +} + +// Save creates the DisputeTimeline in the database. +func (_c *DisputeTimelineCreate) Save(ctx context.Context) (*DisputeTimeline, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *DisputeTimelineCreate) SaveX(ctx context.Context) *DisputeTimeline { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *DisputeTimelineCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *DisputeTimelineCreate) 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 *DisputeTimelineCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := disputetimeline.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *DisputeTimelineCreate) check() error { + if _, ok := _c.mutation.DisputeID(); !ok { + return &ValidationError{Name: "dispute_id", err: errors.New(`models: missing required field "DisputeTimeline.dispute_id"`)} + } + if _, ok := _c.mutation.EventType(); !ok { + return &ValidationError{Name: "event_type", err: errors.New(`models: missing required field "DisputeTimeline.event_type"`)} + } + if v, ok := _c.mutation.EventType(); ok { + if err := disputetimeline.EventTypeValidator(v); err != nil { + return &ValidationError{Name: "event_type", err: fmt.Errorf(`models: validator failed for field "DisputeTimeline.event_type": %w`, err)} + } + } + if v, ok := _c.mutation.ActorName(); ok { + if err := disputetimeline.ActorNameValidator(v); err != nil { + return &ValidationError{Name: "actor_name", err: fmt.Errorf(`models: validator failed for field "DisputeTimeline.actor_name": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "DisputeTimeline.created_at"`)} + } + return nil +} + +func (_c *DisputeTimelineCreate) sqlSave(ctx context.Context) (*DisputeTimeline, 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 *DisputeTimelineCreate) createSpec() (*DisputeTimeline, *sqlgraph.CreateSpec) { + var ( + _node = &DisputeTimeline{config: _c.config} + _spec = sqlgraph.NewCreateSpec(disputetimeline.Table, sqlgraph.NewFieldSpec(disputetimeline.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.DisputeID(); ok { + _spec.SetField(disputetimeline.FieldDisputeID, field.TypeInt64, value) + _node.DisputeID = value + } + if value, ok := _c.mutation.EventType(); ok { + _spec.SetField(disputetimeline.FieldEventType, field.TypeString, value) + _node.EventType = value + } + if value, ok := _c.mutation.ActorID(); ok { + _spec.SetField(disputetimeline.FieldActorID, field.TypeInt64, value) + _node.ActorID = value + } + if value, ok := _c.mutation.ActorName(); ok { + _spec.SetField(disputetimeline.FieldActorName, field.TypeString, value) + _node.ActorName = value + } + if value, ok := _c.mutation.Details(); ok { + _spec.SetField(disputetimeline.FieldDetails, field.TypeJSON, value) + _node.Details = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(disputetimeline.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + return _node, _spec +} + +// DisputeTimelineCreateBulk is the builder for creating many DisputeTimeline entities in bulk. +type DisputeTimelineCreateBulk struct { + config + err error + builders []*DisputeTimelineCreate +} + +// Save creates the DisputeTimeline entities in the database. +func (_c *DisputeTimelineCreateBulk) Save(ctx context.Context) ([]*DisputeTimeline, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*DisputeTimeline, 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.(*DisputeTimelineMutation) + 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 *DisputeTimelineCreateBulk) SaveX(ctx context.Context) []*DisputeTimeline { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *DisputeTimelineCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *DisputeTimelineCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/dispute/rpc/internal/models/disputetimeline_delete.go b/app/dispute/rpc/internal/models/disputetimeline_delete.go new file mode 100644 index 0000000..3eecddf --- /dev/null +++ b/app/dispute/rpc/internal/models/disputetimeline_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "juwan-backend/app/dispute/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputeTimelineDelete is the builder for deleting a DisputeTimeline entity. +type DisputeTimelineDelete struct { + config + hooks []Hook + mutation *DisputeTimelineMutation +} + +// Where appends a list predicates to the DisputeTimelineDelete builder. +func (_d *DisputeTimelineDelete) Where(ps ...predicate.DisputeTimeline) *DisputeTimelineDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *DisputeTimelineDelete) 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 *DisputeTimelineDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *DisputeTimelineDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(disputetimeline.Table, sqlgraph.NewFieldSpec(disputetimeline.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 +} + +// DisputeTimelineDeleteOne is the builder for deleting a single DisputeTimeline entity. +type DisputeTimelineDeleteOne struct { + _d *DisputeTimelineDelete +} + +// Where appends a list predicates to the DisputeTimelineDelete builder. +func (_d *DisputeTimelineDeleteOne) Where(ps ...predicate.DisputeTimeline) *DisputeTimelineDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *DisputeTimelineDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{disputetimeline.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *DisputeTimelineDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/dispute/rpc/internal/models/disputetimeline_query.go b/app/dispute/rpc/internal/models/disputetimeline_query.go new file mode 100644 index 0000000..e67c9e3 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputetimeline_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "juwan-backend/app/dispute/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputeTimelineQuery is the builder for querying DisputeTimeline entities. +type DisputeTimelineQuery struct { + config + ctx *QueryContext + order []disputetimeline.OrderOption + inters []Interceptor + predicates []predicate.DisputeTimeline + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the DisputeTimelineQuery builder. +func (_q *DisputeTimelineQuery) Where(ps ...predicate.DisputeTimeline) *DisputeTimelineQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *DisputeTimelineQuery) Limit(limit int) *DisputeTimelineQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *DisputeTimelineQuery) Offset(offset int) *DisputeTimelineQuery { + _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 *DisputeTimelineQuery) Unique(unique bool) *DisputeTimelineQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *DisputeTimelineQuery) Order(o ...disputetimeline.OrderOption) *DisputeTimelineQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first DisputeTimeline entity from the query. +// Returns a *NotFoundError when no DisputeTimeline was found. +func (_q *DisputeTimelineQuery) First(ctx context.Context) (*DisputeTimeline, 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{disputetimeline.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *DisputeTimelineQuery) FirstX(ctx context.Context) *DisputeTimeline { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first DisputeTimeline ID from the query. +// Returns a *NotFoundError when no DisputeTimeline ID was found. +func (_q *DisputeTimelineQuery) 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{disputetimeline.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *DisputeTimelineQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single DisputeTimeline entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one DisputeTimeline entity is found. +// Returns a *NotFoundError when no DisputeTimeline entities are found. +func (_q *DisputeTimelineQuery) Only(ctx context.Context) (*DisputeTimeline, 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{disputetimeline.Label} + default: + return nil, &NotSingularError{disputetimeline.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *DisputeTimelineQuery) OnlyX(ctx context.Context) *DisputeTimeline { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only DisputeTimeline ID in the query. +// Returns a *NotSingularError when more than one DisputeTimeline ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *DisputeTimelineQuery) 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{disputetimeline.Label} + default: + err = &NotSingularError{disputetimeline.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *DisputeTimelineQuery) 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 DisputeTimelines. +func (_q *DisputeTimelineQuery) All(ctx context.Context) ([]*DisputeTimeline, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*DisputeTimeline, *DisputeTimelineQuery]() + return withInterceptors[[]*DisputeTimeline](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *DisputeTimelineQuery) AllX(ctx context.Context) []*DisputeTimeline { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of DisputeTimeline IDs. +func (_q *DisputeTimelineQuery) 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(disputetimeline.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *DisputeTimelineQuery) 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 *DisputeTimelineQuery) 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[*DisputeTimelineQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *DisputeTimelineQuery) 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 *DisputeTimelineQuery) 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 *DisputeTimelineQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the DisputeTimelineQuery 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 *DisputeTimelineQuery) Clone() *DisputeTimelineQuery { + if _q == nil { + return nil + } + return &DisputeTimelineQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]disputetimeline.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.DisputeTimeline{}, _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 { +// DisputeID int64 `json:"dispute_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.DisputeTimeline.Query(). +// GroupBy(disputetimeline.FieldDisputeID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *DisputeTimelineQuery) GroupBy(field string, fields ...string) *DisputeTimelineGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &DisputeTimelineGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = disputetimeline.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 { +// DisputeID int64 `json:"dispute_id,omitempty"` +// } +// +// client.DisputeTimeline.Query(). +// Select(disputetimeline.FieldDisputeID). +// Scan(ctx, &v) +func (_q *DisputeTimelineQuery) Select(fields ...string) *DisputeTimelineSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &DisputeTimelineSelect{DisputeTimelineQuery: _q} + sbuild.label = disputetimeline.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a DisputeTimelineSelect configured with the given aggregations. +func (_q *DisputeTimelineQuery) Aggregate(fns ...AggregateFunc) *DisputeTimelineSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *DisputeTimelineQuery) 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 !disputetimeline.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 *DisputeTimelineQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DisputeTimeline, error) { + var ( + nodes = []*DisputeTimeline{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*DisputeTimeline).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &DisputeTimeline{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 *DisputeTimelineQuery) 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 *DisputeTimelineQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(disputetimeline.Table, disputetimeline.Columns, sqlgraph.NewFieldSpec(disputetimeline.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, disputetimeline.FieldID) + for i := range fields { + if fields[i] != disputetimeline.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 *DisputeTimelineQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(disputetimeline.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = disputetimeline.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 +} + +// DisputeTimelineGroupBy is the group-by builder for DisputeTimeline entities. +type DisputeTimelineGroupBy struct { + selector + build *DisputeTimelineQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *DisputeTimelineGroupBy) Aggregate(fns ...AggregateFunc) *DisputeTimelineGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *DisputeTimelineGroupBy) 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[*DisputeTimelineQuery, *DisputeTimelineGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *DisputeTimelineGroupBy) sqlScan(ctx context.Context, root *DisputeTimelineQuery, 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) +} + +// DisputeTimelineSelect is the builder for selecting fields of DisputeTimeline entities. +type DisputeTimelineSelect struct { + *DisputeTimelineQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *DisputeTimelineSelect) Aggregate(fns ...AggregateFunc) *DisputeTimelineSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *DisputeTimelineSelect) 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[*DisputeTimelineQuery, *DisputeTimelineSelect](ctx, _s.DisputeTimelineQuery, _s, _s.inters, v) +} + +func (_s *DisputeTimelineSelect) sqlScan(ctx context.Context, root *DisputeTimelineQuery, 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/dispute/rpc/internal/models/disputetimeline_update.go b/app/dispute/rpc/internal/models/disputetimeline_update.go new file mode 100644 index 0000000..03b9530 --- /dev/null +++ b/app/dispute/rpc/internal/models/disputetimeline_update.go @@ -0,0 +1,459 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "juwan-backend/app/dispute/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// DisputeTimelineUpdate is the builder for updating DisputeTimeline entities. +type DisputeTimelineUpdate struct { + config + hooks []Hook + mutation *DisputeTimelineMutation +} + +// Where appends a list predicates to the DisputeTimelineUpdate builder. +func (_u *DisputeTimelineUpdate) Where(ps ...predicate.DisputeTimeline) *DisputeTimelineUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetDisputeID sets the "dispute_id" field. +func (_u *DisputeTimelineUpdate) SetDisputeID(v int64) *DisputeTimelineUpdate { + _u.mutation.ResetDisputeID() + _u.mutation.SetDisputeID(v) + return _u +} + +// SetNillableDisputeID sets the "dispute_id" field if the given value is not nil. +func (_u *DisputeTimelineUpdate) SetNillableDisputeID(v *int64) *DisputeTimelineUpdate { + if v != nil { + _u.SetDisputeID(*v) + } + return _u +} + +// AddDisputeID adds value to the "dispute_id" field. +func (_u *DisputeTimelineUpdate) AddDisputeID(v int64) *DisputeTimelineUpdate { + _u.mutation.AddDisputeID(v) + return _u +} + +// SetEventType sets the "event_type" field. +func (_u *DisputeTimelineUpdate) SetEventType(v string) *DisputeTimelineUpdate { + _u.mutation.SetEventType(v) + return _u +} + +// SetNillableEventType sets the "event_type" field if the given value is not nil. +func (_u *DisputeTimelineUpdate) SetNillableEventType(v *string) *DisputeTimelineUpdate { + if v != nil { + _u.SetEventType(*v) + } + return _u +} + +// SetActorID sets the "actor_id" field. +func (_u *DisputeTimelineUpdate) SetActorID(v int64) *DisputeTimelineUpdate { + _u.mutation.ResetActorID() + _u.mutation.SetActorID(v) + return _u +} + +// SetNillableActorID sets the "actor_id" field if the given value is not nil. +func (_u *DisputeTimelineUpdate) SetNillableActorID(v *int64) *DisputeTimelineUpdate { + if v != nil { + _u.SetActorID(*v) + } + return _u +} + +// AddActorID adds value to the "actor_id" field. +func (_u *DisputeTimelineUpdate) AddActorID(v int64) *DisputeTimelineUpdate { + _u.mutation.AddActorID(v) + return _u +} + +// ClearActorID clears the value of the "actor_id" field. +func (_u *DisputeTimelineUpdate) ClearActorID() *DisputeTimelineUpdate { + _u.mutation.ClearActorID() + return _u +} + +// SetActorName sets the "actor_name" field. +func (_u *DisputeTimelineUpdate) SetActorName(v string) *DisputeTimelineUpdate { + _u.mutation.SetActorName(v) + return _u +} + +// SetNillableActorName sets the "actor_name" field if the given value is not nil. +func (_u *DisputeTimelineUpdate) SetNillableActorName(v *string) *DisputeTimelineUpdate { + if v != nil { + _u.SetActorName(*v) + } + return _u +} + +// ClearActorName clears the value of the "actor_name" field. +func (_u *DisputeTimelineUpdate) ClearActorName() *DisputeTimelineUpdate { + _u.mutation.ClearActorName() + return _u +} + +// SetDetails sets the "details" field. +func (_u *DisputeTimelineUpdate) SetDetails(v map[string]interface{}) *DisputeTimelineUpdate { + _u.mutation.SetDetails(v) + return _u +} + +// ClearDetails clears the value of the "details" field. +func (_u *DisputeTimelineUpdate) ClearDetails() *DisputeTimelineUpdate { + _u.mutation.ClearDetails() + return _u +} + +// Mutation returns the DisputeTimelineMutation object of the builder. +func (_u *DisputeTimelineUpdate) Mutation() *DisputeTimelineMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *DisputeTimelineUpdate) 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 *DisputeTimelineUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *DisputeTimelineUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *DisputeTimelineUpdate) 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 *DisputeTimelineUpdate) check() error { + if v, ok := _u.mutation.EventType(); ok { + if err := disputetimeline.EventTypeValidator(v); err != nil { + return &ValidationError{Name: "event_type", err: fmt.Errorf(`models: validator failed for field "DisputeTimeline.event_type": %w`, err)} + } + } + if v, ok := _u.mutation.ActorName(); ok { + if err := disputetimeline.ActorNameValidator(v); err != nil { + return &ValidationError{Name: "actor_name", err: fmt.Errorf(`models: validator failed for field "DisputeTimeline.actor_name": %w`, err)} + } + } + return nil +} + +func (_u *DisputeTimelineUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(disputetimeline.Table, disputetimeline.Columns, sqlgraph.NewFieldSpec(disputetimeline.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.DisputeID(); ok { + _spec.SetField(disputetimeline.FieldDisputeID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedDisputeID(); ok { + _spec.AddField(disputetimeline.FieldDisputeID, field.TypeInt64, value) + } + if value, ok := _u.mutation.EventType(); ok { + _spec.SetField(disputetimeline.FieldEventType, field.TypeString, value) + } + if value, ok := _u.mutation.ActorID(); ok { + _spec.SetField(disputetimeline.FieldActorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedActorID(); ok { + _spec.AddField(disputetimeline.FieldActorID, field.TypeInt64, value) + } + if _u.mutation.ActorIDCleared() { + _spec.ClearField(disputetimeline.FieldActorID, field.TypeInt64) + } + if value, ok := _u.mutation.ActorName(); ok { + _spec.SetField(disputetimeline.FieldActorName, field.TypeString, value) + } + if _u.mutation.ActorNameCleared() { + _spec.ClearField(disputetimeline.FieldActorName, field.TypeString) + } + if value, ok := _u.mutation.Details(); ok { + _spec.SetField(disputetimeline.FieldDetails, field.TypeJSON, value) + } + if _u.mutation.DetailsCleared() { + _spec.ClearField(disputetimeline.FieldDetails, field.TypeJSON) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{disputetimeline.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// DisputeTimelineUpdateOne is the builder for updating a single DisputeTimeline entity. +type DisputeTimelineUpdateOne struct { + config + fields []string + hooks []Hook + mutation *DisputeTimelineMutation +} + +// SetDisputeID sets the "dispute_id" field. +func (_u *DisputeTimelineUpdateOne) SetDisputeID(v int64) *DisputeTimelineUpdateOne { + _u.mutation.ResetDisputeID() + _u.mutation.SetDisputeID(v) + return _u +} + +// SetNillableDisputeID sets the "dispute_id" field if the given value is not nil. +func (_u *DisputeTimelineUpdateOne) SetNillableDisputeID(v *int64) *DisputeTimelineUpdateOne { + if v != nil { + _u.SetDisputeID(*v) + } + return _u +} + +// AddDisputeID adds value to the "dispute_id" field. +func (_u *DisputeTimelineUpdateOne) AddDisputeID(v int64) *DisputeTimelineUpdateOne { + _u.mutation.AddDisputeID(v) + return _u +} + +// SetEventType sets the "event_type" field. +func (_u *DisputeTimelineUpdateOne) SetEventType(v string) *DisputeTimelineUpdateOne { + _u.mutation.SetEventType(v) + return _u +} + +// SetNillableEventType sets the "event_type" field if the given value is not nil. +func (_u *DisputeTimelineUpdateOne) SetNillableEventType(v *string) *DisputeTimelineUpdateOne { + if v != nil { + _u.SetEventType(*v) + } + return _u +} + +// SetActorID sets the "actor_id" field. +func (_u *DisputeTimelineUpdateOne) SetActorID(v int64) *DisputeTimelineUpdateOne { + _u.mutation.ResetActorID() + _u.mutation.SetActorID(v) + return _u +} + +// SetNillableActorID sets the "actor_id" field if the given value is not nil. +func (_u *DisputeTimelineUpdateOne) SetNillableActorID(v *int64) *DisputeTimelineUpdateOne { + if v != nil { + _u.SetActorID(*v) + } + return _u +} + +// AddActorID adds value to the "actor_id" field. +func (_u *DisputeTimelineUpdateOne) AddActorID(v int64) *DisputeTimelineUpdateOne { + _u.mutation.AddActorID(v) + return _u +} + +// ClearActorID clears the value of the "actor_id" field. +func (_u *DisputeTimelineUpdateOne) ClearActorID() *DisputeTimelineUpdateOne { + _u.mutation.ClearActorID() + return _u +} + +// SetActorName sets the "actor_name" field. +func (_u *DisputeTimelineUpdateOne) SetActorName(v string) *DisputeTimelineUpdateOne { + _u.mutation.SetActorName(v) + return _u +} + +// SetNillableActorName sets the "actor_name" field if the given value is not nil. +func (_u *DisputeTimelineUpdateOne) SetNillableActorName(v *string) *DisputeTimelineUpdateOne { + if v != nil { + _u.SetActorName(*v) + } + return _u +} + +// ClearActorName clears the value of the "actor_name" field. +func (_u *DisputeTimelineUpdateOne) ClearActorName() *DisputeTimelineUpdateOne { + _u.mutation.ClearActorName() + return _u +} + +// SetDetails sets the "details" field. +func (_u *DisputeTimelineUpdateOne) SetDetails(v map[string]interface{}) *DisputeTimelineUpdateOne { + _u.mutation.SetDetails(v) + return _u +} + +// ClearDetails clears the value of the "details" field. +func (_u *DisputeTimelineUpdateOne) ClearDetails() *DisputeTimelineUpdateOne { + _u.mutation.ClearDetails() + return _u +} + +// Mutation returns the DisputeTimelineMutation object of the builder. +func (_u *DisputeTimelineUpdateOne) Mutation() *DisputeTimelineMutation { + return _u.mutation +} + +// Where appends a list predicates to the DisputeTimelineUpdate builder. +func (_u *DisputeTimelineUpdateOne) Where(ps ...predicate.DisputeTimeline) *DisputeTimelineUpdateOne { + _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 *DisputeTimelineUpdateOne) Select(field string, fields ...string) *DisputeTimelineUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated DisputeTimeline entity. +func (_u *DisputeTimelineUpdateOne) Save(ctx context.Context) (*DisputeTimeline, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *DisputeTimelineUpdateOne) SaveX(ctx context.Context) *DisputeTimeline { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *DisputeTimelineUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *DisputeTimelineUpdateOne) 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 *DisputeTimelineUpdateOne) check() error { + if v, ok := _u.mutation.EventType(); ok { + if err := disputetimeline.EventTypeValidator(v); err != nil { + return &ValidationError{Name: "event_type", err: fmt.Errorf(`models: validator failed for field "DisputeTimeline.event_type": %w`, err)} + } + } + if v, ok := _u.mutation.ActorName(); ok { + if err := disputetimeline.ActorNameValidator(v); err != nil { + return &ValidationError{Name: "actor_name", err: fmt.Errorf(`models: validator failed for field "DisputeTimeline.actor_name": %w`, err)} + } + } + return nil +} + +func (_u *DisputeTimelineUpdateOne) sqlSave(ctx context.Context) (_node *DisputeTimeline, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(disputetimeline.Table, disputetimeline.Columns, sqlgraph.NewFieldSpec(disputetimeline.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "DisputeTimeline.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, disputetimeline.FieldID) + for _, f := range fields { + if !disputetimeline.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != disputetimeline.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.DisputeID(); ok { + _spec.SetField(disputetimeline.FieldDisputeID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedDisputeID(); ok { + _spec.AddField(disputetimeline.FieldDisputeID, field.TypeInt64, value) + } + if value, ok := _u.mutation.EventType(); ok { + _spec.SetField(disputetimeline.FieldEventType, field.TypeString, value) + } + if value, ok := _u.mutation.ActorID(); ok { + _spec.SetField(disputetimeline.FieldActorID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedActorID(); ok { + _spec.AddField(disputetimeline.FieldActorID, field.TypeInt64, value) + } + if _u.mutation.ActorIDCleared() { + _spec.ClearField(disputetimeline.FieldActorID, field.TypeInt64) + } + if value, ok := _u.mutation.ActorName(); ok { + _spec.SetField(disputetimeline.FieldActorName, field.TypeString, value) + } + if _u.mutation.ActorNameCleared() { + _spec.ClearField(disputetimeline.FieldActorName, field.TypeString) + } + if value, ok := _u.mutation.Details(); ok { + _spec.SetField(disputetimeline.FieldDetails, field.TypeJSON, value) + } + if _u.mutation.DetailsCleared() { + _spec.ClearField(disputetimeline.FieldDetails, field.TypeJSON) + } + _node = &DisputeTimeline{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{disputetimeline.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/dispute/rpc/internal/models/ent.go b/app/dispute/rpc/internal/models/ent.go new file mode 100644 index 0000000..c5ed8a9 --- /dev/null +++ b/app/dispute/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/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "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{ + disputetimeline.Table: disputetimeline.ValidColumn, + disputes.Table: disputes.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/dispute/rpc/internal/models/enttest/enttest.go b/app/dispute/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..f1e84ba --- /dev/null +++ b/app/dispute/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/dispute/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/dispute/rpc/internal/models/runtime" + + "juwan-backend/app/dispute/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/dispute/rpc/internal/models/generate.go b/app/dispute/rpc/internal/models/generate.go new file mode 100644 index 0000000..d441aca --- /dev/null +++ b/app/dispute/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/dispute/rpc/internal/models/hook/hook.go b/app/dispute/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..29bcf2a --- /dev/null +++ b/app/dispute/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/dispute/rpc/internal/models" +) + +// The DisputeTimelineFunc type is an adapter to allow the use of ordinary +// function as DisputeTimeline mutator. +type DisputeTimelineFunc func(context.Context, *models.DisputeTimelineMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f DisputeTimelineFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.DisputeTimelineMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.DisputeTimelineMutation", m) +} + +// The DisputesFunc type is an adapter to allow the use of ordinary +// function as Disputes mutator. +type DisputesFunc func(context.Context, *models.DisputesMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f DisputesFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.DisputesMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.DisputesMutation", 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/dispute/rpc/internal/models/migrate/migrate.go b/app/dispute/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/dispute/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/dispute/rpc/internal/models/migrate/schema.go b/app/dispute/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..4ba6b83 --- /dev/null +++ b/app/dispute/rpc/internal/models/migrate/schema.go @@ -0,0 +1,99 @@ +// 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 ( + // DisputeTimelineColumns holds the columns for the "dispute_timeline" table. + DisputeTimelineColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "dispute_id", Type: field.TypeInt64}, + {Name: "event_type", Type: field.TypeString, Size: 30}, + {Name: "actor_id", Type: field.TypeInt64, Nullable: true}, + {Name: "actor_name", Type: field.TypeString, Nullable: true, Size: 100}, + {Name: "details", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, + {Name: "created_at", Type: field.TypeTime}, + } + // DisputeTimelineTable holds the schema information for the "dispute_timeline" table. + DisputeTimelineTable = &schema.Table{ + Name: "dispute_timeline", + Columns: DisputeTimelineColumns, + PrimaryKey: []*schema.Column{DisputeTimelineColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "disputetimeline_dispute_id_created_at", + Unique: false, + Columns: []*schema.Column{DisputeTimelineColumns[1], DisputeTimelineColumns[6]}, + }, + }, + } + // DisputesColumns holds the columns for the "disputes" table. + DisputesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "order_id", Type: field.TypeInt64, Unique: true}, + {Name: "initiator_id", Type: field.TypeInt64}, + {Name: "initiator_name", Type: field.TypeString, Size: 100}, + {Name: "respondent_id", Type: field.TypeInt64}, + {Name: "reason", Type: field.TypeString}, + {Name: "evidence", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}}, + {Name: "status", Type: field.TypeString, Size: 20, Default: "open"}, + {Name: "result", Type: field.TypeString, Nullable: true, Size: 30}, + {Name: "respondent_reason", Type: field.TypeString, Nullable: true}, + {Name: "respondent_evidence", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}}, + {Name: "appeal_reason", Type: field.TypeString, Nullable: true}, + {Name: "appealed_at", Type: field.TypeTime, Nullable: true}, + {Name: "resolved_by", Type: field.TypeInt64, Nullable: true}, + {Name: "resolved_at", Type: field.TypeTime, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // DisputesTable holds the schema information for the "disputes" table. + DisputesTable = &schema.Table{ + Name: "disputes", + Columns: DisputesColumns, + PrimaryKey: []*schema.Column{DisputesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "disputes_order_id", + Unique: false, + Columns: []*schema.Column{DisputesColumns[1]}, + }, + { + Name: "disputes_status_created_at", + Unique: false, + Columns: []*schema.Column{DisputesColumns[7], DisputesColumns[15]}, + }, + { + Name: "disputes_initiator_id", + Unique: false, + Columns: []*schema.Column{DisputesColumns[2]}, + }, + { + Name: "disputes_initiator_id_status_created_at", + Unique: false, + Columns: []*schema.Column{DisputesColumns[2], DisputesColumns[7], DisputesColumns[15]}, + }, + { + Name: "disputes_respondent_id_status_created_at", + Unique: false, + Columns: []*schema.Column{DisputesColumns[4], DisputesColumns[7], DisputesColumns[15]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + DisputeTimelineTable, + DisputesTable, + } +) + +func init() { + DisputeTimelineTable.Annotation = &entsql.Annotation{ + Table: "dispute_timeline", + } +} diff --git a/app/dispute/rpc/internal/models/mutation.go b/app/dispute/rpc/internal/models/mutation.go new file mode 100644 index 0000000..18bac05 --- /dev/null +++ b/app/dispute/rpc/internal/models/mutation.go @@ -0,0 +1,2196 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "juwan-backend/app/dispute/rpc/internal/models/predicate" + "juwan-backend/pkg/types" + "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. + TypeDisputeTimeline = "DisputeTimeline" + TypeDisputes = "Disputes" +) + +// DisputeTimelineMutation represents an operation that mutates the DisputeTimeline nodes in the graph. +type DisputeTimelineMutation struct { + config + op Op + typ string + id *int64 + dispute_id *int64 + adddispute_id *int64 + event_type *string + actor_id *int64 + addactor_id *int64 + actor_name *string + details *map[string]interface{} + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*DisputeTimeline, error) + predicates []predicate.DisputeTimeline +} + +var _ ent.Mutation = (*DisputeTimelineMutation)(nil) + +// disputetimelineOption allows management of the mutation configuration using functional options. +type disputetimelineOption func(*DisputeTimelineMutation) + +// newDisputeTimelineMutation creates new mutation for the DisputeTimeline entity. +func newDisputeTimelineMutation(c config, op Op, opts ...disputetimelineOption) *DisputeTimelineMutation { + m := &DisputeTimelineMutation{ + config: c, + op: op, + typ: TypeDisputeTimeline, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withDisputeTimelineID sets the ID field of the mutation. +func withDisputeTimelineID(id int64) disputetimelineOption { + return func(m *DisputeTimelineMutation) { + var ( + err error + once sync.Once + value *DisputeTimeline + ) + m.oldValue = func(ctx context.Context) (*DisputeTimeline, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().DisputeTimeline.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withDisputeTimeline sets the old DisputeTimeline of the mutation. +func withDisputeTimeline(node *DisputeTimeline) disputetimelineOption { + return func(m *DisputeTimelineMutation) { + m.oldValue = func(context.Context) (*DisputeTimeline, 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 DisputeTimelineMutation) 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 DisputeTimelineMutation) 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 DisputeTimeline entities. +func (m *DisputeTimelineMutation) 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 *DisputeTimelineMutation) 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 *DisputeTimelineMutation) 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().DisputeTimeline.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetDisputeID sets the "dispute_id" field. +func (m *DisputeTimelineMutation) SetDisputeID(i int64) { + m.dispute_id = &i + m.adddispute_id = nil +} + +// DisputeID returns the value of the "dispute_id" field in the mutation. +func (m *DisputeTimelineMutation) DisputeID() (r int64, exists bool) { + v := m.dispute_id + if v == nil { + return + } + return *v, true +} + +// OldDisputeID returns the old "dispute_id" field's value of the DisputeTimeline entity. +// If the DisputeTimeline 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 *DisputeTimelineMutation) OldDisputeID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDisputeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDisputeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDisputeID: %w", err) + } + return oldValue.DisputeID, nil +} + +// AddDisputeID adds i to the "dispute_id" field. +func (m *DisputeTimelineMutation) AddDisputeID(i int64) { + if m.adddispute_id != nil { + *m.adddispute_id += i + } else { + m.adddispute_id = &i + } +} + +// AddedDisputeID returns the value that was added to the "dispute_id" field in this mutation. +func (m *DisputeTimelineMutation) AddedDisputeID() (r int64, exists bool) { + v := m.adddispute_id + if v == nil { + return + } + return *v, true +} + +// ResetDisputeID resets all changes to the "dispute_id" field. +func (m *DisputeTimelineMutation) ResetDisputeID() { + m.dispute_id = nil + m.adddispute_id = nil +} + +// SetEventType sets the "event_type" field. +func (m *DisputeTimelineMutation) SetEventType(s string) { + m.event_type = &s +} + +// EventType returns the value of the "event_type" field in the mutation. +func (m *DisputeTimelineMutation) EventType() (r string, exists bool) { + v := m.event_type + if v == nil { + return + } + return *v, true +} + +// OldEventType returns the old "event_type" field's value of the DisputeTimeline entity. +// If the DisputeTimeline 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 *DisputeTimelineMutation) OldEventType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEventType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEventType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEventType: %w", err) + } + return oldValue.EventType, nil +} + +// ResetEventType resets all changes to the "event_type" field. +func (m *DisputeTimelineMutation) ResetEventType() { + m.event_type = nil +} + +// SetActorID sets the "actor_id" field. +func (m *DisputeTimelineMutation) 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 *DisputeTimelineMutation) 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 DisputeTimeline entity. +// If the DisputeTimeline 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 *DisputeTimelineMutation) 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 *DisputeTimelineMutation) 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 *DisputeTimelineMutation) AddedActorID() (r int64, exists bool) { + v := m.addactor_id + if v == nil { + return + } + return *v, true +} + +// ClearActorID clears the value of the "actor_id" field. +func (m *DisputeTimelineMutation) ClearActorID() { + m.actor_id = nil + m.addactor_id = nil + m.clearedFields[disputetimeline.FieldActorID] = struct{}{} +} + +// ActorIDCleared returns if the "actor_id" field was cleared in this mutation. +func (m *DisputeTimelineMutation) ActorIDCleared() bool { + _, ok := m.clearedFields[disputetimeline.FieldActorID] + return ok +} + +// ResetActorID resets all changes to the "actor_id" field. +func (m *DisputeTimelineMutation) ResetActorID() { + m.actor_id = nil + m.addactor_id = nil + delete(m.clearedFields, disputetimeline.FieldActorID) +} + +// SetActorName sets the "actor_name" field. +func (m *DisputeTimelineMutation) SetActorName(s string) { + m.actor_name = &s +} + +// ActorName returns the value of the "actor_name" field in the mutation. +func (m *DisputeTimelineMutation) ActorName() (r string, exists bool) { + v := m.actor_name + if v == nil { + return + } + return *v, true +} + +// OldActorName returns the old "actor_name" field's value of the DisputeTimeline entity. +// If the DisputeTimeline 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 *DisputeTimelineMutation) OldActorName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldActorName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldActorName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldActorName: %w", err) + } + return oldValue.ActorName, nil +} + +// ClearActorName clears the value of the "actor_name" field. +func (m *DisputeTimelineMutation) ClearActorName() { + m.actor_name = nil + m.clearedFields[disputetimeline.FieldActorName] = struct{}{} +} + +// ActorNameCleared returns if the "actor_name" field was cleared in this mutation. +func (m *DisputeTimelineMutation) ActorNameCleared() bool { + _, ok := m.clearedFields[disputetimeline.FieldActorName] + return ok +} + +// ResetActorName resets all changes to the "actor_name" field. +func (m *DisputeTimelineMutation) ResetActorName() { + m.actor_name = nil + delete(m.clearedFields, disputetimeline.FieldActorName) +} + +// SetDetails sets the "details" field. +func (m *DisputeTimelineMutation) SetDetails(value map[string]interface{}) { + m.details = &value +} + +// Details returns the value of the "details" field in the mutation. +func (m *DisputeTimelineMutation) Details() (r map[string]interface{}, exists bool) { + v := m.details + if v == nil { + return + } + return *v, true +} + +// OldDetails returns the old "details" field's value of the DisputeTimeline entity. +// If the DisputeTimeline 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 *DisputeTimelineMutation) OldDetails(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDetails is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDetails requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDetails: %w", err) + } + return oldValue.Details, nil +} + +// ClearDetails clears the value of the "details" field. +func (m *DisputeTimelineMutation) ClearDetails() { + m.details = nil + m.clearedFields[disputetimeline.FieldDetails] = struct{}{} +} + +// DetailsCleared returns if the "details" field was cleared in this mutation. +func (m *DisputeTimelineMutation) DetailsCleared() bool { + _, ok := m.clearedFields[disputetimeline.FieldDetails] + return ok +} + +// ResetDetails resets all changes to the "details" field. +func (m *DisputeTimelineMutation) ResetDetails() { + m.details = nil + delete(m.clearedFields, disputetimeline.FieldDetails) +} + +// SetCreatedAt sets the "created_at" field. +func (m *DisputeTimelineMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *DisputeTimelineMutation) 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 DisputeTimeline entity. +// If the DisputeTimeline 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 *DisputeTimelineMutation) 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 *DisputeTimelineMutation) ResetCreatedAt() { + m.created_at = nil +} + +// Where appends a list predicates to the DisputeTimelineMutation builder. +func (m *DisputeTimelineMutation) Where(ps ...predicate.DisputeTimeline) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the DisputeTimelineMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *DisputeTimelineMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.DisputeTimeline, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *DisputeTimelineMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *DisputeTimelineMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (DisputeTimeline). +func (m *DisputeTimelineMutation) 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 *DisputeTimelineMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.dispute_id != nil { + fields = append(fields, disputetimeline.FieldDisputeID) + } + if m.event_type != nil { + fields = append(fields, disputetimeline.FieldEventType) + } + if m.actor_id != nil { + fields = append(fields, disputetimeline.FieldActorID) + } + if m.actor_name != nil { + fields = append(fields, disputetimeline.FieldActorName) + } + if m.details != nil { + fields = append(fields, disputetimeline.FieldDetails) + } + if m.created_at != nil { + fields = append(fields, disputetimeline.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 *DisputeTimelineMutation) Field(name string) (ent.Value, bool) { + switch name { + case disputetimeline.FieldDisputeID: + return m.DisputeID() + case disputetimeline.FieldEventType: + return m.EventType() + case disputetimeline.FieldActorID: + return m.ActorID() + case disputetimeline.FieldActorName: + return m.ActorName() + case disputetimeline.FieldDetails: + return m.Details() + case disputetimeline.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 *DisputeTimelineMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case disputetimeline.FieldDisputeID: + return m.OldDisputeID(ctx) + case disputetimeline.FieldEventType: + return m.OldEventType(ctx) + case disputetimeline.FieldActorID: + return m.OldActorID(ctx) + case disputetimeline.FieldActorName: + return m.OldActorName(ctx) + case disputetimeline.FieldDetails: + return m.OldDetails(ctx) + case disputetimeline.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown DisputeTimeline 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 *DisputeTimelineMutation) SetField(name string, value ent.Value) error { + switch name { + case disputetimeline.FieldDisputeID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDisputeID(v) + return nil + case disputetimeline.FieldEventType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEventType(v) + return nil + case disputetimeline.FieldActorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActorID(v) + return nil + case disputetimeline.FieldActorName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetActorName(v) + return nil + case disputetimeline.FieldDetails: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDetails(v) + return nil + case disputetimeline.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 DisputeTimeline field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *DisputeTimelineMutation) AddedFields() []string { + var fields []string + if m.adddispute_id != nil { + fields = append(fields, disputetimeline.FieldDisputeID) + } + if m.addactor_id != nil { + fields = append(fields, disputetimeline.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 *DisputeTimelineMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case disputetimeline.FieldDisputeID: + return m.AddedDisputeID() + case disputetimeline.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 *DisputeTimelineMutation) AddField(name string, value ent.Value) error { + switch name { + case disputetimeline.FieldDisputeID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddDisputeID(v) + return nil + case disputetimeline.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 DisputeTimeline numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *DisputeTimelineMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(disputetimeline.FieldActorID) { + fields = append(fields, disputetimeline.FieldActorID) + } + if m.FieldCleared(disputetimeline.FieldActorName) { + fields = append(fields, disputetimeline.FieldActorName) + } + if m.FieldCleared(disputetimeline.FieldDetails) { + fields = append(fields, disputetimeline.FieldDetails) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *DisputeTimelineMutation) 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 *DisputeTimelineMutation) ClearField(name string) error { + switch name { + case disputetimeline.FieldActorID: + m.ClearActorID() + return nil + case disputetimeline.FieldActorName: + m.ClearActorName() + return nil + case disputetimeline.FieldDetails: + m.ClearDetails() + return nil + } + return fmt.Errorf("unknown DisputeTimeline 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 *DisputeTimelineMutation) ResetField(name string) error { + switch name { + case disputetimeline.FieldDisputeID: + m.ResetDisputeID() + return nil + case disputetimeline.FieldEventType: + m.ResetEventType() + return nil + case disputetimeline.FieldActorID: + m.ResetActorID() + return nil + case disputetimeline.FieldActorName: + m.ResetActorName() + return nil + case disputetimeline.FieldDetails: + m.ResetDetails() + return nil + case disputetimeline.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown DisputeTimeline field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *DisputeTimelineMutation) 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 *DisputeTimelineMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *DisputeTimelineMutation) 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 *DisputeTimelineMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *DisputeTimelineMutation) 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 *DisputeTimelineMutation) 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 *DisputeTimelineMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown DisputeTimeline 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 *DisputeTimelineMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown DisputeTimeline edge %s", name) +} + +// DisputesMutation represents an operation that mutates the Disputes nodes in the graph. +type DisputesMutation struct { + config + op Op + typ string + id *int64 + order_id *int64 + addorder_id *int64 + initiator_id *int64 + addinitiator_id *int64 + initiator_name *string + respondent_id *int64 + addrespondent_id *int64 + reason *string + evidence *types.TextArray + status *string + result *string + respondent_reason *string + respondent_evidence *types.TextArray + appeal_reason *string + appealed_at *time.Time + resolved_by *int64 + addresolved_by *int64 + resolved_at *time.Time + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Disputes, error) + predicates []predicate.Disputes +} + +var _ ent.Mutation = (*DisputesMutation)(nil) + +// disputesOption allows management of the mutation configuration using functional options. +type disputesOption func(*DisputesMutation) + +// newDisputesMutation creates new mutation for the Disputes entity. +func newDisputesMutation(c config, op Op, opts ...disputesOption) *DisputesMutation { + m := &DisputesMutation{ + config: c, + op: op, + typ: TypeDisputes, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withDisputesID sets the ID field of the mutation. +func withDisputesID(id int64) disputesOption { + return func(m *DisputesMutation) { + var ( + err error + once sync.Once + value *Disputes + ) + m.oldValue = func(ctx context.Context) (*Disputes, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Disputes.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withDisputes sets the old Disputes of the mutation. +func withDisputes(node *Disputes) disputesOption { + return func(m *DisputesMutation) { + m.oldValue = func(context.Context) (*Disputes, 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 DisputesMutation) 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 DisputesMutation) 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 Disputes entities. +func (m *DisputesMutation) 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 *DisputesMutation) 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 *DisputesMutation) 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().Disputes.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 *DisputesMutation) 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 *DisputesMutation) 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 Disputes entity. +// If the Disputes 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 *DisputesMutation) 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 *DisputesMutation) 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 *DisputesMutation) 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 *DisputesMutation) ResetOrderID() { + m.order_id = nil + m.addorder_id = nil +} + +// SetInitiatorID sets the "initiator_id" field. +func (m *DisputesMutation) SetInitiatorID(i int64) { + m.initiator_id = &i + m.addinitiator_id = nil +} + +// InitiatorID returns the value of the "initiator_id" field in the mutation. +func (m *DisputesMutation) InitiatorID() (r int64, exists bool) { + v := m.initiator_id + if v == nil { + return + } + return *v, true +} + +// OldInitiatorID returns the old "initiator_id" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldInitiatorID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInitiatorID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInitiatorID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInitiatorID: %w", err) + } + return oldValue.InitiatorID, nil +} + +// AddInitiatorID adds i to the "initiator_id" field. +func (m *DisputesMutation) AddInitiatorID(i int64) { + if m.addinitiator_id != nil { + *m.addinitiator_id += i + } else { + m.addinitiator_id = &i + } +} + +// AddedInitiatorID returns the value that was added to the "initiator_id" field in this mutation. +func (m *DisputesMutation) AddedInitiatorID() (r int64, exists bool) { + v := m.addinitiator_id + if v == nil { + return + } + return *v, true +} + +// ResetInitiatorID resets all changes to the "initiator_id" field. +func (m *DisputesMutation) ResetInitiatorID() { + m.initiator_id = nil + m.addinitiator_id = nil +} + +// SetInitiatorName sets the "initiator_name" field. +func (m *DisputesMutation) SetInitiatorName(s string) { + m.initiator_name = &s +} + +// InitiatorName returns the value of the "initiator_name" field in the mutation. +func (m *DisputesMutation) InitiatorName() (r string, exists bool) { + v := m.initiator_name + if v == nil { + return + } + return *v, true +} + +// OldInitiatorName returns the old "initiator_name" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldInitiatorName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInitiatorName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInitiatorName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInitiatorName: %w", err) + } + return oldValue.InitiatorName, nil +} + +// ResetInitiatorName resets all changes to the "initiator_name" field. +func (m *DisputesMutation) ResetInitiatorName() { + m.initiator_name = nil +} + +// SetRespondentID sets the "respondent_id" field. +func (m *DisputesMutation) SetRespondentID(i int64) { + m.respondent_id = &i + m.addrespondent_id = nil +} + +// RespondentID returns the value of the "respondent_id" field in the mutation. +func (m *DisputesMutation) RespondentID() (r int64, exists bool) { + v := m.respondent_id + if v == nil { + return + } + return *v, true +} + +// OldRespondentID returns the old "respondent_id" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldRespondentID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRespondentID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRespondentID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRespondentID: %w", err) + } + return oldValue.RespondentID, nil +} + +// AddRespondentID adds i to the "respondent_id" field. +func (m *DisputesMutation) AddRespondentID(i int64) { + if m.addrespondent_id != nil { + *m.addrespondent_id += i + } else { + m.addrespondent_id = &i + } +} + +// AddedRespondentID returns the value that was added to the "respondent_id" field in this mutation. +func (m *DisputesMutation) AddedRespondentID() (r int64, exists bool) { + v := m.addrespondent_id + if v == nil { + return + } + return *v, true +} + +// ResetRespondentID resets all changes to the "respondent_id" field. +func (m *DisputesMutation) ResetRespondentID() { + m.respondent_id = nil + m.addrespondent_id = nil +} + +// SetReason sets the "reason" field. +func (m *DisputesMutation) SetReason(s string) { + m.reason = &s +} + +// Reason returns the value of the "reason" field in the mutation. +func (m *DisputesMutation) Reason() (r string, exists bool) { + v := m.reason + if v == nil { + return + } + return *v, true +} + +// OldReason returns the old "reason" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldReason(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReason: %w", err) + } + return oldValue.Reason, nil +} + +// ResetReason resets all changes to the "reason" field. +func (m *DisputesMutation) ResetReason() { + m.reason = nil +} + +// SetEvidence sets the "evidence" field. +func (m *DisputesMutation) SetEvidence(ta types.TextArray) { + m.evidence = &ta +} + +// Evidence returns the value of the "evidence" field in the mutation. +func (m *DisputesMutation) Evidence() (r types.TextArray, exists bool) { + v := m.evidence + if v == nil { + return + } + return *v, true +} + +// OldEvidence returns the old "evidence" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldEvidence(ctx context.Context) (v types.TextArray, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEvidence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEvidence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEvidence: %w", err) + } + return oldValue.Evidence, nil +} + +// ClearEvidence clears the value of the "evidence" field. +func (m *DisputesMutation) ClearEvidence() { + m.evidence = nil + m.clearedFields[disputes.FieldEvidence] = struct{}{} +} + +// EvidenceCleared returns if the "evidence" field was cleared in this mutation. +func (m *DisputesMutation) EvidenceCleared() bool { + _, ok := m.clearedFields[disputes.FieldEvidence] + return ok +} + +// ResetEvidence resets all changes to the "evidence" field. +func (m *DisputesMutation) ResetEvidence() { + m.evidence = nil + delete(m.clearedFields, disputes.FieldEvidence) +} + +// SetStatus sets the "status" field. +func (m *DisputesMutation) SetStatus(s string) { + m.status = &s +} + +// Status returns the value of the "status" field in the mutation. +func (m *DisputesMutation) 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 Disputes entity. +// If the Disputes 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 *DisputesMutation) 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 *DisputesMutation) ResetStatus() { + m.status = nil +} + +// SetResult sets the "result" field. +func (m *DisputesMutation) SetResult(s string) { + m.result = &s +} + +// Result returns the value of the "result" field in the mutation. +func (m *DisputesMutation) Result() (r string, exists bool) { + v := m.result + if v == nil { + return + } + return *v, true +} + +// OldResult returns the old "result" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldResult(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResult is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResult requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResult: %w", err) + } + return oldValue.Result, nil +} + +// ClearResult clears the value of the "result" field. +func (m *DisputesMutation) ClearResult() { + m.result = nil + m.clearedFields[disputes.FieldResult] = struct{}{} +} + +// ResultCleared returns if the "result" field was cleared in this mutation. +func (m *DisputesMutation) ResultCleared() bool { + _, ok := m.clearedFields[disputes.FieldResult] + return ok +} + +// ResetResult resets all changes to the "result" field. +func (m *DisputesMutation) ResetResult() { + m.result = nil + delete(m.clearedFields, disputes.FieldResult) +} + +// SetRespondentReason sets the "respondent_reason" field. +func (m *DisputesMutation) SetRespondentReason(s string) { + m.respondent_reason = &s +} + +// RespondentReason returns the value of the "respondent_reason" field in the mutation. +func (m *DisputesMutation) RespondentReason() (r string, exists bool) { + v := m.respondent_reason + if v == nil { + return + } + return *v, true +} + +// OldRespondentReason returns the old "respondent_reason" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldRespondentReason(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRespondentReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRespondentReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRespondentReason: %w", err) + } + return oldValue.RespondentReason, nil +} + +// ClearRespondentReason clears the value of the "respondent_reason" field. +func (m *DisputesMutation) ClearRespondentReason() { + m.respondent_reason = nil + m.clearedFields[disputes.FieldRespondentReason] = struct{}{} +} + +// RespondentReasonCleared returns if the "respondent_reason" field was cleared in this mutation. +func (m *DisputesMutation) RespondentReasonCleared() bool { + _, ok := m.clearedFields[disputes.FieldRespondentReason] + return ok +} + +// ResetRespondentReason resets all changes to the "respondent_reason" field. +func (m *DisputesMutation) ResetRespondentReason() { + m.respondent_reason = nil + delete(m.clearedFields, disputes.FieldRespondentReason) +} + +// SetRespondentEvidence sets the "respondent_evidence" field. +func (m *DisputesMutation) SetRespondentEvidence(ta types.TextArray) { + m.respondent_evidence = &ta +} + +// RespondentEvidence returns the value of the "respondent_evidence" field in the mutation. +func (m *DisputesMutation) RespondentEvidence() (r types.TextArray, exists bool) { + v := m.respondent_evidence + if v == nil { + return + } + return *v, true +} + +// OldRespondentEvidence returns the old "respondent_evidence" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldRespondentEvidence(ctx context.Context) (v types.TextArray, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRespondentEvidence is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRespondentEvidence requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRespondentEvidence: %w", err) + } + return oldValue.RespondentEvidence, nil +} + +// ClearRespondentEvidence clears the value of the "respondent_evidence" field. +func (m *DisputesMutation) ClearRespondentEvidence() { + m.respondent_evidence = nil + m.clearedFields[disputes.FieldRespondentEvidence] = struct{}{} +} + +// RespondentEvidenceCleared returns if the "respondent_evidence" field was cleared in this mutation. +func (m *DisputesMutation) RespondentEvidenceCleared() bool { + _, ok := m.clearedFields[disputes.FieldRespondentEvidence] + return ok +} + +// ResetRespondentEvidence resets all changes to the "respondent_evidence" field. +func (m *DisputesMutation) ResetRespondentEvidence() { + m.respondent_evidence = nil + delete(m.clearedFields, disputes.FieldRespondentEvidence) +} + +// SetAppealReason sets the "appeal_reason" field. +func (m *DisputesMutation) SetAppealReason(s string) { + m.appeal_reason = &s +} + +// AppealReason returns the value of the "appeal_reason" field in the mutation. +func (m *DisputesMutation) AppealReason() (r string, exists bool) { + v := m.appeal_reason + if v == nil { + return + } + return *v, true +} + +// OldAppealReason returns the old "appeal_reason" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldAppealReason(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAppealReason is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAppealReason requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAppealReason: %w", err) + } + return oldValue.AppealReason, nil +} + +// ClearAppealReason clears the value of the "appeal_reason" field. +func (m *DisputesMutation) ClearAppealReason() { + m.appeal_reason = nil + m.clearedFields[disputes.FieldAppealReason] = struct{}{} +} + +// AppealReasonCleared returns if the "appeal_reason" field was cleared in this mutation. +func (m *DisputesMutation) AppealReasonCleared() bool { + _, ok := m.clearedFields[disputes.FieldAppealReason] + return ok +} + +// ResetAppealReason resets all changes to the "appeal_reason" field. +func (m *DisputesMutation) ResetAppealReason() { + m.appeal_reason = nil + delete(m.clearedFields, disputes.FieldAppealReason) +} + +// SetAppealedAt sets the "appealed_at" field. +func (m *DisputesMutation) SetAppealedAt(t time.Time) { + m.appealed_at = &t +} + +// AppealedAt returns the value of the "appealed_at" field in the mutation. +func (m *DisputesMutation) AppealedAt() (r time.Time, exists bool) { + v := m.appealed_at + if v == nil { + return + } + return *v, true +} + +// OldAppealedAt returns the old "appealed_at" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldAppealedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAppealedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAppealedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAppealedAt: %w", err) + } + return oldValue.AppealedAt, nil +} + +// ClearAppealedAt clears the value of the "appealed_at" field. +func (m *DisputesMutation) ClearAppealedAt() { + m.appealed_at = nil + m.clearedFields[disputes.FieldAppealedAt] = struct{}{} +} + +// AppealedAtCleared returns if the "appealed_at" field was cleared in this mutation. +func (m *DisputesMutation) AppealedAtCleared() bool { + _, ok := m.clearedFields[disputes.FieldAppealedAt] + return ok +} + +// ResetAppealedAt resets all changes to the "appealed_at" field. +func (m *DisputesMutation) ResetAppealedAt() { + m.appealed_at = nil + delete(m.clearedFields, disputes.FieldAppealedAt) +} + +// SetResolvedBy sets the "resolved_by" field. +func (m *DisputesMutation) SetResolvedBy(i int64) { + m.resolved_by = &i + m.addresolved_by = nil +} + +// ResolvedBy returns the value of the "resolved_by" field in the mutation. +func (m *DisputesMutation) ResolvedBy() (r int64, exists bool) { + v := m.resolved_by + if v == nil { + return + } + return *v, true +} + +// OldResolvedBy returns the old "resolved_by" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldResolvedBy(ctx context.Context) (v *int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResolvedBy is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResolvedBy requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResolvedBy: %w", err) + } + return oldValue.ResolvedBy, nil +} + +// AddResolvedBy adds i to the "resolved_by" field. +func (m *DisputesMutation) AddResolvedBy(i int64) { + if m.addresolved_by != nil { + *m.addresolved_by += i + } else { + m.addresolved_by = &i + } +} + +// AddedResolvedBy returns the value that was added to the "resolved_by" field in this mutation. +func (m *DisputesMutation) AddedResolvedBy() (r int64, exists bool) { + v := m.addresolved_by + if v == nil { + return + } + return *v, true +} + +// ClearResolvedBy clears the value of the "resolved_by" field. +func (m *DisputesMutation) ClearResolvedBy() { + m.resolved_by = nil + m.addresolved_by = nil + m.clearedFields[disputes.FieldResolvedBy] = struct{}{} +} + +// ResolvedByCleared returns if the "resolved_by" field was cleared in this mutation. +func (m *DisputesMutation) ResolvedByCleared() bool { + _, ok := m.clearedFields[disputes.FieldResolvedBy] + return ok +} + +// ResetResolvedBy resets all changes to the "resolved_by" field. +func (m *DisputesMutation) ResetResolvedBy() { + m.resolved_by = nil + m.addresolved_by = nil + delete(m.clearedFields, disputes.FieldResolvedBy) +} + +// SetResolvedAt sets the "resolved_at" field. +func (m *DisputesMutation) SetResolvedAt(t time.Time) { + m.resolved_at = &t +} + +// ResolvedAt returns the value of the "resolved_at" field in the mutation. +func (m *DisputesMutation) ResolvedAt() (r time.Time, exists bool) { + v := m.resolved_at + if v == nil { + return + } + return *v, true +} + +// OldResolvedAt returns the old "resolved_at" field's value of the Disputes entity. +// If the Disputes 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 *DisputesMutation) OldResolvedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldResolvedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldResolvedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldResolvedAt: %w", err) + } + return oldValue.ResolvedAt, nil +} + +// ClearResolvedAt clears the value of the "resolved_at" field. +func (m *DisputesMutation) ClearResolvedAt() { + m.resolved_at = nil + m.clearedFields[disputes.FieldResolvedAt] = struct{}{} +} + +// ResolvedAtCleared returns if the "resolved_at" field was cleared in this mutation. +func (m *DisputesMutation) ResolvedAtCleared() bool { + _, ok := m.clearedFields[disputes.FieldResolvedAt] + return ok +} + +// ResetResolvedAt resets all changes to the "resolved_at" field. +func (m *DisputesMutation) ResetResolvedAt() { + m.resolved_at = nil + delete(m.clearedFields, disputes.FieldResolvedAt) +} + +// SetCreatedAt sets the "created_at" field. +func (m *DisputesMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *DisputesMutation) 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 Disputes entity. +// If the Disputes 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 *DisputesMutation) 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 *DisputesMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *DisputesMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *DisputesMutation) 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 Disputes entity. +// If the Disputes 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 *DisputesMutation) 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 *DisputesMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the DisputesMutation builder. +func (m *DisputesMutation) Where(ps ...predicate.Disputes) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the DisputesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *DisputesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Disputes, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *DisputesMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *DisputesMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Disputes). +func (m *DisputesMutation) 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 *DisputesMutation) Fields() []string { + fields := make([]string, 0, 16) + if m.order_id != nil { + fields = append(fields, disputes.FieldOrderID) + } + if m.initiator_id != nil { + fields = append(fields, disputes.FieldInitiatorID) + } + if m.initiator_name != nil { + fields = append(fields, disputes.FieldInitiatorName) + } + if m.respondent_id != nil { + fields = append(fields, disputes.FieldRespondentID) + } + if m.reason != nil { + fields = append(fields, disputes.FieldReason) + } + if m.evidence != nil { + fields = append(fields, disputes.FieldEvidence) + } + if m.status != nil { + fields = append(fields, disputes.FieldStatus) + } + if m.result != nil { + fields = append(fields, disputes.FieldResult) + } + if m.respondent_reason != nil { + fields = append(fields, disputes.FieldRespondentReason) + } + if m.respondent_evidence != nil { + fields = append(fields, disputes.FieldRespondentEvidence) + } + if m.appeal_reason != nil { + fields = append(fields, disputes.FieldAppealReason) + } + if m.appealed_at != nil { + fields = append(fields, disputes.FieldAppealedAt) + } + if m.resolved_by != nil { + fields = append(fields, disputes.FieldResolvedBy) + } + if m.resolved_at != nil { + fields = append(fields, disputes.FieldResolvedAt) + } + if m.created_at != nil { + fields = append(fields, disputes.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, disputes.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 *DisputesMutation) Field(name string) (ent.Value, bool) { + switch name { + case disputes.FieldOrderID: + return m.OrderID() + case disputes.FieldInitiatorID: + return m.InitiatorID() + case disputes.FieldInitiatorName: + return m.InitiatorName() + case disputes.FieldRespondentID: + return m.RespondentID() + case disputes.FieldReason: + return m.Reason() + case disputes.FieldEvidence: + return m.Evidence() + case disputes.FieldStatus: + return m.Status() + case disputes.FieldResult: + return m.Result() + case disputes.FieldRespondentReason: + return m.RespondentReason() + case disputes.FieldRespondentEvidence: + return m.RespondentEvidence() + case disputes.FieldAppealReason: + return m.AppealReason() + case disputes.FieldAppealedAt: + return m.AppealedAt() + case disputes.FieldResolvedBy: + return m.ResolvedBy() + case disputes.FieldResolvedAt: + return m.ResolvedAt() + case disputes.FieldCreatedAt: + return m.CreatedAt() + case disputes.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 *DisputesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case disputes.FieldOrderID: + return m.OldOrderID(ctx) + case disputes.FieldInitiatorID: + return m.OldInitiatorID(ctx) + case disputes.FieldInitiatorName: + return m.OldInitiatorName(ctx) + case disputes.FieldRespondentID: + return m.OldRespondentID(ctx) + case disputes.FieldReason: + return m.OldReason(ctx) + case disputes.FieldEvidence: + return m.OldEvidence(ctx) + case disputes.FieldStatus: + return m.OldStatus(ctx) + case disputes.FieldResult: + return m.OldResult(ctx) + case disputes.FieldRespondentReason: + return m.OldRespondentReason(ctx) + case disputes.FieldRespondentEvidence: + return m.OldRespondentEvidence(ctx) + case disputes.FieldAppealReason: + return m.OldAppealReason(ctx) + case disputes.FieldAppealedAt: + return m.OldAppealedAt(ctx) + case disputes.FieldResolvedBy: + return m.OldResolvedBy(ctx) + case disputes.FieldResolvedAt: + return m.OldResolvedAt(ctx) + case disputes.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case disputes.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Disputes 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 *DisputesMutation) SetField(name string, value ent.Value) error { + switch name { + case disputes.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOrderID(v) + return nil + case disputes.FieldInitiatorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInitiatorID(v) + return nil + case disputes.FieldInitiatorName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInitiatorName(v) + return nil + case disputes.FieldRespondentID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRespondentID(v) + return nil + case disputes.FieldReason: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReason(v) + return nil + case disputes.FieldEvidence: + v, ok := value.(types.TextArray) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEvidence(v) + return nil + case disputes.FieldStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case disputes.FieldResult: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResult(v) + return nil + case disputes.FieldRespondentReason: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRespondentReason(v) + return nil + case disputes.FieldRespondentEvidence: + v, ok := value.(types.TextArray) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRespondentEvidence(v) + return nil + case disputes.FieldAppealReason: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAppealReason(v) + return nil + case disputes.FieldAppealedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAppealedAt(v) + return nil + case disputes.FieldResolvedBy: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResolvedBy(v) + return nil + case disputes.FieldResolvedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetResolvedAt(v) + return nil + case disputes.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 disputes.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 Disputes field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *DisputesMutation) AddedFields() []string { + var fields []string + if m.addorder_id != nil { + fields = append(fields, disputes.FieldOrderID) + } + if m.addinitiator_id != nil { + fields = append(fields, disputes.FieldInitiatorID) + } + if m.addrespondent_id != nil { + fields = append(fields, disputes.FieldRespondentID) + } + if m.addresolved_by != nil { + fields = append(fields, disputes.FieldResolvedBy) + } + 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 *DisputesMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case disputes.FieldOrderID: + return m.AddedOrderID() + case disputes.FieldInitiatorID: + return m.AddedInitiatorID() + case disputes.FieldRespondentID: + return m.AddedRespondentID() + case disputes.FieldResolvedBy: + return m.AddedResolvedBy() + } + 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 *DisputesMutation) AddField(name string, value ent.Value) error { + switch name { + case disputes.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOrderID(v) + return nil + case disputes.FieldInitiatorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddInitiatorID(v) + return nil + case disputes.FieldRespondentID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRespondentID(v) + return nil + case disputes.FieldResolvedBy: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddResolvedBy(v) + return nil + } + return fmt.Errorf("unknown Disputes numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *DisputesMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(disputes.FieldEvidence) { + fields = append(fields, disputes.FieldEvidence) + } + if m.FieldCleared(disputes.FieldResult) { + fields = append(fields, disputes.FieldResult) + } + if m.FieldCleared(disputes.FieldRespondentReason) { + fields = append(fields, disputes.FieldRespondentReason) + } + if m.FieldCleared(disputes.FieldRespondentEvidence) { + fields = append(fields, disputes.FieldRespondentEvidence) + } + if m.FieldCleared(disputes.FieldAppealReason) { + fields = append(fields, disputes.FieldAppealReason) + } + if m.FieldCleared(disputes.FieldAppealedAt) { + fields = append(fields, disputes.FieldAppealedAt) + } + if m.FieldCleared(disputes.FieldResolvedBy) { + fields = append(fields, disputes.FieldResolvedBy) + } + if m.FieldCleared(disputes.FieldResolvedAt) { + fields = append(fields, disputes.FieldResolvedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *DisputesMutation) 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 *DisputesMutation) ClearField(name string) error { + switch name { + case disputes.FieldEvidence: + m.ClearEvidence() + return nil + case disputes.FieldResult: + m.ClearResult() + return nil + case disputes.FieldRespondentReason: + m.ClearRespondentReason() + return nil + case disputes.FieldRespondentEvidence: + m.ClearRespondentEvidence() + return nil + case disputes.FieldAppealReason: + m.ClearAppealReason() + return nil + case disputes.FieldAppealedAt: + m.ClearAppealedAt() + return nil + case disputes.FieldResolvedBy: + m.ClearResolvedBy() + return nil + case disputes.FieldResolvedAt: + m.ClearResolvedAt() + return nil + } + return fmt.Errorf("unknown Disputes 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 *DisputesMutation) ResetField(name string) error { + switch name { + case disputes.FieldOrderID: + m.ResetOrderID() + return nil + case disputes.FieldInitiatorID: + m.ResetInitiatorID() + return nil + case disputes.FieldInitiatorName: + m.ResetInitiatorName() + return nil + case disputes.FieldRespondentID: + m.ResetRespondentID() + return nil + case disputes.FieldReason: + m.ResetReason() + return nil + case disputes.FieldEvidence: + m.ResetEvidence() + return nil + case disputes.FieldStatus: + m.ResetStatus() + return nil + case disputes.FieldResult: + m.ResetResult() + return nil + case disputes.FieldRespondentReason: + m.ResetRespondentReason() + return nil + case disputes.FieldRespondentEvidence: + m.ResetRespondentEvidence() + return nil + case disputes.FieldAppealReason: + m.ResetAppealReason() + return nil + case disputes.FieldAppealedAt: + m.ResetAppealedAt() + return nil + case disputes.FieldResolvedBy: + m.ResetResolvedBy() + return nil + case disputes.FieldResolvedAt: + m.ResetResolvedAt() + return nil + case disputes.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case disputes.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Disputes field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *DisputesMutation) 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 *DisputesMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *DisputesMutation) 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 *DisputesMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *DisputesMutation) 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 *DisputesMutation) 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 *DisputesMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Disputes 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 *DisputesMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Disputes edge %s", name) +} diff --git a/app/dispute/rpc/internal/models/predicate/predicate.go b/app/dispute/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..9bb7121 --- /dev/null +++ b/app/dispute/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" +) + +// DisputeTimeline is the predicate function for disputetimeline builders. +type DisputeTimeline func(*sql.Selector) + +// Disputes is the predicate function for disputes builders. +type Disputes func(*sql.Selector) diff --git a/app/dispute/rpc/internal/models/runtime.go b/app/dispute/rpc/internal/models/runtime.go new file mode 100644 index 0000000..3e37dae --- /dev/null +++ b/app/dispute/rpc/internal/models/runtime.go @@ -0,0 +1,56 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/dispute/rpc/internal/models/disputes" + "juwan-backend/app/dispute/rpc/internal/models/disputetimeline" + "juwan-backend/app/dispute/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() { + disputetimelineFields := schema.DisputeTimeline{}.Fields() + _ = disputetimelineFields + // disputetimelineDescEventType is the schema descriptor for event_type field. + disputetimelineDescEventType := disputetimelineFields[2].Descriptor() + // disputetimeline.EventTypeValidator is a validator for the "event_type" field. It is called by the builders before save. + disputetimeline.EventTypeValidator = disputetimelineDescEventType.Validators[0].(func(string) error) + // disputetimelineDescActorName is the schema descriptor for actor_name field. + disputetimelineDescActorName := disputetimelineFields[4].Descriptor() + // disputetimeline.ActorNameValidator is a validator for the "actor_name" field. It is called by the builders before save. + disputetimeline.ActorNameValidator = disputetimelineDescActorName.Validators[0].(func(string) error) + // disputetimelineDescCreatedAt is the schema descriptor for created_at field. + disputetimelineDescCreatedAt := disputetimelineFields[6].Descriptor() + // disputetimeline.DefaultCreatedAt holds the default value on creation for the created_at field. + disputetimeline.DefaultCreatedAt = disputetimelineDescCreatedAt.Default.(func() time.Time) + disputesFields := schema.Disputes{}.Fields() + _ = disputesFields + // disputesDescInitiatorName is the schema descriptor for initiator_name field. + disputesDescInitiatorName := disputesFields[3].Descriptor() + // disputes.InitiatorNameValidator is a validator for the "initiator_name" field. It is called by the builders before save. + disputes.InitiatorNameValidator = disputesDescInitiatorName.Validators[0].(func(string) error) + // disputesDescStatus is the schema descriptor for status field. + disputesDescStatus := disputesFields[7].Descriptor() + // disputes.DefaultStatus holds the default value on creation for the status field. + disputes.DefaultStatus = disputesDescStatus.Default.(string) + // disputes.StatusValidator is a validator for the "status" field. It is called by the builders before save. + disputes.StatusValidator = disputesDescStatus.Validators[0].(func(string) error) + // disputesDescResult is the schema descriptor for result field. + disputesDescResult := disputesFields[8].Descriptor() + // disputes.ResultValidator is a validator for the "result" field. It is called by the builders before save. + disputes.ResultValidator = disputesDescResult.Validators[0].(func(string) error) + // disputesDescCreatedAt is the schema descriptor for created_at field. + disputesDescCreatedAt := disputesFields[15].Descriptor() + // disputes.DefaultCreatedAt holds the default value on creation for the created_at field. + disputes.DefaultCreatedAt = disputesDescCreatedAt.Default.(func() time.Time) + // disputesDescUpdatedAt is the schema descriptor for updated_at field. + disputesDescUpdatedAt := disputesFields[16].Descriptor() + // disputes.DefaultUpdatedAt holds the default value on creation for the updated_at field. + disputes.DefaultUpdatedAt = disputesDescUpdatedAt.Default.(func() time.Time) + // disputes.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + disputes.UpdateDefaultUpdatedAt = disputesDescUpdatedAt.UpdateDefault.(func() time.Time) +} diff --git a/app/dispute/rpc/internal/models/runtime/runtime.go b/app/dispute/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..cebd898 --- /dev/null +++ b/app/dispute/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/dispute/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/dispute/rpc/internal/models/schema/dispute_timeline.go b/app/dispute/rpc/internal/models/schema/dispute_timeline.go new file mode 100644 index 0000000..3ad603b --- /dev/null +++ b/app/dispute/rpc/internal/models/schema/dispute_timeline.go @@ -0,0 +1,46 @@ +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" + "entgo.io/ent/schema/index" +) + +type DisputeTimeline struct { + ent.Schema +} + +func (DisputeTimeline) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("dispute_timeline"), + } +} + +func (DisputeTimeline) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Unique().Immutable(), + field.Int64("dispute_id"), + field.String("event_type").MaxLen(30), + field.Int64("actor_id").Optional(), + field.String("actor_name").MaxLen(100).Optional(), + field.JSON("details", map[string]any{}). + SchemaType(map[string]string{dialect.Postgres: "jsonb"}). + Optional(), + field.Time("created_at").Default(time.Now).Immutable(), + } +} + +func (DisputeTimeline) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("dispute_id", "created_at"), + } +} + +func (DisputeTimeline) Edges() []ent.Edge { + return nil +} diff --git a/app/dispute/rpc/internal/models/schema/disputes.go b/app/dispute/rpc/internal/models/schema/disputes.go new file mode 100644 index 0000000..03de9ab --- /dev/null +++ b/app/dispute/rpc/internal/models/schema/disputes.go @@ -0,0 +1,56 @@ +package schema + +import ( + "time" + + "juwan-backend/pkg/types" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type Disputes struct { + ent.Schema +} + +func (Disputes) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Unique().Immutable(), + field.Int64("order_id").Unique(), + field.Int64("initiator_id"), + field.String("initiator_name").MaxLen(100), + field.Int64("respondent_id"), + field.String("reason"), + field.Other("evidence", types.TextArray{}). + SchemaType(map[string]string{dialect.Postgres: "text[]"}). + Optional(), + field.String("status").MaxLen(20).Default("open"), + field.String("result").MaxLen(30).Optional().Nillable(), + field.String("respondent_reason").Optional().Nillable(), + field.Other("respondent_evidence", types.TextArray{}). + SchemaType(map[string]string{dialect.Postgres: "text[]"}). + Optional(), + field.String("appeal_reason").Optional().Nillable(), + field.Time("appealed_at").Optional().Nillable(), + field.Int64("resolved_by").Optional().Nillable(), + field.Time("resolved_at").Optional().Nillable(), + field.Time("created_at").Default(time.Now).Immutable(), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +func (Disputes) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("order_id"), + index.Fields("status", "created_at"), + index.Fields("initiator_id"), + index.Fields("initiator_id", "status", "created_at"), + index.Fields("respondent_id", "status", "created_at"), + } +} + +func (Disputes) Edges() []ent.Edge { + return nil +} diff --git a/app/dispute/rpc/internal/models/tx.go b/app/dispute/rpc/internal/models/tx.go new file mode 100644 index 0000000..cff482e --- /dev/null +++ b/app/dispute/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 + // DisputeTimeline is the client for interacting with the DisputeTimeline builders. + DisputeTimeline *DisputeTimelineClient + // Disputes is the client for interacting with the Disputes builders. + Disputes *DisputesClient + + // 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.DisputeTimeline = NewDisputeTimelineClient(tx.config) + tx.Disputes = NewDisputesClient(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: DisputeTimeline.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/dispute/rpc/internal/server/disputeServiceServer.go b/app/dispute/rpc/internal/server/disputeServiceServer.go new file mode 100644 index 0000000..73ac2d8 --- /dev/null +++ b/app/dispute/rpc/internal/server/disputeServiceServer.go @@ -0,0 +1,61 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: dispute.proto + +package server + +import ( + "context" + + "juwan-backend/app/dispute/rpc/internal/logic" + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/rpc/pb" +) + +type DisputeServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedDisputeServiceServer +} + +func NewDisputeServiceServer(svcCtx *svc.ServiceContext) *DisputeServiceServer { + return &DisputeServiceServer{ + svcCtx: svcCtx, + } +} + +// -----------------------disputes----------------------- +func (s *DisputeServiceServer) AddDisputes(ctx context.Context, in *pb.AddDisputesReq) (*pb.AddDisputesResp, error) { + l := logic.NewAddDisputesLogic(ctx, s.svcCtx) + return l.AddDisputes(in) +} + +func (s *DisputeServiceServer) UpdateDisputes(ctx context.Context, in *pb.UpdateDisputesReq) (*pb.UpdateDisputesResp, error) { + l := logic.NewUpdateDisputesLogic(ctx, s.svcCtx) + return l.UpdateDisputes(in) +} + +func (s *DisputeServiceServer) DelDisputes(ctx context.Context, in *pb.DelDisputesReq) (*pb.DelDisputesResp, error) { + l := logic.NewDelDisputesLogic(ctx, s.svcCtx) + return l.DelDisputes(in) +} + +func (s *DisputeServiceServer) GetDisputesById(ctx context.Context, in *pb.GetDisputesByIdReq) (*pb.GetDisputesByIdResp, error) { + l := logic.NewGetDisputesByIdLogic(ctx, s.svcCtx) + return l.GetDisputesById(in) +} + +func (s *DisputeServiceServer) SearchDisputes(ctx context.Context, in *pb.SearchDisputesReq) (*pb.SearchDisputesResp, error) { + l := logic.NewSearchDisputesLogic(ctx, s.svcCtx) + return l.SearchDisputes(in) +} + +// -----------------------disputeTimeline----------------------- +func (s *DisputeServiceServer) AddDisputeTimeline(ctx context.Context, in *pb.AddDisputeTimelineReq) (*pb.AddDisputeTimelineResp, error) { + l := logic.NewAddDisputeTimelineLogic(ctx, s.svcCtx) + return l.AddDisputeTimeline(in) +} + +func (s *DisputeServiceServer) SearchDisputeTimeline(ctx context.Context, in *pb.SearchDisputeTimelineReq) (*pb.SearchDisputeTimelineResp, error) { + l := logic.NewSearchDisputeTimelineLogic(ctx, s.svcCtx) + return l.SearchDisputeTimeline(in) +} diff --git a/app/dispute/rpc/internal/svc/serviceContext.go b/app/dispute/rpc/internal/svc/serviceContext.go new file mode 100644 index 0000000..ffa46be --- /dev/null +++ b/app/dispute/rpc/internal/svc/serviceContext.go @@ -0,0 +1,53 @@ +package svc + +import ( + stdsql "database/sql" + "time" + + "juwan-backend/app/dispute/rpc/internal/config" + "juwan-backend/app/dispute/rpc/internal/models" + "juwan-backend/app/snowflake/rpc/snowflake" + "juwan-backend/common/redisx" + "juwan-backend/common/snowflakex" + "juwan-backend/pkg/adapter" + + "ariga.io/entcache" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + + _ "github.com/jackc/pgx/v5/stdlib" +) + +type ServiceContext struct { + Config config.Config + Snowflake snowflake.SnowflakeServiceClient + DisputeModelRW *models.Client + DisputeModelRO *models.Client +} + +func NewServiceContext(c config.Config) *ServiceContext { + rawRW, err := stdsql.Open("pgx", c.DB.Master) + if err != nil { + panic(err) + } + rawRO, err := stdsql.Open("pgx", c.DB.Slaves) + if err != nil { + panic(err) + } + RWConn := sql.OpenDB(dialect.Postgres, rawRW) + ROConn := sql.OpenDB(dialect.Postgres, rawRO) + + redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second) + if redisCluster == nil || err != nil { + 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))) + return &ServiceContext{ + Config: c, + DisputeModelRW: models.NewClient(models.Driver(RWDrv)), + DisputeModelRO: models.NewClient(models.Driver(RODrv)), + Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), + } +} diff --git a/app/dispute/rpc/pb.go b/app/dispute/rpc/pb.go new file mode 100644 index 0000000..854aa5a --- /dev/null +++ b/app/dispute/rpc/pb.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/dispute/rpc/internal/config" + "juwan-backend/app/dispute/rpc/internal/server" + "juwan-backend/app/dispute/rpc/internal/svc" + "juwan-backend/app/dispute/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.RegisterDisputeServiceServer(grpcServer, server.NewDisputeServiceServer(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/dispute/rpc/pb/dispute.pb.go b/app/dispute/rpc/pb/dispute.pb.go new file mode 100644 index 0000000..35fb453 --- /dev/null +++ b/app/dispute/rpc/pb/dispute.pb.go @@ -0,0 +1,1290 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v7.34.1 +// source: dispute.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) +) + +// --------------------------------disputes-------------------------------- +type Disputes struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + OrderId int64 `protobuf:"varint,2,opt,name=orderId,proto3" json:"orderId,omitempty"` + InitiatorId int64 `protobuf:"varint,3,opt,name=initiatorId,proto3" json:"initiatorId,omitempty"` + InitiatorName string `protobuf:"bytes,4,opt,name=initiatorName,proto3" json:"initiatorName,omitempty"` + RespondentId int64 `protobuf:"varint,5,opt,name=respondentId,proto3" json:"respondentId,omitempty"` + Reason string `protobuf:"bytes,6,opt,name=reason,proto3" json:"reason,omitempty"` + Evidence []string `protobuf:"bytes,7,rep,name=evidence,proto3" json:"evidence,omitempty"` + Status string `protobuf:"bytes,8,opt,name=status,proto3" json:"status,omitempty"` + Result string `protobuf:"bytes,9,opt,name=result,proto3" json:"result,omitempty"` + RespondentReason string `protobuf:"bytes,10,opt,name=respondentReason,proto3" json:"respondentReason,omitempty"` + RespondentEvidence []string `protobuf:"bytes,11,rep,name=respondentEvidence,proto3" json:"respondentEvidence,omitempty"` + AppealReason string `protobuf:"bytes,12,opt,name=appealReason,proto3" json:"appealReason,omitempty"` + AppealedAt int64 `protobuf:"varint,13,opt,name=appealedAt,proto3" json:"appealedAt,omitempty"` + ResolvedBy int64 `protobuf:"varint,14,opt,name=resolvedBy,proto3" json:"resolvedBy,omitempty"` + ResolvedAt int64 `protobuf:"varint,15,opt,name=resolvedAt,proto3" json:"resolvedAt,omitempty"` + CreatedAt int64 `protobuf:"varint,16,opt,name=createdAt,proto3" json:"createdAt,omitempty"` + UpdatedAt int64 `protobuf:"varint,17,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Disputes) Reset() { + *x = Disputes{} + mi := &file_dispute_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Disputes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Disputes) ProtoMessage() {} + +func (x *Disputes) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 Disputes.ProtoReflect.Descriptor instead. +func (*Disputes) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{0} +} + +func (x *Disputes) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Disputes) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *Disputes) GetInitiatorId() int64 { + if x != nil { + return x.InitiatorId + } + return 0 +} + +func (x *Disputes) GetInitiatorName() string { + if x != nil { + return x.InitiatorName + } + return "" +} + +func (x *Disputes) GetRespondentId() int64 { + if x != nil { + return x.RespondentId + } + return 0 +} + +func (x *Disputes) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *Disputes) GetEvidence() []string { + if x != nil { + return x.Evidence + } + return nil +} + +func (x *Disputes) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *Disputes) GetResult() string { + if x != nil { + return x.Result + } + return "" +} + +func (x *Disputes) GetRespondentReason() string { + if x != nil { + return x.RespondentReason + } + return "" +} + +func (x *Disputes) GetRespondentEvidence() []string { + if x != nil { + return x.RespondentEvidence + } + return nil +} + +func (x *Disputes) GetAppealReason() string { + if x != nil { + return x.AppealReason + } + return "" +} + +func (x *Disputes) GetAppealedAt() int64 { + if x != nil { + return x.AppealedAt + } + return 0 +} + +func (x *Disputes) GetResolvedBy() int64 { + if x != nil { + return x.ResolvedBy + } + return 0 +} + +func (x *Disputes) GetResolvedAt() int64 { + if x != nil { + return x.ResolvedAt + } + return 0 +} + +func (x *Disputes) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *Disputes) GetUpdatedAt() int64 { + if x != nil { + return x.UpdatedAt + } + return 0 +} + +type AddDisputesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrderId int64 `protobuf:"varint,1,opt,name=orderId,proto3" json:"orderId,omitempty"` + InitiatorId int64 `protobuf:"varint,2,opt,name=initiatorId,proto3" json:"initiatorId,omitempty"` + InitiatorName string `protobuf:"bytes,3,opt,name=initiatorName,proto3" json:"initiatorName,omitempty"` + RespondentId int64 `protobuf:"varint,4,opt,name=respondentId,proto3" json:"respondentId,omitempty"` + Reason string `protobuf:"bytes,5,opt,name=reason,proto3" json:"reason,omitempty"` + Evidence []string `protobuf:"bytes,6,rep,name=evidence,proto3" json:"evidence,omitempty"` + Status string `protobuf:"bytes,7,opt,name=status,proto3" json:"status,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddDisputesReq) Reset() { + *x = AddDisputesReq{} + mi := &file_dispute_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddDisputesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddDisputesReq) ProtoMessage() {} + +func (x *AddDisputesReq) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 AddDisputesReq.ProtoReflect.Descriptor instead. +func (*AddDisputesReq) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{1} +} + +func (x *AddDisputesReq) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *AddDisputesReq) GetInitiatorId() int64 { + if x != nil { + return x.InitiatorId + } + return 0 +} + +func (x *AddDisputesReq) GetInitiatorName() string { + if x != nil { + return x.InitiatorName + } + return "" +} + +func (x *AddDisputesReq) GetRespondentId() int64 { + if x != nil { + return x.RespondentId + } + return 0 +} + +func (x *AddDisputesReq) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *AddDisputesReq) GetEvidence() []string { + if x != nil { + return x.Evidence + } + return nil +} + +func (x *AddDisputesReq) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +type AddDisputesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddDisputesResp) Reset() { + *x = AddDisputesResp{} + mi := &file_dispute_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddDisputesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddDisputesResp) ProtoMessage() {} + +func (x *AddDisputesResp) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 AddDisputesResp.ProtoReflect.Descriptor instead. +func (*AddDisputesResp) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{2} +} + +func (x *AddDisputesResp) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type UpdateDisputesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Status *string `protobuf:"bytes,2,opt,name=status,proto3,oneof" json:"status,omitempty"` + Result *string `protobuf:"bytes,3,opt,name=result,proto3,oneof" json:"result,omitempty"` + RespondentReason *string `protobuf:"bytes,4,opt,name=respondentReason,proto3,oneof" json:"respondentReason,omitempty"` + RespondentEvidence []string `protobuf:"bytes,5,rep,name=respondentEvidence,proto3" json:"respondentEvidence,omitempty"` + AppealReason *string `protobuf:"bytes,6,opt,name=appealReason,proto3,oneof" json:"appealReason,omitempty"` + AppealedAt *int64 `protobuf:"varint,7,opt,name=appealedAt,proto3,oneof" json:"appealedAt,omitempty"` + ResolvedBy *int64 `protobuf:"varint,8,opt,name=resolvedBy,proto3,oneof" json:"resolvedBy,omitempty"` + ResolvedAt *int64 `protobuf:"varint,9,opt,name=resolvedAt,proto3,oneof" json:"resolvedAt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateDisputesReq) Reset() { + *x = UpdateDisputesReq{} + mi := &file_dispute_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateDisputesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateDisputesReq) ProtoMessage() {} + +func (x *UpdateDisputesReq) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 UpdateDisputesReq.ProtoReflect.Descriptor instead. +func (*UpdateDisputesReq) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{3} +} + +func (x *UpdateDisputesReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateDisputesReq) GetStatus() string { + if x != nil && x.Status != nil { + return *x.Status + } + return "" +} + +func (x *UpdateDisputesReq) GetResult() string { + if x != nil && x.Result != nil { + return *x.Result + } + return "" +} + +func (x *UpdateDisputesReq) GetRespondentReason() string { + if x != nil && x.RespondentReason != nil { + return *x.RespondentReason + } + return "" +} + +func (x *UpdateDisputesReq) GetRespondentEvidence() []string { + if x != nil { + return x.RespondentEvidence + } + return nil +} + +func (x *UpdateDisputesReq) GetAppealReason() string { + if x != nil && x.AppealReason != nil { + return *x.AppealReason + } + return "" +} + +func (x *UpdateDisputesReq) GetAppealedAt() int64 { + if x != nil && x.AppealedAt != nil { + return *x.AppealedAt + } + return 0 +} + +func (x *UpdateDisputesReq) GetResolvedBy() int64 { + if x != nil && x.ResolvedBy != nil { + return *x.ResolvedBy + } + return 0 +} + +func (x *UpdateDisputesReq) GetResolvedAt() int64 { + if x != nil && x.ResolvedAt != nil { + return *x.ResolvedAt + } + return 0 +} + +type UpdateDisputesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateDisputesResp) Reset() { + *x = UpdateDisputesResp{} + mi := &file_dispute_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateDisputesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateDisputesResp) ProtoMessage() {} + +func (x *UpdateDisputesResp) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 UpdateDisputesResp.ProtoReflect.Descriptor instead. +func (*UpdateDisputesResp) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{4} +} + +type DelDisputesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelDisputesReq) Reset() { + *x = DelDisputesReq{} + mi := &file_dispute_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelDisputesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelDisputesReq) ProtoMessage() {} + +func (x *DelDisputesReq) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 DelDisputesReq.ProtoReflect.Descriptor instead. +func (*DelDisputesReq) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{5} +} + +func (x *DelDisputesReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelDisputesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelDisputesResp) Reset() { + *x = DelDisputesResp{} + mi := &file_dispute_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelDisputesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelDisputesResp) ProtoMessage() {} + +func (x *DelDisputesResp) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 DelDisputesResp.ProtoReflect.Descriptor instead. +func (*DelDisputesResp) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{6} +} + +type GetDisputesByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetDisputesByIdReq) Reset() { + *x = GetDisputesByIdReq{} + mi := &file_dispute_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetDisputesByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetDisputesByIdReq) ProtoMessage() {} + +func (x *GetDisputesByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 GetDisputesByIdReq.ProtoReflect.Descriptor instead. +func (*GetDisputesByIdReq) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{7} +} + +func (x *GetDisputesByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetDisputesByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Disputes *Disputes `protobuf:"bytes,1,opt,name=disputes,proto3" json:"disputes,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetDisputesByIdResp) Reset() { + *x = GetDisputesByIdResp{} + mi := &file_dispute_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetDisputesByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetDisputesByIdResp) ProtoMessage() {} + +func (x *GetDisputesByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 GetDisputesByIdResp.ProtoReflect.Descriptor instead. +func (*GetDisputesByIdResp) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{8} +} + +func (x *GetDisputesByIdResp) GetDisputes() *Disputes { + if x != nil { + return x.Disputes + } + return nil +} + +type SearchDisputesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Offset int64 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + Id *int64 `protobuf:"varint,3,opt,name=id,proto3,oneof" json:"id,omitempty"` + OrderId *int64 `protobuf:"varint,4,opt,name=orderId,proto3,oneof" json:"orderId,omitempty"` + InitiatorId *int64 `protobuf:"varint,5,opt,name=initiatorId,proto3,oneof" json:"initiatorId,omitempty"` + RespondentId *int64 `protobuf:"varint,6,opt,name=respondentId,proto3,oneof" json:"respondentId,omitempty"` + Status *string `protobuf:"bytes,7,opt,name=status,proto3,oneof" json:"status,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchDisputesReq) Reset() { + *x = SearchDisputesReq{} + mi := &file_dispute_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchDisputesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDisputesReq) ProtoMessage() {} + +func (x *SearchDisputesReq) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 SearchDisputesReq.ProtoReflect.Descriptor instead. +func (*SearchDisputesReq) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{9} +} + +func (x *SearchDisputesReq) GetOffset() int64 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *SearchDisputesReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchDisputesReq) GetId() int64 { + if x != nil && x.Id != nil { + return *x.Id + } + return 0 +} + +func (x *SearchDisputesReq) GetOrderId() int64 { + if x != nil && x.OrderId != nil { + return *x.OrderId + } + return 0 +} + +func (x *SearchDisputesReq) GetInitiatorId() int64 { + if x != nil && x.InitiatorId != nil { + return *x.InitiatorId + } + return 0 +} + +func (x *SearchDisputesReq) GetRespondentId() int64 { + if x != nil && x.RespondentId != nil { + return *x.RespondentId + } + return 0 +} + +func (x *SearchDisputesReq) GetStatus() string { + if x != nil && x.Status != nil { + return *x.Status + } + return "" +} + +type SearchDisputesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Disputes []*Disputes `protobuf:"bytes,1,rep,name=disputes,proto3" json:"disputes,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchDisputesResp) Reset() { + *x = SearchDisputesResp{} + mi := &file_dispute_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchDisputesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDisputesResp) ProtoMessage() {} + +func (x *SearchDisputesResp) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 SearchDisputesResp.ProtoReflect.Descriptor instead. +func (*SearchDisputesResp) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{10} +} + +func (x *SearchDisputesResp) GetDisputes() []*Disputes { + if x != nil { + return x.Disputes + } + return nil +} + +// --------------------------------disputeTimeline-------------------------------- +type DisputeTimeline struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + DisputeId int64 `protobuf:"varint,2,opt,name=disputeId,proto3" json:"disputeId,omitempty"` + EventType string `protobuf:"bytes,3,opt,name=eventType,proto3" json:"eventType,omitempty"` + ActorId int64 `protobuf:"varint,4,opt,name=actorId,proto3" json:"actorId,omitempty"` + ActorName string `protobuf:"bytes,5,opt,name=actorName,proto3" json:"actorName,omitempty"` + Details string `protobuf:"bytes,6,opt,name=details,proto3" json:"details,omitempty"` + CreatedAt int64 `protobuf:"varint,7,opt,name=createdAt,proto3" json:"createdAt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DisputeTimeline) Reset() { + *x = DisputeTimeline{} + mi := &file_dispute_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DisputeTimeline) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DisputeTimeline) ProtoMessage() {} + +func (x *DisputeTimeline) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 DisputeTimeline.ProtoReflect.Descriptor instead. +func (*DisputeTimeline) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{11} +} + +func (x *DisputeTimeline) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *DisputeTimeline) GetDisputeId() int64 { + if x != nil { + return x.DisputeId + } + return 0 +} + +func (x *DisputeTimeline) GetEventType() string { + if x != nil { + return x.EventType + } + return "" +} + +func (x *DisputeTimeline) GetActorId() int64 { + if x != nil { + return x.ActorId + } + return 0 +} + +func (x *DisputeTimeline) GetActorName() string { + if x != nil { + return x.ActorName + } + return "" +} + +func (x *DisputeTimeline) GetDetails() string { + if x != nil { + return x.Details + } + return "" +} + +func (x *DisputeTimeline) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddDisputeTimelineReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + DisputeId int64 `protobuf:"varint,1,opt,name=disputeId,proto3" json:"disputeId,omitempty"` + EventType string `protobuf:"bytes,2,opt,name=eventType,proto3" json:"eventType,omitempty"` + ActorId int64 `protobuf:"varint,3,opt,name=actorId,proto3" json:"actorId,omitempty"` + ActorName string `protobuf:"bytes,4,opt,name=actorName,proto3" json:"actorName,omitempty"` + Details string `protobuf:"bytes,5,opt,name=details,proto3" json:"details,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddDisputeTimelineReq) Reset() { + *x = AddDisputeTimelineReq{} + mi := &file_dispute_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddDisputeTimelineReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddDisputeTimelineReq) ProtoMessage() {} + +func (x *AddDisputeTimelineReq) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 AddDisputeTimelineReq.ProtoReflect.Descriptor instead. +func (*AddDisputeTimelineReq) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{12} +} + +func (x *AddDisputeTimelineReq) GetDisputeId() int64 { + if x != nil { + return x.DisputeId + } + return 0 +} + +func (x *AddDisputeTimelineReq) GetEventType() string { + if x != nil { + return x.EventType + } + return "" +} + +func (x *AddDisputeTimelineReq) GetActorId() int64 { + if x != nil { + return x.ActorId + } + return 0 +} + +func (x *AddDisputeTimelineReq) GetActorName() string { + if x != nil { + return x.ActorName + } + return "" +} + +func (x *AddDisputeTimelineReq) GetDetails() string { + if x != nil { + return x.Details + } + return "" +} + +type AddDisputeTimelineResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddDisputeTimelineResp) Reset() { + *x = AddDisputeTimelineResp{} + mi := &file_dispute_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddDisputeTimelineResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddDisputeTimelineResp) ProtoMessage() {} + +func (x *AddDisputeTimelineResp) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 AddDisputeTimelineResp.ProtoReflect.Descriptor instead. +func (*AddDisputeTimelineResp) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{13} +} + +type SearchDisputeTimelineReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Offset int64 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + DisputeId *int64 `protobuf:"varint,3,opt,name=disputeId,proto3,oneof" json:"disputeId,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchDisputeTimelineReq) Reset() { + *x = SearchDisputeTimelineReq{} + mi := &file_dispute_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchDisputeTimelineReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDisputeTimelineReq) ProtoMessage() {} + +func (x *SearchDisputeTimelineReq) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 SearchDisputeTimelineReq.ProtoReflect.Descriptor instead. +func (*SearchDisputeTimelineReq) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{14} +} + +func (x *SearchDisputeTimelineReq) GetOffset() int64 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *SearchDisputeTimelineReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchDisputeTimelineReq) GetDisputeId() int64 { + if x != nil && x.DisputeId != nil { + return *x.DisputeId + } + return 0 +} + +type SearchDisputeTimelineResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Timeline []*DisputeTimeline `protobuf:"bytes,1,rep,name=timeline,proto3" json:"timeline,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchDisputeTimelineResp) Reset() { + *x = SearchDisputeTimelineResp{} + mi := &file_dispute_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchDisputeTimelineResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDisputeTimelineResp) ProtoMessage() {} + +func (x *SearchDisputeTimelineResp) ProtoReflect() protoreflect.Message { + mi := &file_dispute_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 SearchDisputeTimelineResp.ProtoReflect.Descriptor instead. +func (*SearchDisputeTimelineResp) Descriptor() ([]byte, []int) { + return file_dispute_proto_rawDescGZIP(), []int{15} +} + +func (x *SearchDisputeTimelineResp) GetTimeline() []*DisputeTimeline { + if x != nil { + return x.Timeline + } + return nil +} + +var File_dispute_proto protoreflect.FileDescriptor + +const file_dispute_proto_rawDesc = "" + + "\n" + + "\rdispute.proto\x12\x02pb\"\xa0\x04\n" + + "\bDisputes\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x18\n" + + "\aorderId\x18\x02 \x01(\x03R\aorderId\x12 \n" + + "\vinitiatorId\x18\x03 \x01(\x03R\vinitiatorId\x12$\n" + + "\rinitiatorName\x18\x04 \x01(\tR\rinitiatorName\x12\"\n" + + "\frespondentId\x18\x05 \x01(\x03R\frespondentId\x12\x16\n" + + "\x06reason\x18\x06 \x01(\tR\x06reason\x12\x1a\n" + + "\bevidence\x18\a \x03(\tR\bevidence\x12\x16\n" + + "\x06status\x18\b \x01(\tR\x06status\x12\x16\n" + + "\x06result\x18\t \x01(\tR\x06result\x12*\n" + + "\x10respondentReason\x18\n" + + " \x01(\tR\x10respondentReason\x12.\n" + + "\x12respondentEvidence\x18\v \x03(\tR\x12respondentEvidence\x12\"\n" + + "\fappealReason\x18\f \x01(\tR\fappealReason\x12\x1e\n" + + "\n" + + "appealedAt\x18\r \x01(\x03R\n" + + "appealedAt\x12\x1e\n" + + "\n" + + "resolvedBy\x18\x0e \x01(\x03R\n" + + "resolvedBy\x12\x1e\n" + + "\n" + + "resolvedAt\x18\x0f \x01(\x03R\n" + + "resolvedAt\x12\x1c\n" + + "\tcreatedAt\x18\x10 \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tupdatedAt\x18\x11 \x01(\x03R\tupdatedAt\"\xe2\x01\n" + + "\x0eAddDisputesReq\x12\x18\n" + + "\aorderId\x18\x01 \x01(\x03R\aorderId\x12 \n" + + "\vinitiatorId\x18\x02 \x01(\x03R\vinitiatorId\x12$\n" + + "\rinitiatorName\x18\x03 \x01(\tR\rinitiatorName\x12\"\n" + + "\frespondentId\x18\x04 \x01(\x03R\frespondentId\x12\x16\n" + + "\x06reason\x18\x05 \x01(\tR\x06reason\x12\x1a\n" + + "\bevidence\x18\x06 \x03(\tR\bevidence\x12\x16\n" + + "\x06status\x18\a \x01(\tR\x06status\"!\n" + + "\x0fAddDisputesResp\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\xbf\x03\n" + + "\x11UpdateDisputesReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1b\n" + + "\x06status\x18\x02 \x01(\tH\x00R\x06status\x88\x01\x01\x12\x1b\n" + + "\x06result\x18\x03 \x01(\tH\x01R\x06result\x88\x01\x01\x12/\n" + + "\x10respondentReason\x18\x04 \x01(\tH\x02R\x10respondentReason\x88\x01\x01\x12.\n" + + "\x12respondentEvidence\x18\x05 \x03(\tR\x12respondentEvidence\x12'\n" + + "\fappealReason\x18\x06 \x01(\tH\x03R\fappealReason\x88\x01\x01\x12#\n" + + "\n" + + "appealedAt\x18\a \x01(\x03H\x04R\n" + + "appealedAt\x88\x01\x01\x12#\n" + + "\n" + + "resolvedBy\x18\b \x01(\x03H\x05R\n" + + "resolvedBy\x88\x01\x01\x12#\n" + + "\n" + + "resolvedAt\x18\t \x01(\x03H\x06R\n" + + "resolvedAt\x88\x01\x01B\t\n" + + "\a_statusB\t\n" + + "\a_resultB\x13\n" + + "\x11_respondentReasonB\x0f\n" + + "\r_appealReasonB\r\n" + + "\v_appealedAtB\r\n" + + "\v_resolvedByB\r\n" + + "\v_resolvedAt\"\x14\n" + + "\x12UpdateDisputesResp\" \n" + + "\x0eDelDisputesReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x11\n" + + "\x0fDelDisputesResp\"$\n" + + "\x12GetDisputesByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"?\n" + + "\x13GetDisputesByIdResp\x12(\n" + + "\bdisputes\x18\x01 \x01(\v2\f.pb.DisputesR\bdisputes\"\xa1\x02\n" + + "\x11SearchDisputesReq\x12\x16\n" + + "\x06offset\x18\x01 \x01(\x03R\x06offset\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" + + "\vinitiatorId\x18\x05 \x01(\x03H\x02R\vinitiatorId\x88\x01\x01\x12'\n" + + "\frespondentId\x18\x06 \x01(\x03H\x03R\frespondentId\x88\x01\x01\x12\x1b\n" + + "\x06status\x18\a \x01(\tH\x04R\x06status\x88\x01\x01B\x05\n" + + "\x03_idB\n" + + "\n" + + "\b_orderIdB\x0e\n" + + "\f_initiatorIdB\x0f\n" + + "\r_respondentIdB\t\n" + + "\a_status\">\n" + + "\x12SearchDisputesResp\x12(\n" + + "\bdisputes\x18\x01 \x03(\v2\f.pb.DisputesR\bdisputes\"\xcd\x01\n" + + "\x0fDisputeTimeline\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x1c\n" + + "\tdisputeId\x18\x02 \x01(\x03R\tdisputeId\x12\x1c\n" + + "\teventType\x18\x03 \x01(\tR\teventType\x12\x18\n" + + "\aactorId\x18\x04 \x01(\x03R\aactorId\x12\x1c\n" + + "\tactorName\x18\x05 \x01(\tR\tactorName\x12\x18\n" + + "\adetails\x18\x06 \x01(\tR\adetails\x12\x1c\n" + + "\tcreatedAt\x18\a \x01(\x03R\tcreatedAt\"\xa5\x01\n" + + "\x15AddDisputeTimelineReq\x12\x1c\n" + + "\tdisputeId\x18\x01 \x01(\x03R\tdisputeId\x12\x1c\n" + + "\teventType\x18\x02 \x01(\tR\teventType\x12\x18\n" + + "\aactorId\x18\x03 \x01(\x03R\aactorId\x12\x1c\n" + + "\tactorName\x18\x04 \x01(\tR\tactorName\x12\x18\n" + + "\adetails\x18\x05 \x01(\tR\adetails\"\x18\n" + + "\x16AddDisputeTimelineResp\"y\n" + + "\x18SearchDisputeTimelineReq\x12\x16\n" + + "\x06offset\x18\x01 \x01(\x03R\x06offset\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12!\n" + + "\tdisputeId\x18\x03 \x01(\x03H\x00R\tdisputeId\x88\x01\x01B\f\n" + + "\n" + + "_disputeId\"L\n" + + "\x19SearchDisputeTimelineResp\x12/\n" + + "\btimeline\x18\x01 \x03(\v2\x13.pb.DisputeTimelineR\btimeline2\xe9\x03\n" + + "\x0edisputeService\x126\n" + + "\vAddDisputes\x12\x12.pb.AddDisputesReq\x1a\x13.pb.AddDisputesResp\x12?\n" + + "\x0eUpdateDisputes\x12\x15.pb.UpdateDisputesReq\x1a\x16.pb.UpdateDisputesResp\x126\n" + + "\vDelDisputes\x12\x12.pb.DelDisputesReq\x1a\x13.pb.DelDisputesResp\x12B\n" + + "\x0fGetDisputesById\x12\x16.pb.GetDisputesByIdReq\x1a\x17.pb.GetDisputesByIdResp\x12?\n" + + "\x0eSearchDisputes\x12\x15.pb.SearchDisputesReq\x1a\x16.pb.SearchDisputesResp\x12K\n" + + "\x12AddDisputeTimeline\x12\x19.pb.AddDisputeTimelineReq\x1a\x1a.pb.AddDisputeTimelineResp\x12T\n" + + "\x15SearchDisputeTimeline\x12\x1c.pb.SearchDisputeTimelineReq\x1a\x1d.pb.SearchDisputeTimelineRespB\x06Z\x04./pbb\x06proto3" + +var ( + file_dispute_proto_rawDescOnce sync.Once + file_dispute_proto_rawDescData []byte +) + +func file_dispute_proto_rawDescGZIP() []byte { + file_dispute_proto_rawDescOnce.Do(func() { + file_dispute_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_dispute_proto_rawDesc), len(file_dispute_proto_rawDesc))) + }) + return file_dispute_proto_rawDescData +} + +var file_dispute_proto_msgTypes = make([]protoimpl.MessageInfo, 16) +var file_dispute_proto_goTypes = []any{ + (*Disputes)(nil), // 0: pb.Disputes + (*AddDisputesReq)(nil), // 1: pb.AddDisputesReq + (*AddDisputesResp)(nil), // 2: pb.AddDisputesResp + (*UpdateDisputesReq)(nil), // 3: pb.UpdateDisputesReq + (*UpdateDisputesResp)(nil), // 4: pb.UpdateDisputesResp + (*DelDisputesReq)(nil), // 5: pb.DelDisputesReq + (*DelDisputesResp)(nil), // 6: pb.DelDisputesResp + (*GetDisputesByIdReq)(nil), // 7: pb.GetDisputesByIdReq + (*GetDisputesByIdResp)(nil), // 8: pb.GetDisputesByIdResp + (*SearchDisputesReq)(nil), // 9: pb.SearchDisputesReq + (*SearchDisputesResp)(nil), // 10: pb.SearchDisputesResp + (*DisputeTimeline)(nil), // 11: pb.DisputeTimeline + (*AddDisputeTimelineReq)(nil), // 12: pb.AddDisputeTimelineReq + (*AddDisputeTimelineResp)(nil), // 13: pb.AddDisputeTimelineResp + (*SearchDisputeTimelineReq)(nil), // 14: pb.SearchDisputeTimelineReq + (*SearchDisputeTimelineResp)(nil), // 15: pb.SearchDisputeTimelineResp +} +var file_dispute_proto_depIdxs = []int32{ + 0, // 0: pb.GetDisputesByIdResp.disputes:type_name -> pb.Disputes + 0, // 1: pb.SearchDisputesResp.disputes:type_name -> pb.Disputes + 11, // 2: pb.SearchDisputeTimelineResp.timeline:type_name -> pb.DisputeTimeline + 1, // 3: pb.disputeService.AddDisputes:input_type -> pb.AddDisputesReq + 3, // 4: pb.disputeService.UpdateDisputes:input_type -> pb.UpdateDisputesReq + 5, // 5: pb.disputeService.DelDisputes:input_type -> pb.DelDisputesReq + 7, // 6: pb.disputeService.GetDisputesById:input_type -> pb.GetDisputesByIdReq + 9, // 7: pb.disputeService.SearchDisputes:input_type -> pb.SearchDisputesReq + 12, // 8: pb.disputeService.AddDisputeTimeline:input_type -> pb.AddDisputeTimelineReq + 14, // 9: pb.disputeService.SearchDisputeTimeline:input_type -> pb.SearchDisputeTimelineReq + 2, // 10: pb.disputeService.AddDisputes:output_type -> pb.AddDisputesResp + 4, // 11: pb.disputeService.UpdateDisputes:output_type -> pb.UpdateDisputesResp + 6, // 12: pb.disputeService.DelDisputes:output_type -> pb.DelDisputesResp + 8, // 13: pb.disputeService.GetDisputesById:output_type -> pb.GetDisputesByIdResp + 10, // 14: pb.disputeService.SearchDisputes:output_type -> pb.SearchDisputesResp + 13, // 15: pb.disputeService.AddDisputeTimeline:output_type -> pb.AddDisputeTimelineResp + 15, // 16: pb.disputeService.SearchDisputeTimeline:output_type -> pb.SearchDisputeTimelineResp + 10, // [10:17] is the sub-list for method output_type + 3, // [3:10] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_dispute_proto_init() } +func file_dispute_proto_init() { + if File_dispute_proto != nil { + return + } + file_dispute_proto_msgTypes[3].OneofWrappers = []any{} + file_dispute_proto_msgTypes[9].OneofWrappers = []any{} + file_dispute_proto_msgTypes[14].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_dispute_proto_rawDesc), len(file_dispute_proto_rawDesc)), + NumEnums: 0, + NumMessages: 16, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_dispute_proto_goTypes, + DependencyIndexes: file_dispute_proto_depIdxs, + MessageInfos: file_dispute_proto_msgTypes, + }.Build() + File_dispute_proto = out.File + file_dispute_proto_goTypes = nil + file_dispute_proto_depIdxs = nil +} diff --git a/app/dispute/rpc/pb/dispute_grpc.pb.go b/app/dispute/rpc/pb/dispute_grpc.pb.go new file mode 100644 index 0000000..35ebadf --- /dev/null +++ b/app/dispute/rpc/pb/dispute_grpc.pb.go @@ -0,0 +1,353 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v7.34.1 +// source: dispute.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 ( + DisputeService_AddDisputes_FullMethodName = "/pb.disputeService/AddDisputes" + DisputeService_UpdateDisputes_FullMethodName = "/pb.disputeService/UpdateDisputes" + DisputeService_DelDisputes_FullMethodName = "/pb.disputeService/DelDisputes" + DisputeService_GetDisputesById_FullMethodName = "/pb.disputeService/GetDisputesById" + DisputeService_SearchDisputes_FullMethodName = "/pb.disputeService/SearchDisputes" + DisputeService_AddDisputeTimeline_FullMethodName = "/pb.disputeService/AddDisputeTimeline" + DisputeService_SearchDisputeTimeline_FullMethodName = "/pb.disputeService/SearchDisputeTimeline" +) + +// DisputeServiceClient is the client API for DisputeService 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 DisputeServiceClient interface { + // -----------------------disputes----------------------- + AddDisputes(ctx context.Context, in *AddDisputesReq, opts ...grpc.CallOption) (*AddDisputesResp, error) + UpdateDisputes(ctx context.Context, in *UpdateDisputesReq, opts ...grpc.CallOption) (*UpdateDisputesResp, error) + DelDisputes(ctx context.Context, in *DelDisputesReq, opts ...grpc.CallOption) (*DelDisputesResp, error) + GetDisputesById(ctx context.Context, in *GetDisputesByIdReq, opts ...grpc.CallOption) (*GetDisputesByIdResp, error) + SearchDisputes(ctx context.Context, in *SearchDisputesReq, opts ...grpc.CallOption) (*SearchDisputesResp, error) + // -----------------------disputeTimeline----------------------- + AddDisputeTimeline(ctx context.Context, in *AddDisputeTimelineReq, opts ...grpc.CallOption) (*AddDisputeTimelineResp, error) + SearchDisputeTimeline(ctx context.Context, in *SearchDisputeTimelineReq, opts ...grpc.CallOption) (*SearchDisputeTimelineResp, error) +} + +type disputeServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewDisputeServiceClient(cc grpc.ClientConnInterface) DisputeServiceClient { + return &disputeServiceClient{cc} +} + +func (c *disputeServiceClient) AddDisputes(ctx context.Context, in *AddDisputesReq, opts ...grpc.CallOption) (*AddDisputesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddDisputesResp) + err := c.cc.Invoke(ctx, DisputeService_AddDisputes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *disputeServiceClient) UpdateDisputes(ctx context.Context, in *UpdateDisputesReq, opts ...grpc.CallOption) (*UpdateDisputesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateDisputesResp) + err := c.cc.Invoke(ctx, DisputeService_UpdateDisputes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *disputeServiceClient) DelDisputes(ctx context.Context, in *DelDisputesReq, opts ...grpc.CallOption) (*DelDisputesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelDisputesResp) + err := c.cc.Invoke(ctx, DisputeService_DelDisputes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *disputeServiceClient) GetDisputesById(ctx context.Context, in *GetDisputesByIdReq, opts ...grpc.CallOption) (*GetDisputesByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetDisputesByIdResp) + err := c.cc.Invoke(ctx, DisputeService_GetDisputesById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *disputeServiceClient) SearchDisputes(ctx context.Context, in *SearchDisputesReq, opts ...grpc.CallOption) (*SearchDisputesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchDisputesResp) + err := c.cc.Invoke(ctx, DisputeService_SearchDisputes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *disputeServiceClient) AddDisputeTimeline(ctx context.Context, in *AddDisputeTimelineReq, opts ...grpc.CallOption) (*AddDisputeTimelineResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddDisputeTimelineResp) + err := c.cc.Invoke(ctx, DisputeService_AddDisputeTimeline_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *disputeServiceClient) SearchDisputeTimeline(ctx context.Context, in *SearchDisputeTimelineReq, opts ...grpc.CallOption) (*SearchDisputeTimelineResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchDisputeTimelineResp) + err := c.cc.Invoke(ctx, DisputeService_SearchDisputeTimeline_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// DisputeServiceServer is the server API for DisputeService service. +// All implementations must embed UnimplementedDisputeServiceServer +// for forward compatibility. +type DisputeServiceServer interface { + // -----------------------disputes----------------------- + AddDisputes(context.Context, *AddDisputesReq) (*AddDisputesResp, error) + UpdateDisputes(context.Context, *UpdateDisputesReq) (*UpdateDisputesResp, error) + DelDisputes(context.Context, *DelDisputesReq) (*DelDisputesResp, error) + GetDisputesById(context.Context, *GetDisputesByIdReq) (*GetDisputesByIdResp, error) + SearchDisputes(context.Context, *SearchDisputesReq) (*SearchDisputesResp, error) + // -----------------------disputeTimeline----------------------- + AddDisputeTimeline(context.Context, *AddDisputeTimelineReq) (*AddDisputeTimelineResp, error) + SearchDisputeTimeline(context.Context, *SearchDisputeTimelineReq) (*SearchDisputeTimelineResp, error) + mustEmbedUnimplementedDisputeServiceServer() +} + +// UnimplementedDisputeServiceServer 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 UnimplementedDisputeServiceServer struct{} + +func (UnimplementedDisputeServiceServer) AddDisputes(context.Context, *AddDisputesReq) (*AddDisputesResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddDisputes not implemented") +} +func (UnimplementedDisputeServiceServer) UpdateDisputes(context.Context, *UpdateDisputesReq) (*UpdateDisputesResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateDisputes not implemented") +} +func (UnimplementedDisputeServiceServer) DelDisputes(context.Context, *DelDisputesReq) (*DelDisputesResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelDisputes not implemented") +} +func (UnimplementedDisputeServiceServer) GetDisputesById(context.Context, *GetDisputesByIdReq) (*GetDisputesByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetDisputesById not implemented") +} +func (UnimplementedDisputeServiceServer) SearchDisputes(context.Context, *SearchDisputesReq) (*SearchDisputesResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchDisputes not implemented") +} +func (UnimplementedDisputeServiceServer) AddDisputeTimeline(context.Context, *AddDisputeTimelineReq) (*AddDisputeTimelineResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddDisputeTimeline not implemented") +} +func (UnimplementedDisputeServiceServer) SearchDisputeTimeline(context.Context, *SearchDisputeTimelineReq) (*SearchDisputeTimelineResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchDisputeTimeline not implemented") +} +func (UnimplementedDisputeServiceServer) mustEmbedUnimplementedDisputeServiceServer() {} +func (UnimplementedDisputeServiceServer) testEmbeddedByValue() {} + +// UnsafeDisputeServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to DisputeServiceServer will +// result in compilation errors. +type UnsafeDisputeServiceServer interface { + mustEmbedUnimplementedDisputeServiceServer() +} + +func RegisterDisputeServiceServer(s grpc.ServiceRegistrar, srv DisputeServiceServer) { + // If the following call panics, it indicates UnimplementedDisputeServiceServer 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(&DisputeService_ServiceDesc, srv) +} + +func _DisputeService_AddDisputes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddDisputesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DisputeServiceServer).AddDisputes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DisputeService_AddDisputes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DisputeServiceServer).AddDisputes(ctx, req.(*AddDisputesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _DisputeService_UpdateDisputes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateDisputesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DisputeServiceServer).UpdateDisputes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DisputeService_UpdateDisputes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DisputeServiceServer).UpdateDisputes(ctx, req.(*UpdateDisputesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _DisputeService_DelDisputes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelDisputesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DisputeServiceServer).DelDisputes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DisputeService_DelDisputes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DisputeServiceServer).DelDisputes(ctx, req.(*DelDisputesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _DisputeService_GetDisputesById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetDisputesByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DisputeServiceServer).GetDisputesById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DisputeService_GetDisputesById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DisputeServiceServer).GetDisputesById(ctx, req.(*GetDisputesByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _DisputeService_SearchDisputes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchDisputesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DisputeServiceServer).SearchDisputes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DisputeService_SearchDisputes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DisputeServiceServer).SearchDisputes(ctx, req.(*SearchDisputesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _DisputeService_AddDisputeTimeline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddDisputeTimelineReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DisputeServiceServer).AddDisputeTimeline(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DisputeService_AddDisputeTimeline_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DisputeServiceServer).AddDisputeTimeline(ctx, req.(*AddDisputeTimelineReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _DisputeService_SearchDisputeTimeline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchDisputeTimelineReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DisputeServiceServer).SearchDisputeTimeline(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DisputeService_SearchDisputeTimeline_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DisputeServiceServer).SearchDisputeTimeline(ctx, req.(*SearchDisputeTimelineReq)) + } + return interceptor(ctx, in, info, handler) +} + +// DisputeService_ServiceDesc is the grpc.ServiceDesc for DisputeService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var DisputeService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.disputeService", + HandlerType: (*DisputeServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "AddDisputes", + Handler: _DisputeService_AddDisputes_Handler, + }, + { + MethodName: "UpdateDisputes", + Handler: _DisputeService_UpdateDisputes_Handler, + }, + { + MethodName: "DelDisputes", + Handler: _DisputeService_DelDisputes_Handler, + }, + { + MethodName: "GetDisputesById", + Handler: _DisputeService_GetDisputesById_Handler, + }, + { + MethodName: "SearchDisputes", + Handler: _DisputeService_SearchDisputes_Handler, + }, + { + MethodName: "AddDisputeTimeline", + Handler: _DisputeService_AddDisputeTimeline_Handler, + }, + { + MethodName: "SearchDisputeTimeline", + Handler: _DisputeService_SearchDisputeTimeline_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "dispute.proto", +} diff --git a/app/game/rpc/internal/logic/searchGamesLogic.go b/app/game/rpc/internal/logic/searchGamesLogic.go index 3968130..3deb04b 100644 --- a/app/game/rpc/internal/logic/searchGamesLogic.go +++ b/app/game/rpc/internal/logic/searchGamesLogic.go @@ -26,7 +26,6 @@ func NewSearchGamesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Searc } func (l *SearchGamesLogic) SearchGames(in *pb.SearchGamesReq) (*pb.SearchGamesResp, error) { - notFoundErr := entcache.ErrNotFound if in.Limit <= 0 { in.Limit = 20 } @@ -37,7 +36,7 @@ func (l *SearchGamesLogic) SearchGames(in *pb.SearchGamesReq) (*pb.SearchGamesRe in.Offset = 0 } all, err := l.svcCtx.GameModelRO.Games.Query().Limit(int(in.Limit)).Offset(int(in.Offset)).All(l.ctx) - if err != nil && !errors.As(err, ¬FoundErr) { + if err != nil && !errors.Is(err, entcache.ErrNotFound) { logx.Errorf("failed to query games: %v", err) return nil, errors.New("failed to query games") } diff --git a/app/notification/api/etc/notifi-api.yaml b/app/notification/api/etc/notifi-api.yaml new file mode 100644 index 0000000..c405fdf --- /dev/null +++ b/app/notification/api/etc/notifi-api.yaml @@ -0,0 +1,13 @@ +Name: notifi-api +Host: 0.0.0.0 +Port: 8888 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONFIG ===== +NotificationRpcConf: + Endpoints: + - notification-rpc:8080 diff --git a/app/notification/api/internal/config/config.go b/app/notification/api/internal/config/config.go new file mode 100644 index 0000000..afd8528 --- /dev/null +++ b/app/notification/api/internal/config/config.go @@ -0,0 +1,11 @@ +package config + +import ( + "github.com/zeromicro/go-zero/rest" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + rest.RestConf + NotificationRpcConf zrpc.RpcClientConf +} diff --git a/app/notification/api/internal/handler/notification/listNotificationsHandler.go b/app/notification/api/internal/handler/notification/listNotificationsHandler.go new file mode 100644 index 0000000..9bf95d3 --- /dev/null +++ b/app/notification/api/internal/handler/notification/listNotificationsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package notification + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/notification/api/internal/logic/notification" + "juwan-backend/app/notification/api/internal/svc" + "juwan-backend/app/notification/api/internal/types" +) + +// 获取通知列表 +func ListNotificationsHandler(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 := notification.NewListNotificationsLogic(r.Context(), svcCtx) + resp, err := l.ListNotifications(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/notification/api/internal/handler/notification/readAllNotificationsHandler.go b/app/notification/api/internal/handler/notification/readAllNotificationsHandler.go new file mode 100644 index 0000000..3de78f4 --- /dev/null +++ b/app/notification/api/internal/handler/notification/readAllNotificationsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package notification + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/notification/api/internal/logic/notification" + "juwan-backend/app/notification/api/internal/svc" + "juwan-backend/app/notification/api/internal/types" +) + +// 全部已读 +func ReadAllNotificationsHandler(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 := notification.NewReadAllNotificationsLogic(r.Context(), svcCtx) + resp, err := l.ReadAllNotifications(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/notification/api/internal/handler/notification/readNotificationHandler.go b/app/notification/api/internal/handler/notification/readNotificationHandler.go new file mode 100644 index 0000000..b178ef1 --- /dev/null +++ b/app/notification/api/internal/handler/notification/readNotificationHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package notification + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/notification/api/internal/logic/notification" + "juwan-backend/app/notification/api/internal/svc" + "juwan-backend/app/notification/api/internal/types" +) + +// 标记已读 +func ReadNotificationHandler(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 := notification.NewReadNotificationLogic(r.Context(), svcCtx) + resp, err := l.ReadNotification(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/notification/api/internal/handler/routes.go b/app/notification/api/internal/handler/routes.go new file mode 100644 index 0000000..901f957 --- /dev/null +++ b/app/notification/api/internal/handler/routes.go @@ -0,0 +1,39 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package handler + +import ( + "net/http" + + notification "juwan-backend/app/notification/api/internal/handler/notification" + "juwan-backend/app/notification/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: "/notifications", + Handler: notification.ListNotificationsHandler(serverCtx), + }, + { + // 标记已读 + Method: http.MethodPut, + Path: "/notifications/:id/read", + Handler: notification.ReadNotificationHandler(serverCtx), + }, + { + // 全部已读 + Method: http.MethodPut, + Path: "/notifications/read-all", + Handler: notification.ReadAllNotificationsHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) +} diff --git a/app/notification/api/internal/logic/notification/helpers.go b/app/notification/api/internal/logic/notification/helpers.go new file mode 100644 index 0000000..f6f5cb5 --- /dev/null +++ b/app/notification/api/internal/logic/notification/helpers.go @@ -0,0 +1,27 @@ +package notification + +import ( + "time" + + "juwan-backend/app/notification/api/internal/types" + "juwan-backend/app/notification/rpc/notificationservice" +) + +func formatUnix(ts int64) string { + if ts <= 0 { + return "" + } + return time.Unix(ts, 0).UTC().Format(time.RFC3339) +} + +func toAPINotification(n *notificationservice.Notifications) types.Notification { + return types.Notification{ + Id: n.GetId(), + Type: n.GetType(), + Title: n.GetTitle(), + Content: n.GetContent(), + Read: n.GetRead(), + Link: n.GetLink(), + CreatedAt: formatUnix(n.GetCreatedAt()), + } +} diff --git a/app/notification/api/internal/logic/notification/listNotificationsLogic.go b/app/notification/api/internal/logic/notification/listNotificationsLogic.go new file mode 100644 index 0000000..aa42ff1 --- /dev/null +++ b/app/notification/api/internal/logic/notification/listNotificationsLogic.go @@ -0,0 +1,63 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package notification + +import ( + "context" + + "juwan-backend/app/notification/api/internal/svc" + "juwan-backend/app/notification/api/internal/types" + "juwan-backend/app/notification/rpc/notificationservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListNotificationsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取通知列表 +func NewListNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListNotificationsLogic { + return &ListNotificationsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListNotificationsLogic) ListNotifications(req *types.PageReq) (resp *types.NotificationListResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + limit := req.Limit + if limit <= 0 { + limit = 20 + } + + out, err := l.svcCtx.NotificationRpc.SearchNotifications(l.ctx, ¬ificationservice.SearchNotificationsReq{ + Offset: req.Offset, + Limit: limit, + UserId: &uid, + }) + if err != nil { + return nil, err + } + items := make([]types.Notification, 0, len(out.GetNotifications())) + for _, item := range out.GetNotifications() { + items = append(items, toAPINotification(item)) + } + + return &types.NotificationListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: limit, + }, + }, nil +} diff --git a/app/notification/api/internal/logic/notification/readAllNotificationsLogic.go b/app/notification/api/internal/logic/notification/readAllNotificationsLogic.go new file mode 100644 index 0000000..501d3e5 --- /dev/null +++ b/app/notification/api/internal/logic/notification/readAllNotificationsLogic.go @@ -0,0 +1,62 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package notification + +import ( + "context" + "time" + + "juwan-backend/app/notification/api/internal/svc" + "juwan-backend/app/notification/api/internal/types" + "juwan-backend/app/notification/rpc/notificationservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ReadAllNotificationsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 全部已读 +func NewReadAllNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReadAllNotificationsLogic { + return &ReadAllNotificationsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ReadAllNotificationsLogic) ReadAllNotifications(req *types.EmptyResp) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + unread := false + out, err := l.svcCtx.NotificationRpc.SearchNotifications(l.ctx, ¬ificationservice.SearchNotificationsReq{ + Offset: 0, + Limit: 100, + UserId: &uid, + Read: &unread, + }) + if err != nil { + return nil, err + } + read := true + now := time.Now().Unix() + for _, item := range out.GetNotifications() { + _, err = l.svcCtx.NotificationRpc.UpdateNotifications(l.ctx, ¬ificationservice.UpdateNotificationsReq{ + Id: item.GetId(), + Read: &read, + UpdatedAt: &now, + }) + if err != nil { + return nil, err + } + } + + return &types.EmptyResp{}, nil +} diff --git a/app/notification/api/internal/logic/notification/readNotificationLogic.go b/app/notification/api/internal/logic/notification/readNotificationLogic.go new file mode 100644 index 0000000..42b2682 --- /dev/null +++ b/app/notification/api/internal/logic/notification/readNotificationLogic.go @@ -0,0 +1,63 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package notification + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/notification/api/internal/svc" + "juwan-backend/app/notification/api/internal/types" + "juwan-backend/app/notification/rpc/notificationservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ReadNotificationLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 标记已读 +func NewReadNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReadNotificationLogic { + return &ReadNotificationLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ReadNotificationLogic) ReadNotification(req *types.PathId) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + current, err := l.svcCtx.NotificationRpc.GetNotificationsById(l.ctx, ¬ificationservice.GetNotificationsByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if current.GetNotifications() == nil { + return nil, errors.New("notification not found") + } + if current.GetNotifications().GetUserId() != uid { + return nil, errors.New("notification not found") + } + + read := true + now := time.Now().Unix() + _, err = l.svcCtx.NotificationRpc.UpdateNotifications(l.ctx, ¬ificationservice.UpdateNotificationsReq{ + Id: req.Id, + Read: &read, + UpdatedAt: &now, + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/notification/api/internal/svc/serviceContext.go b/app/notification/api/internal/svc/serviceContext.go new file mode 100644 index 0000000..46af39a --- /dev/null +++ b/app/notification/api/internal/svc/serviceContext.go @@ -0,0 +1,20 @@ +package svc + +import ( + "juwan-backend/app/notification/api/internal/config" + "juwan-backend/app/notification/rpc/notificationservice" + + "github.com/zeromicro/go-zero/zrpc" +) + +type ServiceContext struct { + Config config.Config + NotificationRpc notificationservice.NotificationService +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + NotificationRpc: notificationservice.NewNotificationService(zrpc.MustNewClient(c.NotificationRpcConf)), + } +} diff --git a/app/notification/api/internal/types/types.go b/app/notification/api/internal/types/types.go new file mode 100644 index 0000000..22f7e56 --- /dev/null +++ b/app/notification/api/internal/types/types.go @@ -0,0 +1,56 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package types + +type EmptyResp struct { +} + +type Notification struct { + Id int64 `json:"id"` + Type string `json:"type"` + Title string `json:"title"` + Content string `json:"content"` + Read bool `json:"read"` + Link string `json:"link,optional"` + CreatedAt string `json:"createdAt"` +} + +type NotificationListResp struct { + Items []Notification `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 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/notification/api/notifi.go b/app/notification/api/notifi.go new file mode 100644 index 0000000..7608bad --- /dev/null +++ b/app/notification/api/notifi.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/notification/api/internal/config" + "juwan-backend/app/notification/api/internal/handler" + "juwan-backend/app/notification/api/internal/svc" + "juwan-backend/common/middlewares" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/notifi-api.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + server.Use(middlewares.NewHeaderExtractorMiddleware().Handle) + 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/notification/rpc/etc/pb.yaml b/app/notification/rpc/etc/pb.yaml new file mode 100644 index 0000000..0bbfacb --- /dev/null +++ b/app/notification/rpc/etc/pb.yaml @@ -0,0 +1,23 @@ +Name: pb.rpc +ListenOn: 0.0.0.0:8080 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONF ===== +SnowflakeRpcConf: + Endpoints: + - snowflake:8080 + +DB: + Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + +CacheConf: + - Host: "${REDIS_HOST}:${REDIS_PORT}" + Type: node + +Log: + Level: debug diff --git a/app/notification/rpc/internal/config/config.go b/app/notification/rpc/internal/config/config.go new file mode 100644 index 0000000..f4107e8 --- /dev/null +++ b/app/notification/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/notification/rpc/internal/logic/addNotificationsLogic.go b/app/notification/rpc/internal/logic/addNotificationsLogic.go new file mode 100644 index 0000000..6d776ad --- /dev/null +++ b/app/notification/rpc/internal/logic/addNotificationsLogic.go @@ -0,0 +1,61 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/notification/rpc/internal/svc" + "juwan-backend/app/notification/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddNotificationsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddNotificationsLogic { + return &AddNotificationsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *AddNotificationsLogic) AddNotifications(in *pb.AddNotificationsReq) (*pb.AddNotificationsResp, error) { + if in.GetUserId() <= 0 { + return nil, errors.New("userId is required") + } + if in.GetType() == "" { + return nil, errors.New("type is required") + } + if in.GetTitle() == "" { + return nil, errors.New("title is required") + } + if in.GetContent() == "" { + return nil, errors.New("content is required") + } + + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create notification id failed") + } + + created, err := l.svcCtx.NotificationModelRW.Notifications.Create(). + SetID(idResp.Id). + SetUserID(in.GetUserId()). + SetType(in.GetType()). + SetTitle(in.GetTitle()). + SetContent(in.GetContent()). + SetNillableLink(in.Link). + Save(l.ctx) + if err != nil { + logx.Errorf("addNotifications err: %v", err) + return nil, errors.New("add notification failed") + } + + return &pb.AddNotificationsResp{Id: created.ID}, nil +} diff --git a/app/notification/rpc/internal/logic/delNotificationsLogic.go b/app/notification/rpc/internal/logic/delNotificationsLogic.go new file mode 100644 index 0000000..04137f8 --- /dev/null +++ b/app/notification/rpc/internal/logic/delNotificationsLogic.go @@ -0,0 +1,34 @@ +package logic + +import ( + "context" + + "juwan-backend/app/notification/rpc/internal/svc" + "juwan-backend/app/notification/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelNotificationsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelNotificationsLogic { + return &DelNotificationsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelNotificationsLogic) DelNotifications(in *pb.DelNotificationsReq) (*pb.DelNotificationsResp, error) { + err := l.svcCtx.NotificationModelRW.Notifications.DeleteOneID(in.GetId()).Exec(l.ctx) + if err != nil { + logx.Errorf("delNotifications err: %v", err) + return nil, err + } + + return &pb.DelNotificationsResp{}, nil +} diff --git a/app/notification/rpc/internal/logic/getNotificationsByIdLogic.go b/app/notification/rpc/internal/logic/getNotificationsByIdLogic.go new file mode 100644 index 0000000..d389da6 --- /dev/null +++ b/app/notification/rpc/internal/logic/getNotificationsByIdLogic.go @@ -0,0 +1,33 @@ +package logic + +import ( + "context" + + "juwan-backend/app/notification/rpc/internal/svc" + "juwan-backend/app/notification/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetNotificationsByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetNotificationsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNotificationsByIdLogic { + return &GetNotificationsByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetNotificationsByIdLogic) GetNotificationsById(in *pb.GetNotificationsByIdReq) (*pb.GetNotificationsByIdResp, error) { + n, err := l.svcCtx.NotificationModelRO.Notifications.Get(l.ctx, in.GetId()) + if err != nil { + return nil, err + } + + return &pb.GetNotificationsByIdResp{Notifications: entNotificationToPb(n)}, nil +} diff --git a/app/notification/rpc/internal/logic/helpers.go b/app/notification/rpc/internal/logic/helpers.go new file mode 100644 index 0000000..e65fb53 --- /dev/null +++ b/app/notification/rpc/internal/logic/helpers.go @@ -0,0 +1,23 @@ +package logic + +import ( + "juwan-backend/app/notification/rpc/internal/models" + "juwan-backend/app/notification/rpc/pb" +) + +func entNotificationToPb(n *models.Notifications) *pb.Notifications { + out := &pb.Notifications{ + Id: n.ID, + UserId: n.UserID, + Type: n.Type, + Title: n.Title, + Content: n.Content, + Read: n.Read, + CreatedAt: n.CreatedAt.Unix(), + UpdatedAt: n.UpdatedAt.Unix(), + } + if n.Link != nil { + out.Link = *n.Link + } + return out +} diff --git a/app/notification/rpc/internal/logic/searchNotificationsLogic.go b/app/notification/rpc/internal/logic/searchNotificationsLogic.go new file mode 100644 index 0000000..3f1aa2b --- /dev/null +++ b/app/notification/rpc/internal/logic/searchNotificationsLogic.go @@ -0,0 +1,72 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/notification/rpc/internal/models/notifications" + "juwan-backend/app/notification/rpc/internal/svc" + "juwan-backend/app/notification/rpc/pb" + + "entgo.io/ent/dialect/sql" + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchNotificationsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchNotificationsLogic { + return &SearchNotificationsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchNotificationsLogic) SearchNotifications(in *pb.SearchNotificationsReq) (*pb.SearchNotificationsResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + if limit > 100 { + return nil, errors.New("limit too large") + } + offset := in.GetOffset() + if offset < 0 { + offset = 0 + } + + query := l.svcCtx.NotificationModelRO.Notifications.Query() + if in.Id != nil { + query = query.Where(notifications.IDEQ(in.GetId())) + } + if in.UserId != nil { + query = query.Where(notifications.UserIDEQ(in.GetUserId())) + } + if in.Type != nil { + query = query.Where(notifications.TypeEQ(in.GetType())) + } + if in.Read != nil { + query = query.Where(notifications.ReadEQ(in.GetRead())) + } + + list, err := query. + Order(notifications.ByCreatedAt(sql.OrderDesc()), notifications.ByID(sql.OrderDesc())). + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchNotifications err: %v", err) + return nil, errors.New("search notifications failed") + } + + out := make([]*pb.Notifications, len(list)) + for i, n := range list { + out[i] = entNotificationToPb(n) + } + + return &pb.SearchNotificationsResp{Notifications: out}, nil +} diff --git a/app/notification/rpc/internal/logic/updateNotificationsLogic.go b/app/notification/rpc/internal/logic/updateNotificationsLogic.go new file mode 100644 index 0000000..b20d638 --- /dev/null +++ b/app/notification/rpc/internal/logic/updateNotificationsLogic.go @@ -0,0 +1,55 @@ +package logic + +import ( + "context" + "time" + + "juwan-backend/app/notification/rpc/internal/svc" + "juwan-backend/app/notification/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateNotificationsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateNotificationsLogic { + return &UpdateNotificationsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateNotificationsLogic) UpdateNotifications(in *pb.UpdateNotificationsReq) (*pb.UpdateNotificationsResp, error) { + updater := l.svcCtx.NotificationModelRW.Notifications.UpdateOneID(in.GetId()) + if in.Read != nil { + updater = updater.SetRead(in.GetRead()) + } + if in.Type != nil { + updater = updater.SetType(in.GetType()) + } + if in.Title != nil { + updater = updater.SetTitle(in.GetTitle()) + } + if in.Content != nil { + updater = updater.SetContent(in.GetContent()) + } + if in.Link != nil { + updater = updater.SetLink(in.GetLink()) + } + if in.UpdatedAt != nil { + updater = updater.SetUpdatedAt(time.Unix(in.GetUpdatedAt(), 0)) + } + + _, err := updater.Save(l.ctx) + if err != nil { + logx.Errorf("updateNotifications err: %v", err) + return nil, err + } + + return &pb.UpdateNotificationsResp{}, nil +} diff --git a/app/notification/rpc/internal/models/client.go b/app/notification/rpc/internal/models/client.go new file mode 100644 index 0000000..be2c09a --- /dev/null +++ b/app/notification/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/notification/rpc/internal/models/migrate" + + "juwan-backend/app/notification/rpc/internal/models/notifications" + + "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 + // Notifications is the client for interacting with the Notifications builders. + Notifications *NotificationsClient +} + +// 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.Notifications = NewNotificationsClient(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, + Notifications: NewNotificationsClient(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, + Notifications: NewNotificationsClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Notifications. +// 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.Notifications.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.Notifications.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *NotificationsMutation: + return c.Notifications.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// NotificationsClient is a client for the Notifications schema. +type NotificationsClient struct { + config +} + +// NewNotificationsClient returns a client for the Notifications from the given config. +func NewNotificationsClient(c config) *NotificationsClient { + return &NotificationsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `notifications.Hooks(f(g(h())))`. +func (c *NotificationsClient) Use(hooks ...Hook) { + c.hooks.Notifications = append(c.hooks.Notifications, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `notifications.Intercept(f(g(h())))`. +func (c *NotificationsClient) Intercept(interceptors ...Interceptor) { + c.inters.Notifications = append(c.inters.Notifications, interceptors...) +} + +// Create returns a builder for creating a Notifications entity. +func (c *NotificationsClient) Create() *NotificationsCreate { + mutation := newNotificationsMutation(c.config, OpCreate) + return &NotificationsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Notifications entities. +func (c *NotificationsClient) CreateBulk(builders ...*NotificationsCreate) *NotificationsCreateBulk { + return &NotificationsCreateBulk{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 *NotificationsClient) MapCreateBulk(slice any, setFunc func(*NotificationsCreate, int)) *NotificationsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &NotificationsCreateBulk{err: fmt.Errorf("calling to NotificationsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*NotificationsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &NotificationsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Notifications. +func (c *NotificationsClient) Update() *NotificationsUpdate { + mutation := newNotificationsMutation(c.config, OpUpdate) + return &NotificationsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *NotificationsClient) UpdateOne(_m *Notifications) *NotificationsUpdateOne { + mutation := newNotificationsMutation(c.config, OpUpdateOne, withNotifications(_m)) + return &NotificationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *NotificationsClient) UpdateOneID(id int64) *NotificationsUpdateOne { + mutation := newNotificationsMutation(c.config, OpUpdateOne, withNotificationsID(id)) + return &NotificationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Notifications. +func (c *NotificationsClient) Delete() *NotificationsDelete { + mutation := newNotificationsMutation(c.config, OpDelete) + return &NotificationsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *NotificationsClient) DeleteOne(_m *Notifications) *NotificationsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *NotificationsClient) DeleteOneID(id int64) *NotificationsDeleteOne { + builder := c.Delete().Where(notifications.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &NotificationsDeleteOne{builder} +} + +// Query returns a query builder for Notifications. +func (c *NotificationsClient) Query() *NotificationsQuery { + return &NotificationsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeNotifications}, + inters: c.Interceptors(), + } +} + +// Get returns a Notifications entity by its id. +func (c *NotificationsClient) Get(ctx context.Context, id int64) (*Notifications, error) { + return c.Query().Where(notifications.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *NotificationsClient) GetX(ctx context.Context, id int64) *Notifications { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *NotificationsClient) Hooks() []Hook { + return c.hooks.Notifications +} + +// Interceptors returns the client interceptors. +func (c *NotificationsClient) Interceptors() []Interceptor { + return c.inters.Notifications +} + +func (c *NotificationsClient) mutate(ctx context.Context, m *NotificationsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&NotificationsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&NotificationsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&NotificationsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&NotificationsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Notifications mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Notifications []ent.Hook + } + inters struct { + Notifications []ent.Interceptor + } +) diff --git a/app/notification/rpc/internal/models/ent.go b/app/notification/rpc/internal/models/ent.go new file mode 100644 index 0000000..29bde9a --- /dev/null +++ b/app/notification/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/notification/rpc/internal/models/notifications" + "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{ + notifications.Table: notifications.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/notification/rpc/internal/models/enttest/enttest.go b/app/notification/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..35a142e --- /dev/null +++ b/app/notification/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/notification/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/notification/rpc/internal/models/runtime" + + "juwan-backend/app/notification/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/notification/rpc/internal/models/generate.go b/app/notification/rpc/internal/models/generate.go new file mode 100644 index 0000000..d441aca --- /dev/null +++ b/app/notification/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/notification/rpc/internal/models/hook/hook.go b/app/notification/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..2ad01b1 --- /dev/null +++ b/app/notification/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/notification/rpc/internal/models" +) + +// The NotificationsFunc type is an adapter to allow the use of ordinary +// function as Notifications mutator. +type NotificationsFunc func(context.Context, *models.NotificationsMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f NotificationsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.NotificationsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.NotificationsMutation", 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/notification/rpc/internal/models/migrate/migrate.go b/app/notification/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/notification/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/notification/rpc/internal/models/migrate/schema.go b/app/notification/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..e859a3c --- /dev/null +++ b/app/notification/rpc/internal/models/migrate/schema.go @@ -0,0 +1,53 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // NotificationsColumns holds the columns for the "notifications" table. + NotificationsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "user_id", Type: field.TypeInt64}, + {Name: "type", Type: field.TypeString, Size: 20}, + {Name: "title", Type: field.TypeString, Size: 200}, + {Name: "content", Type: field.TypeString}, + {Name: "read", Type: field.TypeBool, Default: false}, + {Name: "link", Type: field.TypeString, Nullable: true, Size: 500}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // NotificationsTable holds the schema information for the "notifications" table. + NotificationsTable = &schema.Table{ + Name: "notifications", + Columns: NotificationsColumns, + PrimaryKey: []*schema.Column{NotificationsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "notifications_user_id_created_at", + Unique: false, + Columns: []*schema.Column{NotificationsColumns[1], NotificationsColumns[7]}, + }, + { + Name: "notifications_user_id_read_created_at", + Unique: false, + Columns: []*schema.Column{NotificationsColumns[1], NotificationsColumns[5], NotificationsColumns[7]}, + }, + { + Name: "notifications_user_id_type_created_at", + Unique: false, + Columns: []*schema.Column{NotificationsColumns[1], NotificationsColumns[2], NotificationsColumns[7]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + NotificationsTable, + } +) + +func init() { +} diff --git a/app/notification/rpc/internal/models/mutation.go b/app/notification/rpc/internal/models/mutation.go new file mode 100644 index 0000000..0addc3a --- /dev/null +++ b/app/notification/rpc/internal/models/mutation.go @@ -0,0 +1,796 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/notification/rpc/internal/models/notifications" + "juwan-backend/app/notification/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. + TypeNotifications = "Notifications" +) + +// NotificationsMutation represents an operation that mutates the Notifications nodes in the graph. +type NotificationsMutation struct { + config + op Op + typ string + id *int64 + user_id *int64 + adduser_id *int64 + _type *string + title *string + content *string + read *bool + link *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Notifications, error) + predicates []predicate.Notifications +} + +var _ ent.Mutation = (*NotificationsMutation)(nil) + +// notificationsOption allows management of the mutation configuration using functional options. +type notificationsOption func(*NotificationsMutation) + +// newNotificationsMutation creates new mutation for the Notifications entity. +func newNotificationsMutation(c config, op Op, opts ...notificationsOption) *NotificationsMutation { + m := &NotificationsMutation{ + config: c, + op: op, + typ: TypeNotifications, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withNotificationsID sets the ID field of the mutation. +func withNotificationsID(id int64) notificationsOption { + return func(m *NotificationsMutation) { + var ( + err error + once sync.Once + value *Notifications + ) + m.oldValue = func(ctx context.Context) (*Notifications, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Notifications.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withNotifications sets the old Notifications of the mutation. +func withNotifications(node *Notifications) notificationsOption { + return func(m *NotificationsMutation) { + m.oldValue = func(context.Context) (*Notifications, 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 NotificationsMutation) 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 NotificationsMutation) 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 Notifications entities. +func (m *NotificationsMutation) 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 *NotificationsMutation) 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 *NotificationsMutation) 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().Notifications.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 *NotificationsMutation) 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 *NotificationsMutation) 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 Notifications entity. +// If the Notifications 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 *NotificationsMutation) 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 *NotificationsMutation) 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 *NotificationsMutation) 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 *NotificationsMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetType sets the "type" field. +func (m *NotificationsMutation) SetType(s string) { + m._type = &s +} + +// GetType returns the value of the "type" field in the mutation. +func (m *NotificationsMutation) 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 Notifications entity. +// If the Notifications 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 *NotificationsMutation) 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 *NotificationsMutation) ResetType() { + m._type = nil +} + +// SetTitle sets the "title" field. +func (m *NotificationsMutation) SetTitle(s string) { + m.title = &s +} + +// Title returns the value of the "title" field in the mutation. +func (m *NotificationsMutation) Title() (r string, exists bool) { + v := m.title + if v == nil { + return + } + return *v, true +} + +// OldTitle returns the old "title" field's value of the Notifications entity. +// If the Notifications 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 *NotificationsMutation) OldTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTitle: %w", err) + } + return oldValue.Title, nil +} + +// ResetTitle resets all changes to the "title" field. +func (m *NotificationsMutation) ResetTitle() { + m.title = nil +} + +// SetContent sets the "content" field. +func (m *NotificationsMutation) SetContent(s string) { + m.content = &s +} + +// Content returns the value of the "content" field in the mutation. +func (m *NotificationsMutation) Content() (r string, exists bool) { + v := m.content + if v == nil { + return + } + return *v, true +} + +// OldContent returns the old "content" field's value of the Notifications entity. +// If the Notifications 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 *NotificationsMutation) OldContent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContent: %w", err) + } + return oldValue.Content, nil +} + +// ResetContent resets all changes to the "content" field. +func (m *NotificationsMutation) ResetContent() { + m.content = nil +} + +// SetRead sets the "read" field. +func (m *NotificationsMutation) SetRead(b bool) { + m.read = &b +} + +// Read returns the value of the "read" field in the mutation. +func (m *NotificationsMutation) Read() (r bool, exists bool) { + v := m.read + if v == nil { + return + } + return *v, true +} + +// OldRead returns the old "read" field's value of the Notifications entity. +// If the Notifications 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 *NotificationsMutation) OldRead(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRead is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRead requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRead: %w", err) + } + return oldValue.Read, nil +} + +// ResetRead resets all changes to the "read" field. +func (m *NotificationsMutation) ResetRead() { + m.read = nil +} + +// SetLink sets the "link" field. +func (m *NotificationsMutation) SetLink(s string) { + m.link = &s +} + +// Link returns the value of the "link" field in the mutation. +func (m *NotificationsMutation) Link() (r string, exists bool) { + v := m.link + if v == nil { + return + } + return *v, true +} + +// OldLink returns the old "link" field's value of the Notifications entity. +// If the Notifications 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 *NotificationsMutation) OldLink(ctx context.Context) (v *string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLink is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLink requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLink: %w", err) + } + return oldValue.Link, nil +} + +// ClearLink clears the value of the "link" field. +func (m *NotificationsMutation) ClearLink() { + m.link = nil + m.clearedFields[notifications.FieldLink] = struct{}{} +} + +// LinkCleared returns if the "link" field was cleared in this mutation. +func (m *NotificationsMutation) LinkCleared() bool { + _, ok := m.clearedFields[notifications.FieldLink] + return ok +} + +// ResetLink resets all changes to the "link" field. +func (m *NotificationsMutation) ResetLink() { + m.link = nil + delete(m.clearedFields, notifications.FieldLink) +} + +// SetCreatedAt sets the "created_at" field. +func (m *NotificationsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *NotificationsMutation) 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 Notifications entity. +// If the Notifications 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 *NotificationsMutation) 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 *NotificationsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *NotificationsMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *NotificationsMutation) 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 Notifications entity. +// If the Notifications 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 *NotificationsMutation) 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 *NotificationsMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the NotificationsMutation builder. +func (m *NotificationsMutation) Where(ps ...predicate.Notifications) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the NotificationsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *NotificationsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Notifications, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *NotificationsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *NotificationsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Notifications). +func (m *NotificationsMutation) 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 *NotificationsMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.user_id != nil { + fields = append(fields, notifications.FieldUserID) + } + if m._type != nil { + fields = append(fields, notifications.FieldType) + } + if m.title != nil { + fields = append(fields, notifications.FieldTitle) + } + if m.content != nil { + fields = append(fields, notifications.FieldContent) + } + if m.read != nil { + fields = append(fields, notifications.FieldRead) + } + if m.link != nil { + fields = append(fields, notifications.FieldLink) + } + if m.created_at != nil { + fields = append(fields, notifications.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, notifications.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 *NotificationsMutation) Field(name string) (ent.Value, bool) { + switch name { + case notifications.FieldUserID: + return m.UserID() + case notifications.FieldType: + return m.GetType() + case notifications.FieldTitle: + return m.Title() + case notifications.FieldContent: + return m.Content() + case notifications.FieldRead: + return m.Read() + case notifications.FieldLink: + return m.Link() + case notifications.FieldCreatedAt: + return m.CreatedAt() + case notifications.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 *NotificationsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case notifications.FieldUserID: + return m.OldUserID(ctx) + case notifications.FieldType: + return m.OldType(ctx) + case notifications.FieldTitle: + return m.OldTitle(ctx) + case notifications.FieldContent: + return m.OldContent(ctx) + case notifications.FieldRead: + return m.OldRead(ctx) + case notifications.FieldLink: + return m.OldLink(ctx) + case notifications.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case notifications.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Notifications 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 *NotificationsMutation) SetField(name string, value ent.Value) error { + switch name { + case notifications.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case notifications.FieldType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case notifications.FieldTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTitle(v) + return nil + case notifications.FieldContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) + return nil + case notifications.FieldRead: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRead(v) + return nil + case notifications.FieldLink: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLink(v) + return nil + case notifications.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 notifications.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 Notifications field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *NotificationsMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, notifications.FieldUserID) + } + 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 *NotificationsMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case notifications.FieldUserID: + return m.AddedUserID() + } + 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 *NotificationsMutation) AddField(name string, value ent.Value) error { + switch name { + case notifications.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + } + return fmt.Errorf("unknown Notifications numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *NotificationsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(notifications.FieldLink) { + fields = append(fields, notifications.FieldLink) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *NotificationsMutation) 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 *NotificationsMutation) ClearField(name string) error { + switch name { + case notifications.FieldLink: + m.ClearLink() + return nil + } + return fmt.Errorf("unknown Notifications 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 *NotificationsMutation) ResetField(name string) error { + switch name { + case notifications.FieldUserID: + m.ResetUserID() + return nil + case notifications.FieldType: + m.ResetType() + return nil + case notifications.FieldTitle: + m.ResetTitle() + return nil + case notifications.FieldContent: + m.ResetContent() + return nil + case notifications.FieldRead: + m.ResetRead() + return nil + case notifications.FieldLink: + m.ResetLink() + return nil + case notifications.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case notifications.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Notifications field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *NotificationsMutation) 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 *NotificationsMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *NotificationsMutation) 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 *NotificationsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *NotificationsMutation) 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 *NotificationsMutation) 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 *NotificationsMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Notifications 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 *NotificationsMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Notifications edge %s", name) +} diff --git a/app/notification/rpc/internal/models/notifications.go b/app/notification/rpc/internal/models/notifications.go new file mode 100644 index 0000000..026f04d --- /dev/null +++ b/app/notification/rpc/internal/models/notifications.go @@ -0,0 +1,188 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/notification/rpc/internal/models/notifications" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Notifications is the model entity for the Notifications schema. +type Notifications struct { + config `json:"-"` + // ID of the ent. + ID int64 `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"` + // Title holds the value of the "title" field. + Title string `json:"title,omitempty"` + // Content holds the value of the "content" field. + Content string `json:"content,omitempty"` + // Read holds the value of the "read" field. + Read bool `json:"read,omitempty"` + // Link holds the value of the "link" field. + Link *string `json:"link,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 (*Notifications) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case notifications.FieldRead: + values[i] = new(sql.NullBool) + case notifications.FieldID, notifications.FieldUserID: + values[i] = new(sql.NullInt64) + case notifications.FieldType, notifications.FieldTitle, notifications.FieldContent, notifications.FieldLink: + values[i] = new(sql.NullString) + case notifications.FieldCreatedAt, notifications.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 Notifications fields. +func (_m *Notifications) 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 notifications.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 notifications.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 notifications.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 notifications.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + _m.Title = value.String + } + case notifications.FieldContent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field content", values[i]) + } else if value.Valid { + _m.Content = value.String + } + case notifications.FieldRead: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field read", values[i]) + } else if value.Valid { + _m.Read = value.Bool + } + case notifications.FieldLink: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field link", values[i]) + } else if value.Valid { + _m.Link = new(string) + *_m.Link = value.String + } + case notifications.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 notifications.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 Notifications. +// This includes values selected through modifiers, order, etc. +func (_m *Notifications) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Notifications. +// Note that you need to call Notifications.Unwrap() before calling this method if this Notifications +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Notifications) Update() *NotificationsUpdateOne { + return NewNotificationsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Notifications 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 *Notifications) Unwrap() *Notifications { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Notifications is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Notifications) String() string { + var builder strings.Builder + builder.WriteString("Notifications(") + 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("title=") + builder.WriteString(_m.Title) + builder.WriteString(", ") + builder.WriteString("content=") + builder.WriteString(_m.Content) + builder.WriteString(", ") + builder.WriteString("read=") + builder.WriteString(fmt.Sprintf("%v", _m.Read)) + builder.WriteString(", ") + if v := _m.Link; v != nil { + builder.WriteString("link=") + builder.WriteString(*v) + } + 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() +} + +// NotificationsSlice is a parsable slice of Notifications. +type NotificationsSlice []*Notifications diff --git a/app/notification/rpc/internal/models/notifications/notifications.go b/app/notification/rpc/internal/models/notifications/notifications.go new file mode 100644 index 0000000..49efac1 --- /dev/null +++ b/app/notification/rpc/internal/models/notifications/notifications.go @@ -0,0 +1,122 @@ +// Code generated by ent, DO NOT EDIT. + +package notifications + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the notifications type in the database. + Label = "notifications" + // 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" + // FieldTitle holds the string denoting the title field in the database. + FieldTitle = "title" + // FieldContent holds the string denoting the content field in the database. + FieldContent = "content" + // FieldRead holds the string denoting the read field in the database. + FieldRead = "read" + // FieldLink holds the string denoting the link field in the database. + FieldLink = "link" + // 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 notifications in the database. + Table = "notifications" +) + +// Columns holds all SQL columns for notifications fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldType, + FieldTitle, + FieldContent, + FieldRead, + FieldLink, + 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 ( + // TypeValidator is a validator for the "type" field. It is called by the builders before save. + TypeValidator func(string) error + // TitleValidator is a validator for the "title" field. It is called by the builders before save. + TitleValidator func(string) error + // DefaultRead holds the default value on creation for the "read" field. + DefaultRead bool + // LinkValidator is a validator for the "link" field. It is called by the builders before save. + LinkValidator 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 Notifications 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() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByContent orders the results by the content field. +func ByContent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContent, opts...).ToFunc() +} + +// ByRead orders the results by the read field. +func ByRead(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRead, opts...).ToFunc() +} + +// ByLink orders the results by the link field. +func ByLink(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLink, 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/notification/rpc/internal/models/notifications/where.go b/app/notification/rpc/internal/models/notifications/where.go new file mode 100644 index 0000000..3fda527 --- /dev/null +++ b/app/notification/rpc/internal/models/notifications/where.go @@ -0,0 +1,510 @@ +// Code generated by ent, DO NOT EDIT. + +package notifications + +import ( + "juwan-backend/app/notification/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldID, id)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldUserID, v)) +} + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldType, v)) +} + +// Title applies equality check predicate on the "title" field. It's identical to TitleEQ. +func Title(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldTitle, v)) +} + +// Content applies equality check predicate on the "content" field. It's identical to ContentEQ. +func Content(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldContent, v)) +} + +// Read applies equality check predicate on the "read" field. It's identical to ReadEQ. +func Read(v bool) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldRead, v)) +} + +// Link applies equality check predicate on the "link" field. It's identical to LinkEQ. +func Link(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldLink, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Notifications { + return predicate.Notifications(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.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int64) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int64) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int64) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int64) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldUserID, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldType, v)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldType, v)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldType, vs...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldType, vs...)) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldType, v)) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldType, v)) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldType, v)) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldType, v)) +} + +// TypeContains applies the Contains predicate on the "type" field. +func TypeContains(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContains(FieldType, v)) +} + +// TypeHasPrefix applies the HasPrefix predicate on the "type" field. +func TypeHasPrefix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasPrefix(FieldType, v)) +} + +// TypeHasSuffix applies the HasSuffix predicate on the "type" field. +func TypeHasSuffix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasSuffix(FieldType, v)) +} + +// TypeEqualFold applies the EqualFold predicate on the "type" field. +func TypeEqualFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEqualFold(FieldType, v)) +} + +// TypeContainsFold applies the ContainsFold predicate on the "type" field. +func TypeContainsFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContainsFold(FieldType, v)) +} + +// TitleEQ applies the EQ predicate on the "title" field. +func TitleEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldTitle, v)) +} + +// TitleNEQ applies the NEQ predicate on the "title" field. +func TitleNEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldTitle, v)) +} + +// TitleIn applies the In predicate on the "title" field. +func TitleIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldTitle, vs...)) +} + +// TitleNotIn applies the NotIn predicate on the "title" field. +func TitleNotIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldTitle, vs...)) +} + +// TitleGT applies the GT predicate on the "title" field. +func TitleGT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldTitle, v)) +} + +// TitleGTE applies the GTE predicate on the "title" field. +func TitleGTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldTitle, v)) +} + +// TitleLT applies the LT predicate on the "title" field. +func TitleLT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldTitle, v)) +} + +// TitleLTE applies the LTE predicate on the "title" field. +func TitleLTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldTitle, v)) +} + +// TitleContains applies the Contains predicate on the "title" field. +func TitleContains(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContains(FieldTitle, v)) +} + +// TitleHasPrefix applies the HasPrefix predicate on the "title" field. +func TitleHasPrefix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasPrefix(FieldTitle, v)) +} + +// TitleHasSuffix applies the HasSuffix predicate on the "title" field. +func TitleHasSuffix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasSuffix(FieldTitle, v)) +} + +// TitleEqualFold applies the EqualFold predicate on the "title" field. +func TitleEqualFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEqualFold(FieldTitle, v)) +} + +// TitleContainsFold applies the ContainsFold predicate on the "title" field. +func TitleContainsFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContainsFold(FieldTitle, v)) +} + +// ContentEQ applies the EQ predicate on the "content" field. +func ContentEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldContent, v)) +} + +// ContentNEQ applies the NEQ predicate on the "content" field. +func ContentNEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldContent, v)) +} + +// ContentIn applies the In predicate on the "content" field. +func ContentIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldContent, vs...)) +} + +// ContentNotIn applies the NotIn predicate on the "content" field. +func ContentNotIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldContent, vs...)) +} + +// ContentGT applies the GT predicate on the "content" field. +func ContentGT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldContent, v)) +} + +// ContentGTE applies the GTE predicate on the "content" field. +func ContentGTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldContent, v)) +} + +// ContentLT applies the LT predicate on the "content" field. +func ContentLT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldContent, v)) +} + +// ContentLTE applies the LTE predicate on the "content" field. +func ContentLTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldContent, v)) +} + +// ContentContains applies the Contains predicate on the "content" field. +func ContentContains(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContains(FieldContent, v)) +} + +// ContentHasPrefix applies the HasPrefix predicate on the "content" field. +func ContentHasPrefix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasPrefix(FieldContent, v)) +} + +// ContentHasSuffix applies the HasSuffix predicate on the "content" field. +func ContentHasSuffix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasSuffix(FieldContent, v)) +} + +// ContentEqualFold applies the EqualFold predicate on the "content" field. +func ContentEqualFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEqualFold(FieldContent, v)) +} + +// ContentContainsFold applies the ContainsFold predicate on the "content" field. +func ContentContainsFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContainsFold(FieldContent, v)) +} + +// ReadEQ applies the EQ predicate on the "read" field. +func ReadEQ(v bool) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldRead, v)) +} + +// ReadNEQ applies the NEQ predicate on the "read" field. +func ReadNEQ(v bool) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldRead, v)) +} + +// LinkEQ applies the EQ predicate on the "link" field. +func LinkEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldLink, v)) +} + +// LinkNEQ applies the NEQ predicate on the "link" field. +func LinkNEQ(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldLink, v)) +} + +// LinkIn applies the In predicate on the "link" field. +func LinkIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldLink, vs...)) +} + +// LinkNotIn applies the NotIn predicate on the "link" field. +func LinkNotIn(vs ...string) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldLink, vs...)) +} + +// LinkGT applies the GT predicate on the "link" field. +func LinkGT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldLink, v)) +} + +// LinkGTE applies the GTE predicate on the "link" field. +func LinkGTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldLink, v)) +} + +// LinkLT applies the LT predicate on the "link" field. +func LinkLT(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldLink, v)) +} + +// LinkLTE applies the LTE predicate on the "link" field. +func LinkLTE(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldLink, v)) +} + +// LinkContains applies the Contains predicate on the "link" field. +func LinkContains(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContains(FieldLink, v)) +} + +// LinkHasPrefix applies the HasPrefix predicate on the "link" field. +func LinkHasPrefix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasPrefix(FieldLink, v)) +} + +// LinkHasSuffix applies the HasSuffix predicate on the "link" field. +func LinkHasSuffix(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldHasSuffix(FieldLink, v)) +} + +// LinkIsNil applies the IsNil predicate on the "link" field. +func LinkIsNil() predicate.Notifications { + return predicate.Notifications(sql.FieldIsNull(FieldLink)) +} + +// LinkNotNil applies the NotNil predicate on the "link" field. +func LinkNotNil() predicate.Notifications { + return predicate.Notifications(sql.FieldNotNull(FieldLink)) +} + +// LinkEqualFold applies the EqualFold predicate on the "link" field. +func LinkEqualFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldEqualFold(FieldLink, v)) +} + +// LinkContainsFold applies the ContainsFold predicate on the "link" field. +func LinkContainsFold(v string) predicate.Notifications { + return predicate.Notifications(sql.FieldContainsFold(FieldLink, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Notifications { + return predicate.Notifications(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Notifications) predicate.Notifications { + return predicate.Notifications(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Notifications) predicate.Notifications { + return predicate.Notifications(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Notifications) predicate.Notifications { + return predicate.Notifications(sql.NotPredicates(p)) +} diff --git a/app/notification/rpc/internal/models/notifications_create.go b/app/notification/rpc/internal/models/notifications_create.go new file mode 100644 index 0000000..5138fae --- /dev/null +++ b/app/notification/rpc/internal/models/notifications_create.go @@ -0,0 +1,349 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/notification/rpc/internal/models/notifications" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// NotificationsCreate is the builder for creating a Notifications entity. +type NotificationsCreate struct { + config + mutation *NotificationsMutation + hooks []Hook +} + +// SetUserID sets the "user_id" field. +func (_c *NotificationsCreate) SetUserID(v int64) *NotificationsCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetType sets the "type" field. +func (_c *NotificationsCreate) SetType(v string) *NotificationsCreate { + _c.mutation.SetType(v) + return _c +} + +// SetTitle sets the "title" field. +func (_c *NotificationsCreate) SetTitle(v string) *NotificationsCreate { + _c.mutation.SetTitle(v) + return _c +} + +// SetContent sets the "content" field. +func (_c *NotificationsCreate) SetContent(v string) *NotificationsCreate { + _c.mutation.SetContent(v) + return _c +} + +// SetRead sets the "read" field. +func (_c *NotificationsCreate) SetRead(v bool) *NotificationsCreate { + _c.mutation.SetRead(v) + return _c +} + +// SetNillableRead sets the "read" field if the given value is not nil. +func (_c *NotificationsCreate) SetNillableRead(v *bool) *NotificationsCreate { + if v != nil { + _c.SetRead(*v) + } + return _c +} + +// SetLink sets the "link" field. +func (_c *NotificationsCreate) SetLink(v string) *NotificationsCreate { + _c.mutation.SetLink(v) + return _c +} + +// SetNillableLink sets the "link" field if the given value is not nil. +func (_c *NotificationsCreate) SetNillableLink(v *string) *NotificationsCreate { + if v != nil { + _c.SetLink(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *NotificationsCreate) SetCreatedAt(v time.Time) *NotificationsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *NotificationsCreate) SetNillableCreatedAt(v *time.Time) *NotificationsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *NotificationsCreate) SetUpdatedAt(v time.Time) *NotificationsCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *NotificationsCreate) SetNillableUpdatedAt(v *time.Time) *NotificationsCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *NotificationsCreate) SetID(v int64) *NotificationsCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the NotificationsMutation object of the builder. +func (_c *NotificationsCreate) Mutation() *NotificationsMutation { + return _c.mutation +} + +// Save creates the Notifications in the database. +func (_c *NotificationsCreate) Save(ctx context.Context) (*Notifications, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *NotificationsCreate) SaveX(ctx context.Context) *Notifications { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationsCreate) 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 *NotificationsCreate) defaults() { + if _, ok := _c.mutation.Read(); !ok { + v := notifications.DefaultRead + _c.mutation.SetRead(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := notifications.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := notifications.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *NotificationsCreate) check() error { + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "Notifications.user_id"`)} + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`models: missing required field "Notifications.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := notifications.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`models: validator failed for field "Notifications.type": %w`, err)} + } + } + if _, ok := _c.mutation.Title(); !ok { + return &ValidationError{Name: "title", err: errors.New(`models: missing required field "Notifications.title"`)} + } + if v, ok := _c.mutation.Title(); ok { + if err := notifications.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`models: validator failed for field "Notifications.title": %w`, err)} + } + } + if _, ok := _c.mutation.Content(); !ok { + return &ValidationError{Name: "content", err: errors.New(`models: missing required field "Notifications.content"`)} + } + if _, ok := _c.mutation.Read(); !ok { + return &ValidationError{Name: "read", err: errors.New(`models: missing required field "Notifications.read"`)} + } + if v, ok := _c.mutation.Link(); ok { + if err := notifications.LinkValidator(v); err != nil { + return &ValidationError{Name: "link", err: fmt.Errorf(`models: validator failed for field "Notifications.link": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Notifications.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Notifications.updated_at"`)} + } + return nil +} + +func (_c *NotificationsCreate) sqlSave(ctx context.Context) (*Notifications, 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 *NotificationsCreate) createSpec() (*Notifications, *sqlgraph.CreateSpec) { + var ( + _node = &Notifications{config: _c.config} + _spec = sqlgraph.NewCreateSpec(notifications.Table, sqlgraph.NewFieldSpec(notifications.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(notifications.FieldUserID, field.TypeInt64, value) + _node.UserID = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(notifications.FieldType, field.TypeString, value) + _node.Type = value + } + if value, ok := _c.mutation.Title(); ok { + _spec.SetField(notifications.FieldTitle, field.TypeString, value) + _node.Title = value + } + if value, ok := _c.mutation.Content(); ok { + _spec.SetField(notifications.FieldContent, field.TypeString, value) + _node.Content = value + } + if value, ok := _c.mutation.Read(); ok { + _spec.SetField(notifications.FieldRead, field.TypeBool, value) + _node.Read = value + } + if value, ok := _c.mutation.Link(); ok { + _spec.SetField(notifications.FieldLink, field.TypeString, value) + _node.Link = &value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(notifications.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(notifications.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + return _node, _spec +} + +// NotificationsCreateBulk is the builder for creating many Notifications entities in bulk. +type NotificationsCreateBulk struct { + config + err error + builders []*NotificationsCreate +} + +// Save creates the Notifications entities in the database. +func (_c *NotificationsCreateBulk) Save(ctx context.Context) ([]*Notifications, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Notifications, 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.(*NotificationsMutation) + 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 *NotificationsCreateBulk) SaveX(ctx context.Context) []*Notifications { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *NotificationsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *NotificationsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/notification/rpc/internal/models/notifications_delete.go b/app/notification/rpc/internal/models/notifications_delete.go new file mode 100644 index 0000000..d3ab66a --- /dev/null +++ b/app/notification/rpc/internal/models/notifications_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/notification/rpc/internal/models/notifications" + "juwan-backend/app/notification/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// NotificationsDelete is the builder for deleting a Notifications entity. +type NotificationsDelete struct { + config + hooks []Hook + mutation *NotificationsMutation +} + +// Where appends a list predicates to the NotificationsDelete builder. +func (_d *NotificationsDelete) Where(ps ...predicate.Notifications) *NotificationsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *NotificationsDelete) 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 *NotificationsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *NotificationsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(notifications.Table, sqlgraph.NewFieldSpec(notifications.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 +} + +// NotificationsDeleteOne is the builder for deleting a single Notifications entity. +type NotificationsDeleteOne struct { + _d *NotificationsDelete +} + +// Where appends a list predicates to the NotificationsDelete builder. +func (_d *NotificationsDeleteOne) Where(ps ...predicate.Notifications) *NotificationsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *NotificationsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{notifications.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *NotificationsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/notification/rpc/internal/models/notifications_query.go b/app/notification/rpc/internal/models/notifications_query.go new file mode 100644 index 0000000..14f8ee0 --- /dev/null +++ b/app/notification/rpc/internal/models/notifications_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/notification/rpc/internal/models/notifications" + "juwan-backend/app/notification/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// NotificationsQuery is the builder for querying Notifications entities. +type NotificationsQuery struct { + config + ctx *QueryContext + order []notifications.OrderOption + inters []Interceptor + predicates []predicate.Notifications + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the NotificationsQuery builder. +func (_q *NotificationsQuery) Where(ps ...predicate.Notifications) *NotificationsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *NotificationsQuery) Limit(limit int) *NotificationsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *NotificationsQuery) Offset(offset int) *NotificationsQuery { + _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 *NotificationsQuery) Unique(unique bool) *NotificationsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *NotificationsQuery) Order(o ...notifications.OrderOption) *NotificationsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Notifications entity from the query. +// Returns a *NotFoundError when no Notifications was found. +func (_q *NotificationsQuery) First(ctx context.Context) (*Notifications, 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{notifications.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *NotificationsQuery) FirstX(ctx context.Context) *Notifications { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Notifications ID from the query. +// Returns a *NotFoundError when no Notifications ID was found. +func (_q *NotificationsQuery) 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{notifications.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *NotificationsQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Notifications entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Notifications entity is found. +// Returns a *NotFoundError when no Notifications entities are found. +func (_q *NotificationsQuery) Only(ctx context.Context) (*Notifications, 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{notifications.Label} + default: + return nil, &NotSingularError{notifications.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *NotificationsQuery) OnlyX(ctx context.Context) *Notifications { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Notifications ID in the query. +// Returns a *NotSingularError when more than one Notifications ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *NotificationsQuery) 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{notifications.Label} + default: + err = &NotSingularError{notifications.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *NotificationsQuery) 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 NotificationsSlice. +func (_q *NotificationsQuery) All(ctx context.Context) ([]*Notifications, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Notifications, *NotificationsQuery]() + return withInterceptors[[]*Notifications](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *NotificationsQuery) AllX(ctx context.Context) []*Notifications { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Notifications IDs. +func (_q *NotificationsQuery) 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(notifications.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *NotificationsQuery) 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 *NotificationsQuery) 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[*NotificationsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *NotificationsQuery) 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 *NotificationsQuery) 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 *NotificationsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the NotificationsQuery 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 *NotificationsQuery) Clone() *NotificationsQuery { + if _q == nil { + return nil + } + return &NotificationsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]notifications.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Notifications{}, _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.Notifications.Query(). +// GroupBy(notifications.FieldUserID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *NotificationsQuery) GroupBy(field string, fields ...string) *NotificationsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &NotificationsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = notifications.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.Notifications.Query(). +// Select(notifications.FieldUserID). +// Scan(ctx, &v) +func (_q *NotificationsQuery) Select(fields ...string) *NotificationsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &NotificationsSelect{NotificationsQuery: _q} + sbuild.label = notifications.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a NotificationsSelect configured with the given aggregations. +func (_q *NotificationsQuery) Aggregate(fns ...AggregateFunc) *NotificationsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *NotificationsQuery) 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 !notifications.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 *NotificationsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Notifications, error) { + var ( + nodes = []*Notifications{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Notifications).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Notifications{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 *NotificationsQuery) 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 *NotificationsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(notifications.Table, notifications.Columns, sqlgraph.NewFieldSpec(notifications.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, notifications.FieldID) + for i := range fields { + if fields[i] != notifications.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 *NotificationsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(notifications.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = notifications.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 +} + +// NotificationsGroupBy is the group-by builder for Notifications entities. +type NotificationsGroupBy struct { + selector + build *NotificationsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *NotificationsGroupBy) Aggregate(fns ...AggregateFunc) *NotificationsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *NotificationsGroupBy) 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[*NotificationsQuery, *NotificationsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *NotificationsGroupBy) sqlScan(ctx context.Context, root *NotificationsQuery, 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) +} + +// NotificationsSelect is the builder for selecting fields of Notifications entities. +type NotificationsSelect struct { + *NotificationsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *NotificationsSelect) Aggregate(fns ...AggregateFunc) *NotificationsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *NotificationsSelect) 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[*NotificationsQuery, *NotificationsSelect](ctx, _s.NotificationsQuery, _s, _s.inters, v) +} + +func (_s *NotificationsSelect) sqlScan(ctx context.Context, root *NotificationsQuery, 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/notification/rpc/internal/models/notifications_update.go b/app/notification/rpc/internal/models/notifications_update.go new file mode 100644 index 0000000..ed50452 --- /dev/null +++ b/app/notification/rpc/internal/models/notifications_update.go @@ -0,0 +1,500 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/notification/rpc/internal/models/notifications" + "juwan-backend/app/notification/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// NotificationsUpdate is the builder for updating Notifications entities. +type NotificationsUpdate struct { + config + hooks []Hook + mutation *NotificationsMutation +} + +// Where appends a list predicates to the NotificationsUpdate builder. +func (_u *NotificationsUpdate) Where(ps ...predicate.Notifications) *NotificationsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *NotificationsUpdate) SetUserID(v int64) *NotificationsUpdate { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *NotificationsUpdate) SetNillableUserID(v *int64) *NotificationsUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *NotificationsUpdate) AddUserID(v int64) *NotificationsUpdate { + _u.mutation.AddUserID(v) + return _u +} + +// SetType sets the "type" field. +func (_u *NotificationsUpdate) SetType(v string) *NotificationsUpdate { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *NotificationsUpdate) SetNillableType(v *string) *NotificationsUpdate { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *NotificationsUpdate) SetTitle(v string) *NotificationsUpdate { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *NotificationsUpdate) SetNillableTitle(v *string) *NotificationsUpdate { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetContent sets the "content" field. +func (_u *NotificationsUpdate) SetContent(v string) *NotificationsUpdate { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *NotificationsUpdate) SetNillableContent(v *string) *NotificationsUpdate { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetRead sets the "read" field. +func (_u *NotificationsUpdate) SetRead(v bool) *NotificationsUpdate { + _u.mutation.SetRead(v) + return _u +} + +// SetNillableRead sets the "read" field if the given value is not nil. +func (_u *NotificationsUpdate) SetNillableRead(v *bool) *NotificationsUpdate { + if v != nil { + _u.SetRead(*v) + } + return _u +} + +// SetLink sets the "link" field. +func (_u *NotificationsUpdate) SetLink(v string) *NotificationsUpdate { + _u.mutation.SetLink(v) + return _u +} + +// SetNillableLink sets the "link" field if the given value is not nil. +func (_u *NotificationsUpdate) SetNillableLink(v *string) *NotificationsUpdate { + if v != nil { + _u.SetLink(*v) + } + return _u +} + +// ClearLink clears the value of the "link" field. +func (_u *NotificationsUpdate) ClearLink() *NotificationsUpdate { + _u.mutation.ClearLink() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationsUpdate) SetUpdatedAt(v time.Time) *NotificationsUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the NotificationsMutation object of the builder. +func (_u *NotificationsUpdate) Mutation() *NotificationsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *NotificationsUpdate) 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 *NotificationsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *NotificationsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationsUpdate) 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 *NotificationsUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notifications.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationsUpdate) check() error { + if v, ok := _u.mutation.GetType(); ok { + if err := notifications.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`models: validator failed for field "Notifications.type": %w`, err)} + } + } + if v, ok := _u.mutation.Title(); ok { + if err := notifications.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`models: validator failed for field "Notifications.title": %w`, err)} + } + } + if v, ok := _u.mutation.Link(); ok { + if err := notifications.LinkValidator(v); err != nil { + return &ValidationError{Name: "link", err: fmt.Errorf(`models: validator failed for field "Notifications.link": %w`, err)} + } + } + return nil +} + +func (_u *NotificationsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notifications.Table, notifications.Columns, sqlgraph.NewFieldSpec(notifications.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.UserID(); ok { + _spec.SetField(notifications.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(notifications.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(notifications.FieldType, field.TypeString, value) + } + if value, ok := _u.mutation.Title(); ok { + _spec.SetField(notifications.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(notifications.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.Read(); ok { + _spec.SetField(notifications.FieldRead, field.TypeBool, value) + } + if value, ok := _u.mutation.Link(); ok { + _spec.SetField(notifications.FieldLink, field.TypeString, value) + } + if _u.mutation.LinkCleared() { + _spec.ClearField(notifications.FieldLink, field.TypeString) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(notifications.FieldUpdatedAt, field.TypeTime, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{notifications.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// NotificationsUpdateOne is the builder for updating a single Notifications entity. +type NotificationsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *NotificationsMutation +} + +// SetUserID sets the "user_id" field. +func (_u *NotificationsUpdateOne) SetUserID(v int64) *NotificationsUpdateOne { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *NotificationsUpdateOne) SetNillableUserID(v *int64) *NotificationsUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *NotificationsUpdateOne) AddUserID(v int64) *NotificationsUpdateOne { + _u.mutation.AddUserID(v) + return _u +} + +// SetType sets the "type" field. +func (_u *NotificationsUpdateOne) SetType(v string) *NotificationsUpdateOne { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *NotificationsUpdateOne) SetNillableType(v *string) *NotificationsUpdateOne { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetTitle sets the "title" field. +func (_u *NotificationsUpdateOne) SetTitle(v string) *NotificationsUpdateOne { + _u.mutation.SetTitle(v) + return _u +} + +// SetNillableTitle sets the "title" field if the given value is not nil. +func (_u *NotificationsUpdateOne) SetNillableTitle(v *string) *NotificationsUpdateOne { + if v != nil { + _u.SetTitle(*v) + } + return _u +} + +// SetContent sets the "content" field. +func (_u *NotificationsUpdateOne) SetContent(v string) *NotificationsUpdateOne { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *NotificationsUpdateOne) SetNillableContent(v *string) *NotificationsUpdateOne { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// SetRead sets the "read" field. +func (_u *NotificationsUpdateOne) SetRead(v bool) *NotificationsUpdateOne { + _u.mutation.SetRead(v) + return _u +} + +// SetNillableRead sets the "read" field if the given value is not nil. +func (_u *NotificationsUpdateOne) SetNillableRead(v *bool) *NotificationsUpdateOne { + if v != nil { + _u.SetRead(*v) + } + return _u +} + +// SetLink sets the "link" field. +func (_u *NotificationsUpdateOne) SetLink(v string) *NotificationsUpdateOne { + _u.mutation.SetLink(v) + return _u +} + +// SetNillableLink sets the "link" field if the given value is not nil. +func (_u *NotificationsUpdateOne) SetNillableLink(v *string) *NotificationsUpdateOne { + if v != nil { + _u.SetLink(*v) + } + return _u +} + +// ClearLink clears the value of the "link" field. +func (_u *NotificationsUpdateOne) ClearLink() *NotificationsUpdateOne { + _u.mutation.ClearLink() + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *NotificationsUpdateOne) SetUpdatedAt(v time.Time) *NotificationsUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// Mutation returns the NotificationsMutation object of the builder. +func (_u *NotificationsUpdateOne) Mutation() *NotificationsMutation { + return _u.mutation +} + +// Where appends a list predicates to the NotificationsUpdate builder. +func (_u *NotificationsUpdateOne) Where(ps ...predicate.Notifications) *NotificationsUpdateOne { + _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 *NotificationsUpdateOne) Select(field string, fields ...string) *NotificationsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Notifications entity. +func (_u *NotificationsUpdateOne) Save(ctx context.Context) (*Notifications, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *NotificationsUpdateOne) SaveX(ctx context.Context) *Notifications { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *NotificationsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *NotificationsUpdateOne) 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 *NotificationsUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := notifications.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *NotificationsUpdateOne) check() error { + if v, ok := _u.mutation.GetType(); ok { + if err := notifications.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`models: validator failed for field "Notifications.type": %w`, err)} + } + } + if v, ok := _u.mutation.Title(); ok { + if err := notifications.TitleValidator(v); err != nil { + return &ValidationError{Name: "title", err: fmt.Errorf(`models: validator failed for field "Notifications.title": %w`, err)} + } + } + if v, ok := _u.mutation.Link(); ok { + if err := notifications.LinkValidator(v); err != nil { + return &ValidationError{Name: "link", err: fmt.Errorf(`models: validator failed for field "Notifications.link": %w`, err)} + } + } + return nil +} + +func (_u *NotificationsUpdateOne) sqlSave(ctx context.Context) (_node *Notifications, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(notifications.Table, notifications.Columns, sqlgraph.NewFieldSpec(notifications.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Notifications.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, notifications.FieldID) + for _, f := range fields { + if !notifications.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != notifications.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.UserID(); ok { + _spec.SetField(notifications.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(notifications.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(notifications.FieldType, field.TypeString, value) + } + if value, ok := _u.mutation.Title(); ok { + _spec.SetField(notifications.FieldTitle, field.TypeString, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(notifications.FieldContent, field.TypeString, value) + } + if value, ok := _u.mutation.Read(); ok { + _spec.SetField(notifications.FieldRead, field.TypeBool, value) + } + if value, ok := _u.mutation.Link(); ok { + _spec.SetField(notifications.FieldLink, field.TypeString, value) + } + if _u.mutation.LinkCleared() { + _spec.ClearField(notifications.FieldLink, field.TypeString) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(notifications.FieldUpdatedAt, field.TypeTime, value) + } + _node = &Notifications{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{notifications.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/notification/rpc/internal/models/predicate/predicate.go b/app/notification/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..53be8eb --- /dev/null +++ b/app/notification/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" +) + +// Notifications is the predicate function for notifications builders. +type Notifications func(*sql.Selector) diff --git a/app/notification/rpc/internal/models/runtime.go b/app/notification/rpc/internal/models/runtime.go new file mode 100644 index 0000000..3fbf1a1 --- /dev/null +++ b/app/notification/rpc/internal/models/runtime.go @@ -0,0 +1,43 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/notification/rpc/internal/models/notifications" + "juwan-backend/app/notification/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() { + notificationsFields := schema.Notifications{}.Fields() + _ = notificationsFields + // notificationsDescType is the schema descriptor for type field. + notificationsDescType := notificationsFields[2].Descriptor() + // notifications.TypeValidator is a validator for the "type" field. It is called by the builders before save. + notifications.TypeValidator = notificationsDescType.Validators[0].(func(string) error) + // notificationsDescTitle is the schema descriptor for title field. + notificationsDescTitle := notificationsFields[3].Descriptor() + // notifications.TitleValidator is a validator for the "title" field. It is called by the builders before save. + notifications.TitleValidator = notificationsDescTitle.Validators[0].(func(string) error) + // notificationsDescRead is the schema descriptor for read field. + notificationsDescRead := notificationsFields[5].Descriptor() + // notifications.DefaultRead holds the default value on creation for the read field. + notifications.DefaultRead = notificationsDescRead.Default.(bool) + // notificationsDescLink is the schema descriptor for link field. + notificationsDescLink := notificationsFields[6].Descriptor() + // notifications.LinkValidator is a validator for the "link" field. It is called by the builders before save. + notifications.LinkValidator = notificationsDescLink.Validators[0].(func(string) error) + // notificationsDescCreatedAt is the schema descriptor for created_at field. + notificationsDescCreatedAt := notificationsFields[7].Descriptor() + // notifications.DefaultCreatedAt holds the default value on creation for the created_at field. + notifications.DefaultCreatedAt = notificationsDescCreatedAt.Default.(func() time.Time) + // notificationsDescUpdatedAt is the schema descriptor for updated_at field. + notificationsDescUpdatedAt := notificationsFields[8].Descriptor() + // notifications.DefaultUpdatedAt holds the default value on creation for the updated_at field. + notifications.DefaultUpdatedAt = notificationsDescUpdatedAt.Default.(func() time.Time) + // notifications.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + notifications.UpdateDefaultUpdatedAt = notificationsDescUpdatedAt.UpdateDefault.(func() time.Time) +} diff --git a/app/notification/rpc/internal/models/runtime/runtime.go b/app/notification/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..6fbb1f2 --- /dev/null +++ b/app/notification/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/notification/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/notification/rpc/internal/models/schema/notifications.go b/app/notification/rpc/internal/models/schema/notifications.go new file mode 100644 index 0000000..86b67ae --- /dev/null +++ b/app/notification/rpc/internal/models/schema/notifications.go @@ -0,0 +1,39 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type Notifications struct { + ent.Schema +} + +func (Notifications) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Unique().Immutable(), + field.Int64("user_id"), + field.String("type").MaxLen(20), + field.String("title").MaxLen(200), + field.String("content"), + field.Bool("read").Default(false), + field.String("link").MaxLen(500).Optional().Nillable(), + field.Time("created_at").Default(time.Now).Immutable(), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +func (Notifications) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("user_id", "created_at"), + index.Fields("user_id", "read", "created_at"), + index.Fields("user_id", "type", "created_at"), + } +} + +func (Notifications) Edges() []ent.Edge { + return nil +} diff --git a/app/notification/rpc/internal/models/tx.go b/app/notification/rpc/internal/models/tx.go new file mode 100644 index 0000000..c15636f --- /dev/null +++ b/app/notification/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 + // Notifications is the client for interacting with the Notifications builders. + Notifications *NotificationsClient + + // 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.Notifications = NewNotificationsClient(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: Notifications.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/notification/rpc/internal/server/notificationServiceServer.go b/app/notification/rpc/internal/server/notificationServiceServer.go new file mode 100644 index 0000000..24cd72c --- /dev/null +++ b/app/notification/rpc/internal/server/notificationServiceServer.go @@ -0,0 +1,49 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: notification.proto + +package server + +import ( + "context" + + "juwan-backend/app/notification/rpc/internal/logic" + "juwan-backend/app/notification/rpc/internal/svc" + "juwan-backend/app/notification/rpc/pb" +) + +type NotificationServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedNotificationServiceServer +} + +func NewNotificationServiceServer(svcCtx *svc.ServiceContext) *NotificationServiceServer { + return &NotificationServiceServer{ + svcCtx: svcCtx, + } +} + +func (s *NotificationServiceServer) AddNotifications(ctx context.Context, in *pb.AddNotificationsReq) (*pb.AddNotificationsResp, error) { + l := logic.NewAddNotificationsLogic(ctx, s.svcCtx) + return l.AddNotifications(in) +} + +func (s *NotificationServiceServer) UpdateNotifications(ctx context.Context, in *pb.UpdateNotificationsReq) (*pb.UpdateNotificationsResp, error) { + l := logic.NewUpdateNotificationsLogic(ctx, s.svcCtx) + return l.UpdateNotifications(in) +} + +func (s *NotificationServiceServer) DelNotifications(ctx context.Context, in *pb.DelNotificationsReq) (*pb.DelNotificationsResp, error) { + l := logic.NewDelNotificationsLogic(ctx, s.svcCtx) + return l.DelNotifications(in) +} + +func (s *NotificationServiceServer) GetNotificationsById(ctx context.Context, in *pb.GetNotificationsByIdReq) (*pb.GetNotificationsByIdResp, error) { + l := logic.NewGetNotificationsByIdLogic(ctx, s.svcCtx) + return l.GetNotificationsById(in) +} + +func (s *NotificationServiceServer) SearchNotifications(ctx context.Context, in *pb.SearchNotificationsReq) (*pb.SearchNotificationsResp, error) { + l := logic.NewSearchNotificationsLogic(ctx, s.svcCtx) + return l.SearchNotifications(in) +} diff --git a/app/notification/rpc/internal/svc/serviceContext.go b/app/notification/rpc/internal/svc/serviceContext.go new file mode 100644 index 0000000..747f8b2 --- /dev/null +++ b/app/notification/rpc/internal/svc/serviceContext.go @@ -0,0 +1,53 @@ +package svc + +import ( + stdsql "database/sql" + "time" + + "juwan-backend/app/notification/rpc/internal/config" + "juwan-backend/app/notification/rpc/internal/models" + "juwan-backend/app/snowflake/rpc/snowflake" + "juwan-backend/common/redisx" + "juwan-backend/common/snowflakex" + "juwan-backend/pkg/adapter" + + "ariga.io/entcache" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + + _ "github.com/jackc/pgx/v5/stdlib" +) + +type ServiceContext struct { + Config config.Config + Snowflake snowflake.SnowflakeServiceClient + NotificationModelRW *models.Client + NotificationModelRO *models.Client +} + +func NewServiceContext(c config.Config) *ServiceContext { + rawRW, err := stdsql.Open("pgx", c.DB.Master) + if err != nil { + panic(err) + } + rawRO, err := stdsql.Open("pgx", c.DB.Slaves) + if err != nil { + panic(err) + } + RWConn := sql.OpenDB(dialect.Postgres, rawRW) + ROConn := sql.OpenDB(dialect.Postgres, rawRO) + + redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second) + if redisCluster == nil || err != nil { + 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))) + return &ServiceContext{ + Config: c, + NotificationModelRW: models.NewClient(models.Driver(RWDrv)), + NotificationModelRO: models.NewClient(models.Driver(RODrv)), + Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), + } +} diff --git a/app/notification/rpc/notificationservice/notificationService.go b/app/notification/rpc/notificationservice/notificationService.go new file mode 100644 index 0000000..ca981f9 --- /dev/null +++ b/app/notification/rpc/notificationservice/notificationService.go @@ -0,0 +1,71 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: notification.proto + +package notificationservice + +import ( + "context" + + "juwan-backend/app/notification/rpc/pb" + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + AddNotificationsReq = pb.AddNotificationsReq + AddNotificationsResp = pb.AddNotificationsResp + DelNotificationsReq = pb.DelNotificationsReq + DelNotificationsResp = pb.DelNotificationsResp + GetNotificationsByIdReq = pb.GetNotificationsByIdReq + GetNotificationsByIdResp = pb.GetNotificationsByIdResp + Notifications = pb.Notifications + SearchNotificationsReq = pb.SearchNotificationsReq + SearchNotificationsResp = pb.SearchNotificationsResp + UpdateNotificationsReq = pb.UpdateNotificationsReq + UpdateNotificationsResp = pb.UpdateNotificationsResp + + NotificationService interface { + AddNotifications(ctx context.Context, in *AddNotificationsReq, opts ...grpc.CallOption) (*AddNotificationsResp, error) + UpdateNotifications(ctx context.Context, in *UpdateNotificationsReq, opts ...grpc.CallOption) (*UpdateNotificationsResp, error) + DelNotifications(ctx context.Context, in *DelNotificationsReq, opts ...grpc.CallOption) (*DelNotificationsResp, error) + GetNotificationsById(ctx context.Context, in *GetNotificationsByIdReq, opts ...grpc.CallOption) (*GetNotificationsByIdResp, error) + SearchNotifications(ctx context.Context, in *SearchNotificationsReq, opts ...grpc.CallOption) (*SearchNotificationsResp, error) + } + + defaultNotificationService struct { + cli zrpc.Client + } +) + +func NewNotificationService(cli zrpc.Client) NotificationService { + return &defaultNotificationService{ + cli: cli, + } +} + +func (m *defaultNotificationService) AddNotifications(ctx context.Context, in *AddNotificationsReq, opts ...grpc.CallOption) (*AddNotificationsResp, error) { + client := pb.NewNotificationServiceClient(m.cli.Conn()) + return client.AddNotifications(ctx, in, opts...) +} + +func (m *defaultNotificationService) UpdateNotifications(ctx context.Context, in *UpdateNotificationsReq, opts ...grpc.CallOption) (*UpdateNotificationsResp, error) { + client := pb.NewNotificationServiceClient(m.cli.Conn()) + return client.UpdateNotifications(ctx, in, opts...) +} + +func (m *defaultNotificationService) DelNotifications(ctx context.Context, in *DelNotificationsReq, opts ...grpc.CallOption) (*DelNotificationsResp, error) { + client := pb.NewNotificationServiceClient(m.cli.Conn()) + return client.DelNotifications(ctx, in, opts...) +} + +func (m *defaultNotificationService) GetNotificationsById(ctx context.Context, in *GetNotificationsByIdReq, opts ...grpc.CallOption) (*GetNotificationsByIdResp, error) { + client := pb.NewNotificationServiceClient(m.cli.Conn()) + return client.GetNotificationsById(ctx, in, opts...) +} + +func (m *defaultNotificationService) SearchNotifications(ctx context.Context, in *SearchNotificationsReq, opts ...grpc.CallOption) (*SearchNotificationsResp, error) { + client := pb.NewNotificationServiceClient(m.cli.Conn()) + return client.SearchNotifications(ctx, in, opts...) +} diff --git a/app/notification/rpc/pb.go b/app/notification/rpc/pb.go new file mode 100644 index 0000000..beaf225 --- /dev/null +++ b/app/notification/rpc/pb.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/notification/rpc/internal/config" + "juwan-backend/app/notification/rpc/internal/server" + "juwan-backend/app/notification/rpc/internal/svc" + "juwan-backend/app/notification/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.RegisterNotificationServiceServer(grpcServer, server.NewNotificationServiceServer(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/notification/rpc/pb/notification.pb.go b/app/notification/rpc/pb/notification.pb.go new file mode 100644 index 0000000..76a3d30 --- /dev/null +++ b/app/notification/rpc/pb/notification.pb.go @@ -0,0 +1,816 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v7.34.1 +// source: notification.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) +) + +// --------------------------------notifications-------------------------------- +type Notifications struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` + Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` + Title string `protobuf:"bytes,4,opt,name=title,proto3" json:"title,omitempty"` + Content string `protobuf:"bytes,5,opt,name=content,proto3" json:"content,omitempty"` + Read bool `protobuf:"varint,6,opt,name=read,proto3" json:"read,omitempty"` + Link string `protobuf:"bytes,7,opt,name=link,proto3" json:"link,omitempty"` + CreatedAt int64 `protobuf:"varint,8,opt,name=createdAt,proto3" json:"createdAt,omitempty"` + UpdatedAt int64 `protobuf:"varint,9,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Notifications) Reset() { + *x = Notifications{} + mi := &file_notification_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Notifications) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Notifications) ProtoMessage() {} + +func (x *Notifications) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 Notifications.ProtoReflect.Descriptor instead. +func (*Notifications) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{0} +} + +func (x *Notifications) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Notifications) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *Notifications) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *Notifications) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *Notifications) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *Notifications) GetRead() bool { + if x != nil { + return x.Read + } + return false +} + +func (x *Notifications) GetLink() string { + if x != nil { + return x.Link + } + return "" +} + +func (x *Notifications) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *Notifications) GetUpdatedAt() int64 { + if x != nil { + return x.UpdatedAt + } + return 0 +} + +type AddNotificationsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId int64 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"` + Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` + Title string `protobuf:"bytes,3,opt,name=title,proto3" json:"title,omitempty"` + Content string `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"` + Link *string `protobuf:"bytes,5,opt,name=link,proto3,oneof" json:"link,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddNotificationsReq) Reset() { + *x = AddNotificationsReq{} + mi := &file_notification_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddNotificationsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddNotificationsReq) ProtoMessage() {} + +func (x *AddNotificationsReq) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 AddNotificationsReq.ProtoReflect.Descriptor instead. +func (*AddNotificationsReq) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{1} +} + +func (x *AddNotificationsReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *AddNotificationsReq) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *AddNotificationsReq) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *AddNotificationsReq) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *AddNotificationsReq) GetLink() string { + if x != nil && x.Link != nil { + return *x.Link + } + return "" +} + +type AddNotificationsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddNotificationsResp) Reset() { + *x = AddNotificationsResp{} + mi := &file_notification_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddNotificationsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddNotificationsResp) ProtoMessage() {} + +func (x *AddNotificationsResp) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 AddNotificationsResp.ProtoReflect.Descriptor instead. +func (*AddNotificationsResp) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{2} +} + +func (x *AddNotificationsResp) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type UpdateNotificationsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Read *bool `protobuf:"varint,2,opt,name=read,proto3,oneof" json:"read,omitempty"` + Type *string `protobuf:"bytes,3,opt,name=type,proto3,oneof" json:"type,omitempty"` + Title *string `protobuf:"bytes,4,opt,name=title,proto3,oneof" json:"title,omitempty"` + Content *string `protobuf:"bytes,5,opt,name=content,proto3,oneof" json:"content,omitempty"` + Link *string `protobuf:"bytes,6,opt,name=link,proto3,oneof" json:"link,omitempty"` + UpdatedAt *int64 `protobuf:"varint,7,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateNotificationsReq) Reset() { + *x = UpdateNotificationsReq{} + mi := &file_notification_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateNotificationsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateNotificationsReq) ProtoMessage() {} + +func (x *UpdateNotificationsReq) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 UpdateNotificationsReq.ProtoReflect.Descriptor instead. +func (*UpdateNotificationsReq) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{3} +} + +func (x *UpdateNotificationsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateNotificationsReq) GetRead() bool { + if x != nil && x.Read != nil { + return *x.Read + } + return false +} + +func (x *UpdateNotificationsReq) GetType() string { + if x != nil && x.Type != nil { + return *x.Type + } + return "" +} + +func (x *UpdateNotificationsReq) GetTitle() string { + if x != nil && x.Title != nil { + return *x.Title + } + return "" +} + +func (x *UpdateNotificationsReq) GetContent() string { + if x != nil && x.Content != nil { + return *x.Content + } + return "" +} + +func (x *UpdateNotificationsReq) GetLink() string { + if x != nil && x.Link != nil { + return *x.Link + } + return "" +} + +func (x *UpdateNotificationsReq) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +type UpdateNotificationsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateNotificationsResp) Reset() { + *x = UpdateNotificationsResp{} + mi := &file_notification_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateNotificationsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateNotificationsResp) ProtoMessage() {} + +func (x *UpdateNotificationsResp) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 UpdateNotificationsResp.ProtoReflect.Descriptor instead. +func (*UpdateNotificationsResp) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{4} +} + +type DelNotificationsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelNotificationsReq) Reset() { + *x = DelNotificationsReq{} + mi := &file_notification_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelNotificationsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelNotificationsReq) ProtoMessage() {} + +func (x *DelNotificationsReq) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 DelNotificationsReq.ProtoReflect.Descriptor instead. +func (*DelNotificationsReq) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{5} +} + +func (x *DelNotificationsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelNotificationsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelNotificationsResp) Reset() { + *x = DelNotificationsResp{} + mi := &file_notification_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelNotificationsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelNotificationsResp) ProtoMessage() {} + +func (x *DelNotificationsResp) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 DelNotificationsResp.ProtoReflect.Descriptor instead. +func (*DelNotificationsResp) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{6} +} + +type GetNotificationsByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetNotificationsByIdReq) Reset() { + *x = GetNotificationsByIdReq{} + mi := &file_notification_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetNotificationsByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetNotificationsByIdReq) ProtoMessage() {} + +func (x *GetNotificationsByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 GetNotificationsByIdReq.ProtoReflect.Descriptor instead. +func (*GetNotificationsByIdReq) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{7} +} + +func (x *GetNotificationsByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetNotificationsByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Notifications *Notifications `protobuf:"bytes,1,opt,name=notifications,proto3" json:"notifications,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetNotificationsByIdResp) Reset() { + *x = GetNotificationsByIdResp{} + mi := &file_notification_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetNotificationsByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetNotificationsByIdResp) ProtoMessage() {} + +func (x *GetNotificationsByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 GetNotificationsByIdResp.ProtoReflect.Descriptor instead. +func (*GetNotificationsByIdResp) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{8} +} + +func (x *GetNotificationsByIdResp) GetNotifications() *Notifications { + if x != nil { + return x.Notifications + } + return nil +} + +type SearchNotificationsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Offset int64 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + Id *int64 `protobuf:"varint,3,opt,name=id,proto3,oneof" json:"id,omitempty"` + UserId *int64 `protobuf:"varint,4,opt,name=userId,proto3,oneof" json:"userId,omitempty"` + Type *string `protobuf:"bytes,5,opt,name=type,proto3,oneof" json:"type,omitempty"` + Read *bool `protobuf:"varint,6,opt,name=read,proto3,oneof" json:"read,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchNotificationsReq) Reset() { + *x = SearchNotificationsReq{} + mi := &file_notification_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchNotificationsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchNotificationsReq) ProtoMessage() {} + +func (x *SearchNotificationsReq) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 SearchNotificationsReq.ProtoReflect.Descriptor instead. +func (*SearchNotificationsReq) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{9} +} + +func (x *SearchNotificationsReq) GetOffset() int64 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *SearchNotificationsReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchNotificationsReq) GetId() int64 { + if x != nil && x.Id != nil { + return *x.Id + } + return 0 +} + +func (x *SearchNotificationsReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +func (x *SearchNotificationsReq) GetType() string { + if x != nil && x.Type != nil { + return *x.Type + } + return "" +} + +func (x *SearchNotificationsReq) GetRead() bool { + if x != nil && x.Read != nil { + return *x.Read + } + return false +} + +type SearchNotificationsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Notifications []*Notifications `protobuf:"bytes,1,rep,name=notifications,proto3" json:"notifications,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchNotificationsResp) Reset() { + *x = SearchNotificationsResp{} + mi := &file_notification_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchNotificationsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchNotificationsResp) ProtoMessage() {} + +func (x *SearchNotificationsResp) ProtoReflect() protoreflect.Message { + mi := &file_notification_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 SearchNotificationsResp.ProtoReflect.Descriptor instead. +func (*SearchNotificationsResp) Descriptor() ([]byte, []int) { + return file_notification_proto_rawDescGZIP(), []int{10} +} + +func (x *SearchNotificationsResp) GetNotifications() []*Notifications { + if x != nil { + return x.Notifications + } + return nil +} + +var File_notification_proto protoreflect.FileDescriptor + +const file_notification_proto_rawDesc = "" + + "\n" + + "\x12notification.proto\x12\x02pb\"\xdf\x01\n" + + "\rNotifications\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\x14\n" + + "\x05title\x18\x04 \x01(\tR\x05title\x12\x18\n" + + "\acontent\x18\x05 \x01(\tR\acontent\x12\x12\n" + + "\x04read\x18\x06 \x01(\bR\x04read\x12\x12\n" + + "\x04link\x18\a \x01(\tR\x04link\x12\x1c\n" + + "\tcreatedAt\x18\b \x01(\x03R\tcreatedAt\x12\x1c\n" + + "\tupdatedAt\x18\t \x01(\x03R\tupdatedAt\"\x93\x01\n" + + "\x13AddNotificationsReq\x12\x16\n" + + "\x06userId\x18\x01 \x01(\x03R\x06userId\x12\x12\n" + + "\x04type\x18\x02 \x01(\tR\x04type\x12\x14\n" + + "\x05title\x18\x03 \x01(\tR\x05title\x12\x18\n" + + "\acontent\x18\x04 \x01(\tR\acontent\x12\x17\n" + + "\x04link\x18\x05 \x01(\tH\x00R\x04link\x88\x01\x01B\a\n" + + "\x05_link\"&\n" + + "\x14AddNotificationsResp\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x8f\x02\n" + + "\x16UpdateNotificationsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x17\n" + + "\x04read\x18\x02 \x01(\bH\x00R\x04read\x88\x01\x01\x12\x17\n" + + "\x04type\x18\x03 \x01(\tH\x01R\x04type\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\x17\n" + + "\x04link\x18\x06 \x01(\tH\x04R\x04link\x88\x01\x01\x12!\n" + + "\tupdatedAt\x18\a \x01(\x03H\x05R\tupdatedAt\x88\x01\x01B\a\n" + + "\x05_readB\a\n" + + "\x05_typeB\b\n" + + "\x06_titleB\n" + + "\n" + + "\b_contentB\a\n" + + "\x05_linkB\f\n" + + "\n" + + "_updatedAt\"\x19\n" + + "\x17UpdateNotificationsResp\"%\n" + + "\x13DelNotificationsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x16\n" + + "\x14DelNotificationsResp\")\n" + + "\x17GetNotificationsByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"S\n" + + "\x18GetNotificationsByIdResp\x127\n" + + "\rnotifications\x18\x01 \x01(\v2\x11.pb.NotificationsR\rnotifications\"\xce\x01\n" + + "\x16SearchNotificationsReq\x12\x16\n" + + "\x06offset\x18\x01 \x01(\x03R\x06offset\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x13\n" + + "\x02id\x18\x03 \x01(\x03H\x00R\x02id\x88\x01\x01\x12\x1b\n" + + "\x06userId\x18\x04 \x01(\x03H\x01R\x06userId\x88\x01\x01\x12\x17\n" + + "\x04type\x18\x05 \x01(\tH\x02R\x04type\x88\x01\x01\x12\x17\n" + + "\x04read\x18\x06 \x01(\bH\x03R\x04read\x88\x01\x01B\x05\n" + + "\x03_idB\t\n" + + "\a_userIdB\a\n" + + "\x05_typeB\a\n" + + "\x05_read\"R\n" + + "\x17SearchNotificationsResp\x127\n" + + "\rnotifications\x18\x01 \x03(\v2\x11.pb.NotificationsR\rnotifications2\x96\x03\n" + + "\x13notificationService\x12E\n" + + "\x10AddNotifications\x12\x17.pb.AddNotificationsReq\x1a\x18.pb.AddNotificationsResp\x12N\n" + + "\x13UpdateNotifications\x12\x1a.pb.UpdateNotificationsReq\x1a\x1b.pb.UpdateNotificationsResp\x12E\n" + + "\x10DelNotifications\x12\x17.pb.DelNotificationsReq\x1a\x18.pb.DelNotificationsResp\x12Q\n" + + "\x14GetNotificationsById\x12\x1b.pb.GetNotificationsByIdReq\x1a\x1c.pb.GetNotificationsByIdResp\x12N\n" + + "\x13SearchNotifications\x12\x1a.pb.SearchNotificationsReq\x1a\x1b.pb.SearchNotificationsRespB\x06Z\x04./pbb\x06proto3" + +var ( + file_notification_proto_rawDescOnce sync.Once + file_notification_proto_rawDescData []byte +) + +func file_notification_proto_rawDescGZIP() []byte { + file_notification_proto_rawDescOnce.Do(func() { + file_notification_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_notification_proto_rawDesc), len(file_notification_proto_rawDesc))) + }) + return file_notification_proto_rawDescData +} + +var file_notification_proto_msgTypes = make([]protoimpl.MessageInfo, 11) +var file_notification_proto_goTypes = []any{ + (*Notifications)(nil), // 0: pb.Notifications + (*AddNotificationsReq)(nil), // 1: pb.AddNotificationsReq + (*AddNotificationsResp)(nil), // 2: pb.AddNotificationsResp + (*UpdateNotificationsReq)(nil), // 3: pb.UpdateNotificationsReq + (*UpdateNotificationsResp)(nil), // 4: pb.UpdateNotificationsResp + (*DelNotificationsReq)(nil), // 5: pb.DelNotificationsReq + (*DelNotificationsResp)(nil), // 6: pb.DelNotificationsResp + (*GetNotificationsByIdReq)(nil), // 7: pb.GetNotificationsByIdReq + (*GetNotificationsByIdResp)(nil), // 8: pb.GetNotificationsByIdResp + (*SearchNotificationsReq)(nil), // 9: pb.SearchNotificationsReq + (*SearchNotificationsResp)(nil), // 10: pb.SearchNotificationsResp +} +var file_notification_proto_depIdxs = []int32{ + 0, // 0: pb.GetNotificationsByIdResp.notifications:type_name -> pb.Notifications + 0, // 1: pb.SearchNotificationsResp.notifications:type_name -> pb.Notifications + 1, // 2: pb.notificationService.AddNotifications:input_type -> pb.AddNotificationsReq + 3, // 3: pb.notificationService.UpdateNotifications:input_type -> pb.UpdateNotificationsReq + 5, // 4: pb.notificationService.DelNotifications:input_type -> pb.DelNotificationsReq + 7, // 5: pb.notificationService.GetNotificationsById:input_type -> pb.GetNotificationsByIdReq + 9, // 6: pb.notificationService.SearchNotifications:input_type -> pb.SearchNotificationsReq + 2, // 7: pb.notificationService.AddNotifications:output_type -> pb.AddNotificationsResp + 4, // 8: pb.notificationService.UpdateNotifications:output_type -> pb.UpdateNotificationsResp + 6, // 9: pb.notificationService.DelNotifications:output_type -> pb.DelNotificationsResp + 8, // 10: pb.notificationService.GetNotificationsById:output_type -> pb.GetNotificationsByIdResp + 10, // 11: pb.notificationService.SearchNotifications:output_type -> pb.SearchNotificationsResp + 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 + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_notification_proto_init() } +func file_notification_proto_init() { + if File_notification_proto != nil { + return + } + file_notification_proto_msgTypes[1].OneofWrappers = []any{} + file_notification_proto_msgTypes[3].OneofWrappers = []any{} + file_notification_proto_msgTypes[9].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_notification_proto_rawDesc), len(file_notification_proto_rawDesc)), + NumEnums: 0, + NumMessages: 11, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_notification_proto_goTypes, + DependencyIndexes: file_notification_proto_depIdxs, + MessageInfos: file_notification_proto_msgTypes, + }.Build() + File_notification_proto = out.File + file_notification_proto_goTypes = nil + file_notification_proto_depIdxs = nil +} diff --git a/app/notification/rpc/pb/notification_grpc.pb.go b/app/notification/rpc/pb/notification_grpc.pb.go new file mode 100644 index 0000000..911fbb4 --- /dev/null +++ b/app/notification/rpc/pb/notification_grpc.pb.go @@ -0,0 +1,273 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v7.34.1 +// source: notification.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 ( + NotificationService_AddNotifications_FullMethodName = "/pb.notificationService/AddNotifications" + NotificationService_UpdateNotifications_FullMethodName = "/pb.notificationService/UpdateNotifications" + NotificationService_DelNotifications_FullMethodName = "/pb.notificationService/DelNotifications" + NotificationService_GetNotificationsById_FullMethodName = "/pb.notificationService/GetNotificationsById" + NotificationService_SearchNotifications_FullMethodName = "/pb.notificationService/SearchNotifications" +) + +// NotificationServiceClient is the client API for NotificationService 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 NotificationServiceClient interface { + AddNotifications(ctx context.Context, in *AddNotificationsReq, opts ...grpc.CallOption) (*AddNotificationsResp, error) + UpdateNotifications(ctx context.Context, in *UpdateNotificationsReq, opts ...grpc.CallOption) (*UpdateNotificationsResp, error) + DelNotifications(ctx context.Context, in *DelNotificationsReq, opts ...grpc.CallOption) (*DelNotificationsResp, error) + GetNotificationsById(ctx context.Context, in *GetNotificationsByIdReq, opts ...grpc.CallOption) (*GetNotificationsByIdResp, error) + SearchNotifications(ctx context.Context, in *SearchNotificationsReq, opts ...grpc.CallOption) (*SearchNotificationsResp, error) +} + +type notificationServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewNotificationServiceClient(cc grpc.ClientConnInterface) NotificationServiceClient { + return ¬ificationServiceClient{cc} +} + +func (c *notificationServiceClient) AddNotifications(ctx context.Context, in *AddNotificationsReq, opts ...grpc.CallOption) (*AddNotificationsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddNotificationsResp) + err := c.cc.Invoke(ctx, NotificationService_AddNotifications_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *notificationServiceClient) UpdateNotifications(ctx context.Context, in *UpdateNotificationsReq, opts ...grpc.CallOption) (*UpdateNotificationsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateNotificationsResp) + err := c.cc.Invoke(ctx, NotificationService_UpdateNotifications_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *notificationServiceClient) DelNotifications(ctx context.Context, in *DelNotificationsReq, opts ...grpc.CallOption) (*DelNotificationsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelNotificationsResp) + err := c.cc.Invoke(ctx, NotificationService_DelNotifications_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *notificationServiceClient) GetNotificationsById(ctx context.Context, in *GetNotificationsByIdReq, opts ...grpc.CallOption) (*GetNotificationsByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetNotificationsByIdResp) + err := c.cc.Invoke(ctx, NotificationService_GetNotificationsById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *notificationServiceClient) SearchNotifications(ctx context.Context, in *SearchNotificationsReq, opts ...grpc.CallOption) (*SearchNotificationsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchNotificationsResp) + err := c.cc.Invoke(ctx, NotificationService_SearchNotifications_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// NotificationServiceServer is the server API for NotificationService service. +// All implementations must embed UnimplementedNotificationServiceServer +// for forward compatibility. +type NotificationServiceServer interface { + AddNotifications(context.Context, *AddNotificationsReq) (*AddNotificationsResp, error) + UpdateNotifications(context.Context, *UpdateNotificationsReq) (*UpdateNotificationsResp, error) + DelNotifications(context.Context, *DelNotificationsReq) (*DelNotificationsResp, error) + GetNotificationsById(context.Context, *GetNotificationsByIdReq) (*GetNotificationsByIdResp, error) + SearchNotifications(context.Context, *SearchNotificationsReq) (*SearchNotificationsResp, error) + mustEmbedUnimplementedNotificationServiceServer() +} + +// UnimplementedNotificationServiceServer 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 UnimplementedNotificationServiceServer struct{} + +func (UnimplementedNotificationServiceServer) AddNotifications(context.Context, *AddNotificationsReq) (*AddNotificationsResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddNotifications not implemented") +} +func (UnimplementedNotificationServiceServer) UpdateNotifications(context.Context, *UpdateNotificationsReq) (*UpdateNotificationsResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateNotifications not implemented") +} +func (UnimplementedNotificationServiceServer) DelNotifications(context.Context, *DelNotificationsReq) (*DelNotificationsResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelNotifications not implemented") +} +func (UnimplementedNotificationServiceServer) GetNotificationsById(context.Context, *GetNotificationsByIdReq) (*GetNotificationsByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetNotificationsById not implemented") +} +func (UnimplementedNotificationServiceServer) SearchNotifications(context.Context, *SearchNotificationsReq) (*SearchNotificationsResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchNotifications not implemented") +} +func (UnimplementedNotificationServiceServer) mustEmbedUnimplementedNotificationServiceServer() {} +func (UnimplementedNotificationServiceServer) testEmbeddedByValue() {} + +// UnsafeNotificationServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to NotificationServiceServer will +// result in compilation errors. +type UnsafeNotificationServiceServer interface { + mustEmbedUnimplementedNotificationServiceServer() +} + +func RegisterNotificationServiceServer(s grpc.ServiceRegistrar, srv NotificationServiceServer) { + // If the following call panics, it indicates UnimplementedNotificationServiceServer 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(&NotificationService_ServiceDesc, srv) +} + +func _NotificationService_AddNotifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddNotificationsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NotificationServiceServer).AddNotifications(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NotificationService_AddNotifications_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NotificationServiceServer).AddNotifications(ctx, req.(*AddNotificationsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _NotificationService_UpdateNotifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateNotificationsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NotificationServiceServer).UpdateNotifications(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NotificationService_UpdateNotifications_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NotificationServiceServer).UpdateNotifications(ctx, req.(*UpdateNotificationsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _NotificationService_DelNotifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelNotificationsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NotificationServiceServer).DelNotifications(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NotificationService_DelNotifications_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NotificationServiceServer).DelNotifications(ctx, req.(*DelNotificationsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _NotificationService_GetNotificationsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetNotificationsByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NotificationServiceServer).GetNotificationsById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NotificationService_GetNotificationsById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NotificationServiceServer).GetNotificationsById(ctx, req.(*GetNotificationsByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _NotificationService_SearchNotifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchNotificationsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NotificationServiceServer).SearchNotifications(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NotificationService_SearchNotifications_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NotificationServiceServer).SearchNotifications(ctx, req.(*SearchNotificationsReq)) + } + return interceptor(ctx, in, info, handler) +} + +// NotificationService_ServiceDesc is the grpc.ServiceDesc for NotificationService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var NotificationService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.notificationService", + HandlerType: (*NotificationServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "AddNotifications", + Handler: _NotificationService_AddNotifications_Handler, + }, + { + MethodName: "UpdateNotifications", + Handler: _NotificationService_UpdateNotifications_Handler, + }, + { + MethodName: "DelNotifications", + Handler: _NotificationService_DelNotifications_Handler, + }, + { + MethodName: "GetNotificationsById", + Handler: _NotificationService_GetNotificationsById_Handler, + }, + { + MethodName: "SearchNotifications", + Handler: _NotificationService_SearchNotifications_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "notification.proto", +} diff --git a/app/order/api/internal/logic/order/confirmCloseOrderLogic.go b/app/order/api/internal/logic/order/confirmCloseOrderLogic.go index 3c5123d..27ed5cc 100644 --- a/app/order/api/internal/logic/order/confirmCloseOrderLogic.go +++ b/app/order/api/internal/logic/order/confirmCloseOrderLogic.go @@ -28,7 +28,7 @@ func NewConfirmCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) } 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 { + if err = transitionOrderStatus(l.ctx, l.svcCtx, req.Id, "pending_review", false, true, false, false); err != nil { return nil, err } diff --git a/app/order/api/internal/logic/order/helpers.go b/app/order/api/internal/logic/order/helpers.go index 4b7df4b..1025378 100644 --- a/app/order/api/internal/logic/order/helpers.go +++ b/app/order/api/internal/logic/order/helpers.go @@ -3,6 +3,8 @@ package order import ( "context" "encoding/json" + "errors" + "fmt" "strconv" "time" @@ -55,13 +57,39 @@ func toAPIOrder(in *orderservice.Orders) types.Order { return order } +// validTransitions defines the allowed order state transitions per the API spec. +var validTransitions = map[string][]string{ + "pending_payment": {"pending_accept"}, + "pending_accept": {"in_progress", "cancelled"}, + "in_progress": {"pending_close", "disputed"}, + "pending_close": {"pending_review", "disputed"}, + "pending_review": {"completed"}, + "disputed": {"pending_review"}, +} + 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 + return errors.New("order not found") + } + + fromStatus := current.Orders.GetStatus() + allowed, ok := validTransitions[fromStatus] + if !ok { + return fmt.Errorf("order status %q does not allow any transition", fromStatus) + } + found := false + for _, s := range allowed { + if s == toStatus { + found = true + break + } + } + if !found { + return fmt.Errorf("transition from %q to %q is not allowed", fromStatus, toStatus) } now := time.Now().Unix() @@ -87,7 +115,6 @@ func transitionOrderStatus(ctx context.Context, svcCtx *svc.ServiceContext, orde return err } - fromStatus := current.Orders.GetStatus() actorID, _ := contextj.UserIDFrom(ctx) actorRole := "system" if actorID > 0 { diff --git a/app/order/api/internal/logic/order/reorderLogic.go b/app/order/api/internal/logic/order/reorderLogic.go index e40c51b..ad65cf9 100644 --- a/app/order/api/internal/logic/order/reorderLogic.go +++ b/app/order/api/internal/logic/order/reorderLogic.go @@ -5,6 +5,7 @@ package order import ( "context" + "errors" "time" "juwan-backend/app/order/rpc/orderservice" @@ -37,7 +38,7 @@ func (l *ReorderLogic) Reorder(req *types.PathId) (resp *types.CreateOrderResp, } oldOrder := oldOrderResp.GetOrders() if oldOrder == nil { - return nil, nil + return nil, errors.New("order not found") } now := time.Now().Unix() diff --git a/app/player/rpc/internal/logic/updatePlayerServicesLogic.go b/app/player/rpc/internal/logic/updatePlayerServicesLogic.go index 1231056..a649521 100644 --- a/app/player/rpc/internal/logic/updatePlayerServicesLogic.go +++ b/app/player/rpc/internal/logic/updatePlayerServicesLogic.go @@ -45,7 +45,7 @@ func (l *UpdatePlayerServicesLogic) UpdatePlayerServices(in *pb.UpdatePlayerServ _, err := update.Save(l.ctx) if err != nil { - logx.Errorf("failed to update player services: " + err.Error()) + logx.Errorf("failed to update player services: %v", err) return nil, errors.New("failed to update player services") } return &pb.UpdatePlayerServicesResp{}, nil diff --git a/app/review/api/etc/review-api.yaml b/app/review/api/etc/review-api.yaml new file mode 100644 index 0000000..5cf6700 --- /dev/null +++ b/app/review/api/etc/review-api.yaml @@ -0,0 +1,16 @@ +Name: review-api +Host: 0.0.0.0 +Port: 8888 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONFIG ===== +ReviewRpcConf: + Endpoints: + - review-rpc:8080 +OrderRpcConf: + Endpoints: + - order-rpc:8080 diff --git a/app/review/api/internal/config/config.go b/app/review/api/internal/config/config.go new file mode 100644 index 0000000..aa128f3 --- /dev/null +++ b/app/review/api/internal/config/config.go @@ -0,0 +1,12 @@ +package config + +import ( + "github.com/zeromicro/go-zero/rest" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + rest.RestConf + ReviewRpcConf zrpc.RpcClientConf + OrderRpcConf zrpc.RpcClientConf +} diff --git a/app/review/api/internal/handler/review/getOrderReviewsHandler.go b/app/review/api/internal/handler/review/getOrderReviewsHandler.go new file mode 100644 index 0000000..7fd7f6e --- /dev/null +++ b/app/review/api/internal/handler/review/getOrderReviewsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package review + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/review/api/internal/logic/review" + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" +) + +// 获取订单评价 +func GetOrderReviewsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.GetOrderReviewsReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := review.NewGetOrderReviewsLogic(r.Context(), svcCtx) + resp, err := l.GetOrderReviews(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/review/api/internal/handler/review/listReviewsHandler.go b/app/review/api/internal/handler/review/listReviewsHandler.go new file mode 100644 index 0000000..6fb3037 --- /dev/null +++ b/app/review/api/internal/handler/review/listReviewsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package review + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/review/api/internal/logic/review" + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" +) + +// 获取公开评价列表 +func ListReviewsHandler(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 := review.NewListReviewsLogic(r.Context(), svcCtx) + resp, err := l.ListReviews(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/review/api/internal/handler/review/listUserReviewsHandler.go b/app/review/api/internal/handler/review/listUserReviewsHandler.go new file mode 100644 index 0000000..d8171ff --- /dev/null +++ b/app/review/api/internal/handler/review/listUserReviewsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package review + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/review/api/internal/logic/review" + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" +) + +// 获取用户收到的评价 +func ListUserReviewsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.ListUserReviewsReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := review.NewListUserReviewsLogic(r.Context(), svcCtx) + resp, err := l.ListUserReviews(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/review/api/internal/handler/review/submitReviewHandler.go b/app/review/api/internal/handler/review/submitReviewHandler.go new file mode 100644 index 0000000..b53aef0 --- /dev/null +++ b/app/review/api/internal/handler/review/submitReviewHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package review + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/review/api/internal/logic/review" + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" +) + +// 提交评价 +func SubmitReviewHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.SubmitReviewReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := review.NewSubmitReviewLogic(r.Context(), svcCtx) + resp, err := l.SubmitReview(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/review/api/internal/handler/routes.go b/app/review/api/internal/handler/routes.go new file mode 100644 index 0000000..49c7141 --- /dev/null +++ b/app/review/api/internal/handler/routes.go @@ -0,0 +1,51 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package handler + +import ( + "net/http" + + review "juwan-backend/app/review/api/internal/handler/review" + "juwan-backend/app/review/api/internal/svc" + + "github.com/zeromicro/go-zero/rest" +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + server.AddRoutes( + []rest.Route{ + { + // 提交评价 + Method: http.MethodPost, + Path: "/orders/:id/review", + Handler: review.SubmitReviewHandler(serverCtx), + }, + { + // 获取订单评价 + Method: http.MethodGet, + Path: "/orders/:id/reviews", + Handler: review.GetOrderReviewsHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) + + server.AddRoutes( + []rest.Route{ + { + // 获取公开评价列表 + Method: http.MethodGet, + Path: "/reviews", + Handler: review.ListReviewsHandler(serverCtx), + }, + { + // 获取用户收到的评价 + Method: http.MethodGet, + Path: "/users/:id/reviews", + Handler: review.ListUserReviewsHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) +} diff --git a/app/review/api/internal/logic/review/getOrderReviewsLogic.go b/app/review/api/internal/logic/review/getOrderReviewsLogic.go new file mode 100644 index 0000000..3196a34 --- /dev/null +++ b/app/review/api/internal/logic/review/getOrderReviewsLogic.go @@ -0,0 +1,54 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package review + +import ( + "context" + + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" + reviewpb "juwan-backend/app/review/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetOrderReviewsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取订单评价 +func NewGetOrderReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderReviewsLogic { + return &GetOrderReviewsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *GetOrderReviewsLogic) GetOrderReviews(req *types.GetOrderReviewsReq) (resp *types.ReviewListResp, err error) { + orderId := req.Id + result, err := l.svcCtx.ReviewRpc.SearchReviews(l.ctx, &reviewpb.SearchReviewsReq{ + Offset: 0, + Limit: 10, + OrderId: &orderId, + }) + if err != nil { + return nil, err + } + + items := make([]types.Review, 0, len(result.GetReviews())) + for _, r := range result.GetReviews() { + items = append(items, toAPIReview(r)) + } + return &types.ReviewListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: 0, + Limit: 10, + }, + }, nil +} diff --git a/app/review/api/internal/logic/review/helpers.go b/app/review/api/internal/logic/review/helpers.go new file mode 100644 index 0000000..8e35e03 --- /dev/null +++ b/app/review/api/internal/logic/review/helpers.go @@ -0,0 +1,28 @@ +package review + +import ( + "time" + + "juwan-backend/app/review/api/internal/types" + reviewpb "juwan-backend/app/review/rpc/pb" +) + +func formatUnix(ts int64) string { + if ts <= 0 { + return "" + } + return time.Unix(ts, 0).UTC().Format(time.RFC3339) +} + +func toAPIReview(r *reviewpb.Reviews) types.Review { + return types.Review{ + Id: r.GetId(), + OrderId: r.GetOrderId(), + FromUserId: r.GetFromUserId(), + FromUserName: r.GetFromUserName(), + Rating: int(r.GetRating()), + Content: r.GetContent(), + Sealed: r.GetSealed(), + CreatedAt: formatUnix(r.GetCreatedAt()), + } +} diff --git a/app/review/api/internal/logic/review/listReviewsLogic.go b/app/review/api/internal/logic/review/listReviewsLogic.go new file mode 100644 index 0000000..ad5672e --- /dev/null +++ b/app/review/api/internal/logic/review/listReviewsLogic.go @@ -0,0 +1,54 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package review + +import ( + "context" + + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" + reviewpb "juwan-backend/app/review/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListReviewsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取公开评价列表 +func NewListReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListReviewsLogic { + return &ListReviewsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListReviewsLogic) ListReviews(req *types.PageReq) (resp *types.ReviewListResp, err error) { + sealed := false + result, err := l.svcCtx.ReviewRpc.SearchReviews(l.ctx, &reviewpb.SearchReviewsReq{ + Offset: req.Offset, + Limit: req.Limit, + Sealed: &sealed, + }) + if err != nil { + return nil, err + } + + items := make([]types.Review, 0, len(result.GetReviews())) + for _, r := range result.GetReviews() { + items = append(items, toAPIReview(r)) + } + return &types.ReviewListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: req.Limit, + }, + }, nil +} diff --git a/app/review/api/internal/logic/review/listUserReviewsLogic.go b/app/review/api/internal/logic/review/listUserReviewsLogic.go new file mode 100644 index 0000000..46954f4 --- /dev/null +++ b/app/review/api/internal/logic/review/listUserReviewsLogic.go @@ -0,0 +1,56 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package review + +import ( + "context" + + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" + reviewpb "juwan-backend/app/review/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListUserReviewsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取用户收到的评价 +func NewListUserReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUserReviewsLogic { + return &ListUserReviewsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListUserReviewsLogic) ListUserReviews(req *types.ListUserReviewsReq) (resp *types.ReviewListResp, err error) { + sealed := false + toUserId := req.Id + result, err := l.svcCtx.ReviewRpc.SearchReviews(l.ctx, &reviewpb.SearchReviewsReq{ + Offset: req.Offset, + Limit: req.Limit, + ToUserId: &toUserId, + Sealed: &sealed, + }) + if err != nil { + return nil, err + } + + items := make([]types.Review, 0, len(result.GetReviews())) + for _, r := range result.GetReviews() { + items = append(items, toAPIReview(r)) + } + return &types.ReviewListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: req.Limit, + }, + }, nil +} diff --git a/app/review/api/internal/logic/review/submitReviewLogic.go b/app/review/api/internal/logic/review/submitReviewLogic.go new file mode 100644 index 0000000..5b63ad6 --- /dev/null +++ b/app/review/api/internal/logic/review/submitReviewLogic.go @@ -0,0 +1,104 @@ +package review + +import ( + "context" + "errors" + "time" + + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/app/review/api/internal/types" + reviewpb "juwan-backend/app/review/rpc/pb" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SubmitReviewLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewSubmitReviewLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SubmitReviewLogic { + return &SubmitReviewLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *SubmitReviewLogic) SubmitReview(req *types.SubmitReviewReq) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + orderResp, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + order := orderResp.GetOrders() + if order == nil { + return nil, errors.New("order not found") + } + if order.GetStatus() != "pending_review" { + return nil, errors.New("order is not in pending_review status") + } + + var fromUserId, toUserId int64 + if uid == order.GetConsumerId() { + fromUserId = order.GetConsumerId() + toUserId = order.GetPlayerId() + } else if uid == order.GetPlayerId() { + fromUserId = order.GetPlayerId() + toUserId = order.GetConsumerId() + } else { + return nil, errors.New("not a participant of this order") + } + + _, err = l.svcCtx.ReviewRpc.AddReviews(l.ctx, &reviewpb.AddReviewsReq{ + OrderId: req.Id, + FromUserId: fromUserId, + ToUserId: toUserId, + Rating: int32(req.Rating), + Content: req.Content, + Sealed: true, + }) + if err != nil { + return nil, err + } + + existing, err := l.svcCtx.ReviewRpc.SearchReviews(l.ctx, &reviewpb.SearchReviewsReq{ + Offset: 0, + Limit: 2, + OrderId: &req.Id, + }) + if err != nil { + return nil, err + } + + if len(existing.GetReviews()) >= 2 { + now := time.Now().Unix() + sealed := false + for _, r := range existing.GetReviews() { + _, _ = l.svcCtx.ReviewRpc.UpdateReviews(l.ctx, &reviewpb.UpdateReviewsReq{ + Id: r.GetId(), + Sealed: &sealed, + UnsealedAt: &now, + }) + } + + completedStatus := "completed" + completedAt := now + updatedAt := now + _, _ = l.svcCtx.OrderRpc.UpdateOrders(l.ctx, &orderservice.UpdateOrdersReq{ + Id: req.Id, + Status: &completedStatus, + CompletedAt: &completedAt, + UpdatedAt: &updatedAt, + }) + } + + return &types.EmptyResp{}, nil +} diff --git a/app/review/api/internal/svc/serviceContext.go b/app/review/api/internal/svc/serviceContext.go new file mode 100644 index 0000000..4c02f7d --- /dev/null +++ b/app/review/api/internal/svc/serviceContext.go @@ -0,0 +1,23 @@ +package svc + +import ( + "juwan-backend/app/order/rpc/orderservice" + "juwan-backend/app/review/api/internal/config" + "juwan-backend/app/review/rpc/reviewservice" + + "github.com/zeromicro/go-zero/zrpc" +) + +type ServiceContext struct { + Config config.Config + ReviewRpc reviewservice.ReviewService + OrderRpc orderservice.OrderService +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + ReviewRpc: reviewservice.NewReviewService(zrpc.MustNewClient(c.ReviewRpcConf)), + OrderRpc: orderservice.NewOrderService(zrpc.MustNewClient(c.OrderRpcConf)), + } +} diff --git a/app/review/api/internal/types/types.go b/app/review/api/internal/types/types.go new file mode 100644 index 0000000..fa9084c --- /dev/null +++ b/app/review/api/internal/types/types.go @@ -0,0 +1,72 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package types + +type EmptyResp struct { +} + +type GetOrderReviewsReq struct { + ReviewPathId +} + +type ListUserReviewsReq struct { + ReviewPathId + 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 Review struct { + Id int64 `json:"id"` + OrderId int64 `json:"orderId"` + FromUserId int64 `json:"fromUserId"` + FromUserName string `json:"fromUserName"` + Rating int `json:"rating"` + Content string `json:"content"` + Sealed bool `json:"sealed"` + CreatedAt string `json:"createdAt"` +} + +type ReviewListResp struct { + Items []Review `json:"items"` + Meta PageMeta `json:"meta"` +} + +type ReviewPathId struct { + Id int64 `path:"id"` +} + +type SimpleUser struct { + Id string `json:"id"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` +} + +type SubmitReviewReq struct { + ReviewPathId + Rating int `json:"rating"` + Content string `json:"content,optional"` +} + +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/review/api/review.go b/app/review/api/review.go new file mode 100644 index 0000000..cea80e9 --- /dev/null +++ b/app/review/api/review.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/review/api/internal/config" + "juwan-backend/app/review/api/internal/handler" + "juwan-backend/app/review/api/internal/svc" + "juwan-backend/common/middlewares" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/review-api.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + server.Use(middlewares.NewHeaderExtractorMiddleware().Handle) + 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/review/rpc/etc/pb.yaml b/app/review/rpc/etc/pb.yaml new file mode 100644 index 0000000..0bbfacb --- /dev/null +++ b/app/review/rpc/etc/pb.yaml @@ -0,0 +1,23 @@ +Name: pb.rpc +ListenOn: 0.0.0.0:8080 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONF ===== +SnowflakeRpcConf: + Endpoints: + - snowflake:8080 + +DB: + Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + +CacheConf: + - Host: "${REDIS_HOST}:${REDIS_PORT}" + Type: node + +Log: + Level: debug diff --git a/app/review/rpc/internal/config/config.go b/app/review/rpc/internal/config/config.go new file mode 100644 index 0000000..f4107e8 --- /dev/null +++ b/app/review/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/review/rpc/internal/logic/addReviewsLogic.go b/app/review/rpc/internal/logic/addReviewsLogic.go new file mode 100644 index 0000000..39f10da --- /dev/null +++ b/app/review/rpc/internal/logic/addReviewsLogic.go @@ -0,0 +1,64 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/review/rpc/internal/svc" + "juwan-backend/app/review/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddReviewsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddReviewsLogic { + return &AddReviewsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *AddReviewsLogic) AddReviews(in *pb.AddReviewsReq) (*pb.AddReviewsResp, error) { + if in.GetOrderId() <= 0 { + return nil, errors.New("orderId is required") + } + if in.GetFromUserId() <= 0 { + return nil, errors.New("fromUserId is required") + } + if in.GetToUserId() <= 0 { + return nil, errors.New("toUserId is required") + } + if in.GetRating() < 1 || in.GetRating() > 5 { + return nil, errors.New("rating must be between 1 and 5") + } + + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create review id failed") + } + + created, err := l.svcCtx.ReviewModelRW.Reviews.Create(). + SetID(idResp.Id). + SetOrderID(in.GetOrderId()). + SetFromUserID(in.GetFromUserId()). + SetFromUserName(in.GetFromUserName()). + SetFromUserAvatar(in.GetFromUserAvatar()). + SetToUserID(in.GetToUserId()). + SetRating(int16(in.GetRating())). + SetContent(in.GetContent()). + SetSealed(in.GetSealed()). + Save(l.ctx) + if err != nil { + logx.Errorf("addReviews err: %v", err) + return nil, errors.New("add review failed") + } + + return &pb.AddReviewsResp{Id: created.ID}, nil +} diff --git a/app/review/rpc/internal/logic/delReviewsLogic.go b/app/review/rpc/internal/logic/delReviewsLogic.go new file mode 100644 index 0000000..8a19024 --- /dev/null +++ b/app/review/rpc/internal/logic/delReviewsLogic.go @@ -0,0 +1,33 @@ +package logic + +import ( + "context" + + "juwan-backend/app/review/rpc/internal/svc" + "juwan-backend/app/review/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelReviewsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelReviewsLogic { + return &DelReviewsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelReviewsLogic) DelReviews(in *pb.DelReviewsReq) (*pb.DelReviewsResp, error) { + err := l.svcCtx.ReviewModelRW.Reviews.DeleteOneID(in.GetId()).Exec(l.ctx) + if err != nil { + logx.Errorf("delReviews err: %v", err) + return nil, err + } + return &pb.DelReviewsResp{}, nil +} diff --git a/app/review/rpc/internal/logic/getReviewsByIdLogic.go b/app/review/rpc/internal/logic/getReviewsByIdLogic.go new file mode 100644 index 0000000..d7e796c --- /dev/null +++ b/app/review/rpc/internal/logic/getReviewsByIdLogic.go @@ -0,0 +1,32 @@ +package logic + +import ( + "context" + + "juwan-backend/app/review/rpc/internal/svc" + "juwan-backend/app/review/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetReviewsByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetReviewsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetReviewsByIdLogic { + return &GetReviewsByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetReviewsByIdLogic) GetReviewsById(in *pb.GetReviewsByIdReq) (*pb.GetReviewsByIdResp, error) { + r, err := l.svcCtx.ReviewModelRO.Reviews.Get(l.ctx, in.GetId()) + if err != nil { + return nil, err + } + return &pb.GetReviewsByIdResp{Reviews: entReviewToPb(r)}, nil +} diff --git a/app/review/rpc/internal/logic/helpers.go b/app/review/rpc/internal/logic/helpers.go new file mode 100644 index 0000000..40f49b3 --- /dev/null +++ b/app/review/rpc/internal/logic/helpers.go @@ -0,0 +1,25 @@ +package logic + +import ( + "juwan-backend/app/review/rpc/internal/models" + "juwan-backend/app/review/rpc/pb" +) + +func entReviewToPb(r *models.Reviews) *pb.Reviews { + out := &pb.Reviews{ + Id: r.ID, + OrderId: r.OrderID, + FromUserId: r.FromUserID, + FromUserName: r.FromUserName, + FromUserAvatar: r.FromUserAvatar, + ToUserId: r.ToUserID, + Rating: int32(r.Rating), + Content: r.Content, + Sealed: r.Sealed, + CreatedAt: r.CreatedAt.Unix(), + } + if r.UnsealedAt != nil { + out.UnsealedAt = r.UnsealedAt.Unix() + } + return out +} diff --git a/app/review/rpc/internal/logic/searchReviewsLogic.go b/app/review/rpc/internal/logic/searchReviewsLogic.go new file mode 100644 index 0000000..063c4bc --- /dev/null +++ b/app/review/rpc/internal/logic/searchReviewsLogic.go @@ -0,0 +1,76 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/review/rpc/internal/models/reviews" + "juwan-backend/app/review/rpc/internal/svc" + "juwan-backend/app/review/rpc/pb" + + "entgo.io/ent/dialect/sql" + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchReviewsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchReviewsLogic { + return &SearchReviewsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchReviewsLogic) SearchReviews(in *pb.SearchReviewsReq) (*pb.SearchReviewsResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + if limit > 100 { + return nil, errors.New("limit too large") + } + offset := in.GetOffset() + if offset < 0 { + offset = 0 + } + + query := l.svcCtx.ReviewModelRO.Reviews.Query() + + if in.Id != nil { + query = query.Where(reviews.IDEQ(in.GetId())) + } + if in.OrderId != nil { + query = query.Where(reviews.OrderIDEQ(in.GetOrderId())) + } + if in.FromUserId != nil { + query = query.Where(reviews.FromUserIDEQ(in.GetFromUserId())) + } + if in.ToUserId != nil { + query = query.Where(reviews.ToUserIDEQ(in.GetToUserId())) + } + if in.Sealed != nil { + query = query.Where(reviews.SealedEQ(in.GetSealed())) + } + + list, err := query. + Order(reviews.ByCreatedAt(sql.OrderDesc()), reviews.ByID(sql.OrderDesc())). + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchReviews err: %v", err) + return nil, errors.New("search reviews failed") + } + + out := make([]*pb.Reviews, len(list)) + for i, r := range list { + out[i] = entReviewToPb(r) + } + + return &pb.SearchReviewsResp{Reviews: out}, nil +} diff --git a/app/review/rpc/internal/logic/updateReviewsLogic.go b/app/review/rpc/internal/logic/updateReviewsLogic.go new file mode 100644 index 0000000..83cda7e --- /dev/null +++ b/app/review/rpc/internal/logic/updateReviewsLogic.go @@ -0,0 +1,49 @@ +package logic + +import ( + "context" + "time" + + "juwan-backend/app/review/rpc/internal/svc" + "juwan-backend/app/review/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UpdateReviewsLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewUpdateReviewsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateReviewsLogic { + return &UpdateReviewsLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *UpdateReviewsLogic) UpdateReviews(in *pb.UpdateReviewsReq) (*pb.UpdateReviewsResp, error) { + updater := l.svcCtx.ReviewModelRW.Reviews.UpdateOneID(in.GetId()) + + if in.Sealed != nil { + updater = updater.SetSealed(in.GetSealed()) + } + if in.UnsealedAt != nil { + updater = updater.SetUnsealedAt(time.Unix(in.GetUnsealedAt(), 0)) + } + if in.Rating != nil { + updater = updater.SetRating(int16(in.GetRating())) + } + if in.Content != nil { + updater = updater.SetContent(in.GetContent()) + } + + _, err := updater.Save(l.ctx) + if err != nil { + logx.Errorf("updateReviews err: %v", err) + return nil, err + } + return &pb.UpdateReviewsResp{}, nil +} diff --git a/app/review/rpc/internal/models/client.go b/app/review/rpc/internal/models/client.go new file mode 100644 index 0000000..850962e --- /dev/null +++ b/app/review/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/review/rpc/internal/models/migrate" + + "juwan-backend/app/review/rpc/internal/models/reviews" + + "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 + // Reviews is the client for interacting with the Reviews builders. + Reviews *ReviewsClient +} + +// 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.Reviews = NewReviewsClient(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, + Reviews: NewReviewsClient(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, + Reviews: NewReviewsClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Reviews. +// 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.Reviews.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.Reviews.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *ReviewsMutation: + return c.Reviews.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// ReviewsClient is a client for the Reviews schema. +type ReviewsClient struct { + config +} + +// NewReviewsClient returns a client for the Reviews from the given config. +func NewReviewsClient(c config) *ReviewsClient { + return &ReviewsClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `reviews.Hooks(f(g(h())))`. +func (c *ReviewsClient) Use(hooks ...Hook) { + c.hooks.Reviews = append(c.hooks.Reviews, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `reviews.Intercept(f(g(h())))`. +func (c *ReviewsClient) Intercept(interceptors ...Interceptor) { + c.inters.Reviews = append(c.inters.Reviews, interceptors...) +} + +// Create returns a builder for creating a Reviews entity. +func (c *ReviewsClient) Create() *ReviewsCreate { + mutation := newReviewsMutation(c.config, OpCreate) + return &ReviewsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Reviews entities. +func (c *ReviewsClient) CreateBulk(builders ...*ReviewsCreate) *ReviewsCreateBulk { + return &ReviewsCreateBulk{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 *ReviewsClient) MapCreateBulk(slice any, setFunc func(*ReviewsCreate, int)) *ReviewsCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ReviewsCreateBulk{err: fmt.Errorf("calling to ReviewsClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ReviewsCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ReviewsCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Reviews. +func (c *ReviewsClient) Update() *ReviewsUpdate { + mutation := newReviewsMutation(c.config, OpUpdate) + return &ReviewsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ReviewsClient) UpdateOne(_m *Reviews) *ReviewsUpdateOne { + mutation := newReviewsMutation(c.config, OpUpdateOne, withReviews(_m)) + return &ReviewsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ReviewsClient) UpdateOneID(id int64) *ReviewsUpdateOne { + mutation := newReviewsMutation(c.config, OpUpdateOne, withReviewsID(id)) + return &ReviewsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Reviews. +func (c *ReviewsClient) Delete() *ReviewsDelete { + mutation := newReviewsMutation(c.config, OpDelete) + return &ReviewsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ReviewsClient) DeleteOne(_m *Reviews) *ReviewsDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ReviewsClient) DeleteOneID(id int64) *ReviewsDeleteOne { + builder := c.Delete().Where(reviews.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ReviewsDeleteOne{builder} +} + +// Query returns a query builder for Reviews. +func (c *ReviewsClient) Query() *ReviewsQuery { + return &ReviewsQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeReviews}, + inters: c.Interceptors(), + } +} + +// Get returns a Reviews entity by its id. +func (c *ReviewsClient) Get(ctx context.Context, id int64) (*Reviews, error) { + return c.Query().Where(reviews.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ReviewsClient) GetX(ctx context.Context, id int64) *Reviews { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *ReviewsClient) Hooks() []Hook { + return c.hooks.Reviews +} + +// Interceptors returns the client interceptors. +func (c *ReviewsClient) Interceptors() []Interceptor { + return c.inters.Reviews +} + +func (c *ReviewsClient) mutate(ctx context.Context, m *ReviewsMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ReviewsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ReviewsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ReviewsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ReviewsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Reviews mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Reviews []ent.Hook + } + inters struct { + Reviews []ent.Interceptor + } +) diff --git a/app/review/rpc/internal/models/ent.go b/app/review/rpc/internal/models/ent.go new file mode 100644 index 0000000..bd4a7d5 --- /dev/null +++ b/app/review/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/review/rpc/internal/models/reviews" + "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{ + reviews.Table: reviews.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/review/rpc/internal/models/enttest/enttest.go b/app/review/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..e3bd1e9 --- /dev/null +++ b/app/review/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/review/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/review/rpc/internal/models/runtime" + + "juwan-backend/app/review/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/review/rpc/internal/models/generate.go b/app/review/rpc/internal/models/generate.go new file mode 100644 index 0000000..d441aca --- /dev/null +++ b/app/review/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/review/rpc/internal/models/hook/hook.go b/app/review/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..4886436 --- /dev/null +++ b/app/review/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/review/rpc/internal/models" +) + +// The ReviewsFunc type is an adapter to allow the use of ordinary +// function as Reviews mutator. +type ReviewsFunc func(context.Context, *models.ReviewsMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f ReviewsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.ReviewsMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.ReviewsMutation", 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/review/rpc/internal/models/migrate/migrate.go b/app/review/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/review/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/review/rpc/internal/models/migrate/schema.go b/app/review/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..2b4f8a1 --- /dev/null +++ b/app/review/rpc/internal/models/migrate/schema.go @@ -0,0 +1,60 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // ReviewsColumns holds the columns for the "reviews" table. + ReviewsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "order_id", Type: field.TypeInt64}, + {Name: "from_user_id", Type: field.TypeInt64}, + {Name: "from_user_name", Type: field.TypeString, Size: 100}, + {Name: "from_user_avatar", Type: field.TypeString, Nullable: true, Default: ""}, + {Name: "to_user_id", Type: field.TypeInt64}, + {Name: "rating", Type: field.TypeInt16}, + {Name: "content", Type: field.TypeString, Nullable: true, Default: ""}, + {Name: "sealed", Type: field.TypeBool, Default: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "unsealed_at", Type: field.TypeTime, Nullable: true}, + } + // ReviewsTable holds the schema information for the "reviews" table. + ReviewsTable = &schema.Table{ + Name: "reviews", + Columns: ReviewsColumns, + PrimaryKey: []*schema.Column{ReviewsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "reviews_order_id_from_user_id", + Unique: true, + Columns: []*schema.Column{ReviewsColumns[1], ReviewsColumns[2]}, + }, + { + Name: "reviews_order_id", + Unique: false, + Columns: []*schema.Column{ReviewsColumns[1]}, + }, + { + Name: "reviews_to_user_id_created_at", + Unique: false, + Columns: []*schema.Column{ReviewsColumns[5], ReviewsColumns[9]}, + }, + { + Name: "reviews_from_user_id", + Unique: false, + Columns: []*schema.Column{ReviewsColumns[2]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + ReviewsTable, + } +) + +func init() { +} diff --git a/app/review/rpc/internal/models/mutation.go b/app/review/rpc/internal/models/mutation.go new file mode 100644 index 0000000..007cecb --- /dev/null +++ b/app/review/rpc/internal/models/mutation.go @@ -0,0 +1,1041 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/review/rpc/internal/models/predicate" + "juwan-backend/app/review/rpc/internal/models/reviews" + "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. + TypeReviews = "Reviews" +) + +// ReviewsMutation represents an operation that mutates the Reviews nodes in the graph. +type ReviewsMutation struct { + config + op Op + typ string + id *int64 + order_id *int64 + addorder_id *int64 + from_user_id *int64 + addfrom_user_id *int64 + from_user_name *string + from_user_avatar *string + to_user_id *int64 + addto_user_id *int64 + rating *int16 + addrating *int16 + content *string + sealed *bool + created_at *time.Time + unsealed_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Reviews, error) + predicates []predicate.Reviews +} + +var _ ent.Mutation = (*ReviewsMutation)(nil) + +// reviewsOption allows management of the mutation configuration using functional options. +type reviewsOption func(*ReviewsMutation) + +// newReviewsMutation creates new mutation for the Reviews entity. +func newReviewsMutation(c config, op Op, opts ...reviewsOption) *ReviewsMutation { + m := &ReviewsMutation{ + config: c, + op: op, + typ: TypeReviews, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withReviewsID sets the ID field of the mutation. +func withReviewsID(id int64) reviewsOption { + return func(m *ReviewsMutation) { + var ( + err error + once sync.Once + value *Reviews + ) + m.oldValue = func(ctx context.Context) (*Reviews, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Reviews.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withReviews sets the old Reviews of the mutation. +func withReviews(node *Reviews) reviewsOption { + return func(m *ReviewsMutation) { + m.oldValue = func(context.Context) (*Reviews, 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 ReviewsMutation) 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 ReviewsMutation) 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 Reviews entities. +func (m *ReviewsMutation) 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 *ReviewsMutation) 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 *ReviewsMutation) 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().Reviews.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 *ReviewsMutation) 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 *ReviewsMutation) 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 Reviews entity. +// If the Reviews 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 *ReviewsMutation) 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 *ReviewsMutation) 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 *ReviewsMutation) 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 *ReviewsMutation) ResetOrderID() { + m.order_id = nil + m.addorder_id = nil +} + +// SetFromUserID sets the "from_user_id" field. +func (m *ReviewsMutation) SetFromUserID(i int64) { + m.from_user_id = &i + m.addfrom_user_id = nil +} + +// FromUserID returns the value of the "from_user_id" field in the mutation. +func (m *ReviewsMutation) FromUserID() (r int64, exists bool) { + v := m.from_user_id + if v == nil { + return + } + return *v, true +} + +// OldFromUserID returns the old "from_user_id" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldFromUserID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFromUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFromUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFromUserID: %w", err) + } + return oldValue.FromUserID, nil +} + +// AddFromUserID adds i to the "from_user_id" field. +func (m *ReviewsMutation) AddFromUserID(i int64) { + if m.addfrom_user_id != nil { + *m.addfrom_user_id += i + } else { + m.addfrom_user_id = &i + } +} + +// AddedFromUserID returns the value that was added to the "from_user_id" field in this mutation. +func (m *ReviewsMutation) AddedFromUserID() (r int64, exists bool) { + v := m.addfrom_user_id + if v == nil { + return + } + return *v, true +} + +// ResetFromUserID resets all changes to the "from_user_id" field. +func (m *ReviewsMutation) ResetFromUserID() { + m.from_user_id = nil + m.addfrom_user_id = nil +} + +// SetFromUserName sets the "from_user_name" field. +func (m *ReviewsMutation) SetFromUserName(s string) { + m.from_user_name = &s +} + +// FromUserName returns the value of the "from_user_name" field in the mutation. +func (m *ReviewsMutation) FromUserName() (r string, exists bool) { + v := m.from_user_name + if v == nil { + return + } + return *v, true +} + +// OldFromUserName returns the old "from_user_name" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldFromUserName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFromUserName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFromUserName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFromUserName: %w", err) + } + return oldValue.FromUserName, nil +} + +// ResetFromUserName resets all changes to the "from_user_name" field. +func (m *ReviewsMutation) ResetFromUserName() { + m.from_user_name = nil +} + +// SetFromUserAvatar sets the "from_user_avatar" field. +func (m *ReviewsMutation) SetFromUserAvatar(s string) { + m.from_user_avatar = &s +} + +// FromUserAvatar returns the value of the "from_user_avatar" field in the mutation. +func (m *ReviewsMutation) FromUserAvatar() (r string, exists bool) { + v := m.from_user_avatar + if v == nil { + return + } + return *v, true +} + +// OldFromUserAvatar returns the old "from_user_avatar" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldFromUserAvatar(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFromUserAvatar is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFromUserAvatar requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFromUserAvatar: %w", err) + } + return oldValue.FromUserAvatar, nil +} + +// ClearFromUserAvatar clears the value of the "from_user_avatar" field. +func (m *ReviewsMutation) ClearFromUserAvatar() { + m.from_user_avatar = nil + m.clearedFields[reviews.FieldFromUserAvatar] = struct{}{} +} + +// FromUserAvatarCleared returns if the "from_user_avatar" field was cleared in this mutation. +func (m *ReviewsMutation) FromUserAvatarCleared() bool { + _, ok := m.clearedFields[reviews.FieldFromUserAvatar] + return ok +} + +// ResetFromUserAvatar resets all changes to the "from_user_avatar" field. +func (m *ReviewsMutation) ResetFromUserAvatar() { + m.from_user_avatar = nil + delete(m.clearedFields, reviews.FieldFromUserAvatar) +} + +// SetToUserID sets the "to_user_id" field. +func (m *ReviewsMutation) SetToUserID(i int64) { + m.to_user_id = &i + m.addto_user_id = nil +} + +// ToUserID returns the value of the "to_user_id" field in the mutation. +func (m *ReviewsMutation) ToUserID() (r int64, exists bool) { + v := m.to_user_id + if v == nil { + return + } + return *v, true +} + +// OldToUserID returns the old "to_user_id" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldToUserID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldToUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldToUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldToUserID: %w", err) + } + return oldValue.ToUserID, nil +} + +// AddToUserID adds i to the "to_user_id" field. +func (m *ReviewsMutation) AddToUserID(i int64) { + if m.addto_user_id != nil { + *m.addto_user_id += i + } else { + m.addto_user_id = &i + } +} + +// AddedToUserID returns the value that was added to the "to_user_id" field in this mutation. +func (m *ReviewsMutation) AddedToUserID() (r int64, exists bool) { + v := m.addto_user_id + if v == nil { + return + } + return *v, true +} + +// ResetToUserID resets all changes to the "to_user_id" field. +func (m *ReviewsMutation) ResetToUserID() { + m.to_user_id = nil + m.addto_user_id = nil +} + +// SetRating sets the "rating" field. +func (m *ReviewsMutation) SetRating(i int16) { + m.rating = &i + m.addrating = nil +} + +// Rating returns the value of the "rating" field in the mutation. +func (m *ReviewsMutation) Rating() (r int16, exists bool) { + v := m.rating + if v == nil { + return + } + return *v, true +} + +// OldRating returns the old "rating" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldRating(ctx context.Context) (v int16, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRating is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRating requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRating: %w", err) + } + return oldValue.Rating, nil +} + +// AddRating adds i to the "rating" field. +func (m *ReviewsMutation) AddRating(i int16) { + if m.addrating != nil { + *m.addrating += i + } else { + m.addrating = &i + } +} + +// AddedRating returns the value that was added to the "rating" field in this mutation. +func (m *ReviewsMutation) AddedRating() (r int16, exists bool) { + v := m.addrating + if v == nil { + return + } + return *v, true +} + +// ResetRating resets all changes to the "rating" field. +func (m *ReviewsMutation) ResetRating() { + m.rating = nil + m.addrating = nil +} + +// SetContent sets the "content" field. +func (m *ReviewsMutation) SetContent(s string) { + m.content = &s +} + +// Content returns the value of the "content" field in the mutation. +func (m *ReviewsMutation) Content() (r string, exists bool) { + v := m.content + if v == nil { + return + } + return *v, true +} + +// OldContent returns the old "content" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldContent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContent: %w", err) + } + return oldValue.Content, nil +} + +// ClearContent clears the value of the "content" field. +func (m *ReviewsMutation) ClearContent() { + m.content = nil + m.clearedFields[reviews.FieldContent] = struct{}{} +} + +// ContentCleared returns if the "content" field was cleared in this mutation. +func (m *ReviewsMutation) ContentCleared() bool { + _, ok := m.clearedFields[reviews.FieldContent] + return ok +} + +// ResetContent resets all changes to the "content" field. +func (m *ReviewsMutation) ResetContent() { + m.content = nil + delete(m.clearedFields, reviews.FieldContent) +} + +// SetSealed sets the "sealed" field. +func (m *ReviewsMutation) SetSealed(b bool) { + m.sealed = &b +} + +// Sealed returns the value of the "sealed" field in the mutation. +func (m *ReviewsMutation) Sealed() (r bool, exists bool) { + v := m.sealed + if v == nil { + return + } + return *v, true +} + +// OldSealed returns the old "sealed" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldSealed(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSealed is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSealed requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSealed: %w", err) + } + return oldValue.Sealed, nil +} + +// ResetSealed resets all changes to the "sealed" field. +func (m *ReviewsMutation) ResetSealed() { + m.sealed = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ReviewsMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ReviewsMutation) 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 Reviews entity. +// If the Reviews 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 *ReviewsMutation) 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 *ReviewsMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUnsealedAt sets the "unsealed_at" field. +func (m *ReviewsMutation) SetUnsealedAt(t time.Time) { + m.unsealed_at = &t +} + +// UnsealedAt returns the value of the "unsealed_at" field in the mutation. +func (m *ReviewsMutation) UnsealedAt() (r time.Time, exists bool) { + v := m.unsealed_at + if v == nil { + return + } + return *v, true +} + +// OldUnsealedAt returns the old "unsealed_at" field's value of the Reviews entity. +// If the Reviews 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 *ReviewsMutation) OldUnsealedAt(ctx context.Context) (v *time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUnsealedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUnsealedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUnsealedAt: %w", err) + } + return oldValue.UnsealedAt, nil +} + +// ClearUnsealedAt clears the value of the "unsealed_at" field. +func (m *ReviewsMutation) ClearUnsealedAt() { + m.unsealed_at = nil + m.clearedFields[reviews.FieldUnsealedAt] = struct{}{} +} + +// UnsealedAtCleared returns if the "unsealed_at" field was cleared in this mutation. +func (m *ReviewsMutation) UnsealedAtCleared() bool { + _, ok := m.clearedFields[reviews.FieldUnsealedAt] + return ok +} + +// ResetUnsealedAt resets all changes to the "unsealed_at" field. +func (m *ReviewsMutation) ResetUnsealedAt() { + m.unsealed_at = nil + delete(m.clearedFields, reviews.FieldUnsealedAt) +} + +// Where appends a list predicates to the ReviewsMutation builder. +func (m *ReviewsMutation) Where(ps ...predicate.Reviews) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ReviewsMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ReviewsMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Reviews, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ReviewsMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ReviewsMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Reviews). +func (m *ReviewsMutation) 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 *ReviewsMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.order_id != nil { + fields = append(fields, reviews.FieldOrderID) + } + if m.from_user_id != nil { + fields = append(fields, reviews.FieldFromUserID) + } + if m.from_user_name != nil { + fields = append(fields, reviews.FieldFromUserName) + } + if m.from_user_avatar != nil { + fields = append(fields, reviews.FieldFromUserAvatar) + } + if m.to_user_id != nil { + fields = append(fields, reviews.FieldToUserID) + } + if m.rating != nil { + fields = append(fields, reviews.FieldRating) + } + if m.content != nil { + fields = append(fields, reviews.FieldContent) + } + if m.sealed != nil { + fields = append(fields, reviews.FieldSealed) + } + if m.created_at != nil { + fields = append(fields, reviews.FieldCreatedAt) + } + if m.unsealed_at != nil { + fields = append(fields, reviews.FieldUnsealedAt) + } + 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 *ReviewsMutation) Field(name string) (ent.Value, bool) { + switch name { + case reviews.FieldOrderID: + return m.OrderID() + case reviews.FieldFromUserID: + return m.FromUserID() + case reviews.FieldFromUserName: + return m.FromUserName() + case reviews.FieldFromUserAvatar: + return m.FromUserAvatar() + case reviews.FieldToUserID: + return m.ToUserID() + case reviews.FieldRating: + return m.Rating() + case reviews.FieldContent: + return m.Content() + case reviews.FieldSealed: + return m.Sealed() + case reviews.FieldCreatedAt: + return m.CreatedAt() + case reviews.FieldUnsealedAt: + return m.UnsealedAt() + } + 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 *ReviewsMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case reviews.FieldOrderID: + return m.OldOrderID(ctx) + case reviews.FieldFromUserID: + return m.OldFromUserID(ctx) + case reviews.FieldFromUserName: + return m.OldFromUserName(ctx) + case reviews.FieldFromUserAvatar: + return m.OldFromUserAvatar(ctx) + case reviews.FieldToUserID: + return m.OldToUserID(ctx) + case reviews.FieldRating: + return m.OldRating(ctx) + case reviews.FieldContent: + return m.OldContent(ctx) + case reviews.FieldSealed: + return m.OldSealed(ctx) + case reviews.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case reviews.FieldUnsealedAt: + return m.OldUnsealedAt(ctx) + } + return nil, fmt.Errorf("unknown Reviews 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 *ReviewsMutation) SetField(name string, value ent.Value) error { + switch name { + case reviews.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOrderID(v) + return nil + case reviews.FieldFromUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFromUserID(v) + return nil + case reviews.FieldFromUserName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFromUserName(v) + return nil + case reviews.FieldFromUserAvatar: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFromUserAvatar(v) + return nil + case reviews.FieldToUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetToUserID(v) + return nil + case reviews.FieldRating: + v, ok := value.(int16) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRating(v) + return nil + case reviews.FieldContent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContent(v) + return nil + case reviews.FieldSealed: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSealed(v) + return nil + case reviews.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 reviews.FieldUnsealedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUnsealedAt(v) + return nil + } + return fmt.Errorf("unknown Reviews field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ReviewsMutation) AddedFields() []string { + var fields []string + if m.addorder_id != nil { + fields = append(fields, reviews.FieldOrderID) + } + if m.addfrom_user_id != nil { + fields = append(fields, reviews.FieldFromUserID) + } + if m.addto_user_id != nil { + fields = append(fields, reviews.FieldToUserID) + } + if m.addrating != nil { + fields = append(fields, reviews.FieldRating) + } + 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 *ReviewsMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case reviews.FieldOrderID: + return m.AddedOrderID() + case reviews.FieldFromUserID: + return m.AddedFromUserID() + case reviews.FieldToUserID: + return m.AddedToUserID() + case reviews.FieldRating: + return m.AddedRating() + } + 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 *ReviewsMutation) AddField(name string, value ent.Value) error { + switch name { + case reviews.FieldOrderID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOrderID(v) + return nil + case reviews.FieldFromUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddFromUserID(v) + return nil + case reviews.FieldToUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddToUserID(v) + return nil + case reviews.FieldRating: + v, ok := value.(int16) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRating(v) + return nil + } + return fmt.Errorf("unknown Reviews numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ReviewsMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(reviews.FieldFromUserAvatar) { + fields = append(fields, reviews.FieldFromUserAvatar) + } + if m.FieldCleared(reviews.FieldContent) { + fields = append(fields, reviews.FieldContent) + } + if m.FieldCleared(reviews.FieldUnsealedAt) { + fields = append(fields, reviews.FieldUnsealedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ReviewsMutation) 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 *ReviewsMutation) ClearField(name string) error { + switch name { + case reviews.FieldFromUserAvatar: + m.ClearFromUserAvatar() + return nil + case reviews.FieldContent: + m.ClearContent() + return nil + case reviews.FieldUnsealedAt: + m.ClearUnsealedAt() + return nil + } + return fmt.Errorf("unknown Reviews 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 *ReviewsMutation) ResetField(name string) error { + switch name { + case reviews.FieldOrderID: + m.ResetOrderID() + return nil + case reviews.FieldFromUserID: + m.ResetFromUserID() + return nil + case reviews.FieldFromUserName: + m.ResetFromUserName() + return nil + case reviews.FieldFromUserAvatar: + m.ResetFromUserAvatar() + return nil + case reviews.FieldToUserID: + m.ResetToUserID() + return nil + case reviews.FieldRating: + m.ResetRating() + return nil + case reviews.FieldContent: + m.ResetContent() + return nil + case reviews.FieldSealed: + m.ResetSealed() + return nil + case reviews.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case reviews.FieldUnsealedAt: + m.ResetUnsealedAt() + return nil + } + return fmt.Errorf("unknown Reviews field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ReviewsMutation) 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 *ReviewsMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ReviewsMutation) 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 *ReviewsMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ReviewsMutation) 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 *ReviewsMutation) 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 *ReviewsMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Reviews 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 *ReviewsMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Reviews edge %s", name) +} diff --git a/app/review/rpc/internal/models/predicate/predicate.go b/app/review/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..db94644 --- /dev/null +++ b/app/review/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" +) + +// Reviews is the predicate function for reviews builders. +type Reviews func(*sql.Selector) diff --git a/app/review/rpc/internal/models/reviews.go b/app/review/rpc/internal/models/reviews.go new file mode 100644 index 0000000..242f29f --- /dev/null +++ b/app/review/rpc/internal/models/reviews.go @@ -0,0 +1,210 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/review/rpc/internal/models/reviews" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Reviews is the model entity for the Reviews schema. +type Reviews 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"` + // FromUserID holds the value of the "from_user_id" field. + FromUserID int64 `json:"from_user_id,omitempty"` + // FromUserName holds the value of the "from_user_name" field. + FromUserName string `json:"from_user_name,omitempty"` + // FromUserAvatar holds the value of the "from_user_avatar" field. + FromUserAvatar string `json:"from_user_avatar,omitempty"` + // ToUserID holds the value of the "to_user_id" field. + ToUserID int64 `json:"to_user_id,omitempty"` + // Rating holds the value of the "rating" field. + Rating int16 `json:"rating,omitempty"` + // Content holds the value of the "content" field. + Content string `json:"content,omitempty"` + // Sealed holds the value of the "sealed" field. + Sealed bool `json:"sealed,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UnsealedAt holds the value of the "unsealed_at" field. + UnsealedAt *time.Time `json:"unsealed_at,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Reviews) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case reviews.FieldSealed: + values[i] = new(sql.NullBool) + case reviews.FieldID, reviews.FieldOrderID, reviews.FieldFromUserID, reviews.FieldToUserID, reviews.FieldRating: + values[i] = new(sql.NullInt64) + case reviews.FieldFromUserName, reviews.FieldFromUserAvatar, reviews.FieldContent: + values[i] = new(sql.NullString) + case reviews.FieldCreatedAt, reviews.FieldUnsealedAt: + 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 Reviews fields. +func (_m *Reviews) 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 reviews.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 reviews.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 reviews.FieldFromUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field from_user_id", values[i]) + } else if value.Valid { + _m.FromUserID = value.Int64 + } + case reviews.FieldFromUserName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field from_user_name", values[i]) + } else if value.Valid { + _m.FromUserName = value.String + } + case reviews.FieldFromUserAvatar: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field from_user_avatar", values[i]) + } else if value.Valid { + _m.FromUserAvatar = value.String + } + case reviews.FieldToUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field to_user_id", values[i]) + } else if value.Valid { + _m.ToUserID = value.Int64 + } + case reviews.FieldRating: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field rating", values[i]) + } else if value.Valid { + _m.Rating = int16(value.Int64) + } + case reviews.FieldContent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field content", values[i]) + } else if value.Valid { + _m.Content = value.String + } + case reviews.FieldSealed: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field sealed", values[i]) + } else if value.Valid { + _m.Sealed = value.Bool + } + case reviews.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 reviews.FieldUnsealedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field unsealed_at", values[i]) + } else if value.Valid { + _m.UnsealedAt = new(time.Time) + *_m.UnsealedAt = 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 Reviews. +// This includes values selected through modifiers, order, etc. +func (_m *Reviews) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Reviews. +// Note that you need to call Reviews.Unwrap() before calling this method if this Reviews +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Reviews) Update() *ReviewsUpdateOne { + return NewReviewsClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Reviews 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 *Reviews) Unwrap() *Reviews { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Reviews is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Reviews) String() string { + var builder strings.Builder + builder.WriteString("Reviews(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("order_id=") + builder.WriteString(fmt.Sprintf("%v", _m.OrderID)) + builder.WriteString(", ") + builder.WriteString("from_user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.FromUserID)) + builder.WriteString(", ") + builder.WriteString("from_user_name=") + builder.WriteString(_m.FromUserName) + builder.WriteString(", ") + builder.WriteString("from_user_avatar=") + builder.WriteString(_m.FromUserAvatar) + builder.WriteString(", ") + builder.WriteString("to_user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ToUserID)) + builder.WriteString(", ") + builder.WriteString("rating=") + builder.WriteString(fmt.Sprintf("%v", _m.Rating)) + builder.WriteString(", ") + builder.WriteString("content=") + builder.WriteString(_m.Content) + builder.WriteString(", ") + builder.WriteString("sealed=") + builder.WriteString(fmt.Sprintf("%v", _m.Sealed)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.UnsealedAt; v != nil { + builder.WriteString("unsealed_at=") + builder.WriteString(v.Format(time.ANSIC)) + } + builder.WriteByte(')') + return builder.String() +} + +// ReviewsSlice is a parsable slice of Reviews. +type ReviewsSlice []*Reviews diff --git a/app/review/rpc/internal/models/reviews/reviews.go b/app/review/rpc/internal/models/reviews/reviews.go new file mode 100644 index 0000000..da451d3 --- /dev/null +++ b/app/review/rpc/internal/models/reviews/reviews.go @@ -0,0 +1,134 @@ +// Code generated by ent, DO NOT EDIT. + +package reviews + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the reviews type in the database. + Label = "reviews" + // 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" + // FieldFromUserID holds the string denoting the from_user_id field in the database. + FieldFromUserID = "from_user_id" + // FieldFromUserName holds the string denoting the from_user_name field in the database. + FieldFromUserName = "from_user_name" + // FieldFromUserAvatar holds the string denoting the from_user_avatar field in the database. + FieldFromUserAvatar = "from_user_avatar" + // FieldToUserID holds the string denoting the to_user_id field in the database. + FieldToUserID = "to_user_id" + // FieldRating holds the string denoting the rating field in the database. + FieldRating = "rating" + // FieldContent holds the string denoting the content field in the database. + FieldContent = "content" + // FieldSealed holds the string denoting the sealed field in the database. + FieldSealed = "sealed" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUnsealedAt holds the string denoting the unsealed_at field in the database. + FieldUnsealedAt = "unsealed_at" + // Table holds the table name of the reviews in the database. + Table = "reviews" +) + +// Columns holds all SQL columns for reviews fields. +var Columns = []string{ + FieldID, + FieldOrderID, + FieldFromUserID, + FieldFromUserName, + FieldFromUserAvatar, + FieldToUserID, + FieldRating, + FieldContent, + FieldSealed, + FieldCreatedAt, + FieldUnsealedAt, +} + +// 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 ( + // FromUserNameValidator is a validator for the "from_user_name" field. It is called by the builders before save. + FromUserNameValidator func(string) error + // DefaultFromUserAvatar holds the default value on creation for the "from_user_avatar" field. + DefaultFromUserAvatar string + // DefaultContent holds the default value on creation for the "content" field. + DefaultContent string + // DefaultSealed holds the default value on creation for the "sealed" field. + DefaultSealed bool + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Reviews 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() +} + +// ByFromUserID orders the results by the from_user_id field. +func ByFromUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFromUserID, opts...).ToFunc() +} + +// ByFromUserName orders the results by the from_user_name field. +func ByFromUserName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFromUserName, opts...).ToFunc() +} + +// ByFromUserAvatar orders the results by the from_user_avatar field. +func ByFromUserAvatar(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFromUserAvatar, opts...).ToFunc() +} + +// ByToUserID orders the results by the to_user_id field. +func ByToUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldToUserID, opts...).ToFunc() +} + +// ByRating orders the results by the rating field. +func ByRating(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRating, opts...).ToFunc() +} + +// ByContent orders the results by the content field. +func ByContent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContent, opts...).ToFunc() +} + +// BySealed orders the results by the sealed field. +func BySealed(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSealed, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUnsealedAt orders the results by the unsealed_at field. +func ByUnsealedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnsealedAt, opts...).ToFunc() +} diff --git a/app/review/rpc/internal/models/reviews/where.go b/app/review/rpc/internal/models/reviews/where.go new file mode 100644 index 0000000..8a35132 --- /dev/null +++ b/app/review/rpc/internal/models/reviews/where.go @@ -0,0 +1,595 @@ +// Code generated by ent, DO NOT EDIT. + +package reviews + +import ( + "juwan-backend/app/review/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldID, id)) +} + +// OrderID applies equality check predicate on the "order_id" field. It's identical to OrderIDEQ. +func OrderID(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldOrderID, v)) +} + +// FromUserID applies equality check predicate on the "from_user_id" field. It's identical to FromUserIDEQ. +func FromUserID(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldFromUserID, v)) +} + +// FromUserName applies equality check predicate on the "from_user_name" field. It's identical to FromUserNameEQ. +func FromUserName(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldFromUserName, v)) +} + +// FromUserAvatar applies equality check predicate on the "from_user_avatar" field. It's identical to FromUserAvatarEQ. +func FromUserAvatar(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldFromUserAvatar, v)) +} + +// ToUserID applies equality check predicate on the "to_user_id" field. It's identical to ToUserIDEQ. +func ToUserID(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldToUserID, v)) +} + +// Rating applies equality check predicate on the "rating" field. It's identical to RatingEQ. +func Rating(v int16) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldRating, v)) +} + +// Content applies equality check predicate on the "content" field. It's identical to ContentEQ. +func Content(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldContent, v)) +} + +// Sealed applies equality check predicate on the "sealed" field. It's identical to SealedEQ. +func Sealed(v bool) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldSealed, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UnsealedAt applies equality check predicate on the "unsealed_at" field. It's identical to UnsealedAtEQ. +func UnsealedAt(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldUnsealedAt, v)) +} + +// OrderIDEQ applies the EQ predicate on the "order_id" field. +func OrderIDEQ(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldOrderID, v)) +} + +// OrderIDNEQ applies the NEQ predicate on the "order_id" field. +func OrderIDNEQ(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldOrderID, v)) +} + +// OrderIDIn applies the In predicate on the "order_id" field. +func OrderIDIn(vs ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldOrderID, vs...)) +} + +// OrderIDNotIn applies the NotIn predicate on the "order_id" field. +func OrderIDNotIn(vs ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldOrderID, vs...)) +} + +// OrderIDGT applies the GT predicate on the "order_id" field. +func OrderIDGT(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldOrderID, v)) +} + +// OrderIDGTE applies the GTE predicate on the "order_id" field. +func OrderIDGTE(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldOrderID, v)) +} + +// OrderIDLT applies the LT predicate on the "order_id" field. +func OrderIDLT(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldOrderID, v)) +} + +// OrderIDLTE applies the LTE predicate on the "order_id" field. +func OrderIDLTE(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldOrderID, v)) +} + +// FromUserIDEQ applies the EQ predicate on the "from_user_id" field. +func FromUserIDEQ(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldFromUserID, v)) +} + +// FromUserIDNEQ applies the NEQ predicate on the "from_user_id" field. +func FromUserIDNEQ(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldFromUserID, v)) +} + +// FromUserIDIn applies the In predicate on the "from_user_id" field. +func FromUserIDIn(vs ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldFromUserID, vs...)) +} + +// FromUserIDNotIn applies the NotIn predicate on the "from_user_id" field. +func FromUserIDNotIn(vs ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldFromUserID, vs...)) +} + +// FromUserIDGT applies the GT predicate on the "from_user_id" field. +func FromUserIDGT(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldFromUserID, v)) +} + +// FromUserIDGTE applies the GTE predicate on the "from_user_id" field. +func FromUserIDGTE(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldFromUserID, v)) +} + +// FromUserIDLT applies the LT predicate on the "from_user_id" field. +func FromUserIDLT(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldFromUserID, v)) +} + +// FromUserIDLTE applies the LTE predicate on the "from_user_id" field. +func FromUserIDLTE(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldFromUserID, v)) +} + +// FromUserNameEQ applies the EQ predicate on the "from_user_name" field. +func FromUserNameEQ(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldFromUserName, v)) +} + +// FromUserNameNEQ applies the NEQ predicate on the "from_user_name" field. +func FromUserNameNEQ(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldFromUserName, v)) +} + +// FromUserNameIn applies the In predicate on the "from_user_name" field. +func FromUserNameIn(vs ...string) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldFromUserName, vs...)) +} + +// FromUserNameNotIn applies the NotIn predicate on the "from_user_name" field. +func FromUserNameNotIn(vs ...string) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldFromUserName, vs...)) +} + +// FromUserNameGT applies the GT predicate on the "from_user_name" field. +func FromUserNameGT(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldFromUserName, v)) +} + +// FromUserNameGTE applies the GTE predicate on the "from_user_name" field. +func FromUserNameGTE(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldFromUserName, v)) +} + +// FromUserNameLT applies the LT predicate on the "from_user_name" field. +func FromUserNameLT(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldFromUserName, v)) +} + +// FromUserNameLTE applies the LTE predicate on the "from_user_name" field. +func FromUserNameLTE(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldFromUserName, v)) +} + +// FromUserNameContains applies the Contains predicate on the "from_user_name" field. +func FromUserNameContains(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldContains(FieldFromUserName, v)) +} + +// FromUserNameHasPrefix applies the HasPrefix predicate on the "from_user_name" field. +func FromUserNameHasPrefix(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldHasPrefix(FieldFromUserName, v)) +} + +// FromUserNameHasSuffix applies the HasSuffix predicate on the "from_user_name" field. +func FromUserNameHasSuffix(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldHasSuffix(FieldFromUserName, v)) +} + +// FromUserNameEqualFold applies the EqualFold predicate on the "from_user_name" field. +func FromUserNameEqualFold(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEqualFold(FieldFromUserName, v)) +} + +// FromUserNameContainsFold applies the ContainsFold predicate on the "from_user_name" field. +func FromUserNameContainsFold(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldContainsFold(FieldFromUserName, v)) +} + +// FromUserAvatarEQ applies the EQ predicate on the "from_user_avatar" field. +func FromUserAvatarEQ(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldFromUserAvatar, v)) +} + +// FromUserAvatarNEQ applies the NEQ predicate on the "from_user_avatar" field. +func FromUserAvatarNEQ(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldFromUserAvatar, v)) +} + +// FromUserAvatarIn applies the In predicate on the "from_user_avatar" field. +func FromUserAvatarIn(vs ...string) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldFromUserAvatar, vs...)) +} + +// FromUserAvatarNotIn applies the NotIn predicate on the "from_user_avatar" field. +func FromUserAvatarNotIn(vs ...string) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldFromUserAvatar, vs...)) +} + +// FromUserAvatarGT applies the GT predicate on the "from_user_avatar" field. +func FromUserAvatarGT(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldFromUserAvatar, v)) +} + +// FromUserAvatarGTE applies the GTE predicate on the "from_user_avatar" field. +func FromUserAvatarGTE(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldFromUserAvatar, v)) +} + +// FromUserAvatarLT applies the LT predicate on the "from_user_avatar" field. +func FromUserAvatarLT(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldFromUserAvatar, v)) +} + +// FromUserAvatarLTE applies the LTE predicate on the "from_user_avatar" field. +func FromUserAvatarLTE(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldFromUserAvatar, v)) +} + +// FromUserAvatarContains applies the Contains predicate on the "from_user_avatar" field. +func FromUserAvatarContains(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldContains(FieldFromUserAvatar, v)) +} + +// FromUserAvatarHasPrefix applies the HasPrefix predicate on the "from_user_avatar" field. +func FromUserAvatarHasPrefix(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldHasPrefix(FieldFromUserAvatar, v)) +} + +// FromUserAvatarHasSuffix applies the HasSuffix predicate on the "from_user_avatar" field. +func FromUserAvatarHasSuffix(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldHasSuffix(FieldFromUserAvatar, v)) +} + +// FromUserAvatarIsNil applies the IsNil predicate on the "from_user_avatar" field. +func FromUserAvatarIsNil() predicate.Reviews { + return predicate.Reviews(sql.FieldIsNull(FieldFromUserAvatar)) +} + +// FromUserAvatarNotNil applies the NotNil predicate on the "from_user_avatar" field. +func FromUserAvatarNotNil() predicate.Reviews { + return predicate.Reviews(sql.FieldNotNull(FieldFromUserAvatar)) +} + +// FromUserAvatarEqualFold applies the EqualFold predicate on the "from_user_avatar" field. +func FromUserAvatarEqualFold(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEqualFold(FieldFromUserAvatar, v)) +} + +// FromUserAvatarContainsFold applies the ContainsFold predicate on the "from_user_avatar" field. +func FromUserAvatarContainsFold(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldContainsFold(FieldFromUserAvatar, v)) +} + +// ToUserIDEQ applies the EQ predicate on the "to_user_id" field. +func ToUserIDEQ(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldToUserID, v)) +} + +// ToUserIDNEQ applies the NEQ predicate on the "to_user_id" field. +func ToUserIDNEQ(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldToUserID, v)) +} + +// ToUserIDIn applies the In predicate on the "to_user_id" field. +func ToUserIDIn(vs ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldToUserID, vs...)) +} + +// ToUserIDNotIn applies the NotIn predicate on the "to_user_id" field. +func ToUserIDNotIn(vs ...int64) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldToUserID, vs...)) +} + +// ToUserIDGT applies the GT predicate on the "to_user_id" field. +func ToUserIDGT(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldToUserID, v)) +} + +// ToUserIDGTE applies the GTE predicate on the "to_user_id" field. +func ToUserIDGTE(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldToUserID, v)) +} + +// ToUserIDLT applies the LT predicate on the "to_user_id" field. +func ToUserIDLT(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldToUserID, v)) +} + +// ToUserIDLTE applies the LTE predicate on the "to_user_id" field. +func ToUserIDLTE(v int64) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldToUserID, v)) +} + +// RatingEQ applies the EQ predicate on the "rating" field. +func RatingEQ(v int16) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldRating, v)) +} + +// RatingNEQ applies the NEQ predicate on the "rating" field. +func RatingNEQ(v int16) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldRating, v)) +} + +// RatingIn applies the In predicate on the "rating" field. +func RatingIn(vs ...int16) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldRating, vs...)) +} + +// RatingNotIn applies the NotIn predicate on the "rating" field. +func RatingNotIn(vs ...int16) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldRating, vs...)) +} + +// RatingGT applies the GT predicate on the "rating" field. +func RatingGT(v int16) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldRating, v)) +} + +// RatingGTE applies the GTE predicate on the "rating" field. +func RatingGTE(v int16) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldRating, v)) +} + +// RatingLT applies the LT predicate on the "rating" field. +func RatingLT(v int16) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldRating, v)) +} + +// RatingLTE applies the LTE predicate on the "rating" field. +func RatingLTE(v int16) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldRating, v)) +} + +// ContentEQ applies the EQ predicate on the "content" field. +func ContentEQ(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldContent, v)) +} + +// ContentNEQ applies the NEQ predicate on the "content" field. +func ContentNEQ(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldContent, v)) +} + +// ContentIn applies the In predicate on the "content" field. +func ContentIn(vs ...string) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldContent, vs...)) +} + +// ContentNotIn applies the NotIn predicate on the "content" field. +func ContentNotIn(vs ...string) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldContent, vs...)) +} + +// ContentGT applies the GT predicate on the "content" field. +func ContentGT(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldContent, v)) +} + +// ContentGTE applies the GTE predicate on the "content" field. +func ContentGTE(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldContent, v)) +} + +// ContentLT applies the LT predicate on the "content" field. +func ContentLT(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldContent, v)) +} + +// ContentLTE applies the LTE predicate on the "content" field. +func ContentLTE(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldContent, v)) +} + +// ContentContains applies the Contains predicate on the "content" field. +func ContentContains(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldContains(FieldContent, v)) +} + +// ContentHasPrefix applies the HasPrefix predicate on the "content" field. +func ContentHasPrefix(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldHasPrefix(FieldContent, v)) +} + +// ContentHasSuffix applies the HasSuffix predicate on the "content" field. +func ContentHasSuffix(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldHasSuffix(FieldContent, v)) +} + +// ContentIsNil applies the IsNil predicate on the "content" field. +func ContentIsNil() predicate.Reviews { + return predicate.Reviews(sql.FieldIsNull(FieldContent)) +} + +// ContentNotNil applies the NotNil predicate on the "content" field. +func ContentNotNil() predicate.Reviews { + return predicate.Reviews(sql.FieldNotNull(FieldContent)) +} + +// ContentEqualFold applies the EqualFold predicate on the "content" field. +func ContentEqualFold(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldEqualFold(FieldContent, v)) +} + +// ContentContainsFold applies the ContainsFold predicate on the "content" field. +func ContentContainsFold(v string) predicate.Reviews { + return predicate.Reviews(sql.FieldContainsFold(FieldContent, v)) +} + +// SealedEQ applies the EQ predicate on the "sealed" field. +func SealedEQ(v bool) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldSealed, v)) +} + +// SealedNEQ applies the NEQ predicate on the "sealed" field. +func SealedNEQ(v bool) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldSealed, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UnsealedAtEQ applies the EQ predicate on the "unsealed_at" field. +func UnsealedAtEQ(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldEQ(FieldUnsealedAt, v)) +} + +// UnsealedAtNEQ applies the NEQ predicate on the "unsealed_at" field. +func UnsealedAtNEQ(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldNEQ(FieldUnsealedAt, v)) +} + +// UnsealedAtIn applies the In predicate on the "unsealed_at" field. +func UnsealedAtIn(vs ...time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldIn(FieldUnsealedAt, vs...)) +} + +// UnsealedAtNotIn applies the NotIn predicate on the "unsealed_at" field. +func UnsealedAtNotIn(vs ...time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldNotIn(FieldUnsealedAt, vs...)) +} + +// UnsealedAtGT applies the GT predicate on the "unsealed_at" field. +func UnsealedAtGT(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldGT(FieldUnsealedAt, v)) +} + +// UnsealedAtGTE applies the GTE predicate on the "unsealed_at" field. +func UnsealedAtGTE(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldGTE(FieldUnsealedAt, v)) +} + +// UnsealedAtLT applies the LT predicate on the "unsealed_at" field. +func UnsealedAtLT(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldLT(FieldUnsealedAt, v)) +} + +// UnsealedAtLTE applies the LTE predicate on the "unsealed_at" field. +func UnsealedAtLTE(v time.Time) predicate.Reviews { + return predicate.Reviews(sql.FieldLTE(FieldUnsealedAt, v)) +} + +// UnsealedAtIsNil applies the IsNil predicate on the "unsealed_at" field. +func UnsealedAtIsNil() predicate.Reviews { + return predicate.Reviews(sql.FieldIsNull(FieldUnsealedAt)) +} + +// UnsealedAtNotNil applies the NotNil predicate on the "unsealed_at" field. +func UnsealedAtNotNil() predicate.Reviews { + return predicate.Reviews(sql.FieldNotNull(FieldUnsealedAt)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Reviews) predicate.Reviews { + return predicate.Reviews(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Reviews) predicate.Reviews { + return predicate.Reviews(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Reviews) predicate.Reviews { + return predicate.Reviews(sql.NotPredicates(p)) +} diff --git a/app/review/rpc/internal/models/reviews_create.go b/app/review/rpc/internal/models/reviews_create.go new file mode 100644 index 0000000..a29686d --- /dev/null +++ b/app/review/rpc/internal/models/reviews_create.go @@ -0,0 +1,371 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/review/rpc/internal/models/reviews" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ReviewsCreate is the builder for creating a Reviews entity. +type ReviewsCreate struct { + config + mutation *ReviewsMutation + hooks []Hook +} + +// SetOrderID sets the "order_id" field. +func (_c *ReviewsCreate) SetOrderID(v int64) *ReviewsCreate { + _c.mutation.SetOrderID(v) + return _c +} + +// SetFromUserID sets the "from_user_id" field. +func (_c *ReviewsCreate) SetFromUserID(v int64) *ReviewsCreate { + _c.mutation.SetFromUserID(v) + return _c +} + +// SetFromUserName sets the "from_user_name" field. +func (_c *ReviewsCreate) SetFromUserName(v string) *ReviewsCreate { + _c.mutation.SetFromUserName(v) + return _c +} + +// SetFromUserAvatar sets the "from_user_avatar" field. +func (_c *ReviewsCreate) SetFromUserAvatar(v string) *ReviewsCreate { + _c.mutation.SetFromUserAvatar(v) + return _c +} + +// SetNillableFromUserAvatar sets the "from_user_avatar" field if the given value is not nil. +func (_c *ReviewsCreate) SetNillableFromUserAvatar(v *string) *ReviewsCreate { + if v != nil { + _c.SetFromUserAvatar(*v) + } + return _c +} + +// SetToUserID sets the "to_user_id" field. +func (_c *ReviewsCreate) SetToUserID(v int64) *ReviewsCreate { + _c.mutation.SetToUserID(v) + return _c +} + +// SetRating sets the "rating" field. +func (_c *ReviewsCreate) SetRating(v int16) *ReviewsCreate { + _c.mutation.SetRating(v) + return _c +} + +// SetContent sets the "content" field. +func (_c *ReviewsCreate) SetContent(v string) *ReviewsCreate { + _c.mutation.SetContent(v) + return _c +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_c *ReviewsCreate) SetNillableContent(v *string) *ReviewsCreate { + if v != nil { + _c.SetContent(*v) + } + return _c +} + +// SetSealed sets the "sealed" field. +func (_c *ReviewsCreate) SetSealed(v bool) *ReviewsCreate { + _c.mutation.SetSealed(v) + return _c +} + +// SetNillableSealed sets the "sealed" field if the given value is not nil. +func (_c *ReviewsCreate) SetNillableSealed(v *bool) *ReviewsCreate { + if v != nil { + _c.SetSealed(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ReviewsCreate) SetCreatedAt(v time.Time) *ReviewsCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *ReviewsCreate) SetNillableCreatedAt(v *time.Time) *ReviewsCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUnsealedAt sets the "unsealed_at" field. +func (_c *ReviewsCreate) SetUnsealedAt(v time.Time) *ReviewsCreate { + _c.mutation.SetUnsealedAt(v) + return _c +} + +// SetNillableUnsealedAt sets the "unsealed_at" field if the given value is not nil. +func (_c *ReviewsCreate) SetNillableUnsealedAt(v *time.Time) *ReviewsCreate { + if v != nil { + _c.SetUnsealedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *ReviewsCreate) SetID(v int64) *ReviewsCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the ReviewsMutation object of the builder. +func (_c *ReviewsCreate) Mutation() *ReviewsMutation { + return _c.mutation +} + +// Save creates the Reviews in the database. +func (_c *ReviewsCreate) Save(ctx context.Context) (*Reviews, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ReviewsCreate) SaveX(ctx context.Context) *Reviews { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ReviewsCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ReviewsCreate) 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 *ReviewsCreate) defaults() { + if _, ok := _c.mutation.FromUserAvatar(); !ok { + v := reviews.DefaultFromUserAvatar + _c.mutation.SetFromUserAvatar(v) + } + if _, ok := _c.mutation.Content(); !ok { + v := reviews.DefaultContent + _c.mutation.SetContent(v) + } + if _, ok := _c.mutation.Sealed(); !ok { + v := reviews.DefaultSealed + _c.mutation.SetSealed(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + v := reviews.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ReviewsCreate) check() error { + if _, ok := _c.mutation.OrderID(); !ok { + return &ValidationError{Name: "order_id", err: errors.New(`models: missing required field "Reviews.order_id"`)} + } + if _, ok := _c.mutation.FromUserID(); !ok { + return &ValidationError{Name: "from_user_id", err: errors.New(`models: missing required field "Reviews.from_user_id"`)} + } + if _, ok := _c.mutation.FromUserName(); !ok { + return &ValidationError{Name: "from_user_name", err: errors.New(`models: missing required field "Reviews.from_user_name"`)} + } + if v, ok := _c.mutation.FromUserName(); ok { + if err := reviews.FromUserNameValidator(v); err != nil { + return &ValidationError{Name: "from_user_name", err: fmt.Errorf(`models: validator failed for field "Reviews.from_user_name": %w`, err)} + } + } + if _, ok := _c.mutation.ToUserID(); !ok { + return &ValidationError{Name: "to_user_id", err: errors.New(`models: missing required field "Reviews.to_user_id"`)} + } + if _, ok := _c.mutation.Rating(); !ok { + return &ValidationError{Name: "rating", err: errors.New(`models: missing required field "Reviews.rating"`)} + } + if _, ok := _c.mutation.Sealed(); !ok { + return &ValidationError{Name: "sealed", err: errors.New(`models: missing required field "Reviews.sealed"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Reviews.created_at"`)} + } + return nil +} + +func (_c *ReviewsCreate) sqlSave(ctx context.Context) (*Reviews, 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 *ReviewsCreate) createSpec() (*Reviews, *sqlgraph.CreateSpec) { + var ( + _node = &Reviews{config: _c.config} + _spec = sqlgraph.NewCreateSpec(reviews.Table, sqlgraph.NewFieldSpec(reviews.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(reviews.FieldOrderID, field.TypeInt64, value) + _node.OrderID = value + } + if value, ok := _c.mutation.FromUserID(); ok { + _spec.SetField(reviews.FieldFromUserID, field.TypeInt64, value) + _node.FromUserID = value + } + if value, ok := _c.mutation.FromUserName(); ok { + _spec.SetField(reviews.FieldFromUserName, field.TypeString, value) + _node.FromUserName = value + } + if value, ok := _c.mutation.FromUserAvatar(); ok { + _spec.SetField(reviews.FieldFromUserAvatar, field.TypeString, value) + _node.FromUserAvatar = value + } + if value, ok := _c.mutation.ToUserID(); ok { + _spec.SetField(reviews.FieldToUserID, field.TypeInt64, value) + _node.ToUserID = value + } + if value, ok := _c.mutation.Rating(); ok { + _spec.SetField(reviews.FieldRating, field.TypeInt16, value) + _node.Rating = value + } + if value, ok := _c.mutation.Content(); ok { + _spec.SetField(reviews.FieldContent, field.TypeString, value) + _node.Content = value + } + if value, ok := _c.mutation.Sealed(); ok { + _spec.SetField(reviews.FieldSealed, field.TypeBool, value) + _node.Sealed = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(reviews.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UnsealedAt(); ok { + _spec.SetField(reviews.FieldUnsealedAt, field.TypeTime, value) + _node.UnsealedAt = &value + } + return _node, _spec +} + +// ReviewsCreateBulk is the builder for creating many Reviews entities in bulk. +type ReviewsCreateBulk struct { + config + err error + builders []*ReviewsCreate +} + +// Save creates the Reviews entities in the database. +func (_c *ReviewsCreateBulk) Save(ctx context.Context) ([]*Reviews, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Reviews, 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.(*ReviewsMutation) + 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 *ReviewsCreateBulk) SaveX(ctx context.Context) []*Reviews { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ReviewsCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ReviewsCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/review/rpc/internal/models/reviews_delete.go b/app/review/rpc/internal/models/reviews_delete.go new file mode 100644 index 0000000..00296d7 --- /dev/null +++ b/app/review/rpc/internal/models/reviews_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/review/rpc/internal/models/predicate" + "juwan-backend/app/review/rpc/internal/models/reviews" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ReviewsDelete is the builder for deleting a Reviews entity. +type ReviewsDelete struct { + config + hooks []Hook + mutation *ReviewsMutation +} + +// Where appends a list predicates to the ReviewsDelete builder. +func (_d *ReviewsDelete) Where(ps ...predicate.Reviews) *ReviewsDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ReviewsDelete) 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 *ReviewsDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ReviewsDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(reviews.Table, sqlgraph.NewFieldSpec(reviews.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 +} + +// ReviewsDeleteOne is the builder for deleting a single Reviews entity. +type ReviewsDeleteOne struct { + _d *ReviewsDelete +} + +// Where appends a list predicates to the ReviewsDelete builder. +func (_d *ReviewsDeleteOne) Where(ps ...predicate.Reviews) *ReviewsDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ReviewsDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{reviews.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ReviewsDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/review/rpc/internal/models/reviews_query.go b/app/review/rpc/internal/models/reviews_query.go new file mode 100644 index 0000000..cc83961 --- /dev/null +++ b/app/review/rpc/internal/models/reviews_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/review/rpc/internal/models/predicate" + "juwan-backend/app/review/rpc/internal/models/reviews" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ReviewsQuery is the builder for querying Reviews entities. +type ReviewsQuery struct { + config + ctx *QueryContext + order []reviews.OrderOption + inters []Interceptor + predicates []predicate.Reviews + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ReviewsQuery builder. +func (_q *ReviewsQuery) Where(ps ...predicate.Reviews) *ReviewsQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ReviewsQuery) Limit(limit int) *ReviewsQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ReviewsQuery) Offset(offset int) *ReviewsQuery { + _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 *ReviewsQuery) Unique(unique bool) *ReviewsQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ReviewsQuery) Order(o ...reviews.OrderOption) *ReviewsQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Reviews entity from the query. +// Returns a *NotFoundError when no Reviews was found. +func (_q *ReviewsQuery) First(ctx context.Context) (*Reviews, 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{reviews.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ReviewsQuery) FirstX(ctx context.Context) *Reviews { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Reviews ID from the query. +// Returns a *NotFoundError when no Reviews ID was found. +func (_q *ReviewsQuery) 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{reviews.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ReviewsQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Reviews entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Reviews entity is found. +// Returns a *NotFoundError when no Reviews entities are found. +func (_q *ReviewsQuery) Only(ctx context.Context) (*Reviews, 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{reviews.Label} + default: + return nil, &NotSingularError{reviews.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ReviewsQuery) OnlyX(ctx context.Context) *Reviews { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Reviews ID in the query. +// Returns a *NotSingularError when more than one Reviews ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ReviewsQuery) 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{reviews.Label} + default: + err = &NotSingularError{reviews.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ReviewsQuery) 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 ReviewsSlice. +func (_q *ReviewsQuery) All(ctx context.Context) ([]*Reviews, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Reviews, *ReviewsQuery]() + return withInterceptors[[]*Reviews](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ReviewsQuery) AllX(ctx context.Context) []*Reviews { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Reviews IDs. +func (_q *ReviewsQuery) 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(reviews.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ReviewsQuery) 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 *ReviewsQuery) 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[*ReviewsQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ReviewsQuery) 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 *ReviewsQuery) 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 *ReviewsQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ReviewsQuery 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 *ReviewsQuery) Clone() *ReviewsQuery { + if _q == nil { + return nil + } + return &ReviewsQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]reviews.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Reviews{}, _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.Reviews.Query(). +// GroupBy(reviews.FieldOrderID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *ReviewsQuery) GroupBy(field string, fields ...string) *ReviewsGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ReviewsGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = reviews.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.Reviews.Query(). +// Select(reviews.FieldOrderID). +// Scan(ctx, &v) +func (_q *ReviewsQuery) Select(fields ...string) *ReviewsSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ReviewsSelect{ReviewsQuery: _q} + sbuild.label = reviews.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ReviewsSelect configured with the given aggregations. +func (_q *ReviewsQuery) Aggregate(fns ...AggregateFunc) *ReviewsSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ReviewsQuery) 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 !reviews.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 *ReviewsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Reviews, error) { + var ( + nodes = []*Reviews{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Reviews).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Reviews{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 *ReviewsQuery) 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 *ReviewsQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(reviews.Table, reviews.Columns, sqlgraph.NewFieldSpec(reviews.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, reviews.FieldID) + for i := range fields { + if fields[i] != reviews.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 *ReviewsQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(reviews.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = reviews.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 +} + +// ReviewsGroupBy is the group-by builder for Reviews entities. +type ReviewsGroupBy struct { + selector + build *ReviewsQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ReviewsGroupBy) Aggregate(fns ...AggregateFunc) *ReviewsGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ReviewsGroupBy) 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[*ReviewsQuery, *ReviewsGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ReviewsGroupBy) sqlScan(ctx context.Context, root *ReviewsQuery, 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) +} + +// ReviewsSelect is the builder for selecting fields of Reviews entities. +type ReviewsSelect struct { + *ReviewsQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ReviewsSelect) Aggregate(fns ...AggregateFunc) *ReviewsSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ReviewsSelect) 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[*ReviewsQuery, *ReviewsSelect](ctx, _s.ReviewsQuery, _s, _s.inters, v) +} + +func (_s *ReviewsSelect) sqlScan(ctx context.Context, root *ReviewsQuery, 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/review/rpc/internal/models/reviews_update.go b/app/review/rpc/internal/models/reviews_update.go new file mode 100644 index 0000000..dc90009 --- /dev/null +++ b/app/review/rpc/internal/models/reviews_update.go @@ -0,0 +1,642 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/review/rpc/internal/models/predicate" + "juwan-backend/app/review/rpc/internal/models/reviews" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ReviewsUpdate is the builder for updating Reviews entities. +type ReviewsUpdate struct { + config + hooks []Hook + mutation *ReviewsMutation +} + +// Where appends a list predicates to the ReviewsUpdate builder. +func (_u *ReviewsUpdate) Where(ps ...predicate.Reviews) *ReviewsUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetOrderID sets the "order_id" field. +func (_u *ReviewsUpdate) SetOrderID(v int64) *ReviewsUpdate { + _u.mutation.ResetOrderID() + _u.mutation.SetOrderID(v) + return _u +} + +// SetNillableOrderID sets the "order_id" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableOrderID(v *int64) *ReviewsUpdate { + if v != nil { + _u.SetOrderID(*v) + } + return _u +} + +// AddOrderID adds value to the "order_id" field. +func (_u *ReviewsUpdate) AddOrderID(v int64) *ReviewsUpdate { + _u.mutation.AddOrderID(v) + return _u +} + +// SetFromUserID sets the "from_user_id" field. +func (_u *ReviewsUpdate) SetFromUserID(v int64) *ReviewsUpdate { + _u.mutation.ResetFromUserID() + _u.mutation.SetFromUserID(v) + return _u +} + +// SetNillableFromUserID sets the "from_user_id" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableFromUserID(v *int64) *ReviewsUpdate { + if v != nil { + _u.SetFromUserID(*v) + } + return _u +} + +// AddFromUserID adds value to the "from_user_id" field. +func (_u *ReviewsUpdate) AddFromUserID(v int64) *ReviewsUpdate { + _u.mutation.AddFromUserID(v) + return _u +} + +// SetFromUserName sets the "from_user_name" field. +func (_u *ReviewsUpdate) SetFromUserName(v string) *ReviewsUpdate { + _u.mutation.SetFromUserName(v) + return _u +} + +// SetNillableFromUserName sets the "from_user_name" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableFromUserName(v *string) *ReviewsUpdate { + if v != nil { + _u.SetFromUserName(*v) + } + return _u +} + +// SetFromUserAvatar sets the "from_user_avatar" field. +func (_u *ReviewsUpdate) SetFromUserAvatar(v string) *ReviewsUpdate { + _u.mutation.SetFromUserAvatar(v) + return _u +} + +// SetNillableFromUserAvatar sets the "from_user_avatar" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableFromUserAvatar(v *string) *ReviewsUpdate { + if v != nil { + _u.SetFromUserAvatar(*v) + } + return _u +} + +// ClearFromUserAvatar clears the value of the "from_user_avatar" field. +func (_u *ReviewsUpdate) ClearFromUserAvatar() *ReviewsUpdate { + _u.mutation.ClearFromUserAvatar() + return _u +} + +// SetToUserID sets the "to_user_id" field. +func (_u *ReviewsUpdate) SetToUserID(v int64) *ReviewsUpdate { + _u.mutation.ResetToUserID() + _u.mutation.SetToUserID(v) + return _u +} + +// SetNillableToUserID sets the "to_user_id" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableToUserID(v *int64) *ReviewsUpdate { + if v != nil { + _u.SetToUserID(*v) + } + return _u +} + +// AddToUserID adds value to the "to_user_id" field. +func (_u *ReviewsUpdate) AddToUserID(v int64) *ReviewsUpdate { + _u.mutation.AddToUserID(v) + return _u +} + +// SetRating sets the "rating" field. +func (_u *ReviewsUpdate) SetRating(v int16) *ReviewsUpdate { + _u.mutation.ResetRating() + _u.mutation.SetRating(v) + return _u +} + +// SetNillableRating sets the "rating" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableRating(v *int16) *ReviewsUpdate { + if v != nil { + _u.SetRating(*v) + } + return _u +} + +// AddRating adds value to the "rating" field. +func (_u *ReviewsUpdate) AddRating(v int16) *ReviewsUpdate { + _u.mutation.AddRating(v) + return _u +} + +// SetContent sets the "content" field. +func (_u *ReviewsUpdate) SetContent(v string) *ReviewsUpdate { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableContent(v *string) *ReviewsUpdate { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// ClearContent clears the value of the "content" field. +func (_u *ReviewsUpdate) ClearContent() *ReviewsUpdate { + _u.mutation.ClearContent() + return _u +} + +// SetSealed sets the "sealed" field. +func (_u *ReviewsUpdate) SetSealed(v bool) *ReviewsUpdate { + _u.mutation.SetSealed(v) + return _u +} + +// SetNillableSealed sets the "sealed" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableSealed(v *bool) *ReviewsUpdate { + if v != nil { + _u.SetSealed(*v) + } + return _u +} + +// SetUnsealedAt sets the "unsealed_at" field. +func (_u *ReviewsUpdate) SetUnsealedAt(v time.Time) *ReviewsUpdate { + _u.mutation.SetUnsealedAt(v) + return _u +} + +// SetNillableUnsealedAt sets the "unsealed_at" field if the given value is not nil. +func (_u *ReviewsUpdate) SetNillableUnsealedAt(v *time.Time) *ReviewsUpdate { + if v != nil { + _u.SetUnsealedAt(*v) + } + return _u +} + +// ClearUnsealedAt clears the value of the "unsealed_at" field. +func (_u *ReviewsUpdate) ClearUnsealedAt() *ReviewsUpdate { + _u.mutation.ClearUnsealedAt() + return _u +} + +// Mutation returns the ReviewsMutation object of the builder. +func (_u *ReviewsUpdate) Mutation() *ReviewsMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ReviewsUpdate) 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 *ReviewsUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ReviewsUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ReviewsUpdate) 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 *ReviewsUpdate) check() error { + if v, ok := _u.mutation.FromUserName(); ok { + if err := reviews.FromUserNameValidator(v); err != nil { + return &ValidationError{Name: "from_user_name", err: fmt.Errorf(`models: validator failed for field "Reviews.from_user_name": %w`, err)} + } + } + return nil +} + +func (_u *ReviewsUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(reviews.Table, reviews.Columns, sqlgraph.NewFieldSpec(reviews.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(reviews.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedOrderID(); ok { + _spec.AddField(reviews.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.FromUserID(); ok { + _spec.SetField(reviews.FieldFromUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedFromUserID(); ok { + _spec.AddField(reviews.FieldFromUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.FromUserName(); ok { + _spec.SetField(reviews.FieldFromUserName, field.TypeString, value) + } + if value, ok := _u.mutation.FromUserAvatar(); ok { + _spec.SetField(reviews.FieldFromUserAvatar, field.TypeString, value) + } + if _u.mutation.FromUserAvatarCleared() { + _spec.ClearField(reviews.FieldFromUserAvatar, field.TypeString) + } + if value, ok := _u.mutation.ToUserID(); ok { + _spec.SetField(reviews.FieldToUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedToUserID(); ok { + _spec.AddField(reviews.FieldToUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Rating(); ok { + _spec.SetField(reviews.FieldRating, field.TypeInt16, value) + } + if value, ok := _u.mutation.AddedRating(); ok { + _spec.AddField(reviews.FieldRating, field.TypeInt16, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(reviews.FieldContent, field.TypeString, value) + } + if _u.mutation.ContentCleared() { + _spec.ClearField(reviews.FieldContent, field.TypeString) + } + if value, ok := _u.mutation.Sealed(); ok { + _spec.SetField(reviews.FieldSealed, field.TypeBool, value) + } + if value, ok := _u.mutation.UnsealedAt(); ok { + _spec.SetField(reviews.FieldUnsealedAt, field.TypeTime, value) + } + if _u.mutation.UnsealedAtCleared() { + _spec.ClearField(reviews.FieldUnsealedAt, field.TypeTime) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{reviews.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ReviewsUpdateOne is the builder for updating a single Reviews entity. +type ReviewsUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ReviewsMutation +} + +// SetOrderID sets the "order_id" field. +func (_u *ReviewsUpdateOne) SetOrderID(v int64) *ReviewsUpdateOne { + _u.mutation.ResetOrderID() + _u.mutation.SetOrderID(v) + return _u +} + +// SetNillableOrderID sets the "order_id" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableOrderID(v *int64) *ReviewsUpdateOne { + if v != nil { + _u.SetOrderID(*v) + } + return _u +} + +// AddOrderID adds value to the "order_id" field. +func (_u *ReviewsUpdateOne) AddOrderID(v int64) *ReviewsUpdateOne { + _u.mutation.AddOrderID(v) + return _u +} + +// SetFromUserID sets the "from_user_id" field. +func (_u *ReviewsUpdateOne) SetFromUserID(v int64) *ReviewsUpdateOne { + _u.mutation.ResetFromUserID() + _u.mutation.SetFromUserID(v) + return _u +} + +// SetNillableFromUserID sets the "from_user_id" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableFromUserID(v *int64) *ReviewsUpdateOne { + if v != nil { + _u.SetFromUserID(*v) + } + return _u +} + +// AddFromUserID adds value to the "from_user_id" field. +func (_u *ReviewsUpdateOne) AddFromUserID(v int64) *ReviewsUpdateOne { + _u.mutation.AddFromUserID(v) + return _u +} + +// SetFromUserName sets the "from_user_name" field. +func (_u *ReviewsUpdateOne) SetFromUserName(v string) *ReviewsUpdateOne { + _u.mutation.SetFromUserName(v) + return _u +} + +// SetNillableFromUserName sets the "from_user_name" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableFromUserName(v *string) *ReviewsUpdateOne { + if v != nil { + _u.SetFromUserName(*v) + } + return _u +} + +// SetFromUserAvatar sets the "from_user_avatar" field. +func (_u *ReviewsUpdateOne) SetFromUserAvatar(v string) *ReviewsUpdateOne { + _u.mutation.SetFromUserAvatar(v) + return _u +} + +// SetNillableFromUserAvatar sets the "from_user_avatar" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableFromUserAvatar(v *string) *ReviewsUpdateOne { + if v != nil { + _u.SetFromUserAvatar(*v) + } + return _u +} + +// ClearFromUserAvatar clears the value of the "from_user_avatar" field. +func (_u *ReviewsUpdateOne) ClearFromUserAvatar() *ReviewsUpdateOne { + _u.mutation.ClearFromUserAvatar() + return _u +} + +// SetToUserID sets the "to_user_id" field. +func (_u *ReviewsUpdateOne) SetToUserID(v int64) *ReviewsUpdateOne { + _u.mutation.ResetToUserID() + _u.mutation.SetToUserID(v) + return _u +} + +// SetNillableToUserID sets the "to_user_id" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableToUserID(v *int64) *ReviewsUpdateOne { + if v != nil { + _u.SetToUserID(*v) + } + return _u +} + +// AddToUserID adds value to the "to_user_id" field. +func (_u *ReviewsUpdateOne) AddToUserID(v int64) *ReviewsUpdateOne { + _u.mutation.AddToUserID(v) + return _u +} + +// SetRating sets the "rating" field. +func (_u *ReviewsUpdateOne) SetRating(v int16) *ReviewsUpdateOne { + _u.mutation.ResetRating() + _u.mutation.SetRating(v) + return _u +} + +// SetNillableRating sets the "rating" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableRating(v *int16) *ReviewsUpdateOne { + if v != nil { + _u.SetRating(*v) + } + return _u +} + +// AddRating adds value to the "rating" field. +func (_u *ReviewsUpdateOne) AddRating(v int16) *ReviewsUpdateOne { + _u.mutation.AddRating(v) + return _u +} + +// SetContent sets the "content" field. +func (_u *ReviewsUpdateOne) SetContent(v string) *ReviewsUpdateOne { + _u.mutation.SetContent(v) + return _u +} + +// SetNillableContent sets the "content" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableContent(v *string) *ReviewsUpdateOne { + if v != nil { + _u.SetContent(*v) + } + return _u +} + +// ClearContent clears the value of the "content" field. +func (_u *ReviewsUpdateOne) ClearContent() *ReviewsUpdateOne { + _u.mutation.ClearContent() + return _u +} + +// SetSealed sets the "sealed" field. +func (_u *ReviewsUpdateOne) SetSealed(v bool) *ReviewsUpdateOne { + _u.mutation.SetSealed(v) + return _u +} + +// SetNillableSealed sets the "sealed" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableSealed(v *bool) *ReviewsUpdateOne { + if v != nil { + _u.SetSealed(*v) + } + return _u +} + +// SetUnsealedAt sets the "unsealed_at" field. +func (_u *ReviewsUpdateOne) SetUnsealedAt(v time.Time) *ReviewsUpdateOne { + _u.mutation.SetUnsealedAt(v) + return _u +} + +// SetNillableUnsealedAt sets the "unsealed_at" field if the given value is not nil. +func (_u *ReviewsUpdateOne) SetNillableUnsealedAt(v *time.Time) *ReviewsUpdateOne { + if v != nil { + _u.SetUnsealedAt(*v) + } + return _u +} + +// ClearUnsealedAt clears the value of the "unsealed_at" field. +func (_u *ReviewsUpdateOne) ClearUnsealedAt() *ReviewsUpdateOne { + _u.mutation.ClearUnsealedAt() + return _u +} + +// Mutation returns the ReviewsMutation object of the builder. +func (_u *ReviewsUpdateOne) Mutation() *ReviewsMutation { + return _u.mutation +} + +// Where appends a list predicates to the ReviewsUpdate builder. +func (_u *ReviewsUpdateOne) Where(ps ...predicate.Reviews) *ReviewsUpdateOne { + _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 *ReviewsUpdateOne) Select(field string, fields ...string) *ReviewsUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Reviews entity. +func (_u *ReviewsUpdateOne) Save(ctx context.Context) (*Reviews, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ReviewsUpdateOne) SaveX(ctx context.Context) *Reviews { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ReviewsUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ReviewsUpdateOne) 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 *ReviewsUpdateOne) check() error { + if v, ok := _u.mutation.FromUserName(); ok { + if err := reviews.FromUserNameValidator(v); err != nil { + return &ValidationError{Name: "from_user_name", err: fmt.Errorf(`models: validator failed for field "Reviews.from_user_name": %w`, err)} + } + } + return nil +} + +func (_u *ReviewsUpdateOne) sqlSave(ctx context.Context) (_node *Reviews, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(reviews.Table, reviews.Columns, sqlgraph.NewFieldSpec(reviews.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Reviews.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, reviews.FieldID) + for _, f := range fields { + if !reviews.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != reviews.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(reviews.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedOrderID(); ok { + _spec.AddField(reviews.FieldOrderID, field.TypeInt64, value) + } + if value, ok := _u.mutation.FromUserID(); ok { + _spec.SetField(reviews.FieldFromUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedFromUserID(); ok { + _spec.AddField(reviews.FieldFromUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.FromUserName(); ok { + _spec.SetField(reviews.FieldFromUserName, field.TypeString, value) + } + if value, ok := _u.mutation.FromUserAvatar(); ok { + _spec.SetField(reviews.FieldFromUserAvatar, field.TypeString, value) + } + if _u.mutation.FromUserAvatarCleared() { + _spec.ClearField(reviews.FieldFromUserAvatar, field.TypeString) + } + if value, ok := _u.mutation.ToUserID(); ok { + _spec.SetField(reviews.FieldToUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedToUserID(); ok { + _spec.AddField(reviews.FieldToUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.Rating(); ok { + _spec.SetField(reviews.FieldRating, field.TypeInt16, value) + } + if value, ok := _u.mutation.AddedRating(); ok { + _spec.AddField(reviews.FieldRating, field.TypeInt16, value) + } + if value, ok := _u.mutation.Content(); ok { + _spec.SetField(reviews.FieldContent, field.TypeString, value) + } + if _u.mutation.ContentCleared() { + _spec.ClearField(reviews.FieldContent, field.TypeString) + } + if value, ok := _u.mutation.Sealed(); ok { + _spec.SetField(reviews.FieldSealed, field.TypeBool, value) + } + if value, ok := _u.mutation.UnsealedAt(); ok { + _spec.SetField(reviews.FieldUnsealedAt, field.TypeTime, value) + } + if _u.mutation.UnsealedAtCleared() { + _spec.ClearField(reviews.FieldUnsealedAt, field.TypeTime) + } + _node = &Reviews{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{reviews.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/review/rpc/internal/models/runtime.go b/app/review/rpc/internal/models/runtime.go new file mode 100644 index 0000000..f07944e --- /dev/null +++ b/app/review/rpc/internal/models/runtime.go @@ -0,0 +1,37 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/review/rpc/internal/models/reviews" + "juwan-backend/app/review/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() { + reviewsFields := schema.Reviews{}.Fields() + _ = reviewsFields + // reviewsDescFromUserName is the schema descriptor for from_user_name field. + reviewsDescFromUserName := reviewsFields[3].Descriptor() + // reviews.FromUserNameValidator is a validator for the "from_user_name" field. It is called by the builders before save. + reviews.FromUserNameValidator = reviewsDescFromUserName.Validators[0].(func(string) error) + // reviewsDescFromUserAvatar is the schema descriptor for from_user_avatar field. + reviewsDescFromUserAvatar := reviewsFields[4].Descriptor() + // reviews.DefaultFromUserAvatar holds the default value on creation for the from_user_avatar field. + reviews.DefaultFromUserAvatar = reviewsDescFromUserAvatar.Default.(string) + // reviewsDescContent is the schema descriptor for content field. + reviewsDescContent := reviewsFields[7].Descriptor() + // reviews.DefaultContent holds the default value on creation for the content field. + reviews.DefaultContent = reviewsDescContent.Default.(string) + // reviewsDescSealed is the schema descriptor for sealed field. + reviewsDescSealed := reviewsFields[8].Descriptor() + // reviews.DefaultSealed holds the default value on creation for the sealed field. + reviews.DefaultSealed = reviewsDescSealed.Default.(bool) + // reviewsDescCreatedAt is the schema descriptor for created_at field. + reviewsDescCreatedAt := reviewsFields[9].Descriptor() + // reviews.DefaultCreatedAt holds the default value on creation for the created_at field. + reviews.DefaultCreatedAt = reviewsDescCreatedAt.Default.(func() time.Time) +} diff --git a/app/review/rpc/internal/models/runtime/runtime.go b/app/review/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..2fb0a7e --- /dev/null +++ b/app/review/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/review/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/review/rpc/internal/models/schema/reviews.go b/app/review/rpc/internal/models/schema/reviews.go new file mode 100644 index 0000000..a3e0404 --- /dev/null +++ b/app/review/rpc/internal/models/schema/reviews.go @@ -0,0 +1,42 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type Reviews struct { + ent.Schema +} + +func (Reviews) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Unique().Immutable(), + field.Int64("order_id"), + field.Int64("from_user_id"), + field.String("from_user_name").MaxLen(100), + field.String("from_user_avatar").Optional().Default(""), + field.Int64("to_user_id"), + field.Int16("rating"), + field.String("content").Optional().Default(""), + field.Bool("sealed").Default(true), + field.Time("created_at").Default(time.Now).Immutable(), + field.Time("unsealed_at").Optional().Nillable(), + } +} + +func (Reviews) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("order_id", "from_user_id").Unique(), + index.Fields("order_id"), + index.Fields("to_user_id", "created_at"), + index.Fields("from_user_id"), + } +} + +func (Reviews) Edges() []ent.Edge { + return nil +} diff --git a/app/review/rpc/internal/models/tx.go b/app/review/rpc/internal/models/tx.go new file mode 100644 index 0000000..8a0c9e4 --- /dev/null +++ b/app/review/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 + // Reviews is the client for interacting with the Reviews builders. + Reviews *ReviewsClient + + // 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.Reviews = NewReviewsClient(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: Reviews.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/review/rpc/internal/server/reviewServiceServer.go b/app/review/rpc/internal/server/reviewServiceServer.go new file mode 100644 index 0000000..a60ca0a --- /dev/null +++ b/app/review/rpc/internal/server/reviewServiceServer.go @@ -0,0 +1,50 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: review.proto + +package server + +import ( + "context" + + "juwan-backend/app/review/rpc/internal/logic" + "juwan-backend/app/review/rpc/internal/svc" + "juwan-backend/app/review/rpc/pb" +) + +type ReviewServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedReviewServiceServer +} + +func NewReviewServiceServer(svcCtx *svc.ServiceContext) *ReviewServiceServer { + return &ReviewServiceServer{ + svcCtx: svcCtx, + } +} + +// -----------------------reviews----------------------- +func (s *ReviewServiceServer) AddReviews(ctx context.Context, in *pb.AddReviewsReq) (*pb.AddReviewsResp, error) { + l := logic.NewAddReviewsLogic(ctx, s.svcCtx) + return l.AddReviews(in) +} + +func (s *ReviewServiceServer) UpdateReviews(ctx context.Context, in *pb.UpdateReviewsReq) (*pb.UpdateReviewsResp, error) { + l := logic.NewUpdateReviewsLogic(ctx, s.svcCtx) + return l.UpdateReviews(in) +} + +func (s *ReviewServiceServer) DelReviews(ctx context.Context, in *pb.DelReviewsReq) (*pb.DelReviewsResp, error) { + l := logic.NewDelReviewsLogic(ctx, s.svcCtx) + return l.DelReviews(in) +} + +func (s *ReviewServiceServer) GetReviewsById(ctx context.Context, in *pb.GetReviewsByIdReq) (*pb.GetReviewsByIdResp, error) { + l := logic.NewGetReviewsByIdLogic(ctx, s.svcCtx) + return l.GetReviewsById(in) +} + +func (s *ReviewServiceServer) SearchReviews(ctx context.Context, in *pb.SearchReviewsReq) (*pb.SearchReviewsResp, error) { + l := logic.NewSearchReviewsLogic(ctx, s.svcCtx) + return l.SearchReviews(in) +} diff --git a/app/review/rpc/internal/svc/serviceContext.go b/app/review/rpc/internal/svc/serviceContext.go new file mode 100644 index 0000000..6125ef5 --- /dev/null +++ b/app/review/rpc/internal/svc/serviceContext.go @@ -0,0 +1,52 @@ +package svc + +import ( + stdsql "database/sql" + "juwan-backend/app/review/rpc/internal/config" + "juwan-backend/app/review/rpc/internal/models" + "juwan-backend/app/snowflake/rpc/snowflake" + "juwan-backend/common/redisx" + "juwan-backend/common/snowflakex" + "juwan-backend/pkg/adapter" + "time" + + "ariga.io/entcache" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + + _ "github.com/jackc/pgx/v5/stdlib" +) + +type ServiceContext struct { + Config config.Config + Snowflake snowflake.SnowflakeServiceClient + ReviewModelRW *models.Client + ReviewModelRO *models.Client +} + +func NewServiceContext(c config.Config) *ServiceContext { + rawRW, err := stdsql.Open("pgx", c.DB.Master) + if err != nil { + panic(err) + } + rawRO, err := stdsql.Open("pgx", c.DB.Slaves) + if err != nil { + panic(err) + } + RWConn := sql.OpenDB(dialect.Postgres, rawRW) + ROConn := sql.OpenDB(dialect.Postgres, rawRO) + + redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second) + if redisCluster == nil || err != nil { + 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))) + return &ServiceContext{ + Config: c, + ReviewModelRW: models.NewClient(models.Driver(RWDrv)), + ReviewModelRO: models.NewClient(models.Driver(RODrv)), + Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), + } +} diff --git a/app/review/rpc/pb.go b/app/review/rpc/pb.go new file mode 100644 index 0000000..bfc4f74 --- /dev/null +++ b/app/review/rpc/pb.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/review/rpc/internal/config" + "juwan-backend/app/review/rpc/internal/server" + "juwan-backend/app/review/rpc/internal/svc" + "juwan-backend/app/review/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.RegisterReviewServiceServer(grpcServer, server.NewReviewServiceServer(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/review/rpc/pb/review.pb.go b/app/review/rpc/pb/review.pb.go new file mode 100644 index 0000000..34b2bde --- /dev/null +++ b/app/review/rpc/pb/review.pb.go @@ -0,0 +1,936 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v7.34.1 +// source: review.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) +) + +// --------------------------------reviews-------------------------------- +type Reviews 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 + FromUserId int64 `protobuf:"varint,3,opt,name=fromUserId,proto3" json:"fromUserId,omitempty"` //fromUserId + FromUserName string `protobuf:"bytes,4,opt,name=fromUserName,proto3" json:"fromUserName,omitempty"` //fromUserName + FromUserAvatar string `protobuf:"bytes,5,opt,name=fromUserAvatar,proto3" json:"fromUserAvatar,omitempty"` //fromUserAvatar + ToUserId int64 `protobuf:"varint,6,opt,name=toUserId,proto3" json:"toUserId,omitempty"` //toUserId + Rating int32 `protobuf:"varint,7,opt,name=rating,proto3" json:"rating,omitempty"` //rating + Content string `protobuf:"bytes,8,opt,name=content,proto3" json:"content,omitempty"` //content + Sealed bool `protobuf:"varint,9,opt,name=sealed,proto3" json:"sealed,omitempty"` //sealed + CreatedAt int64 `protobuf:"varint,10,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + UnsealedAt int64 `protobuf:"varint,11,opt,name=unsealedAt,proto3" json:"unsealedAt,omitempty"` //unsealedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Reviews) Reset() { + *x = Reviews{} + mi := &file_review_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Reviews) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Reviews) ProtoMessage() {} + +func (x *Reviews) ProtoReflect() protoreflect.Message { + mi := &file_review_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 Reviews.ProtoReflect.Descriptor instead. +func (*Reviews) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{0} +} + +func (x *Reviews) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Reviews) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *Reviews) GetFromUserId() int64 { + if x != nil { + return x.FromUserId + } + return 0 +} + +func (x *Reviews) GetFromUserName() string { + if x != nil { + return x.FromUserName + } + return "" +} + +func (x *Reviews) GetFromUserAvatar() string { + if x != nil { + return x.FromUserAvatar + } + return "" +} + +func (x *Reviews) GetToUserId() int64 { + if x != nil { + return x.ToUserId + } + return 0 +} + +func (x *Reviews) GetRating() int32 { + if x != nil { + return x.Rating + } + return 0 +} + +func (x *Reviews) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *Reviews) GetSealed() bool { + if x != nil { + return x.Sealed + } + return false +} + +func (x *Reviews) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *Reviews) GetUnsealedAt() int64 { + if x != nil { + return x.UnsealedAt + } + return 0 +} + +type AddReviewsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrderId int64 `protobuf:"varint,1,opt,name=orderId,proto3" json:"orderId,omitempty"` //orderId + FromUserId int64 `protobuf:"varint,2,opt,name=fromUserId,proto3" json:"fromUserId,omitempty"` //fromUserId + FromUserName string `protobuf:"bytes,3,opt,name=fromUserName,proto3" json:"fromUserName,omitempty"` //fromUserName + FromUserAvatar string `protobuf:"bytes,4,opt,name=fromUserAvatar,proto3" json:"fromUserAvatar,omitempty"` //fromUserAvatar + ToUserId int64 `protobuf:"varint,5,opt,name=toUserId,proto3" json:"toUserId,omitempty"` //toUserId + Rating int32 `protobuf:"varint,6,opt,name=rating,proto3" json:"rating,omitempty"` //rating + Content string `protobuf:"bytes,7,opt,name=content,proto3" json:"content,omitempty"` //content + Sealed bool `protobuf:"varint,8,opt,name=sealed,proto3" json:"sealed,omitempty"` //sealed + CreatedAt int64 `protobuf:"varint,9,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddReviewsReq) Reset() { + *x = AddReviewsReq{} + mi := &file_review_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddReviewsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddReviewsReq) ProtoMessage() {} + +func (x *AddReviewsReq) ProtoReflect() protoreflect.Message { + mi := &file_review_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 AddReviewsReq.ProtoReflect.Descriptor instead. +func (*AddReviewsReq) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{1} +} + +func (x *AddReviewsReq) GetOrderId() int64 { + if x != nil { + return x.OrderId + } + return 0 +} + +func (x *AddReviewsReq) GetFromUserId() int64 { + if x != nil { + return x.FromUserId + } + return 0 +} + +func (x *AddReviewsReq) GetFromUserName() string { + if x != nil { + return x.FromUserName + } + return "" +} + +func (x *AddReviewsReq) GetFromUserAvatar() string { + if x != nil { + return x.FromUserAvatar + } + return "" +} + +func (x *AddReviewsReq) GetToUserId() int64 { + if x != nil { + return x.ToUserId + } + return 0 +} + +func (x *AddReviewsReq) GetRating() int32 { + if x != nil { + return x.Rating + } + return 0 +} + +func (x *AddReviewsReq) GetContent() string { + if x != nil { + return x.Content + } + return "" +} + +func (x *AddReviewsReq) GetSealed() bool { + if x != nil { + return x.Sealed + } + return false +} + +func (x *AddReviewsReq) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddReviewsResp 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 *AddReviewsResp) Reset() { + *x = AddReviewsResp{} + mi := &file_review_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddReviewsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddReviewsResp) ProtoMessage() {} + +func (x *AddReviewsResp) ProtoReflect() protoreflect.Message { + mi := &file_review_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 AddReviewsResp.ProtoReflect.Descriptor instead. +func (*AddReviewsResp) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{2} +} + +func (x *AddReviewsResp) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type UpdateReviewsReq 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 + FromUserId *int64 `protobuf:"varint,3,opt,name=fromUserId,proto3,oneof" json:"fromUserId,omitempty"` //fromUserId + FromUserName *string `protobuf:"bytes,4,opt,name=fromUserName,proto3,oneof" json:"fromUserName,omitempty"` //fromUserName + FromUserAvatar *string `protobuf:"bytes,5,opt,name=fromUserAvatar,proto3,oneof" json:"fromUserAvatar,omitempty"` //fromUserAvatar + ToUserId *int64 `protobuf:"varint,6,opt,name=toUserId,proto3,oneof" json:"toUserId,omitempty"` //toUserId + Rating *int32 `protobuf:"varint,7,opt,name=rating,proto3,oneof" json:"rating,omitempty"` //rating + Content *string `protobuf:"bytes,8,opt,name=content,proto3,oneof" json:"content,omitempty"` //content + Sealed *bool `protobuf:"varint,9,opt,name=sealed,proto3,oneof" json:"sealed,omitempty"` //sealed + CreatedAt *int64 `protobuf:"varint,10,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` //createdAt + UnsealedAt *int64 `protobuf:"varint,11,opt,name=unsealedAt,proto3,oneof" json:"unsealedAt,omitempty"` //unsealedAt + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateReviewsReq) Reset() { + *x = UpdateReviewsReq{} + mi := &file_review_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateReviewsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateReviewsReq) ProtoMessage() {} + +func (x *UpdateReviewsReq) ProtoReflect() protoreflect.Message { + mi := &file_review_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 UpdateReviewsReq.ProtoReflect.Descriptor instead. +func (*UpdateReviewsReq) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{3} +} + +func (x *UpdateReviewsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateReviewsReq) GetOrderId() int64 { + if x != nil && x.OrderId != nil { + return *x.OrderId + } + return 0 +} + +func (x *UpdateReviewsReq) GetFromUserId() int64 { + if x != nil && x.FromUserId != nil { + return *x.FromUserId + } + return 0 +} + +func (x *UpdateReviewsReq) GetFromUserName() string { + if x != nil && x.FromUserName != nil { + return *x.FromUserName + } + return "" +} + +func (x *UpdateReviewsReq) GetFromUserAvatar() string { + if x != nil && x.FromUserAvatar != nil { + return *x.FromUserAvatar + } + return "" +} + +func (x *UpdateReviewsReq) GetToUserId() int64 { + if x != nil && x.ToUserId != nil { + return *x.ToUserId + } + return 0 +} + +func (x *UpdateReviewsReq) GetRating() int32 { + if x != nil && x.Rating != nil { + return *x.Rating + } + return 0 +} + +func (x *UpdateReviewsReq) GetContent() string { + if x != nil && x.Content != nil { + return *x.Content + } + return "" +} + +func (x *UpdateReviewsReq) GetSealed() bool { + if x != nil && x.Sealed != nil { + return *x.Sealed + } + return false +} + +func (x *UpdateReviewsReq) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *UpdateReviewsReq) GetUnsealedAt() int64 { + if x != nil && x.UnsealedAt != nil { + return *x.UnsealedAt + } + return 0 +} + +type UpdateReviewsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateReviewsResp) Reset() { + *x = UpdateReviewsResp{} + mi := &file_review_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateReviewsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateReviewsResp) ProtoMessage() {} + +func (x *UpdateReviewsResp) ProtoReflect() protoreflect.Message { + mi := &file_review_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 UpdateReviewsResp.ProtoReflect.Descriptor instead. +func (*UpdateReviewsResp) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{4} +} + +type DelReviewsReq 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 *DelReviewsReq) Reset() { + *x = DelReviewsReq{} + mi := &file_review_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelReviewsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelReviewsReq) ProtoMessage() {} + +func (x *DelReviewsReq) ProtoReflect() protoreflect.Message { + mi := &file_review_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 DelReviewsReq.ProtoReflect.Descriptor instead. +func (*DelReviewsReq) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{5} +} + +func (x *DelReviewsReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelReviewsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelReviewsResp) Reset() { + *x = DelReviewsResp{} + mi := &file_review_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelReviewsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelReviewsResp) ProtoMessage() {} + +func (x *DelReviewsResp) ProtoReflect() protoreflect.Message { + mi := &file_review_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 DelReviewsResp.ProtoReflect.Descriptor instead. +func (*DelReviewsResp) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{6} +} + +type GetReviewsByIdReq 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 *GetReviewsByIdReq) Reset() { + *x = GetReviewsByIdReq{} + mi := &file_review_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetReviewsByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetReviewsByIdReq) ProtoMessage() {} + +func (x *GetReviewsByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_review_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 GetReviewsByIdReq.ProtoReflect.Descriptor instead. +func (*GetReviewsByIdReq) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{7} +} + +func (x *GetReviewsByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetReviewsByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Reviews *Reviews `protobuf:"bytes,1,opt,name=reviews,proto3" json:"reviews,omitempty"` //reviews + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetReviewsByIdResp) Reset() { + *x = GetReviewsByIdResp{} + mi := &file_review_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetReviewsByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetReviewsByIdResp) ProtoMessage() {} + +func (x *GetReviewsByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_review_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 GetReviewsByIdResp.ProtoReflect.Descriptor instead. +func (*GetReviewsByIdResp) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{8} +} + +func (x *GetReviewsByIdResp) GetReviews() *Reviews { + if x != nil { + return x.Reviews + } + return nil +} + +type SearchReviewsReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Offset int64 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` //offset + 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 + FromUserId *int64 `protobuf:"varint,5,opt,name=fromUserId,proto3,oneof" json:"fromUserId,omitempty"` //fromUserId + ToUserId *int64 `protobuf:"varint,6,opt,name=toUserId,proto3,oneof" json:"toUserId,omitempty"` //toUserId + Sealed *bool `protobuf:"varint,7,opt,name=sealed,proto3,oneof" json:"sealed,omitempty"` //sealed + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchReviewsReq) Reset() { + *x = SearchReviewsReq{} + mi := &file_review_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchReviewsReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchReviewsReq) ProtoMessage() {} + +func (x *SearchReviewsReq) ProtoReflect() protoreflect.Message { + mi := &file_review_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 SearchReviewsReq.ProtoReflect.Descriptor instead. +func (*SearchReviewsReq) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{9} +} + +func (x *SearchReviewsReq) GetOffset() int64 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *SearchReviewsReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchReviewsReq) GetId() int64 { + if x != nil && x.Id != nil { + return *x.Id + } + return 0 +} + +func (x *SearchReviewsReq) GetOrderId() int64 { + if x != nil && x.OrderId != nil { + return *x.OrderId + } + return 0 +} + +func (x *SearchReviewsReq) GetFromUserId() int64 { + if x != nil && x.FromUserId != nil { + return *x.FromUserId + } + return 0 +} + +func (x *SearchReviewsReq) GetToUserId() int64 { + if x != nil && x.ToUserId != nil { + return *x.ToUserId + } + return 0 +} + +func (x *SearchReviewsReq) GetSealed() bool { + if x != nil && x.Sealed != nil { + return *x.Sealed + } + return false +} + +type SearchReviewsResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Reviews []*Reviews `protobuf:"bytes,1,rep,name=reviews,proto3" json:"reviews,omitempty"` //reviews + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchReviewsResp) Reset() { + *x = SearchReviewsResp{} + mi := &file_review_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchReviewsResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchReviewsResp) ProtoMessage() {} + +func (x *SearchReviewsResp) ProtoReflect() protoreflect.Message { + mi := &file_review_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 SearchReviewsResp.ProtoReflect.Descriptor instead. +func (*SearchReviewsResp) Descriptor() ([]byte, []int) { + return file_review_proto_rawDescGZIP(), []int{10} +} + +func (x *SearchReviewsResp) GetReviews() []*Reviews { + if x != nil { + return x.Reviews + } + return nil +} + +var File_review_proto protoreflect.FileDescriptor + +const file_review_proto_rawDesc = "" + + "\n" + + "\freview.proto\x12\x02pb\"\xc3\x02\n" + + "\aReviews\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x18\n" + + "\aorderId\x18\x02 \x01(\x03R\aorderId\x12\x1e\n" + + "\n" + + "fromUserId\x18\x03 \x01(\x03R\n" + + "fromUserId\x12\"\n" + + "\ffromUserName\x18\x04 \x01(\tR\ffromUserName\x12&\n" + + "\x0efromUserAvatar\x18\x05 \x01(\tR\x0efromUserAvatar\x12\x1a\n" + + "\btoUserId\x18\x06 \x01(\x03R\btoUserId\x12\x16\n" + + "\x06rating\x18\a \x01(\x05R\x06rating\x12\x18\n" + + "\acontent\x18\b \x01(\tR\acontent\x12\x16\n" + + "\x06sealed\x18\t \x01(\bR\x06sealed\x12\x1c\n" + + "\tcreatedAt\x18\n" + + " \x01(\x03R\tcreatedAt\x12\x1e\n" + + "\n" + + "unsealedAt\x18\v \x01(\x03R\n" + + "unsealedAt\"\x99\x02\n" + + "\rAddReviewsReq\x12\x18\n" + + "\aorderId\x18\x01 \x01(\x03R\aorderId\x12\x1e\n" + + "\n" + + "fromUserId\x18\x02 \x01(\x03R\n" + + "fromUserId\x12\"\n" + + "\ffromUserName\x18\x03 \x01(\tR\ffromUserName\x12&\n" + + "\x0efromUserAvatar\x18\x04 \x01(\tR\x0efromUserAvatar\x12\x1a\n" + + "\btoUserId\x18\x05 \x01(\x03R\btoUserId\x12\x16\n" + + "\x06rating\x18\x06 \x01(\x05R\x06rating\x12\x18\n" + + "\acontent\x18\a \x01(\tR\acontent\x12\x16\n" + + "\x06sealed\x18\b \x01(\bR\x06sealed\x12\x1c\n" + + "\tcreatedAt\x18\t \x01(\x03R\tcreatedAt\" \n" + + "\x0eAddReviewsResp\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x89\x04\n" + + "\x10UpdateReviewsReq\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" + + "fromUserId\x18\x03 \x01(\x03H\x01R\n" + + "fromUserId\x88\x01\x01\x12'\n" + + "\ffromUserName\x18\x04 \x01(\tH\x02R\ffromUserName\x88\x01\x01\x12+\n" + + "\x0efromUserAvatar\x18\x05 \x01(\tH\x03R\x0efromUserAvatar\x88\x01\x01\x12\x1f\n" + + "\btoUserId\x18\x06 \x01(\x03H\x04R\btoUserId\x88\x01\x01\x12\x1b\n" + + "\x06rating\x18\a \x01(\x05H\x05R\x06rating\x88\x01\x01\x12\x1d\n" + + "\acontent\x18\b \x01(\tH\x06R\acontent\x88\x01\x01\x12\x1b\n" + + "\x06sealed\x18\t \x01(\bH\aR\x06sealed\x88\x01\x01\x12!\n" + + "\tcreatedAt\x18\n" + + " \x01(\x03H\bR\tcreatedAt\x88\x01\x01\x12#\n" + + "\n" + + "unsealedAt\x18\v \x01(\x03H\tR\n" + + "unsealedAt\x88\x01\x01B\n" + + "\n" + + "\b_orderIdB\r\n" + + "\v_fromUserIdB\x0f\n" + + "\r_fromUserNameB\x11\n" + + "\x0f_fromUserAvatarB\v\n" + + "\t_toUserIdB\t\n" + + "\a_ratingB\n" + + "\n" + + "\b_contentB\t\n" + + "\a_sealedB\f\n" + + "\n" + + "_createdAtB\r\n" + + "\v_unsealedAt\"\x13\n" + + "\x11UpdateReviewsResp\"\x1f\n" + + "\rDelReviewsReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x10\n" + + "\x0eDelReviewsResp\"#\n" + + "\x11GetReviewsByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\";\n" + + "\x12GetReviewsByIdResp\x12%\n" + + "\areviews\x18\x01 \x01(\v2\v.pb.ReviewsR\areviews\"\x91\x02\n" + + "\x10SearchReviewsReq\x12\x16\n" + + "\x06offset\x18\x01 \x01(\x03R\x06offset\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" + + "fromUserId\x18\x05 \x01(\x03H\x02R\n" + + "fromUserId\x88\x01\x01\x12\x1f\n" + + "\btoUserId\x18\x06 \x01(\x03H\x03R\btoUserId\x88\x01\x01\x12\x1b\n" + + "\x06sealed\x18\a \x01(\bH\x04R\x06sealed\x88\x01\x01B\x05\n" + + "\x03_idB\n" + + "\n" + + "\b_orderIdB\r\n" + + "\v_fromUserIdB\v\n" + + "\t_toUserIdB\t\n" + + "\a_sealed\":\n" + + "\x11SearchReviewsResp\x12%\n" + + "\areviews\x18\x01 \x03(\v2\v.pb.ReviewsR\areviews2\xb6\x02\n" + + "\rreviewService\x123\n" + + "\n" + + "AddReviews\x12\x11.pb.AddReviewsReq\x1a\x12.pb.AddReviewsResp\x12<\n" + + "\rUpdateReviews\x12\x14.pb.UpdateReviewsReq\x1a\x15.pb.UpdateReviewsResp\x123\n" + + "\n" + + "DelReviews\x12\x11.pb.DelReviewsReq\x1a\x12.pb.DelReviewsResp\x12?\n" + + "\x0eGetReviewsById\x12\x15.pb.GetReviewsByIdReq\x1a\x16.pb.GetReviewsByIdResp\x12<\n" + + "\rSearchReviews\x12\x14.pb.SearchReviewsReq\x1a\x15.pb.SearchReviewsRespB\x06Z\x04./pbb\x06proto3" + +var ( + file_review_proto_rawDescOnce sync.Once + file_review_proto_rawDescData []byte +) + +func file_review_proto_rawDescGZIP() []byte { + file_review_proto_rawDescOnce.Do(func() { + file_review_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_review_proto_rawDesc), len(file_review_proto_rawDesc))) + }) + return file_review_proto_rawDescData +} + +var file_review_proto_msgTypes = make([]protoimpl.MessageInfo, 11) +var file_review_proto_goTypes = []any{ + (*Reviews)(nil), // 0: pb.Reviews + (*AddReviewsReq)(nil), // 1: pb.AddReviewsReq + (*AddReviewsResp)(nil), // 2: pb.AddReviewsResp + (*UpdateReviewsReq)(nil), // 3: pb.UpdateReviewsReq + (*UpdateReviewsResp)(nil), // 4: pb.UpdateReviewsResp + (*DelReviewsReq)(nil), // 5: pb.DelReviewsReq + (*DelReviewsResp)(nil), // 6: pb.DelReviewsResp + (*GetReviewsByIdReq)(nil), // 7: pb.GetReviewsByIdReq + (*GetReviewsByIdResp)(nil), // 8: pb.GetReviewsByIdResp + (*SearchReviewsReq)(nil), // 9: pb.SearchReviewsReq + (*SearchReviewsResp)(nil), // 10: pb.SearchReviewsResp +} +var file_review_proto_depIdxs = []int32{ + 0, // 0: pb.GetReviewsByIdResp.reviews:type_name -> pb.Reviews + 0, // 1: pb.SearchReviewsResp.reviews:type_name -> pb.Reviews + 1, // 2: pb.reviewService.AddReviews:input_type -> pb.AddReviewsReq + 3, // 3: pb.reviewService.UpdateReviews:input_type -> pb.UpdateReviewsReq + 5, // 4: pb.reviewService.DelReviews:input_type -> pb.DelReviewsReq + 7, // 5: pb.reviewService.GetReviewsById:input_type -> pb.GetReviewsByIdReq + 9, // 6: pb.reviewService.SearchReviews:input_type -> pb.SearchReviewsReq + 2, // 7: pb.reviewService.AddReviews:output_type -> pb.AddReviewsResp + 4, // 8: pb.reviewService.UpdateReviews:output_type -> pb.UpdateReviewsResp + 6, // 9: pb.reviewService.DelReviews:output_type -> pb.DelReviewsResp + 8, // 10: pb.reviewService.GetReviewsById:output_type -> pb.GetReviewsByIdResp + 10, // 11: pb.reviewService.SearchReviews:output_type -> pb.SearchReviewsResp + 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 + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_review_proto_init() } +func file_review_proto_init() { + if File_review_proto != nil { + return + } + file_review_proto_msgTypes[3].OneofWrappers = []any{} + file_review_proto_msgTypes[9].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_review_proto_rawDesc), len(file_review_proto_rawDesc)), + NumEnums: 0, + NumMessages: 11, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_review_proto_goTypes, + DependencyIndexes: file_review_proto_depIdxs, + MessageInfos: file_review_proto_msgTypes, + }.Build() + File_review_proto = out.File + file_review_proto_goTypes = nil + file_review_proto_depIdxs = nil +} diff --git a/app/review/rpc/pb/review_grpc.pb.go b/app/review/rpc/pb/review_grpc.pb.go new file mode 100644 index 0000000..f5c7e2c --- /dev/null +++ b/app/review/rpc/pb/review_grpc.pb.go @@ -0,0 +1,275 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v7.34.1 +// source: review.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 ( + ReviewService_AddReviews_FullMethodName = "/pb.reviewService/AddReviews" + ReviewService_UpdateReviews_FullMethodName = "/pb.reviewService/UpdateReviews" + ReviewService_DelReviews_FullMethodName = "/pb.reviewService/DelReviews" + ReviewService_GetReviewsById_FullMethodName = "/pb.reviewService/GetReviewsById" + ReviewService_SearchReviews_FullMethodName = "/pb.reviewService/SearchReviews" +) + +// ReviewServiceClient is the client API for ReviewService 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 ReviewServiceClient interface { + // -----------------------reviews----------------------- + AddReviews(ctx context.Context, in *AddReviewsReq, opts ...grpc.CallOption) (*AddReviewsResp, error) + UpdateReviews(ctx context.Context, in *UpdateReviewsReq, opts ...grpc.CallOption) (*UpdateReviewsResp, error) + DelReviews(ctx context.Context, in *DelReviewsReq, opts ...grpc.CallOption) (*DelReviewsResp, error) + GetReviewsById(ctx context.Context, in *GetReviewsByIdReq, opts ...grpc.CallOption) (*GetReviewsByIdResp, error) + SearchReviews(ctx context.Context, in *SearchReviewsReq, opts ...grpc.CallOption) (*SearchReviewsResp, error) +} + +type reviewServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewReviewServiceClient(cc grpc.ClientConnInterface) ReviewServiceClient { + return &reviewServiceClient{cc} +} + +func (c *reviewServiceClient) AddReviews(ctx context.Context, in *AddReviewsReq, opts ...grpc.CallOption) (*AddReviewsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddReviewsResp) + err := c.cc.Invoke(ctx, ReviewService_AddReviews_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *reviewServiceClient) UpdateReviews(ctx context.Context, in *UpdateReviewsReq, opts ...grpc.CallOption) (*UpdateReviewsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateReviewsResp) + err := c.cc.Invoke(ctx, ReviewService_UpdateReviews_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *reviewServiceClient) DelReviews(ctx context.Context, in *DelReviewsReq, opts ...grpc.CallOption) (*DelReviewsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelReviewsResp) + err := c.cc.Invoke(ctx, ReviewService_DelReviews_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *reviewServiceClient) GetReviewsById(ctx context.Context, in *GetReviewsByIdReq, opts ...grpc.CallOption) (*GetReviewsByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetReviewsByIdResp) + err := c.cc.Invoke(ctx, ReviewService_GetReviewsById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *reviewServiceClient) SearchReviews(ctx context.Context, in *SearchReviewsReq, opts ...grpc.CallOption) (*SearchReviewsResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchReviewsResp) + err := c.cc.Invoke(ctx, ReviewService_SearchReviews_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ReviewServiceServer is the server API for ReviewService service. +// All implementations must embed UnimplementedReviewServiceServer +// for forward compatibility. +type ReviewServiceServer interface { + // -----------------------reviews----------------------- + AddReviews(context.Context, *AddReviewsReq) (*AddReviewsResp, error) + UpdateReviews(context.Context, *UpdateReviewsReq) (*UpdateReviewsResp, error) + DelReviews(context.Context, *DelReviewsReq) (*DelReviewsResp, error) + GetReviewsById(context.Context, *GetReviewsByIdReq) (*GetReviewsByIdResp, error) + SearchReviews(context.Context, *SearchReviewsReq) (*SearchReviewsResp, error) + mustEmbedUnimplementedReviewServiceServer() +} + +// UnimplementedReviewServiceServer 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 UnimplementedReviewServiceServer struct{} + +func (UnimplementedReviewServiceServer) AddReviews(context.Context, *AddReviewsReq) (*AddReviewsResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddReviews not implemented") +} +func (UnimplementedReviewServiceServer) UpdateReviews(context.Context, *UpdateReviewsReq) (*UpdateReviewsResp, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateReviews not implemented") +} +func (UnimplementedReviewServiceServer) DelReviews(context.Context, *DelReviewsReq) (*DelReviewsResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelReviews not implemented") +} +func (UnimplementedReviewServiceServer) GetReviewsById(context.Context, *GetReviewsByIdReq) (*GetReviewsByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetReviewsById not implemented") +} +func (UnimplementedReviewServiceServer) SearchReviews(context.Context, *SearchReviewsReq) (*SearchReviewsResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchReviews not implemented") +} +func (UnimplementedReviewServiceServer) mustEmbedUnimplementedReviewServiceServer() {} +func (UnimplementedReviewServiceServer) testEmbeddedByValue() {} + +// UnsafeReviewServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ReviewServiceServer will +// result in compilation errors. +type UnsafeReviewServiceServer interface { + mustEmbedUnimplementedReviewServiceServer() +} + +func RegisterReviewServiceServer(s grpc.ServiceRegistrar, srv ReviewServiceServer) { + // If the following call panics, it indicates UnimplementedReviewServiceServer 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(&ReviewService_ServiceDesc, srv) +} + +func _ReviewService_AddReviews_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddReviewsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ReviewServiceServer).AddReviews(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ReviewService_AddReviews_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ReviewServiceServer).AddReviews(ctx, req.(*AddReviewsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _ReviewService_UpdateReviews_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateReviewsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ReviewServiceServer).UpdateReviews(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ReviewService_UpdateReviews_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ReviewServiceServer).UpdateReviews(ctx, req.(*UpdateReviewsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _ReviewService_DelReviews_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelReviewsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ReviewServiceServer).DelReviews(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ReviewService_DelReviews_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ReviewServiceServer).DelReviews(ctx, req.(*DelReviewsReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _ReviewService_GetReviewsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetReviewsByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ReviewServiceServer).GetReviewsById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ReviewService_GetReviewsById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ReviewServiceServer).GetReviewsById(ctx, req.(*GetReviewsByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _ReviewService_SearchReviews_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchReviewsReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ReviewServiceServer).SearchReviews(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ReviewService_SearchReviews_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ReviewServiceServer).SearchReviews(ctx, req.(*SearchReviewsReq)) + } + return interceptor(ctx, in, info, handler) +} + +// ReviewService_ServiceDesc is the grpc.ServiceDesc for ReviewService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ReviewService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.reviewService", + HandlerType: (*ReviewServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "AddReviews", + Handler: _ReviewService_AddReviews_Handler, + }, + { + MethodName: "UpdateReviews", + Handler: _ReviewService_UpdateReviews_Handler, + }, + { + MethodName: "DelReviews", + Handler: _ReviewService_DelReviews_Handler, + }, + { + MethodName: "GetReviewsById", + Handler: _ReviewService_GetReviewsById_Handler, + }, + { + MethodName: "SearchReviews", + Handler: _ReviewService_SearchReviews_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "review.proto", +} diff --git a/app/review/rpc/reviewservice/reviewService.go b/app/review/rpc/reviewservice/reviewService.go new file mode 100644 index 0000000..1f2fcfa --- /dev/null +++ b/app/review/rpc/reviewservice/reviewService.go @@ -0,0 +1,73 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: review.proto + +package reviewservice + +import ( + "context" + + "juwan-backend/app/review/rpc/pb" + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + AddReviewsReq = pb.AddReviewsReq + AddReviewsResp = pb.AddReviewsResp + DelReviewsReq = pb.DelReviewsReq + DelReviewsResp = pb.DelReviewsResp + GetReviewsByIdReq = pb.GetReviewsByIdReq + GetReviewsByIdResp = pb.GetReviewsByIdResp + Reviews = pb.Reviews + SearchReviewsReq = pb.SearchReviewsReq + SearchReviewsResp = pb.SearchReviewsResp + UpdateReviewsReq = pb.UpdateReviewsReq + UpdateReviewsResp = pb.UpdateReviewsResp + + ReviewService interface { + // -----------------------reviews----------------------- + AddReviews(ctx context.Context, in *AddReviewsReq, opts ...grpc.CallOption) (*AddReviewsResp, error) + UpdateReviews(ctx context.Context, in *UpdateReviewsReq, opts ...grpc.CallOption) (*UpdateReviewsResp, error) + DelReviews(ctx context.Context, in *DelReviewsReq, opts ...grpc.CallOption) (*DelReviewsResp, error) + GetReviewsById(ctx context.Context, in *GetReviewsByIdReq, opts ...grpc.CallOption) (*GetReviewsByIdResp, error) + SearchReviews(ctx context.Context, in *SearchReviewsReq, opts ...grpc.CallOption) (*SearchReviewsResp, error) + } + + defaultReviewService struct { + cli zrpc.Client + } +) + +func NewReviewService(cli zrpc.Client) ReviewService { + return &defaultReviewService{ + cli: cli, + } +} + +// -----------------------reviews----------------------- +func (m *defaultReviewService) AddReviews(ctx context.Context, in *AddReviewsReq, opts ...grpc.CallOption) (*AddReviewsResp, error) { + client := pb.NewReviewServiceClient(m.cli.Conn()) + return client.AddReviews(ctx, in, opts...) +} + +func (m *defaultReviewService) UpdateReviews(ctx context.Context, in *UpdateReviewsReq, opts ...grpc.CallOption) (*UpdateReviewsResp, error) { + client := pb.NewReviewServiceClient(m.cli.Conn()) + return client.UpdateReviews(ctx, in, opts...) +} + +func (m *defaultReviewService) DelReviews(ctx context.Context, in *DelReviewsReq, opts ...grpc.CallOption) (*DelReviewsResp, error) { + client := pb.NewReviewServiceClient(m.cli.Conn()) + return client.DelReviews(ctx, in, opts...) +} + +func (m *defaultReviewService) GetReviewsById(ctx context.Context, in *GetReviewsByIdReq, opts ...grpc.CallOption) (*GetReviewsByIdResp, error) { + client := pb.NewReviewServiceClient(m.cli.Conn()) + return client.GetReviewsById(ctx, in, opts...) +} + +func (m *defaultReviewService) SearchReviews(ctx context.Context, in *SearchReviewsReq, opts ...grpc.CallOption) (*SearchReviewsResp, error) { + client := pb.NewReviewServiceClient(m.cli.Conn()) + return client.SearchReviews(ctx, in, opts...) +} diff --git a/app/search/api/etc/search-api.yaml b/app/search/api/etc/search-api.yaml new file mode 100644 index 0000000..00b12fb --- /dev/null +++ b/app/search/api/etc/search-api.yaml @@ -0,0 +1,13 @@ +Name: search-api +Host: 0.0.0.0 +Port: 8888 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONFIG ===== +SearchRpcConf: + Endpoints: + - search-rpc:8080 diff --git a/app/search/api/internal/config/config.go b/app/search/api/internal/config/config.go new file mode 100644 index 0000000..de4d367 --- /dev/null +++ b/app/search/api/internal/config/config.go @@ -0,0 +1,11 @@ +package config + +import ( + "github.com/zeromicro/go-zero/rest" + "github.com/zeromicro/go-zero/zrpc" +) + +type Config struct { + rest.RestConf + SearchRpcConf zrpc.RpcClientConf +} diff --git a/app/search/api/internal/handler/favorites/addFavoriteHandler.go b/app/search/api/internal/handler/favorites/addFavoriteHandler.go new file mode 100644 index 0000000..a9da652 --- /dev/null +++ b/app/search/api/internal/handler/favorites/addFavoriteHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/search/api/internal/logic/favorites" + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" +) + +// 添加收藏 +func AddFavoriteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.FavoriteReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := favorites.NewAddFavoriteLogic(r.Context(), svcCtx) + resp, err := l.AddFavorite(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/search/api/internal/handler/favorites/checkFavoriteHandler.go b/app/search/api/internal/handler/favorites/checkFavoriteHandler.go new file mode 100644 index 0000000..0bc425a --- /dev/null +++ b/app/search/api/internal/handler/favorites/checkFavoriteHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/search/api/internal/logic/favorites" + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" +) + +// 检查收藏状态 +func CheckFavoriteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.FavoriteCheckReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := favorites.NewCheckFavoriteLogic(r.Context(), svcCtx) + resp, err := l.CheckFavorite(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/search/api/internal/handler/favorites/listFavoritesHandler.go b/app/search/api/internal/handler/favorites/listFavoritesHandler.go new file mode 100644 index 0000000..f0fbf75 --- /dev/null +++ b/app/search/api/internal/handler/favorites/listFavoritesHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/search/api/internal/logic/favorites" + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" +) + +// 获取收藏列表 +func ListFavoritesHandler(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 := favorites.NewListFavoritesLogic(r.Context(), svcCtx) + resp, err := l.ListFavorites(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/search/api/internal/handler/favorites/removeFavoriteHandler.go b/app/search/api/internal/handler/favorites/removeFavoriteHandler.go new file mode 100644 index 0000000..83bbcf8 --- /dev/null +++ b/app/search/api/internal/handler/favorites/removeFavoriteHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/search/api/internal/logic/favorites" + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" +) + +// 取消收藏 +func RemoveFavoriteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.PathIDReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := favorites.NewRemoveFavoriteLogic(r.Context(), svcCtx) + resp, err := l.RemoveFavorite(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/search/api/internal/handler/routes.go b/app/search/api/internal/handler/routes.go new file mode 100644 index 0000000..e3e06c7 --- /dev/null +++ b/app/search/api/internal/handler/routes.go @@ -0,0 +1,64 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package handler + +import ( + "net/http" + + favorites "juwan-backend/app/search/api/internal/handler/favorites" + search "juwan-backend/app/search/api/internal/handler/search" + "juwan-backend/app/search/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: "/favorites", + Handler: favorites.ListFavoritesHandler(serverCtx), + }, + { + // 添加收藏 + Method: http.MethodPost, + Path: "/favorites", + Handler: favorites.AddFavoriteHandler(serverCtx), + }, + { + // 取消收藏 + Method: http.MethodDelete, + Path: "/favorites/:id", + Handler: favorites.RemoveFavoriteHandler(serverCtx), + }, + { + // 检查收藏状态 + Method: http.MethodGet, + Path: "/users/:id/favorites/check", + Handler: favorites.CheckFavoriteHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) + + server.AddRoutes( + []rest.Route{ + { + // 首页推荐 + Method: http.MethodGet, + Path: "/recommendations/home", + Handler: search.RecommendationsHandler(serverCtx), + }, + { + // 统一搜索 + Method: http.MethodGet, + Path: "/search", + Handler: search.SearchHandler(serverCtx), + }, + }, + rest.WithPrefix("/api/v1"), + ) +} diff --git a/app/search/api/internal/handler/search/recommendationsHandler.go b/app/search/api/internal/handler/search/recommendationsHandler.go new file mode 100644 index 0000000..e4d5598 --- /dev/null +++ b/app/search/api/internal/handler/search/recommendationsHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package search + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/search/api/internal/logic/search" + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" +) + +// 首页推荐 +func RecommendationsHandler(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 := search.NewRecommendationsLogic(r.Context(), svcCtx) + resp, err := l.Recommendations(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/search/api/internal/handler/search/searchHandler.go b/app/search/api/internal/handler/search/searchHandler.go new file mode 100644 index 0000000..c7a00e3 --- /dev/null +++ b/app/search/api/internal/handler/search/searchHandler.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package search + +import ( + "net/http" + + "github.com/zeromicro/go-zero/rest/httpx" + "juwan-backend/app/search/api/internal/logic/search" + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" +) + +// 统一搜索 +func SearchHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.SearchReq + if err := httpx.Parse(r, &req); err != nil { + httpx.ErrorCtx(r.Context(), w, err) + return + } + + l := search.NewSearchLogic(r.Context(), svcCtx) + resp, err := l.Search(&req) + if err != nil { + httpx.ErrorCtx(r.Context(), w, err) + } else { + httpx.OkJsonCtx(r.Context(), w, resp) + } + } +} diff --git a/app/search/api/internal/logic/favorites/addFavoriteLogic.go b/app/search/api/internal/logic/favorites/addFavoriteLogic.go new file mode 100644 index 0000000..a02867a --- /dev/null +++ b/app/search/api/internal/logic/favorites/addFavoriteLogic.go @@ -0,0 +1,52 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "context" + + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" + "juwan-backend/app/search/rpc/searchservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddFavoriteLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 添加收藏 +func NewAddFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddFavoriteLogic { + return &AddFavoriteLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *AddFavoriteLogic) AddFavorite(req *types.FavoriteReq) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + targetID, err := parseSnowflakeID(req.TargetId) + if err != nil { + return nil, err + } + + _, err = l.svcCtx.SearchRpc.AddFavorites(l.ctx, &searchservice.AddFavoritesReq{ + UserId: uid, + TargetType: req.TargetType, + TargetId: targetID, + }) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/search/api/internal/logic/favorites/checkFavoriteLogic.go b/app/search/api/internal/logic/favorites/checkFavoriteLogic.go new file mode 100644 index 0000000..8bf2f6a --- /dev/null +++ b/app/search/api/internal/logic/favorites/checkFavoriteLogic.go @@ -0,0 +1,58 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "context" + "errors" + + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" + "juwan-backend/app/search/rpc/searchservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CheckFavoriteLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 检查收藏状态 +func NewCheckFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckFavoriteLogic { + return &CheckFavoriteLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *CheckFavoriteLogic) CheckFavorite(req *types.FavoriteCheckReq) (resp *types.FavoriteCheckResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + if req.Id != uid { + return nil, errors.New("user mismatch") + } + targetID, err := parseSnowflakeID(req.TargetId) + if err != nil { + return nil, err + } + + out, err := l.svcCtx.SearchRpc.SearchFavorites(l.ctx, &searchservice.SearchFavoritesReq{ + Offset: 0, + Limit: 1, + UserId: &uid, + TargetType: &req.TargetType, + TargetId: &targetID, + }) + if err != nil { + return nil, err + } + + return &types.FavoriteCheckResp{Favorited: len(out.GetFavorites()) > 0}, nil +} diff --git a/app/search/api/internal/logic/favorites/helpers.go b/app/search/api/internal/logic/favorites/helpers.go new file mode 100644 index 0000000..45b8885 --- /dev/null +++ b/app/search/api/internal/logic/favorites/helpers.go @@ -0,0 +1,23 @@ +package favorites + +import ( + "strconv" + "time" + + "juwan-backend/app/search/api/internal/types" + "juwan-backend/app/search/rpc/searchservice" +) + +func toAPIFavorite(f *searchservice.Favorites) types.Favorite { + return types.Favorite{ + Id: strconv.FormatInt(f.GetId(), 10), + UserId: strconv.FormatInt(f.GetUserId(), 10), + TargetType: f.GetTargetType(), + TargetId: strconv.FormatInt(f.GetTargetId(), 10), + CreatedAt: time.Unix(f.GetCreatedAt(), 0).Format(time.RFC3339), + } +} + +func parseSnowflakeID(value string) (int64, error) { + return strconv.ParseInt(value, 10, 64) +} diff --git a/app/search/api/internal/logic/favorites/listFavoritesLogic.go b/app/search/api/internal/logic/favorites/listFavoritesLogic.go new file mode 100644 index 0000000..b88e6ce --- /dev/null +++ b/app/search/api/internal/logic/favorites/listFavoritesLogic.go @@ -0,0 +1,63 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "context" + + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" + "juwan-backend/app/search/rpc/searchservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ListFavoritesLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 获取收藏列表 +func NewListFavoritesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListFavoritesLogic { + return &ListFavoritesLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *ListFavoritesLogic) ListFavorites(req *types.PageReq) (resp *types.FavoriteListResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + limit := req.Limit + if limit <= 0 { + limit = 20 + } + + out, err := l.svcCtx.SearchRpc.SearchFavorites(l.ctx, &searchservice.SearchFavoritesReq{ + Offset: req.Offset, + Limit: limit, + UserId: &uid, + }) + if err != nil { + return nil, err + } + items := make([]types.Favorite, 0, len(out.GetFavorites())) + for _, item := range out.GetFavorites() { + items = append(items, toAPIFavorite(item)) + } + + return &types.FavoriteListResp{ + Items: items, + Meta: types.PageMeta{ + Total: int64(len(items)), + Offset: req.Offset, + Limit: limit, + }, + }, nil +} diff --git a/app/search/api/internal/logic/favorites/removeFavoriteLogic.go b/app/search/api/internal/logic/favorites/removeFavoriteLogic.go new file mode 100644 index 0000000..ead5b69 --- /dev/null +++ b/app/search/api/internal/logic/favorites/removeFavoriteLogic.go @@ -0,0 +1,53 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package favorites + +import ( + "context" + "errors" + + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" + "juwan-backend/app/search/rpc/searchservice" + "juwan-backend/common/utils/contextj" + + "github.com/zeromicro/go-zero/core/logx" +) + +type RemoveFavoriteLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 取消收藏 +func NewRemoveFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemoveFavoriteLogic { + return &RemoveFavoriteLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *RemoveFavoriteLogic) RemoveFavorite(req *types.PathIDReq) (resp *types.EmptyResp, err error) { + uid, err := contextj.UserIDFrom(l.ctx) + if err != nil { + return nil, err + } + + current, err := l.svcCtx.SearchRpc.GetFavoritesById(l.ctx, &searchservice.GetFavoritesByIdReq{Id: req.Id}) + if err != nil { + return nil, err + } + if current.GetFavorites() == nil || current.GetFavorites().GetUserId() != uid { + return nil, errors.New("favorite not found") + } + + _, err = l.svcCtx.SearchRpc.DelFavorites(l.ctx, &searchservice.DelFavoritesReq{Id: req.Id}) + if err != nil { + return nil, err + } + + return &types.EmptyResp{}, nil +} diff --git a/app/search/api/internal/logic/search/helpers.go b/app/search/api/internal/logic/search/helpers.go new file mode 100644 index 0000000..8d224b3 --- /dev/null +++ b/app/search/api/internal/logic/search/helpers.go @@ -0,0 +1,17 @@ +package search + +import "juwan-backend/app/search/api/internal/types" + +func emptySearchResp(offset, limit int64) *types.SearchResp { + if limit <= 0 { + limit = 20 + } + return &types.SearchResp{ + Items: make([]interface{}, 0), + Meta: types.PageMeta{ + Total: 0, + Offset: offset, + Limit: limit, + }, + } +} diff --git a/app/search/api/internal/logic/search/recommendationsLogic.go b/app/search/api/internal/logic/search/recommendationsLogic.go new file mode 100644 index 0000000..4da6812 --- /dev/null +++ b/app/search/api/internal/logic/search/recommendationsLogic.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package search + +import ( + "context" + + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type RecommendationsLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 首页推荐 +func NewRecommendationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RecommendationsLogic { + return &RecommendationsLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *RecommendationsLogic) Recommendations(req *types.PageReq) (resp *types.SearchResp, err error) { + return emptySearchResp(req.Offset, req.Limit), nil +} diff --git a/app/search/api/internal/logic/search/searchLogic.go b/app/search/api/internal/logic/search/searchLogic.go new file mode 100644 index 0000000..dc80d47 --- /dev/null +++ b/app/search/api/internal/logic/search/searchLogic.go @@ -0,0 +1,32 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package search + +import ( + "context" + + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/app/search/api/internal/types" + + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +// 统一搜索 +func NewSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchLogic { + return &SearchLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *SearchLogic) Search(req *types.SearchReq) (resp *types.SearchResp, err error) { + return emptySearchResp(req.Offset, req.Limit), nil +} diff --git a/app/search/api/internal/svc/serviceContext.go b/app/search/api/internal/svc/serviceContext.go new file mode 100644 index 0000000..218c80e --- /dev/null +++ b/app/search/api/internal/svc/serviceContext.go @@ -0,0 +1,20 @@ +package svc + +import ( + "juwan-backend/app/search/api/internal/config" + "juwan-backend/app/search/rpc/searchservice" + + "github.com/zeromicro/go-zero/zrpc" +) + +type ServiceContext struct { + Config config.Config + SearchRpc searchservice.SearchService +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + SearchRpc: searchservice.NewSearchService(zrpc.MustNewClient(c.SearchRpcConf)), + } +} diff --git a/app/search/api/internal/types/types.go b/app/search/api/internal/types/types.go new file mode 100644 index 0000000..7680eff --- /dev/null +++ b/app/search/api/internal/types/types.go @@ -0,0 +1,83 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 + +package types + +type EmptyResp struct { +} + +type Favorite struct { + Id string `json:"id"` + UserId string `json:"userId"` + TargetType string `json:"targetType"` + TargetId string `json:"targetId"` + CreatedAt string `json:"createdAt"` +} + +type FavoriteCheckReq struct { + PathIDReq + TargetType string `form:"targetType"` + TargetId string `form:"targetId"` +} + +type FavoriteCheckResp struct { + Favorited bool `json:"favorited"` +} + +type FavoriteListResp struct { + Items []Favorite `json:"items"` + Meta PageMeta `json:"meta"` +} + +type FavoriteReq struct { + TargetType string `json:"targetType"` // player, shop + TargetId string `json:"targetId"` +} + +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 PathIDReq struct { + Id int64 `path:"id"` +} + +type SearchReq struct { + PageReq + Q string `form:"q,optional"` + MinPrice float64 `form:"min,optional"` + MaxPrice float64 `form:"max,optional"` + OnlyOnline bool `form:"onlyOnline,optional"` + Sort string `form:"sort,optional"` +} + +type SearchResp struct { + Items []interface{} `json:"items"` // Mixed 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/search/api/search.go b/app/search/api/search.go new file mode 100644 index 0000000..8cce7f6 --- /dev/null +++ b/app/search/api/search.go @@ -0,0 +1,36 @@ +// Code scaffolded by goctl. Safe to edit. +// goctl 1.10.1 + +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/search/api/internal/config" + "juwan-backend/app/search/api/internal/handler" + "juwan-backend/app/search/api/internal/svc" + "juwan-backend/common/middlewares" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var configFile = flag.String("f", "etc/search-api.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + server.Use(middlewares.NewHeaderExtractorMiddleware().Handle) + 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/search/rpc/etc/pb.yaml b/app/search/rpc/etc/pb.yaml new file mode 100644 index 0000000..0bbfacb --- /dev/null +++ b/app/search/rpc/etc/pb.yaml @@ -0,0 +1,23 @@ +Name: pb.rpc +ListenOn: 0.0.0.0:8080 + +Prometheus: + Host: 0.0.0.0 + Port: 4001 + Path: /metrics + +# ===== DEV CONF ===== +SnowflakeRpcConf: + Endpoints: + - snowflake:8080 + +DB: + Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + Slaves: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable" + +CacheConf: + - Host: "${REDIS_HOST}:${REDIS_PORT}" + Type: node + +Log: + Level: debug diff --git a/app/search/rpc/internal/config/config.go b/app/search/rpc/internal/config/config.go new file mode 100644 index 0000000..f4107e8 --- /dev/null +++ b/app/search/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/search/rpc/internal/logic/addFavoritesLogic.go b/app/search/rpc/internal/logic/addFavoritesLogic.go new file mode 100644 index 0000000..831c442 --- /dev/null +++ b/app/search/rpc/internal/logic/addFavoritesLogic.go @@ -0,0 +1,70 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/search/rpc/internal/models" + "juwan-backend/app/search/rpc/internal/models/favorites" + "juwan-backend/app/search/rpc/internal/svc" + "juwan-backend/app/search/rpc/pb" + "juwan-backend/app/snowflake/rpc/snowflake" + + "github.com/zeromicro/go-zero/core/logx" +) + +type AddFavoritesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewAddFavoritesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddFavoritesLogic { + return &AddFavoritesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *AddFavoritesLogic) AddFavorites(in *pb.AddFavoritesReq) (*pb.AddFavoritesResp, error) { + if in.GetUserId() <= 0 { + return nil, errors.New("userId is required") + } + if !validTargetType(in.GetTargetType()) { + return nil, errors.New("invalid targetType") + } + if in.GetTargetId() <= 0 { + return nil, errors.New("targetId is required") + } + + idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{}) + if err != nil { + return nil, errors.New("create favorite id failed") + } + + created, err := l.svcCtx.SearchModelRW.Favorites.Create(). + SetID(idResp.Id). + SetUserID(in.GetUserId()). + SetTargetType(in.GetTargetType()). + SetTargetID(in.GetTargetId()). + Save(l.ctx) + if err != nil { + if models.IsConstraintError(err) { + existing, getErr := l.svcCtx.SearchModelRW.Favorites.Query(). + Where( + favorites.UserIDEQ(in.GetUserId()), + favorites.TargetTypeEQ(in.GetTargetType()), + favorites.TargetIDEQ(in.GetTargetId()), + ). + Only(l.ctx) + if getErr == nil { + return &pb.AddFavoritesResp{Id: existing.ID}, nil + } + } + logx.Errorf("addFavorites err: %v", err) + return nil, errors.New("add favorite failed") + } + + return &pb.AddFavoritesResp{Id: created.ID}, nil +} diff --git a/app/search/rpc/internal/logic/delFavoritesLogic.go b/app/search/rpc/internal/logic/delFavoritesLogic.go new file mode 100644 index 0000000..0a5dbcc --- /dev/null +++ b/app/search/rpc/internal/logic/delFavoritesLogic.go @@ -0,0 +1,34 @@ +package logic + +import ( + "context" + + "juwan-backend/app/search/rpc/internal/svc" + "juwan-backend/app/search/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type DelFavoritesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewDelFavoritesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelFavoritesLogic { + return &DelFavoritesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *DelFavoritesLogic) DelFavorites(in *pb.DelFavoritesReq) (*pb.DelFavoritesResp, error) { + err := l.svcCtx.SearchModelRW.Favorites.DeleteOneID(in.GetId()).Exec(l.ctx) + if err != nil { + logx.Errorf("delFavorites err: %v", err) + return nil, err + } + + return &pb.DelFavoritesResp{}, nil +} diff --git a/app/search/rpc/internal/logic/getFavoritesByIdLogic.go b/app/search/rpc/internal/logic/getFavoritesByIdLogic.go new file mode 100644 index 0000000..85dc4c7 --- /dev/null +++ b/app/search/rpc/internal/logic/getFavoritesByIdLogic.go @@ -0,0 +1,33 @@ +package logic + +import ( + "context" + + "juwan-backend/app/search/rpc/internal/svc" + "juwan-backend/app/search/rpc/pb" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetFavoritesByIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetFavoritesByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFavoritesByIdLogic { + return &GetFavoritesByIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *GetFavoritesByIdLogic) GetFavoritesById(in *pb.GetFavoritesByIdReq) (*pb.GetFavoritesByIdResp, error) { + f, err := l.svcCtx.SearchModelRO.Favorites.Get(l.ctx, in.GetId()) + if err != nil { + return nil, err + } + + return &pb.GetFavoritesByIdResp{Favorites: entFavoriteToPb(f)}, nil +} diff --git a/app/search/rpc/internal/logic/helpers.go b/app/search/rpc/internal/logic/helpers.go new file mode 100644 index 0000000..5897729 --- /dev/null +++ b/app/search/rpc/internal/logic/helpers.go @@ -0,0 +1,20 @@ +package logic + +import ( + "juwan-backend/app/search/rpc/internal/models" + "juwan-backend/app/search/rpc/pb" +) + +func entFavoriteToPb(f *models.Favorites) *pb.Favorites { + return &pb.Favorites{ + Id: f.ID, + UserId: f.UserID, + TargetType: f.TargetType, + TargetId: f.TargetID, + CreatedAt: f.CreatedAt.Unix(), + } +} + +func validTargetType(targetType string) bool { + return targetType == "player" || targetType == "shop" +} diff --git a/app/search/rpc/internal/logic/searchFavoritesLogic.go b/app/search/rpc/internal/logic/searchFavoritesLogic.go new file mode 100644 index 0000000..43de74b --- /dev/null +++ b/app/search/rpc/internal/logic/searchFavoritesLogic.go @@ -0,0 +1,72 @@ +package logic + +import ( + "context" + "errors" + + "juwan-backend/app/search/rpc/internal/models/favorites" + "juwan-backend/app/search/rpc/internal/svc" + "juwan-backend/app/search/rpc/pb" + + "entgo.io/ent/dialect/sql" + "github.com/zeromicro/go-zero/core/logx" +) + +type SearchFavoritesLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewSearchFavoritesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchFavoritesLogic { + return &SearchFavoritesLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +func (l *SearchFavoritesLogic) SearchFavorites(in *pb.SearchFavoritesReq) (*pb.SearchFavoritesResp, error) { + limit := in.GetLimit() + if limit <= 0 { + limit = 20 + } + if limit > 100 { + return nil, errors.New("limit too large") + } + offset := in.GetOffset() + if offset < 0 { + offset = 0 + } + + query := l.svcCtx.SearchModelRO.Favorites.Query() + if in.Id != nil { + query = query.Where(favorites.IDEQ(in.GetId())) + } + if in.UserId != nil { + query = query.Where(favorites.UserIDEQ(in.GetUserId())) + } + if in.TargetType != nil { + query = query.Where(favorites.TargetTypeEQ(in.GetTargetType())) + } + if in.TargetId != nil { + query = query.Where(favorites.TargetIDEQ(in.GetTargetId())) + } + + list, err := query. + Order(favorites.ByCreatedAt(sql.OrderDesc()), favorites.ByID(sql.OrderDesc())). + Offset(int(offset)). + Limit(int(limit)). + All(l.ctx) + if err != nil { + logx.Errorf("searchFavorites err: %v", err) + return nil, errors.New("search favorites failed") + } + + out := make([]*pb.Favorites, len(list)) + for i, f := range list { + out[i] = entFavoriteToPb(f) + } + + return &pb.SearchFavoritesResp{Favorites: out}, nil +} diff --git a/app/search/rpc/internal/models/client.go b/app/search/rpc/internal/models/client.go new file mode 100644 index 0000000..1c9d066 --- /dev/null +++ b/app/search/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/search/rpc/internal/models/migrate" + + "juwan-backend/app/search/rpc/internal/models/favorites" + + "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 + // Favorites is the client for interacting with the Favorites builders. + Favorites *FavoritesClient +} + +// 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.Favorites = NewFavoritesClient(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, + Favorites: NewFavoritesClient(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, + Favorites: NewFavoritesClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Favorites. +// 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.Favorites.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.Favorites.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *FavoritesMutation: + return c.Favorites.mutate(ctx, m) + default: + return nil, fmt.Errorf("models: unknown mutation type %T", m) + } +} + +// FavoritesClient is a client for the Favorites schema. +type FavoritesClient struct { + config +} + +// NewFavoritesClient returns a client for the Favorites from the given config. +func NewFavoritesClient(c config) *FavoritesClient { + return &FavoritesClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `favorites.Hooks(f(g(h())))`. +func (c *FavoritesClient) Use(hooks ...Hook) { + c.hooks.Favorites = append(c.hooks.Favorites, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `favorites.Intercept(f(g(h())))`. +func (c *FavoritesClient) Intercept(interceptors ...Interceptor) { + c.inters.Favorites = append(c.inters.Favorites, interceptors...) +} + +// Create returns a builder for creating a Favorites entity. +func (c *FavoritesClient) Create() *FavoritesCreate { + mutation := newFavoritesMutation(c.config, OpCreate) + return &FavoritesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Favorites entities. +func (c *FavoritesClient) CreateBulk(builders ...*FavoritesCreate) *FavoritesCreateBulk { + return &FavoritesCreateBulk{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 *FavoritesClient) MapCreateBulk(slice any, setFunc func(*FavoritesCreate, int)) *FavoritesCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &FavoritesCreateBulk{err: fmt.Errorf("calling to FavoritesClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*FavoritesCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &FavoritesCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Favorites. +func (c *FavoritesClient) Update() *FavoritesUpdate { + mutation := newFavoritesMutation(c.config, OpUpdate) + return &FavoritesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *FavoritesClient) UpdateOne(_m *Favorites) *FavoritesUpdateOne { + mutation := newFavoritesMutation(c.config, OpUpdateOne, withFavorites(_m)) + return &FavoritesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *FavoritesClient) UpdateOneID(id int64) *FavoritesUpdateOne { + mutation := newFavoritesMutation(c.config, OpUpdateOne, withFavoritesID(id)) + return &FavoritesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Favorites. +func (c *FavoritesClient) Delete() *FavoritesDelete { + mutation := newFavoritesMutation(c.config, OpDelete) + return &FavoritesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *FavoritesClient) DeleteOne(_m *Favorites) *FavoritesDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *FavoritesClient) DeleteOneID(id int64) *FavoritesDeleteOne { + builder := c.Delete().Where(favorites.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &FavoritesDeleteOne{builder} +} + +// Query returns a query builder for Favorites. +func (c *FavoritesClient) Query() *FavoritesQuery { + return &FavoritesQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeFavorites}, + inters: c.Interceptors(), + } +} + +// Get returns a Favorites entity by its id. +func (c *FavoritesClient) Get(ctx context.Context, id int64) (*Favorites, error) { + return c.Query().Where(favorites.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *FavoritesClient) GetX(ctx context.Context, id int64) *Favorites { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *FavoritesClient) Hooks() []Hook { + return c.hooks.Favorites +} + +// Interceptors returns the client interceptors. +func (c *FavoritesClient) Interceptors() []Interceptor { + return c.inters.Favorites +} + +func (c *FavoritesClient) mutate(ctx context.Context, m *FavoritesMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&FavoritesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&FavoritesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&FavoritesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&FavoritesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("models: unknown Favorites mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Favorites []ent.Hook + } + inters struct { + Favorites []ent.Interceptor + } +) diff --git a/app/search/rpc/internal/models/ent.go b/app/search/rpc/internal/models/ent.go new file mode 100644 index 0000000..4bd9e8e --- /dev/null +++ b/app/search/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/search/rpc/internal/models/favorites" + "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{ + favorites.Table: favorites.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/search/rpc/internal/models/enttest/enttest.go b/app/search/rpc/internal/models/enttest/enttest.go new file mode 100644 index 0000000..d652e20 --- /dev/null +++ b/app/search/rpc/internal/models/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "juwan-backend/app/search/rpc/internal/models" + // required by schema hooks. + _ "juwan-backend/app/search/rpc/internal/models/runtime" + + "juwan-backend/app/search/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/search/rpc/internal/models/favorites.go b/app/search/rpc/internal/models/favorites.go new file mode 100644 index 0000000..c3af321 --- /dev/null +++ b/app/search/rpc/internal/models/favorites.go @@ -0,0 +1,139 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "fmt" + "juwan-backend/app/search/rpc/internal/models/favorites" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Favorites is the model entity for the Favorites schema. +type Favorites struct { + config `json:"-"` + // ID of the ent. + ID int64 `json:"id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int64 `json:"user_id,omitempty"` + // TargetType holds the value of the "target_type" field. + TargetType string `json:"target_type,omitempty"` + // TargetID holds the value of the "target_id" field. + TargetID int64 `json:"target_id,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 (*Favorites) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case favorites.FieldID, favorites.FieldUserID, favorites.FieldTargetID: + values[i] = new(sql.NullInt64) + case favorites.FieldTargetType: + values[i] = new(sql.NullString) + case favorites.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 Favorites fields. +func (_m *Favorites) 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 favorites.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 favorites.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 favorites.FieldTargetType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field target_type", values[i]) + } else if value.Valid { + _m.TargetType = value.String + } + case favorites.FieldTargetID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field target_id", values[i]) + } else if value.Valid { + _m.TargetID = value.Int64 + } + case favorites.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 Favorites. +// This includes values selected through modifiers, order, etc. +func (_m *Favorites) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Favorites. +// Note that you need to call Favorites.Unwrap() before calling this method if this Favorites +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Favorites) Update() *FavoritesUpdateOne { + return NewFavoritesClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Favorites 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 *Favorites) Unwrap() *Favorites { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("models: Favorites is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Favorites) String() string { + var builder strings.Builder + builder.WriteString("Favorites(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("target_type=") + builder.WriteString(_m.TargetType) + builder.WriteString(", ") + builder.WriteString("target_id=") + builder.WriteString(fmt.Sprintf("%v", _m.TargetID)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// FavoritesSlice is a parsable slice of Favorites. +type FavoritesSlice []*Favorites diff --git a/app/search/rpc/internal/models/favorites/favorites.go b/app/search/rpc/internal/models/favorites/favorites.go new file mode 100644 index 0000000..4552c8d --- /dev/null +++ b/app/search/rpc/internal/models/favorites/favorites.go @@ -0,0 +1,80 @@ +// Code generated by ent, DO NOT EDIT. + +package favorites + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the favorites type in the database. + Label = "favorites" + // 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" + // FieldTargetType holds the string denoting the target_type field in the database. + FieldTargetType = "target_type" + // FieldTargetID holds the string denoting the target_id field in the database. + FieldTargetID = "target_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // Table holds the table name of the favorites in the database. + Table = "favorites" +) + +// Columns holds all SQL columns for favorites fields. +var Columns = []string{ + FieldID, + FieldUserID, + FieldTargetType, + FieldTargetID, + 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 ( + // TargetTypeValidator is a validator for the "target_type" field. It is called by the builders before save. + TargetTypeValidator 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 Favorites 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() +} + +// ByTargetType orders the results by the target_type field. +func ByTargetType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTargetType, opts...).ToFunc() +} + +// ByTargetID orders the results by the target_id field. +func ByTargetID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTargetID, 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/search/rpc/internal/models/favorites/where.go b/app/search/rpc/internal/models/favorites/where.go new file mode 100644 index 0000000..a0174be --- /dev/null +++ b/app/search/rpc/internal/models/favorites/where.go @@ -0,0 +1,275 @@ +// Code generated by ent, DO NOT EDIT. + +package favorites + +import ( + "juwan-backend/app/search/rpc/internal/models/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int64) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int64) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int64) predicate.Favorites { + return predicate.Favorites(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int64) predicate.Favorites { + return predicate.Favorites(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int64) predicate.Favorites { + return predicate.Favorites(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int64) predicate.Favorites { + return predicate.Favorites(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int64) predicate.Favorites { + return predicate.Favorites(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int64) predicate.Favorites { + return predicate.Favorites(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int64) predicate.Favorites { + return predicate.Favorites(sql.FieldLTE(FieldID, id)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldUserID, v)) +} + +// TargetType applies equality check predicate on the "target_type" field. It's identical to TargetTypeEQ. +func TargetType(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldTargetType, v)) +} + +// TargetID applies equality check predicate on the "target_id" field. It's identical to TargetIDEQ. +func TargetID(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldTargetID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.Favorites { + return predicate.Favorites(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.Favorites { + return predicate.Favorites(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldLTE(FieldUserID, v)) +} + +// TargetTypeEQ applies the EQ predicate on the "target_type" field. +func TargetTypeEQ(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldTargetType, v)) +} + +// TargetTypeNEQ applies the NEQ predicate on the "target_type" field. +func TargetTypeNEQ(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldNEQ(FieldTargetType, v)) +} + +// TargetTypeIn applies the In predicate on the "target_type" field. +func TargetTypeIn(vs ...string) predicate.Favorites { + return predicate.Favorites(sql.FieldIn(FieldTargetType, vs...)) +} + +// TargetTypeNotIn applies the NotIn predicate on the "target_type" field. +func TargetTypeNotIn(vs ...string) predicate.Favorites { + return predicate.Favorites(sql.FieldNotIn(FieldTargetType, vs...)) +} + +// TargetTypeGT applies the GT predicate on the "target_type" field. +func TargetTypeGT(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldGT(FieldTargetType, v)) +} + +// TargetTypeGTE applies the GTE predicate on the "target_type" field. +func TargetTypeGTE(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldGTE(FieldTargetType, v)) +} + +// TargetTypeLT applies the LT predicate on the "target_type" field. +func TargetTypeLT(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldLT(FieldTargetType, v)) +} + +// TargetTypeLTE applies the LTE predicate on the "target_type" field. +func TargetTypeLTE(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldLTE(FieldTargetType, v)) +} + +// TargetTypeContains applies the Contains predicate on the "target_type" field. +func TargetTypeContains(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldContains(FieldTargetType, v)) +} + +// TargetTypeHasPrefix applies the HasPrefix predicate on the "target_type" field. +func TargetTypeHasPrefix(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldHasPrefix(FieldTargetType, v)) +} + +// TargetTypeHasSuffix applies the HasSuffix predicate on the "target_type" field. +func TargetTypeHasSuffix(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldHasSuffix(FieldTargetType, v)) +} + +// TargetTypeEqualFold applies the EqualFold predicate on the "target_type" field. +func TargetTypeEqualFold(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldEqualFold(FieldTargetType, v)) +} + +// TargetTypeContainsFold applies the ContainsFold predicate on the "target_type" field. +func TargetTypeContainsFold(v string) predicate.Favorites { + return predicate.Favorites(sql.FieldContainsFold(FieldTargetType, v)) +} + +// TargetIDEQ applies the EQ predicate on the "target_id" field. +func TargetIDEQ(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldTargetID, v)) +} + +// TargetIDNEQ applies the NEQ predicate on the "target_id" field. +func TargetIDNEQ(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldNEQ(FieldTargetID, v)) +} + +// TargetIDIn applies the In predicate on the "target_id" field. +func TargetIDIn(vs ...int64) predicate.Favorites { + return predicate.Favorites(sql.FieldIn(FieldTargetID, vs...)) +} + +// TargetIDNotIn applies the NotIn predicate on the "target_id" field. +func TargetIDNotIn(vs ...int64) predicate.Favorites { + return predicate.Favorites(sql.FieldNotIn(FieldTargetID, vs...)) +} + +// TargetIDGT applies the GT predicate on the "target_id" field. +func TargetIDGT(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldGT(FieldTargetID, v)) +} + +// TargetIDGTE applies the GTE predicate on the "target_id" field. +func TargetIDGTE(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldGTE(FieldTargetID, v)) +} + +// TargetIDLT applies the LT predicate on the "target_id" field. +func TargetIDLT(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldLT(FieldTargetID, v)) +} + +// TargetIDLTE applies the LTE predicate on the "target_id" field. +func TargetIDLTE(v int64) predicate.Favorites { + return predicate.Favorites(sql.FieldLTE(FieldTargetID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Favorites { + return predicate.Favorites(sql.FieldLTE(FieldCreatedAt, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Favorites) predicate.Favorites { + return predicate.Favorites(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Favorites) predicate.Favorites { + return predicate.Favorites(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Favorites) predicate.Favorites { + return predicate.Favorites(sql.NotPredicates(p)) +} diff --git a/app/search/rpc/internal/models/favorites_create.go b/app/search/rpc/internal/models/favorites_create.go new file mode 100644 index 0000000..4abee17 --- /dev/null +++ b/app/search/rpc/internal/models/favorites_create.go @@ -0,0 +1,258 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/search/rpc/internal/models/favorites" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FavoritesCreate is the builder for creating a Favorites entity. +type FavoritesCreate struct { + config + mutation *FavoritesMutation + hooks []Hook +} + +// SetUserID sets the "user_id" field. +func (_c *FavoritesCreate) SetUserID(v int64) *FavoritesCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetTargetType sets the "target_type" field. +func (_c *FavoritesCreate) SetTargetType(v string) *FavoritesCreate { + _c.mutation.SetTargetType(v) + return _c +} + +// SetTargetID sets the "target_id" field. +func (_c *FavoritesCreate) SetTargetID(v int64) *FavoritesCreate { + _c.mutation.SetTargetID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *FavoritesCreate) SetCreatedAt(v time.Time) *FavoritesCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *FavoritesCreate) SetNillableCreatedAt(v *time.Time) *FavoritesCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *FavoritesCreate) SetID(v int64) *FavoritesCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the FavoritesMutation object of the builder. +func (_c *FavoritesCreate) Mutation() *FavoritesMutation { + return _c.mutation +} + +// Save creates the Favorites in the database. +func (_c *FavoritesCreate) Save(ctx context.Context) (*Favorites, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *FavoritesCreate) SaveX(ctx context.Context) *Favorites { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *FavoritesCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *FavoritesCreate) 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 *FavoritesCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := favorites.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *FavoritesCreate) check() error { + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "Favorites.user_id"`)} + } + if _, ok := _c.mutation.TargetType(); !ok { + return &ValidationError{Name: "target_type", err: errors.New(`models: missing required field "Favorites.target_type"`)} + } + if v, ok := _c.mutation.TargetType(); ok { + if err := favorites.TargetTypeValidator(v); err != nil { + return &ValidationError{Name: "target_type", err: fmt.Errorf(`models: validator failed for field "Favorites.target_type": %w`, err)} + } + } + if _, ok := _c.mutation.TargetID(); !ok { + return &ValidationError{Name: "target_id", err: errors.New(`models: missing required field "Favorites.target_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Favorites.created_at"`)} + } + return nil +} + +func (_c *FavoritesCreate) sqlSave(ctx context.Context) (*Favorites, 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 *FavoritesCreate) createSpec() (*Favorites, *sqlgraph.CreateSpec) { + var ( + _node = &Favorites{config: _c.config} + _spec = sqlgraph.NewCreateSpec(favorites.Table, sqlgraph.NewFieldSpec(favorites.FieldID, field.TypeInt64)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(favorites.FieldUserID, field.TypeInt64, value) + _node.UserID = value + } + if value, ok := _c.mutation.TargetType(); ok { + _spec.SetField(favorites.FieldTargetType, field.TypeString, value) + _node.TargetType = value + } + if value, ok := _c.mutation.TargetID(); ok { + _spec.SetField(favorites.FieldTargetID, field.TypeInt64, value) + _node.TargetID = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(favorites.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + return _node, _spec +} + +// FavoritesCreateBulk is the builder for creating many Favorites entities in bulk. +type FavoritesCreateBulk struct { + config + err error + builders []*FavoritesCreate +} + +// Save creates the Favorites entities in the database. +func (_c *FavoritesCreateBulk) Save(ctx context.Context) ([]*Favorites, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Favorites, 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.(*FavoritesMutation) + 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 *FavoritesCreateBulk) SaveX(ctx context.Context) []*Favorites { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *FavoritesCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *FavoritesCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/search/rpc/internal/models/favorites_delete.go b/app/search/rpc/internal/models/favorites_delete.go new file mode 100644 index 0000000..4077bdc --- /dev/null +++ b/app/search/rpc/internal/models/favorites_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "juwan-backend/app/search/rpc/internal/models/favorites" + "juwan-backend/app/search/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FavoritesDelete is the builder for deleting a Favorites entity. +type FavoritesDelete struct { + config + hooks []Hook + mutation *FavoritesMutation +} + +// Where appends a list predicates to the FavoritesDelete builder. +func (_d *FavoritesDelete) Where(ps ...predicate.Favorites) *FavoritesDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *FavoritesDelete) 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 *FavoritesDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *FavoritesDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(favorites.Table, sqlgraph.NewFieldSpec(favorites.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 +} + +// FavoritesDeleteOne is the builder for deleting a single Favorites entity. +type FavoritesDeleteOne struct { + _d *FavoritesDelete +} + +// Where appends a list predicates to the FavoritesDelete builder. +func (_d *FavoritesDeleteOne) Where(ps ...predicate.Favorites) *FavoritesDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *FavoritesDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{favorites.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *FavoritesDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/search/rpc/internal/models/favorites_query.go b/app/search/rpc/internal/models/favorites_query.go new file mode 100644 index 0000000..a9e0953 --- /dev/null +++ b/app/search/rpc/internal/models/favorites_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "fmt" + "juwan-backend/app/search/rpc/internal/models/favorites" + "juwan-backend/app/search/rpc/internal/models/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FavoritesQuery is the builder for querying Favorites entities. +type FavoritesQuery struct { + config + ctx *QueryContext + order []favorites.OrderOption + inters []Interceptor + predicates []predicate.Favorites + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the FavoritesQuery builder. +func (_q *FavoritesQuery) Where(ps ...predicate.Favorites) *FavoritesQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *FavoritesQuery) Limit(limit int) *FavoritesQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *FavoritesQuery) Offset(offset int) *FavoritesQuery { + _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 *FavoritesQuery) Unique(unique bool) *FavoritesQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *FavoritesQuery) Order(o ...favorites.OrderOption) *FavoritesQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Favorites entity from the query. +// Returns a *NotFoundError when no Favorites was found. +func (_q *FavoritesQuery) First(ctx context.Context) (*Favorites, 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{favorites.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *FavoritesQuery) FirstX(ctx context.Context) *Favorites { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Favorites ID from the query. +// Returns a *NotFoundError when no Favorites ID was found. +func (_q *FavoritesQuery) 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{favorites.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *FavoritesQuery) FirstIDX(ctx context.Context) int64 { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Favorites entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Favorites entity is found. +// Returns a *NotFoundError when no Favorites entities are found. +func (_q *FavoritesQuery) Only(ctx context.Context) (*Favorites, 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{favorites.Label} + default: + return nil, &NotSingularError{favorites.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *FavoritesQuery) OnlyX(ctx context.Context) *Favorites { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Favorites ID in the query. +// Returns a *NotSingularError when more than one Favorites ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *FavoritesQuery) 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{favorites.Label} + default: + err = &NotSingularError{favorites.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *FavoritesQuery) 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 FavoritesSlice. +func (_q *FavoritesQuery) All(ctx context.Context) ([]*Favorites, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Favorites, *FavoritesQuery]() + return withInterceptors[[]*Favorites](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *FavoritesQuery) AllX(ctx context.Context) []*Favorites { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Favorites IDs. +func (_q *FavoritesQuery) 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(favorites.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *FavoritesQuery) 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 *FavoritesQuery) 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[*FavoritesQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *FavoritesQuery) 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 *FavoritesQuery) 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 *FavoritesQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the FavoritesQuery 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 *FavoritesQuery) Clone() *FavoritesQuery { + if _q == nil { + return nil + } + return &FavoritesQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]favorites.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Favorites{}, _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.Favorites.Query(). +// GroupBy(favorites.FieldUserID). +// Aggregate(models.Count()). +// Scan(ctx, &v) +func (_q *FavoritesQuery) GroupBy(field string, fields ...string) *FavoritesGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &FavoritesGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = favorites.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.Favorites.Query(). +// Select(favorites.FieldUserID). +// Scan(ctx, &v) +func (_q *FavoritesQuery) Select(fields ...string) *FavoritesSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &FavoritesSelect{FavoritesQuery: _q} + sbuild.label = favorites.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a FavoritesSelect configured with the given aggregations. +func (_q *FavoritesQuery) Aggregate(fns ...AggregateFunc) *FavoritesSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *FavoritesQuery) 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 !favorites.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 *FavoritesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Favorites, error) { + var ( + nodes = []*Favorites{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Favorites).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Favorites{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 *FavoritesQuery) 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 *FavoritesQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(favorites.Table, favorites.Columns, sqlgraph.NewFieldSpec(favorites.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, favorites.FieldID) + for i := range fields { + if fields[i] != favorites.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 *FavoritesQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(favorites.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = favorites.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 +} + +// FavoritesGroupBy is the group-by builder for Favorites entities. +type FavoritesGroupBy struct { + selector + build *FavoritesQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *FavoritesGroupBy) Aggregate(fns ...AggregateFunc) *FavoritesGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *FavoritesGroupBy) 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[*FavoritesQuery, *FavoritesGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *FavoritesGroupBy) sqlScan(ctx context.Context, root *FavoritesQuery, 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) +} + +// FavoritesSelect is the builder for selecting fields of Favorites entities. +type FavoritesSelect struct { + *FavoritesQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *FavoritesSelect) Aggregate(fns ...AggregateFunc) *FavoritesSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *FavoritesSelect) 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[*FavoritesQuery, *FavoritesSelect](ctx, _s.FavoritesQuery, _s, _s.inters, v) +} + +func (_s *FavoritesSelect) sqlScan(ctx context.Context, root *FavoritesQuery, 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/search/rpc/internal/models/favorites_update.go b/app/search/rpc/internal/models/favorites_update.go new file mode 100644 index 0000000..e3df04b --- /dev/null +++ b/app/search/rpc/internal/models/favorites_update.go @@ -0,0 +1,343 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/search/rpc/internal/models/favorites" + "juwan-backend/app/search/rpc/internal/models/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FavoritesUpdate is the builder for updating Favorites entities. +type FavoritesUpdate struct { + config + hooks []Hook + mutation *FavoritesMutation +} + +// Where appends a list predicates to the FavoritesUpdate builder. +func (_u *FavoritesUpdate) Where(ps ...predicate.Favorites) *FavoritesUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *FavoritesUpdate) SetUserID(v int64) *FavoritesUpdate { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *FavoritesUpdate) SetNillableUserID(v *int64) *FavoritesUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *FavoritesUpdate) AddUserID(v int64) *FavoritesUpdate { + _u.mutation.AddUserID(v) + return _u +} + +// SetTargetType sets the "target_type" field. +func (_u *FavoritesUpdate) SetTargetType(v string) *FavoritesUpdate { + _u.mutation.SetTargetType(v) + return _u +} + +// SetNillableTargetType sets the "target_type" field if the given value is not nil. +func (_u *FavoritesUpdate) SetNillableTargetType(v *string) *FavoritesUpdate { + if v != nil { + _u.SetTargetType(*v) + } + return _u +} + +// SetTargetID sets the "target_id" field. +func (_u *FavoritesUpdate) SetTargetID(v int64) *FavoritesUpdate { + _u.mutation.ResetTargetID() + _u.mutation.SetTargetID(v) + return _u +} + +// SetNillableTargetID sets the "target_id" field if the given value is not nil. +func (_u *FavoritesUpdate) SetNillableTargetID(v *int64) *FavoritesUpdate { + if v != nil { + _u.SetTargetID(*v) + } + return _u +} + +// AddTargetID adds value to the "target_id" field. +func (_u *FavoritesUpdate) AddTargetID(v int64) *FavoritesUpdate { + _u.mutation.AddTargetID(v) + return _u +} + +// Mutation returns the FavoritesMutation object of the builder. +func (_u *FavoritesUpdate) Mutation() *FavoritesMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *FavoritesUpdate) 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 *FavoritesUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *FavoritesUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *FavoritesUpdate) 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 *FavoritesUpdate) check() error { + if v, ok := _u.mutation.TargetType(); ok { + if err := favorites.TargetTypeValidator(v); err != nil { + return &ValidationError{Name: "target_type", err: fmt.Errorf(`models: validator failed for field "Favorites.target_type": %w`, err)} + } + } + return nil +} + +func (_u *FavoritesUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(favorites.Table, favorites.Columns, sqlgraph.NewFieldSpec(favorites.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.UserID(); ok { + _spec.SetField(favorites.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(favorites.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.TargetType(); ok { + _spec.SetField(favorites.FieldTargetType, field.TypeString, value) + } + if value, ok := _u.mutation.TargetID(); ok { + _spec.SetField(favorites.FieldTargetID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTargetID(); ok { + _spec.AddField(favorites.FieldTargetID, field.TypeInt64, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{favorites.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// FavoritesUpdateOne is the builder for updating a single Favorites entity. +type FavoritesUpdateOne struct { + config + fields []string + hooks []Hook + mutation *FavoritesMutation +} + +// SetUserID sets the "user_id" field. +func (_u *FavoritesUpdateOne) SetUserID(v int64) *FavoritesUpdateOne { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *FavoritesUpdateOne) SetNillableUserID(v *int64) *FavoritesUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *FavoritesUpdateOne) AddUserID(v int64) *FavoritesUpdateOne { + _u.mutation.AddUserID(v) + return _u +} + +// SetTargetType sets the "target_type" field. +func (_u *FavoritesUpdateOne) SetTargetType(v string) *FavoritesUpdateOne { + _u.mutation.SetTargetType(v) + return _u +} + +// SetNillableTargetType sets the "target_type" field if the given value is not nil. +func (_u *FavoritesUpdateOne) SetNillableTargetType(v *string) *FavoritesUpdateOne { + if v != nil { + _u.SetTargetType(*v) + } + return _u +} + +// SetTargetID sets the "target_id" field. +func (_u *FavoritesUpdateOne) SetTargetID(v int64) *FavoritesUpdateOne { + _u.mutation.ResetTargetID() + _u.mutation.SetTargetID(v) + return _u +} + +// SetNillableTargetID sets the "target_id" field if the given value is not nil. +func (_u *FavoritesUpdateOne) SetNillableTargetID(v *int64) *FavoritesUpdateOne { + if v != nil { + _u.SetTargetID(*v) + } + return _u +} + +// AddTargetID adds value to the "target_id" field. +func (_u *FavoritesUpdateOne) AddTargetID(v int64) *FavoritesUpdateOne { + _u.mutation.AddTargetID(v) + return _u +} + +// Mutation returns the FavoritesMutation object of the builder. +func (_u *FavoritesUpdateOne) Mutation() *FavoritesMutation { + return _u.mutation +} + +// Where appends a list predicates to the FavoritesUpdate builder. +func (_u *FavoritesUpdateOne) Where(ps ...predicate.Favorites) *FavoritesUpdateOne { + _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 *FavoritesUpdateOne) Select(field string, fields ...string) *FavoritesUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Favorites entity. +func (_u *FavoritesUpdateOne) Save(ctx context.Context) (*Favorites, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *FavoritesUpdateOne) SaveX(ctx context.Context) *Favorites { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *FavoritesUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *FavoritesUpdateOne) 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 *FavoritesUpdateOne) check() error { + if v, ok := _u.mutation.TargetType(); ok { + if err := favorites.TargetTypeValidator(v); err != nil { + return &ValidationError{Name: "target_type", err: fmt.Errorf(`models: validator failed for field "Favorites.target_type": %w`, err)} + } + } + return nil +} + +func (_u *FavoritesUpdateOne) sqlSave(ctx context.Context) (_node *Favorites, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(favorites.Table, favorites.Columns, sqlgraph.NewFieldSpec(favorites.FieldID, field.TypeInt64)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Favorites.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, favorites.FieldID) + for _, f := range fields { + if !favorites.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)} + } + if f != favorites.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.UserID(); ok { + _spec.SetField(favorites.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(favorites.FieldUserID, field.TypeInt64, value) + } + if value, ok := _u.mutation.TargetType(); ok { + _spec.SetField(favorites.FieldTargetType, field.TypeString, value) + } + if value, ok := _u.mutation.TargetID(); ok { + _spec.SetField(favorites.FieldTargetID, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTargetID(); ok { + _spec.AddField(favorites.FieldTargetID, field.TypeInt64, value) + } + _node = &Favorites{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{favorites.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/search/rpc/internal/models/generate.go b/app/search/rpc/internal/models/generate.go new file mode 100644 index 0000000..d441aca --- /dev/null +++ b/app/search/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/search/rpc/internal/models/hook/hook.go b/app/search/rpc/internal/models/hook/hook.go new file mode 100644 index 0000000..4bd9d61 --- /dev/null +++ b/app/search/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/search/rpc/internal/models" +) + +// The FavoritesFunc type is an adapter to allow the use of ordinary +// function as Favorites mutator. +type FavoritesFunc func(context.Context, *models.FavoritesMutation) (models.Value, error) + +// Mutate calls f(ctx, m). +func (f FavoritesFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) { + if mv, ok := m.(*models.FavoritesMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *models.FavoritesMutation", 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/search/rpc/internal/models/migrate/migrate.go b/app/search/rpc/internal/models/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/app/search/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/search/rpc/internal/models/migrate/schema.go b/app/search/rpc/internal/models/migrate/schema.go new file mode 100644 index 0000000..c9543b2 --- /dev/null +++ b/app/search/rpc/internal/models/migrate/schema.go @@ -0,0 +1,54 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // FavoritesColumns holds the columns for the "favorites" table. + FavoritesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt64, Increment: true}, + {Name: "user_id", Type: field.TypeInt64}, + {Name: "target_type", Type: field.TypeString, Size: 20}, + {Name: "target_id", Type: field.TypeInt64}, + {Name: "created_at", Type: field.TypeTime}, + } + // FavoritesTable holds the schema information for the "favorites" table. + FavoritesTable = &schema.Table{ + Name: "favorites", + Columns: FavoritesColumns, + PrimaryKey: []*schema.Column{FavoritesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "favorites_user_id_target_type_target_id", + Unique: true, + Columns: []*schema.Column{FavoritesColumns[1], FavoritesColumns[2], FavoritesColumns[3]}, + }, + { + Name: "favorites_user_id_created_at", + Unique: false, + Columns: []*schema.Column{FavoritesColumns[1], FavoritesColumns[4]}, + }, + { + Name: "favorites_target_type_target_id", + Unique: false, + Columns: []*schema.Column{FavoritesColumns[2], FavoritesColumns[3]}, + }, + { + Name: "favorites_user_id_target_type_created_at", + Unique: false, + Columns: []*schema.Column{FavoritesColumns[1], FavoritesColumns[2], FavoritesColumns[4]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + FavoritesTable, + } +) + +func init() { +} diff --git a/app/search/rpc/internal/models/mutation.go b/app/search/rpc/internal/models/mutation.go new file mode 100644 index 0000000..0d1333b --- /dev/null +++ b/app/search/rpc/internal/models/mutation.go @@ -0,0 +1,591 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "context" + "errors" + "fmt" + "juwan-backend/app/search/rpc/internal/models/favorites" + "juwan-backend/app/search/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. + TypeFavorites = "Favorites" +) + +// FavoritesMutation represents an operation that mutates the Favorites nodes in the graph. +type FavoritesMutation struct { + config + op Op + typ string + id *int64 + user_id *int64 + adduser_id *int64 + target_type *string + target_id *int64 + addtarget_id *int64 + created_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Favorites, error) + predicates []predicate.Favorites +} + +var _ ent.Mutation = (*FavoritesMutation)(nil) + +// favoritesOption allows management of the mutation configuration using functional options. +type favoritesOption func(*FavoritesMutation) + +// newFavoritesMutation creates new mutation for the Favorites entity. +func newFavoritesMutation(c config, op Op, opts ...favoritesOption) *FavoritesMutation { + m := &FavoritesMutation{ + config: c, + op: op, + typ: TypeFavorites, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withFavoritesID sets the ID field of the mutation. +func withFavoritesID(id int64) favoritesOption { + return func(m *FavoritesMutation) { + var ( + err error + once sync.Once + value *Favorites + ) + m.oldValue = func(ctx context.Context) (*Favorites, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Favorites.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withFavorites sets the old Favorites of the mutation. +func withFavorites(node *Favorites) favoritesOption { + return func(m *FavoritesMutation) { + m.oldValue = func(context.Context) (*Favorites, 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 FavoritesMutation) 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 FavoritesMutation) 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 Favorites entities. +func (m *FavoritesMutation) 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 *FavoritesMutation) 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 *FavoritesMutation) 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().Favorites.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 *FavoritesMutation) 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 *FavoritesMutation) 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 Favorites entity. +// If the Favorites 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 *FavoritesMutation) 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 *FavoritesMutation) 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 *FavoritesMutation) 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 *FavoritesMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// SetTargetType sets the "target_type" field. +func (m *FavoritesMutation) SetTargetType(s string) { + m.target_type = &s +} + +// TargetType returns the value of the "target_type" field in the mutation. +func (m *FavoritesMutation) TargetType() (r string, exists bool) { + v := m.target_type + if v == nil { + return + } + return *v, true +} + +// OldTargetType returns the old "target_type" field's value of the Favorites entity. +// If the Favorites 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 *FavoritesMutation) OldTargetType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTargetType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTargetType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTargetType: %w", err) + } + return oldValue.TargetType, nil +} + +// ResetTargetType resets all changes to the "target_type" field. +func (m *FavoritesMutation) ResetTargetType() { + m.target_type = nil +} + +// SetTargetID sets the "target_id" field. +func (m *FavoritesMutation) SetTargetID(i int64) { + m.target_id = &i + m.addtarget_id = nil +} + +// TargetID returns the value of the "target_id" field in the mutation. +func (m *FavoritesMutation) TargetID() (r int64, exists bool) { + v := m.target_id + if v == nil { + return + } + return *v, true +} + +// OldTargetID returns the old "target_id" field's value of the Favorites entity. +// If the Favorites 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 *FavoritesMutation) OldTargetID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTargetID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTargetID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTargetID: %w", err) + } + return oldValue.TargetID, nil +} + +// AddTargetID adds i to the "target_id" field. +func (m *FavoritesMutation) AddTargetID(i int64) { + if m.addtarget_id != nil { + *m.addtarget_id += i + } else { + m.addtarget_id = &i + } +} + +// AddedTargetID returns the value that was added to the "target_id" field in this mutation. +func (m *FavoritesMutation) AddedTargetID() (r int64, exists bool) { + v := m.addtarget_id + if v == nil { + return + } + return *v, true +} + +// ResetTargetID resets all changes to the "target_id" field. +func (m *FavoritesMutation) ResetTargetID() { + m.target_id = nil + m.addtarget_id = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *FavoritesMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *FavoritesMutation) 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 Favorites entity. +// If the Favorites 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 *FavoritesMutation) 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 *FavoritesMutation) ResetCreatedAt() { + m.created_at = nil +} + +// Where appends a list predicates to the FavoritesMutation builder. +func (m *FavoritesMutation) Where(ps ...predicate.Favorites) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the FavoritesMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *FavoritesMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Favorites, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *FavoritesMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *FavoritesMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Favorites). +func (m *FavoritesMutation) 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 *FavoritesMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.user_id != nil { + fields = append(fields, favorites.FieldUserID) + } + if m.target_type != nil { + fields = append(fields, favorites.FieldTargetType) + } + if m.target_id != nil { + fields = append(fields, favorites.FieldTargetID) + } + if m.created_at != nil { + fields = append(fields, favorites.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 *FavoritesMutation) Field(name string) (ent.Value, bool) { + switch name { + case favorites.FieldUserID: + return m.UserID() + case favorites.FieldTargetType: + return m.TargetType() + case favorites.FieldTargetID: + return m.TargetID() + case favorites.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 *FavoritesMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case favorites.FieldUserID: + return m.OldUserID(ctx) + case favorites.FieldTargetType: + return m.OldTargetType(ctx) + case favorites.FieldTargetID: + return m.OldTargetID(ctx) + case favorites.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown Favorites 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 *FavoritesMutation) SetField(name string, value ent.Value) error { + switch name { + case favorites.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case favorites.FieldTargetType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTargetType(v) + return nil + case favorites.FieldTargetID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTargetID(v) + return nil + case favorites.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 Favorites field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *FavoritesMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, favorites.FieldUserID) + } + if m.addtarget_id != nil { + fields = append(fields, favorites.FieldTargetID) + } + 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 *FavoritesMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case favorites.FieldUserID: + return m.AddedUserID() + case favorites.FieldTargetID: + return m.AddedTargetID() + } + 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 *FavoritesMutation) AddField(name string, value ent.Value) error { + switch name { + case favorites.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + case favorites.FieldTargetID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTargetID(v) + return nil + } + return fmt.Errorf("unknown Favorites numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *FavoritesMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *FavoritesMutation) 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 *FavoritesMutation) ClearField(name string) error { + return fmt.Errorf("unknown Favorites 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 *FavoritesMutation) ResetField(name string) error { + switch name { + case favorites.FieldUserID: + m.ResetUserID() + return nil + case favorites.FieldTargetType: + m.ResetTargetType() + return nil + case favorites.FieldTargetID: + m.ResetTargetID() + return nil + case favorites.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown Favorites field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *FavoritesMutation) 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 *FavoritesMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *FavoritesMutation) 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 *FavoritesMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *FavoritesMutation) 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 *FavoritesMutation) 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 *FavoritesMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Favorites 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 *FavoritesMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Favorites edge %s", name) +} diff --git a/app/search/rpc/internal/models/predicate/predicate.go b/app/search/rpc/internal/models/predicate/predicate.go new file mode 100644 index 0000000..996a963 --- /dev/null +++ b/app/search/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" +) + +// Favorites is the predicate function for favorites builders. +type Favorites func(*sql.Selector) diff --git a/app/search/rpc/internal/models/runtime.go b/app/search/rpc/internal/models/runtime.go new file mode 100644 index 0000000..4e5ff01 --- /dev/null +++ b/app/search/rpc/internal/models/runtime.go @@ -0,0 +1,25 @@ +// Code generated by ent, DO NOT EDIT. + +package models + +import ( + "juwan-backend/app/search/rpc/internal/models/favorites" + "juwan-backend/app/search/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() { + favoritesFields := schema.Favorites{}.Fields() + _ = favoritesFields + // favoritesDescTargetType is the schema descriptor for target_type field. + favoritesDescTargetType := favoritesFields[2].Descriptor() + // favorites.TargetTypeValidator is a validator for the "target_type" field. It is called by the builders before save. + favorites.TargetTypeValidator = favoritesDescTargetType.Validators[0].(func(string) error) + // favoritesDescCreatedAt is the schema descriptor for created_at field. + favoritesDescCreatedAt := favoritesFields[4].Descriptor() + // favorites.DefaultCreatedAt holds the default value on creation for the created_at field. + favorites.DefaultCreatedAt = favoritesDescCreatedAt.Default.(func() time.Time) +} diff --git a/app/search/rpc/internal/models/runtime/runtime.go b/app/search/rpc/internal/models/runtime/runtime.go new file mode 100644 index 0000000..7fbe003 --- /dev/null +++ b/app/search/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/search/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/search/rpc/internal/models/schema/favorites.go b/app/search/rpc/internal/models/schema/favorites.go new file mode 100644 index 0000000..5cc683e --- /dev/null +++ b/app/search/rpc/internal/models/schema/favorites.go @@ -0,0 +1,36 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +type Favorites struct { + ent.Schema +} + +func (Favorites) Fields() []ent.Field { + return []ent.Field{ + field.Int64("id").Unique().Immutable(), + field.Int64("user_id"), + field.String("target_type").MaxLen(20), + field.Int64("target_id"), + field.Time("created_at").Default(time.Now).Immutable(), + } +} + +func (Favorites) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("user_id", "target_type", "target_id").Unique(), + index.Fields("user_id", "created_at"), + index.Fields("target_type", "target_id"), + index.Fields("user_id", "target_type", "created_at"), + } +} + +func (Favorites) Edges() []ent.Edge { + return nil +} diff --git a/app/search/rpc/internal/models/tx.go b/app/search/rpc/internal/models/tx.go new file mode 100644 index 0000000..c5c26e1 --- /dev/null +++ b/app/search/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 + // Favorites is the client for interacting with the Favorites builders. + Favorites *FavoritesClient + + // 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.Favorites = NewFavoritesClient(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: Favorites.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/search/rpc/internal/server/searchServiceServer.go b/app/search/rpc/internal/server/searchServiceServer.go new file mode 100644 index 0000000..37bf3df --- /dev/null +++ b/app/search/rpc/internal/server/searchServiceServer.go @@ -0,0 +1,44 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: search.proto + +package server + +import ( + "context" + + "juwan-backend/app/search/rpc/internal/logic" + "juwan-backend/app/search/rpc/internal/svc" + "juwan-backend/app/search/rpc/pb" +) + +type SearchServiceServer struct { + svcCtx *svc.ServiceContext + pb.UnimplementedSearchServiceServer +} + +func NewSearchServiceServer(svcCtx *svc.ServiceContext) *SearchServiceServer { + return &SearchServiceServer{ + svcCtx: svcCtx, + } +} + +func (s *SearchServiceServer) AddFavorites(ctx context.Context, in *pb.AddFavoritesReq) (*pb.AddFavoritesResp, error) { + l := logic.NewAddFavoritesLogic(ctx, s.svcCtx) + return l.AddFavorites(in) +} + +func (s *SearchServiceServer) DelFavorites(ctx context.Context, in *pb.DelFavoritesReq) (*pb.DelFavoritesResp, error) { + l := logic.NewDelFavoritesLogic(ctx, s.svcCtx) + return l.DelFavorites(in) +} + +func (s *SearchServiceServer) GetFavoritesById(ctx context.Context, in *pb.GetFavoritesByIdReq) (*pb.GetFavoritesByIdResp, error) { + l := logic.NewGetFavoritesByIdLogic(ctx, s.svcCtx) + return l.GetFavoritesById(in) +} + +func (s *SearchServiceServer) SearchFavorites(ctx context.Context, in *pb.SearchFavoritesReq) (*pb.SearchFavoritesResp, error) { + l := logic.NewSearchFavoritesLogic(ctx, s.svcCtx) + return l.SearchFavorites(in) +} diff --git a/app/search/rpc/internal/svc/serviceContext.go b/app/search/rpc/internal/svc/serviceContext.go new file mode 100644 index 0000000..16453fd --- /dev/null +++ b/app/search/rpc/internal/svc/serviceContext.go @@ -0,0 +1,53 @@ +package svc + +import ( + stdsql "database/sql" + "time" + + "juwan-backend/app/search/rpc/internal/config" + "juwan-backend/app/search/rpc/internal/models" + "juwan-backend/app/snowflake/rpc/snowflake" + "juwan-backend/common/redisx" + "juwan-backend/common/snowflakex" + "juwan-backend/pkg/adapter" + + "ariga.io/entcache" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + + _ "github.com/jackc/pgx/v5/stdlib" +) + +type ServiceContext struct { + Config config.Config + Snowflake snowflake.SnowflakeServiceClient + SearchModelRW *models.Client + SearchModelRO *models.Client +} + +func NewServiceContext(c config.Config) *ServiceContext { + rawRW, err := stdsql.Open("pgx", c.DB.Master) + if err != nil { + panic(err) + } + rawRO, err := stdsql.Open("pgx", c.DB.Slaves) + if err != nil { + panic(err) + } + RWConn := sql.OpenDB(dialect.Postgres, rawRW) + ROConn := sql.OpenDB(dialect.Postgres, rawRO) + + redisCluster, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second) + if redisCluster == nil || err != nil { + 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))) + return &ServiceContext{ + Config: c, + SearchModelRW: models.NewClient(models.Driver(RWDrv)), + SearchModelRO: models.NewClient(models.Driver(RODrv)), + Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf), + } +} diff --git a/app/search/rpc/pb.go b/app/search/rpc/pb.go new file mode 100644 index 0000000..b6bf6d6 --- /dev/null +++ b/app/search/rpc/pb.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "juwan-backend/app/search/rpc/internal/config" + "juwan-backend/app/search/rpc/internal/server" + "juwan-backend/app/search/rpc/internal/svc" + "juwan-backend/app/search/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.RegisterSearchServiceServer(grpcServer, server.NewSearchServiceServer(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/search/rpc/pb/search.pb.go b/app/search/rpc/pb/search.pb.go new file mode 100644 index 0000000..165488b --- /dev/null +++ b/app/search/rpc/pb/search.pb.go @@ -0,0 +1,615 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v7.34.1 +// source: search.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) +) + +// --------------------------------favorites-------------------------------- +type Favorites struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` + TargetType string `protobuf:"bytes,3,opt,name=targetType,proto3" json:"targetType,omitempty"` + TargetId int64 `protobuf:"varint,4,opt,name=targetId,proto3" json:"targetId,omitempty"` + CreatedAt int64 `protobuf:"varint,5,opt,name=createdAt,proto3" json:"createdAt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Favorites) Reset() { + *x = Favorites{} + mi := &file_search_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Favorites) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Favorites) ProtoMessage() {} + +func (x *Favorites) ProtoReflect() protoreflect.Message { + mi := &file_search_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 Favorites.ProtoReflect.Descriptor instead. +func (*Favorites) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{0} +} + +func (x *Favorites) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Favorites) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *Favorites) GetTargetType() string { + if x != nil { + return x.TargetType + } + return "" +} + +func (x *Favorites) GetTargetId() int64 { + if x != nil { + return x.TargetId + } + return 0 +} + +func (x *Favorites) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +type AddFavoritesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId int64 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"` + TargetType string `protobuf:"bytes,2,opt,name=targetType,proto3" json:"targetType,omitempty"` + TargetId int64 `protobuf:"varint,3,opt,name=targetId,proto3" json:"targetId,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddFavoritesReq) Reset() { + *x = AddFavoritesReq{} + mi := &file_search_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddFavoritesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddFavoritesReq) ProtoMessage() {} + +func (x *AddFavoritesReq) ProtoReflect() protoreflect.Message { + mi := &file_search_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 AddFavoritesReq.ProtoReflect.Descriptor instead. +func (*AddFavoritesReq) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{1} +} + +func (x *AddFavoritesReq) GetUserId() int64 { + if x != nil { + return x.UserId + } + return 0 +} + +func (x *AddFavoritesReq) GetTargetType() string { + if x != nil { + return x.TargetType + } + return "" +} + +func (x *AddFavoritesReq) GetTargetId() int64 { + if x != nil { + return x.TargetId + } + return 0 +} + +type AddFavoritesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AddFavoritesResp) Reset() { + *x = AddFavoritesResp{} + mi := &file_search_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AddFavoritesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddFavoritesResp) ProtoMessage() {} + +func (x *AddFavoritesResp) ProtoReflect() protoreflect.Message { + mi := &file_search_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 AddFavoritesResp.ProtoReflect.Descriptor instead. +func (*AddFavoritesResp) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{2} +} + +func (x *AddFavoritesResp) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelFavoritesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelFavoritesReq) Reset() { + *x = DelFavoritesReq{} + mi := &file_search_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelFavoritesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelFavoritesReq) ProtoMessage() {} + +func (x *DelFavoritesReq) ProtoReflect() protoreflect.Message { + mi := &file_search_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 DelFavoritesReq.ProtoReflect.Descriptor instead. +func (*DelFavoritesReq) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{3} +} + +func (x *DelFavoritesReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type DelFavoritesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DelFavoritesResp) Reset() { + *x = DelFavoritesResp{} + mi := &file_search_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DelFavoritesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DelFavoritesResp) ProtoMessage() {} + +func (x *DelFavoritesResp) ProtoReflect() protoreflect.Message { + mi := &file_search_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 DelFavoritesResp.ProtoReflect.Descriptor instead. +func (*DelFavoritesResp) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{4} +} + +type GetFavoritesByIdReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetFavoritesByIdReq) Reset() { + *x = GetFavoritesByIdReq{} + mi := &file_search_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetFavoritesByIdReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetFavoritesByIdReq) ProtoMessage() {} + +func (x *GetFavoritesByIdReq) ProtoReflect() protoreflect.Message { + mi := &file_search_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 GetFavoritesByIdReq.ProtoReflect.Descriptor instead. +func (*GetFavoritesByIdReq) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{5} +} + +func (x *GetFavoritesByIdReq) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type GetFavoritesByIdResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Favorites *Favorites `protobuf:"bytes,1,opt,name=favorites,proto3" json:"favorites,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetFavoritesByIdResp) Reset() { + *x = GetFavoritesByIdResp{} + mi := &file_search_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetFavoritesByIdResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetFavoritesByIdResp) ProtoMessage() {} + +func (x *GetFavoritesByIdResp) ProtoReflect() protoreflect.Message { + mi := &file_search_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 GetFavoritesByIdResp.ProtoReflect.Descriptor instead. +func (*GetFavoritesByIdResp) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{6} +} + +func (x *GetFavoritesByIdResp) GetFavorites() *Favorites { + if x != nil { + return x.Favorites + } + return nil +} + +type SearchFavoritesReq struct { + state protoimpl.MessageState `protogen:"open.v1"` + Offset int64 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + Id *int64 `protobuf:"varint,3,opt,name=id,proto3,oneof" json:"id,omitempty"` + UserId *int64 `protobuf:"varint,4,opt,name=userId,proto3,oneof" json:"userId,omitempty"` + TargetType *string `protobuf:"bytes,5,opt,name=targetType,proto3,oneof" json:"targetType,omitempty"` + TargetId *int64 `protobuf:"varint,6,opt,name=targetId,proto3,oneof" json:"targetId,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchFavoritesReq) Reset() { + *x = SearchFavoritesReq{} + mi := &file_search_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchFavoritesReq) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchFavoritesReq) ProtoMessage() {} + +func (x *SearchFavoritesReq) ProtoReflect() protoreflect.Message { + mi := &file_search_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 SearchFavoritesReq.ProtoReflect.Descriptor instead. +func (*SearchFavoritesReq) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{7} +} + +func (x *SearchFavoritesReq) GetOffset() int64 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *SearchFavoritesReq) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *SearchFavoritesReq) GetId() int64 { + if x != nil && x.Id != nil { + return *x.Id + } + return 0 +} + +func (x *SearchFavoritesReq) GetUserId() int64 { + if x != nil && x.UserId != nil { + return *x.UserId + } + return 0 +} + +func (x *SearchFavoritesReq) GetTargetType() string { + if x != nil && x.TargetType != nil { + return *x.TargetType + } + return "" +} + +func (x *SearchFavoritesReq) GetTargetId() int64 { + if x != nil && x.TargetId != nil { + return *x.TargetId + } + return 0 +} + +type SearchFavoritesResp struct { + state protoimpl.MessageState `protogen:"open.v1"` + Favorites []*Favorites `protobuf:"bytes,1,rep,name=favorites,proto3" json:"favorites,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SearchFavoritesResp) Reset() { + *x = SearchFavoritesResp{} + mi := &file_search_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SearchFavoritesResp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchFavoritesResp) ProtoMessage() {} + +func (x *SearchFavoritesResp) ProtoReflect() protoreflect.Message { + mi := &file_search_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 SearchFavoritesResp.ProtoReflect.Descriptor instead. +func (*SearchFavoritesResp) Descriptor() ([]byte, []int) { + return file_search_proto_rawDescGZIP(), []int{8} +} + +func (x *SearchFavoritesResp) GetFavorites() []*Favorites { + if x != nil { + return x.Favorites + } + return nil +} + +var File_search_proto protoreflect.FileDescriptor + +const file_search_proto_rawDesc = "" + + "\n" + + "\fsearch.proto\x12\x02pb\"\x8d\x01\n" + + "\tFavorites\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x16\n" + + "\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x1e\n" + + "\n" + + "targetType\x18\x03 \x01(\tR\n" + + "targetType\x12\x1a\n" + + "\btargetId\x18\x04 \x01(\x03R\btargetId\x12\x1c\n" + + "\tcreatedAt\x18\x05 \x01(\x03R\tcreatedAt\"e\n" + + "\x0fAddFavoritesReq\x12\x16\n" + + "\x06userId\x18\x01 \x01(\x03R\x06userId\x12\x1e\n" + + "\n" + + "targetType\x18\x02 \x01(\tR\n" + + "targetType\x12\x1a\n" + + "\btargetId\x18\x03 \x01(\x03R\btargetId\"\"\n" + + "\x10AddFavoritesResp\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"!\n" + + "\x0fDelFavoritesReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"\x12\n" + + "\x10DelFavoritesResp\"%\n" + + "\x13GetFavoritesByIdReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\"C\n" + + "\x14GetFavoritesByIdResp\x12+\n" + + "\tfavorites\x18\x01 \x01(\v2\r.pb.FavoritesR\tfavorites\"\xe8\x01\n" + + "\x12SearchFavoritesReq\x12\x16\n" + + "\x06offset\x18\x01 \x01(\x03R\x06offset\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x13\n" + + "\x02id\x18\x03 \x01(\x03H\x00R\x02id\x88\x01\x01\x12\x1b\n" + + "\x06userId\x18\x04 \x01(\x03H\x01R\x06userId\x88\x01\x01\x12#\n" + + "\n" + + "targetType\x18\x05 \x01(\tH\x02R\n" + + "targetType\x88\x01\x01\x12\x1f\n" + + "\btargetId\x18\x06 \x01(\x03H\x03R\btargetId\x88\x01\x01B\x05\n" + + "\x03_idB\t\n" + + "\a_userIdB\r\n" + + "\v_targetTypeB\v\n" + + "\t_targetId\"B\n" + + "\x13SearchFavoritesResp\x12+\n" + + "\tfavorites\x18\x01 \x03(\v2\r.pb.FavoritesR\tfavorites2\x90\x02\n" + + "\rsearchService\x129\n" + + "\fAddFavorites\x12\x13.pb.AddFavoritesReq\x1a\x14.pb.AddFavoritesResp\x129\n" + + "\fDelFavorites\x12\x13.pb.DelFavoritesReq\x1a\x14.pb.DelFavoritesResp\x12E\n" + + "\x10GetFavoritesById\x12\x17.pb.GetFavoritesByIdReq\x1a\x18.pb.GetFavoritesByIdResp\x12B\n" + + "\x0fSearchFavorites\x12\x16.pb.SearchFavoritesReq\x1a\x17.pb.SearchFavoritesRespB\x06Z\x04./pbb\x06proto3" + +var ( + file_search_proto_rawDescOnce sync.Once + file_search_proto_rawDescData []byte +) + +func file_search_proto_rawDescGZIP() []byte { + file_search_proto_rawDescOnce.Do(func() { + file_search_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_search_proto_rawDesc), len(file_search_proto_rawDesc))) + }) + return file_search_proto_rawDescData +} + +var file_search_proto_msgTypes = make([]protoimpl.MessageInfo, 9) +var file_search_proto_goTypes = []any{ + (*Favorites)(nil), // 0: pb.Favorites + (*AddFavoritesReq)(nil), // 1: pb.AddFavoritesReq + (*AddFavoritesResp)(nil), // 2: pb.AddFavoritesResp + (*DelFavoritesReq)(nil), // 3: pb.DelFavoritesReq + (*DelFavoritesResp)(nil), // 4: pb.DelFavoritesResp + (*GetFavoritesByIdReq)(nil), // 5: pb.GetFavoritesByIdReq + (*GetFavoritesByIdResp)(nil), // 6: pb.GetFavoritesByIdResp + (*SearchFavoritesReq)(nil), // 7: pb.SearchFavoritesReq + (*SearchFavoritesResp)(nil), // 8: pb.SearchFavoritesResp +} +var file_search_proto_depIdxs = []int32{ + 0, // 0: pb.GetFavoritesByIdResp.favorites:type_name -> pb.Favorites + 0, // 1: pb.SearchFavoritesResp.favorites:type_name -> pb.Favorites + 1, // 2: pb.searchService.AddFavorites:input_type -> pb.AddFavoritesReq + 3, // 3: pb.searchService.DelFavorites:input_type -> pb.DelFavoritesReq + 5, // 4: pb.searchService.GetFavoritesById:input_type -> pb.GetFavoritesByIdReq + 7, // 5: pb.searchService.SearchFavorites:input_type -> pb.SearchFavoritesReq + 2, // 6: pb.searchService.AddFavorites:output_type -> pb.AddFavoritesResp + 4, // 7: pb.searchService.DelFavorites:output_type -> pb.DelFavoritesResp + 6, // 8: pb.searchService.GetFavoritesById:output_type -> pb.GetFavoritesByIdResp + 8, // 9: pb.searchService.SearchFavorites:output_type -> pb.SearchFavoritesResp + 6, // [6:10] is the sub-list for method output_type + 2, // [2:6] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_search_proto_init() } +func file_search_proto_init() { + if File_search_proto != nil { + return + } + file_search_proto_msgTypes[7].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_search_proto_rawDesc), len(file_search_proto_rawDesc)), + NumEnums: 0, + NumMessages: 9, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_search_proto_goTypes, + DependencyIndexes: file_search_proto_depIdxs, + MessageInfos: file_search_proto_msgTypes, + }.Build() + File_search_proto = out.File + file_search_proto_goTypes = nil + file_search_proto_depIdxs = nil +} diff --git a/app/search/rpc/pb/search_grpc.pb.go b/app/search/rpc/pb/search_grpc.pb.go new file mode 100644 index 0000000..0ae863e --- /dev/null +++ b/app/search/rpc/pb/search_grpc.pb.go @@ -0,0 +1,235 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v7.34.1 +// source: search.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 ( + SearchService_AddFavorites_FullMethodName = "/pb.searchService/AddFavorites" + SearchService_DelFavorites_FullMethodName = "/pb.searchService/DelFavorites" + SearchService_GetFavoritesById_FullMethodName = "/pb.searchService/GetFavoritesById" + SearchService_SearchFavorites_FullMethodName = "/pb.searchService/SearchFavorites" +) + +// SearchServiceClient is the client API for SearchService 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 SearchServiceClient interface { + AddFavorites(ctx context.Context, in *AddFavoritesReq, opts ...grpc.CallOption) (*AddFavoritesResp, error) + DelFavorites(ctx context.Context, in *DelFavoritesReq, opts ...grpc.CallOption) (*DelFavoritesResp, error) + GetFavoritesById(ctx context.Context, in *GetFavoritesByIdReq, opts ...grpc.CallOption) (*GetFavoritesByIdResp, error) + SearchFavorites(ctx context.Context, in *SearchFavoritesReq, opts ...grpc.CallOption) (*SearchFavoritesResp, error) +} + +type searchServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewSearchServiceClient(cc grpc.ClientConnInterface) SearchServiceClient { + return &searchServiceClient{cc} +} + +func (c *searchServiceClient) AddFavorites(ctx context.Context, in *AddFavoritesReq, opts ...grpc.CallOption) (*AddFavoritesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AddFavoritesResp) + err := c.cc.Invoke(ctx, SearchService_AddFavorites_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *searchServiceClient) DelFavorites(ctx context.Context, in *DelFavoritesReq, opts ...grpc.CallOption) (*DelFavoritesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DelFavoritesResp) + err := c.cc.Invoke(ctx, SearchService_DelFavorites_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *searchServiceClient) GetFavoritesById(ctx context.Context, in *GetFavoritesByIdReq, opts ...grpc.CallOption) (*GetFavoritesByIdResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetFavoritesByIdResp) + err := c.cc.Invoke(ctx, SearchService_GetFavoritesById_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *searchServiceClient) SearchFavorites(ctx context.Context, in *SearchFavoritesReq, opts ...grpc.CallOption) (*SearchFavoritesResp, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SearchFavoritesResp) + err := c.cc.Invoke(ctx, SearchService_SearchFavorites_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// SearchServiceServer is the server API for SearchService service. +// All implementations must embed UnimplementedSearchServiceServer +// for forward compatibility. +type SearchServiceServer interface { + AddFavorites(context.Context, *AddFavoritesReq) (*AddFavoritesResp, error) + DelFavorites(context.Context, *DelFavoritesReq) (*DelFavoritesResp, error) + GetFavoritesById(context.Context, *GetFavoritesByIdReq) (*GetFavoritesByIdResp, error) + SearchFavorites(context.Context, *SearchFavoritesReq) (*SearchFavoritesResp, error) + mustEmbedUnimplementedSearchServiceServer() +} + +// UnimplementedSearchServiceServer 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 UnimplementedSearchServiceServer struct{} + +func (UnimplementedSearchServiceServer) AddFavorites(context.Context, *AddFavoritesReq) (*AddFavoritesResp, error) { + return nil, status.Error(codes.Unimplemented, "method AddFavorites not implemented") +} +func (UnimplementedSearchServiceServer) DelFavorites(context.Context, *DelFavoritesReq) (*DelFavoritesResp, error) { + return nil, status.Error(codes.Unimplemented, "method DelFavorites not implemented") +} +func (UnimplementedSearchServiceServer) GetFavoritesById(context.Context, *GetFavoritesByIdReq) (*GetFavoritesByIdResp, error) { + return nil, status.Error(codes.Unimplemented, "method GetFavoritesById not implemented") +} +func (UnimplementedSearchServiceServer) SearchFavorites(context.Context, *SearchFavoritesReq) (*SearchFavoritesResp, error) { + return nil, status.Error(codes.Unimplemented, "method SearchFavorites not implemented") +} +func (UnimplementedSearchServiceServer) mustEmbedUnimplementedSearchServiceServer() {} +func (UnimplementedSearchServiceServer) testEmbeddedByValue() {} + +// UnsafeSearchServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to SearchServiceServer will +// result in compilation errors. +type UnsafeSearchServiceServer interface { + mustEmbedUnimplementedSearchServiceServer() +} + +func RegisterSearchServiceServer(s grpc.ServiceRegistrar, srv SearchServiceServer) { + // If the following call panics, it indicates UnimplementedSearchServiceServer 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(&SearchService_ServiceDesc, srv) +} + +func _SearchService_AddFavorites_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddFavoritesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SearchServiceServer).AddFavorites(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SearchService_AddFavorites_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SearchServiceServer).AddFavorites(ctx, req.(*AddFavoritesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _SearchService_DelFavorites_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DelFavoritesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SearchServiceServer).DelFavorites(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SearchService_DelFavorites_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SearchServiceServer).DelFavorites(ctx, req.(*DelFavoritesReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _SearchService_GetFavoritesById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetFavoritesByIdReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SearchServiceServer).GetFavoritesById(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SearchService_GetFavoritesById_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SearchServiceServer).GetFavoritesById(ctx, req.(*GetFavoritesByIdReq)) + } + return interceptor(ctx, in, info, handler) +} + +func _SearchService_SearchFavorites_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchFavoritesReq) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SearchServiceServer).SearchFavorites(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SearchService_SearchFavorites_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SearchServiceServer).SearchFavorites(ctx, req.(*SearchFavoritesReq)) + } + return interceptor(ctx, in, info, handler) +} + +// SearchService_ServiceDesc is the grpc.ServiceDesc for SearchService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var SearchService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "pb.searchService", + HandlerType: (*SearchServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "AddFavorites", + Handler: _SearchService_AddFavorites_Handler, + }, + { + MethodName: "DelFavorites", + Handler: _SearchService_DelFavorites_Handler, + }, + { + MethodName: "GetFavoritesById", + Handler: _SearchService_GetFavoritesById_Handler, + }, + { + MethodName: "SearchFavorites", + Handler: _SearchService_SearchFavorites_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "search.proto", +} diff --git a/app/search/rpc/searchservice/searchService.go b/app/search/rpc/searchservice/searchService.go new file mode 100644 index 0000000..7f0ac33 --- /dev/null +++ b/app/search/rpc/searchservice/searchService.go @@ -0,0 +1,63 @@ +// Code generated by goctl. DO NOT EDIT. +// goctl 1.10.1 +// Source: search.proto + +package searchservice + +import ( + "context" + + "juwan-backend/app/search/rpc/pb" + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + AddFavoritesReq = pb.AddFavoritesReq + AddFavoritesResp = pb.AddFavoritesResp + DelFavoritesReq = pb.DelFavoritesReq + DelFavoritesResp = pb.DelFavoritesResp + Favorites = pb.Favorites + GetFavoritesByIdReq = pb.GetFavoritesByIdReq + GetFavoritesByIdResp = pb.GetFavoritesByIdResp + SearchFavoritesReq = pb.SearchFavoritesReq + SearchFavoritesResp = pb.SearchFavoritesResp + + SearchService interface { + AddFavorites(ctx context.Context, in *AddFavoritesReq, opts ...grpc.CallOption) (*AddFavoritesResp, error) + DelFavorites(ctx context.Context, in *DelFavoritesReq, opts ...grpc.CallOption) (*DelFavoritesResp, error) + GetFavoritesById(ctx context.Context, in *GetFavoritesByIdReq, opts ...grpc.CallOption) (*GetFavoritesByIdResp, error) + SearchFavorites(ctx context.Context, in *SearchFavoritesReq, opts ...grpc.CallOption) (*SearchFavoritesResp, error) + } + + defaultSearchService struct { + cli zrpc.Client + } +) + +func NewSearchService(cli zrpc.Client) SearchService { + return &defaultSearchService{ + cli: cli, + } +} + +func (m *defaultSearchService) AddFavorites(ctx context.Context, in *AddFavoritesReq, opts ...grpc.CallOption) (*AddFavoritesResp, error) { + client := pb.NewSearchServiceClient(m.cli.Conn()) + return client.AddFavorites(ctx, in, opts...) +} + +func (m *defaultSearchService) DelFavorites(ctx context.Context, in *DelFavoritesReq, opts ...grpc.CallOption) (*DelFavoritesResp, error) { + client := pb.NewSearchServiceClient(m.cli.Conn()) + return client.DelFavorites(ctx, in, opts...) +} + +func (m *defaultSearchService) GetFavoritesById(ctx context.Context, in *GetFavoritesByIdReq, opts ...grpc.CallOption) (*GetFavoritesByIdResp, error) { + client := pb.NewSearchServiceClient(m.cli.Conn()) + return client.GetFavoritesById(ctx, in, opts...) +} + +func (m *defaultSearchService) SearchFavorites(ctx context.Context, in *SearchFavoritesReq, opts ...grpc.CallOption) (*SearchFavoritesResp, error) { + client := pb.NewSearchServiceClient(m.cli.Conn()) + return client.SearchFavorites(ctx, in, opts...) +} diff --git a/deploy/dev/README.md b/deploy/dev/README.md index 012ecda..34acb0c 100644 --- a/deploy/dev/README.md +++ b/deploy/dev/README.md @@ -29,7 +29,7 @@ docker compose down 构建脚本会扫描 `app/` 下所有 `api`、`rpc`、`mq`、`adapter` 入口,通过 `docker buildx bake` 并行构建所有服务镜像,生成 `juwan/-:dev`。 -端到端接口测试走网关 `http://127.0.0.1:18080`,`18801-18809` 是各服务的直连端口,不经过认证链路。 +端到端接口测试走网关 `http://127.0.0.1:18080`,`18801-18814` 是各服务的直连端口,不经过认证链路。 如需只启动部分服务: @@ -39,21 +39,26 @@ docker compose up -d postgres redis snowflake player-rpc player-api ## 端口映射 -| 服务 | 宿主机端口 | -| --------------- | ---------- | -| PostgreSQL | 15432 | -| Redis | 16379 | -| Kafka | 19092 | -| Envoy Gateway | 18080 | -| users-api | 18801 | -| player-api | 18802 | -| game-api | 18803 | -| shop-api | 18804 | -| order-api | 18805 | -| wallet-api | 18806 | -| community-api | 18807 | -| objectstory-api | 18808 | -| email-api | 18809 | +| 服务 | 宿主机端口 | +| ---------------- | ---------- | +| PostgreSQL | 15432 | +| Redis | 16379 | +| Kafka | 19092 | +| Envoy Gateway | 18080 | +| users-api | 18801 | +| player-api | 18802 | +| game-api | 18803 | +| shop-api | 18804 | +| order-api | 18805 | +| wallet-api | 18806 | +| community-api | 18807 | +| objectstory-api | 18808 | +| email-api | 18809 | +| chat-api | 18810 | +| review-api | 18811 | +| dispute-api | 18812 | +| notification-api | 18813 | +| search-api | 18814 | ## 环境变量 diff --git a/deploy/dev/docker-compose.yml b/deploy/dev/docker-compose.yml index cc14ac0..2833400 100644 --- a/deploy/dev/docker-compose.yml +++ b/deploy/dev/docker-compose.yml @@ -121,6 +121,14 @@ services: condition: service_started chat-api: condition: service_started + review-api: + condition: service_started + dispute-api: + condition: service_started + notification-api: + condition: service_started + search-api: + condition: service_started ratelimit: image: envoyproxy/ratelimit:05c08d03 @@ -268,6 +276,58 @@ services: restart: unless-stopped env_file: .env + review-rpc: + image: juwan/review-rpc:dev + container_name: juwan-review-rpc + restart: unless-stopped + env_file: .env + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + snowflake: + condition: service_started + + dispute-rpc: + image: juwan/dispute-rpc:dev + container_name: juwan-dispute-rpc + restart: unless-stopped + env_file: .env + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + snowflake: + condition: service_started + + notification-rpc: + image: juwan/notification-rpc:dev + container_name: juwan-notification-rpc + restart: unless-stopped + env_file: .env + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + snowflake: + condition: service_started + + search-rpc: + image: juwan/search-rpc:dev + container_name: juwan-search-rpc + restart: unless-stopped + env_file: .env + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + snowflake: + condition: service_started + # ==================== API 层 ==================== users-api: image: juwan/users-api:dev @@ -392,6 +452,54 @@ services: chat-rpc: condition: service_started + review-api: + image: juwan/review-api:dev + container_name: juwan-review-api + restart: unless-stopped + env_file: .env + ports: + - "18811:8888" + depends_on: + review-rpc: + condition: service_started + order-rpc: + condition: service_started + + dispute-api: + image: juwan/dispute-api:dev + container_name: juwan-dispute-api + restart: unless-stopped + env_file: .env + ports: + - "18812:8888" + depends_on: + dispute-rpc: + condition: service_started + order-rpc: + condition: service_started + + notification-api: + image: juwan/notification-api:dev + container_name: juwan-notification-api + restart: unless-stopped + env_file: .env + ports: + - "18813:8888" + depends_on: + notification-rpc: + condition: service_started + + search-api: + image: juwan/search-api:dev + container_name: juwan-search-api + restart: unless-stopped + env_file: .env + ports: + - "18814:8888" + depends_on: + search-rpc: + condition: service_started + # ==================== MQ ==================== email-mq: image: juwan/email-mq:dev diff --git a/deploy/dev/envoy.yaml b/deploy/dev/envoy.yaml index 241eb0d..0dc1575 100644 --- a/deploy/dev/envoy.yaml +++ b/deploy/dev/envoy.yaml @@ -224,6 +224,32 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true + - match: + path: /api/v1/search + headers: + - name: ":method" + exact_match: GET + route: + cluster: search_api_cluster + timeout: 30s + typed_per_filter_config: + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + + - match: + prefix: /api/v1/recommendations + headers: + - name: ":method" + exact_match: GET + route: + cluster: search_api_cluster + timeout: 30s + typed_per_filter_config: + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - match: prefix: /api/v1/posts headers: @@ -249,6 +275,29 @@ static_resources: cluster: user_api_cluster timeout: 30s + - match: + safe_regex: + google_re2: {} + regex: "^/api/v1/users/[0-9]+/favorites/check$" + route: + cluster: search_api_cluster + timeout: 30s + + - match: + safe_regex: + google_re2: {} + regex: "^/api/v1/users/[0-9]+/reviews$" + headers: + - name: ":method" + exact_match: GET + route: + cluster: review_api_cluster + timeout: 30s + typed_per_filter_config: + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - match: prefix: /api/v1/users route: @@ -285,6 +334,22 @@ static_resources: cluster: shop_api_cluster timeout: 30s + - match: + safe_regex: + google_re2: {} + regex: "^/api/v1/orders/[0-9]+/review.*" + route: + cluster: review_api_cluster + timeout: 30s + + - match: + safe_regex: + google_re2: {} + regex: "^/api/v1/orders/[0-9]+/dispute$" + route: + cluster: dispute_api_cluster + timeout: 30s + - match: prefix: /api/v1/orders route: @@ -327,6 +392,37 @@ static_resources: cluster: objectstory_api_cluster timeout: 30s + - match: + prefix: /api/v1/reviews + headers: + - name: ":method" + exact_match: GET + route: + cluster: review_api_cluster + timeout: 30s + typed_per_filter_config: + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + + - match: + prefix: /api/v1/disputes + route: + cluster: dispute_api_cluster + timeout: 30s + + - match: + prefix: /api/v1/notifications + route: + cluster: notification_api_cluster + timeout: 30s + + - match: + prefix: /api/v1/favorites + route: + cluster: search_api_cluster + timeout: 30s + - match: prefix: / direct_response: @@ -571,6 +667,28 @@ static_resources: headers: - name: ":method" exact_match: GET + - match: + prefix: /api/v1/reviews + headers: + - name: ":method" + exact_match: GET + - match: + safe_regex: + google_re2: {} + regex: "^/api/v1/users/[0-9]+/reviews$" + headers: + - name: ":method" + exact_match: GET + - match: + path: /api/v1/search + headers: + - name: ":method" + exact_match: GET + - match: + path: /api/v1/recommendations/home + headers: + - name: ":method" + exact_match: GET - match: prefix: /api/v1 requires: @@ -748,6 +866,62 @@ static_resources: address: chat-api port_value: 8888 + - name: review_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: review_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: review-api + port_value: 8888 + + - name: dispute_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: dispute_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: dispute-api + port_value: 8888 + + - name: notification_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: notification_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: notification-api + port_value: 8888 + + - name: search_api_cluster + connect_timeout: 2s + type: STRICT_DNS + lb_policy: ROUND_ROBIN + load_assignment: + cluster_name: search_api_cluster + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: search-api + port_value: 8888 + - name: authz_adapter_cluster connect_timeout: 0.5s type: STRICT_DNS diff --git a/deploy/dev/init-db.sh b/deploy/dev/init-db.sh index 32606c0..5b835fb 100755 --- a/deploy/dev/init-db.sh +++ b/deploy/dev/init-db.sh @@ -27,6 +27,7 @@ ordered=( dispute/disputes.sql dispute/dispute_timeline.sql review/reviews.sql + notification/notifications.sql search/favorites.sql ) diff --git a/deploy/dev/test_all_apis.py b/deploy/dev/test_all_apis.py index b2d7f68..4d1d1ff 100644 --- a/deploy/dev/test_all_apis.py +++ b/deploy/dev/test_all_apis.py @@ -926,6 +926,13 @@ def phase8_order(s_consumer: Session, s_actor: Session, player_id, service_id, s report(f"POST /orders/{order_id}/reorder", code, body) if order2_id: + code, body, _ = s_consumer.post( + f"{GATEWAY}/api/v1/orders/{order2_id}/pay", + json_body={}, + headers=csrf, + ) + report(f"POST /orders/{order2_id}/pay (before cancel)", code, body) + code, body, _ = s_consumer.post( f"{GATEWAY}/api/v1/orders/{order2_id}/cancel", json_body={}, @@ -947,6 +954,237 @@ def phase8_order(s_consumer: Session, s_actor: Session, player_id, service_id, s return order_id +def phase8b_review(s_consumer: Session, order_id, player_id): + print("\n=== Phase 8b: Reviews ===") + if not order_id: + skip("Review flow", "No pending_review order id") + return + + csrf = s_consumer.csrf_headers() + code, body, _ = s_consumer.post( + f"{GATEWAY}/api/v1/orders/{order_id}/review", + json_body={"rating": 5, "content": "great service"}, + headers=csrf, + ) + report(f"POST /orders/{order_id}/review", code, body) + + code, body, _ = s_consumer.get(f"{GATEWAY}/api/v1/orders/{order_id}/reviews") + report(f"GET /orders/{order_id}/reviews", code, body) + if code == 200: + report_check( + f"GET /orders/{order_id}/reviews shape", + isinstance(pick_items(body), list) and isinstance(body.get("meta"), dict), + body, + ) + + code, body, _ = s_consumer.get(f"{GATEWAY}/api/v1/reviews?limit=20") + report("GET /reviews?limit=20", code, body) + + if player_id: + code, body, _ = s_consumer.get( + f"{GATEWAY}/api/v1/users/{player_id}/reviews?limit=20", + ) + report(f"GET /users/{player_id}/reviews?limit=20", code, body) + + +def phase8c_dispute(s_consumer: Session, s_actor: Session, player_id, service_id, shop_id): + print("\n=== Phase 8c: Disputes ===") + if not player_id or not service_id: + skip("Dispute flow", "Missing player or service id") + return 0 + + csrf = s_consumer.csrf_headers() + payload = { + "playerId": player_id, + "serviceId": service_id, + "quantity": 1, + "note": "test dispute order", + } + if shop_id: + payload["shopId"] = shop_id + + code, body, _ = s_consumer.post( + f"{GATEWAY}/api/v1/orders", + json_body=payload, + headers=csrf, + ) + report("POST /orders (create for dispute)", code, body) + order_obj = body.get("order", {}) if isinstance(body, dict) else {} + order_id = order_obj.get("id", 0) if isinstance(order_obj, dict) else 0 + if not order_id: + skip("Dispute flow", "No order id returned") + return 0 + + code, body, _ = s_consumer.post( + f"{GATEWAY}/api/v1/orders/{order_id}/pay", + json_body={}, + headers=csrf, + ) + report(f"POST /orders/{order_id}/pay (dispute flow)", code, body) + + code, body, _ = s_actor.post( + f"{GATEWAY}/api/v1/orders/{order_id}/accept", + json_body={}, + headers=s_actor.csrf_headers(), + ) + report(f"POST /orders/{order_id}/accept (dispute flow)", code, body) + + code, body, _ = s_consumer.post( + f"{GATEWAY}/api/v1/orders/{order_id}/dispute", + json_body={ + "reason": "test dispute reason", + "evidence": ["http://example.com/evidence.jpg"], + }, + headers=csrf, + ) + report(f"POST /orders/{order_id}/dispute", code, body) + + code, body, _ = s_consumer.get(f"{GATEWAY}/api/v1/orders/{order_id}/dispute") + report(f"GET /orders/{order_id}/dispute", code, body) + dispute_id = as_int(body.get("id")) if isinstance(body, dict) else 0 + + code, body, _ = s_consumer.get(f"{GATEWAY}/api/v1/disputes") + report("GET /disputes", code, body) + + code, body, _ = s_consumer.get(f"{GATEWAY}/api/v1/disputes?status=open") + report("GET /disputes?status=open", code, body) + + if dispute_id: + code, body, _ = s_actor.post( + f"{GATEWAY}/api/v1/disputes/{dispute_id}/response", + json_body={ + "reason": "test respondent guard", + "evidence": ["http://example.com/response.jpg"], + }, + headers=s_actor.csrf_headers(), + ) + report( + f"POST /disputes/{dispute_id}/response (expect participant check)", + code, + body, + expect_status=(400, 403, 500), + ) + + code, body, _ = s_consumer.post( + f"{GATEWAY}/api/v1/disputes/{dispute_id}/appeal", + json_body={"reason": "test appeal guard"}, + headers=csrf, + ) + report( + f"POST /disputes/{dispute_id}/appeal (expect status check)", + code, + body, + expect_status=(400, 403, 500), + ) + + return dispute_id + + +def phase8d_notifications(s: Session): + print("\n=== Phase 8d: Notifications ===") + code, body, _ = s.get(f"{GATEWAY}/api/v1/notifications") + report("GET /notifications", code, body) + + items = pick_items(body) if code == 200 and isinstance(body, dict) else [] + if items: + notification_id = as_int(items[0].get("id")) + if notification_id: + code, body, _ = s.put( + f"{GATEWAY}/api/v1/notifications/{notification_id}/read", + json_body={}, + headers=s.csrf_headers(), + ) + report(f"PUT /notifications/{notification_id}/read", code, body) + else: + skip("PUT /notifications/:id/read", "No notification item returned") + + code, body, _ = s.put( + f"{GATEWAY}/api/v1/notifications/read-all", + json_body={}, + headers=s.csrf_headers(), + ) + report("PUT /notifications/read-all", code, body) + + +def phase8e_search_and_favorites(s: Session, user_id, player_id, shop_id): + print("\n=== Phase 8e: Search & Favorites ===") + + code, body, _ = s.get(f"{GATEWAY}/api/v1/search?q=LOL&limit=10") + report("GET /search?q=LOL&limit=10", code, body) + if code == 200: + report_check( + "GET /search response shape", + isinstance(pick_items(body), list) and isinstance(body.get("meta"), dict), + body, + ) + + code, body, _ = s.get(f"{GATEWAY}/api/v1/recommendations/home?limit=10") + report("GET /recommendations/home?limit=10", code, body) + if code == 200: + report_check( + "GET /recommendations/home response shape", + isinstance(pick_items(body), list) and isinstance(body.get("meta"), dict), + body, + ) + + code, body, _ = s.get(f"{GATEWAY}/api/v1/favorites") + report("GET /favorites", code, body) + + if not player_id or not user_id: + skip("Favorites mutation flow", "Missing user or player id") + return + + code, body, _ = s.post( + f"{GATEWAY}/api/v1/favorites", + json_body={"targetType": "player", "targetId": str(player_id)}, + headers=s.csrf_headers(), + ) + report("POST /favorites (player)", code, body) + + code, body, _ = s.get( + f"{GATEWAY}/api/v1/users/{user_id}/favorites/check" + f"?targetType=player&targetId={player_id}", + ) + report(f"GET /users/{user_id}/favorites/check (player)", code, body) + if code == 200: + report_check("favorite check after add", body.get("favorited") is True, body) + + if shop_id: + code, body, _ = s.post( + f"{GATEWAY}/api/v1/favorites", + json_body={"targetType": "shop", "targetId": str(shop_id)}, + headers=s.csrf_headers(), + ) + report("POST /favorites (shop)", code, body) + + code, body, _ = s.get(f"{GATEWAY}/api/v1/favorites") + report("GET /favorites (after add)", code, body) + favorite_id = 0 + for item in pick_items(body): + if ( + item.get("targetType") == "player" + and str(item.get("targetId")) == str(player_id) + ): + favorite_id = as_int(item.get("id")) + break + report_check("locate favorite id", bool(favorite_id), {"id": favorite_id}) + + if favorite_id: + code, body, _ = s.delete( + f"{GATEWAY}/api/v1/favorites/{favorite_id}", + headers=s.csrf_headers(), + ) + report(f"DELETE /favorites/{favorite_id}", code, body) + + code, body, _ = s.get( + f"{GATEWAY}/api/v1/users/{user_id}/favorites/check" + f"?targetType=player&targetId={player_id}", + ) + report(f"GET /users/{user_id}/favorites/check (after delete)", code, body) + if code == 200: + report_check("favorite check after delete", body.get("favorited") is False, body) + + def phase9_wallet(s: Session): print("\n=== Phase 9: Wallet ===") csrf = s.csrf_headers() @@ -1242,7 +1480,11 @@ def main(): player_id, service_id = phase6_player(s_user, game_id) shop_id = phase7_shop(s_user, s_consumer, user_id, invited_player_id) - phase8_order(s_consumer, s_user, player_id, service_id, shop_id) + order_id = phase8_order(s_consumer, s_user, player_id, service_id, shop_id) + phase8b_review(s_consumer, order_id, player_id) + phase8c_dispute(s_consumer, s_user, player_id, service_id, shop_id) + phase8d_notifications(s_consumer) + phase8e_search_and_favorites(s_consumer, consumer_user_id, player_id, shop_id) phase9_wallet(s_user) phase10_community(s_user, user_id) phase11_objectstory(s_user) diff --git a/desc/api/dispute.api b/desc/api/dispute.api index 0be559d..54b3654 100644 --- a/desc/api/dispute.api +++ b/desc/api/dispute.api @@ -3,34 +3,48 @@ syntax = "v1" import "common.api" type ( - PathId { + DisputePathId { Id int64 `path:"id"` } Dispute { - Id int64 `json:"id"` - OrderId int64 `json:"orderId"` - Reason string `json:"reason"` - Status string `json:"status"` - Evidence []string `json:"evidence"` - Result string `json:"result,optional"` - CreatedAt string `json:"createdAt"` + Id int64 `json:"id"` + OrderId int64 `json:"orderId"` + InitiatorId int64 `json:"initiatorId"` + InitiatorName string `json:"initiatorName"` + RespondentId int64 `json:"respondentId"` + Reason string `json:"reason"` + Evidence []string `json:"evidence"` + Status string `json:"status"` + Result string `json:"result,optional"` + RespondentReason string `json:"respondentReason,optional"` + RespondentEvidence []string `json:"respondentEvidence"` + AppealReason string `json:"appealReason,optional"` + AppealedAt string `json:"appealedAt,optional"` + ResolvedBy int64 `json:"resolvedBy,optional"` + ResolvedAt string `json:"resolvedAt,optional"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` + } + DisputeListReq { + PageReq + Status string `form:"status,optional"` } DisputeListResp { Items []Dispute `json:"items"` Meta PageMeta `json:"meta"` } CreateDisputeReq { - PathId + DisputePathId Reason string `json:"reason"` Evidence []string `json:"evidence"` } DisputeResponseReq { - PathId + DisputePathId Reason string `json:"reason"` Evidence []string `json:"evidence"` } AppealReq { - PathId + DisputePathId Reason string `json:"reason"` } ) @@ -42,11 +56,11 @@ type ( service dispute-api { @doc "获取争议列表" @handler ListDisputes - get /disputes (PageReq) returns (DisputeListResp) + get /disputes (DisputeListReq) returns (DisputeListResp) @doc "获取订单争议" @handler GetOrderDispute - get /orders/:id/dispute (PathId) returns (Dispute) + get /orders/:id/dispute (DisputePathId) returns (Dispute) @doc "发起争议" @handler CreateDispute diff --git a/desc/api/review.api b/desc/api/review.api index cbff4f1..ae4e3fa 100644 --- a/desc/api/review.api +++ b/desc/api/review.api @@ -3,6 +3,9 @@ syntax = "v1" import "common.api" type ( + ReviewPathId { + Id int64 `path:"id"` + } Review { Id int64 `json:"id"` OrderId int64 `json:"orderId"` @@ -18,9 +21,17 @@ type ( Meta PageMeta `json:"meta"` } SubmitReviewReq { + ReviewPathId Rating int `json:"rating"` Content string `json:"content,optional"` } + GetOrderReviewsReq { + ReviewPathId + } + ListUserReviewsReq { + ReviewPathId + PageReq + } ) @server ( @@ -34,7 +45,7 @@ service review-api { @doc "获取订单评价" @handler GetOrderReviews - get /orders/:id/reviews (EmptyResp) returns ([]Review) + get /orders/:id/reviews (GetOrderReviewsReq) returns (ReviewListResp) } @server ( @@ -48,5 +59,5 @@ service review-api { @doc "获取用户收到的评价" @handler ListUserReviews - get /users/:id/reviews (PageReq) returns (ReviewListResp) + get /users/:id/reviews (ListUserReviewsReq) returns (ReviewListResp) } diff --git a/desc/api/search.api b/desc/api/search.api index bb0ca72..17636b6 100644 --- a/desc/api/search.api +++ b/desc/api/search.api @@ -8,7 +8,7 @@ type ( } SearchReq { PageReq - Q string `form:"q"` + Q string `form:"q,optional"` MinPrice float64 `form:"min,optional"` MaxPrice float64 `form:"max,optional"` OnlyOnline bool `form:"onlyOnline,optional"` @@ -18,14 +18,25 @@ type ( Items []interface{} `json:"items"` // Mixed items Meta PageMeta `json:"meta"` } + Favorite { + Id string `json:"id"` + UserId string `json:"userId"` + TargetType string `json:"targetType"` + TargetId string `json:"targetId"` + CreatedAt string `json:"createdAt"` + } + FavoriteListResp { + Items []Favorite `json:"items"` + Meta PageMeta `json:"meta"` + } FavoriteReq { TargetType string `json:"targetType"` // player, shop - TargetId int64 `json:"targetId"` + TargetId string `json:"targetId"` } FavoriteCheckReq { PathIDReq TargetType string `form:"targetType"` - TargetId int64 `form:"targetId"` + TargetId string `form:"targetId"` } FavoriteCheckResp { Favorited bool `json:"favorited"` @@ -53,7 +64,7 @@ service search-api { service search-api { @doc "获取收藏列表" @handler ListFavorites - get /favorites (PageReq) returns (SearchResp) + get /favorites (PageReq) returns (FavoriteListResp) @doc "添加收藏" @handler AddFavorite diff --git a/desc/rpc/dispute.proto b/desc/rpc/dispute.proto new file mode 100644 index 0000000..009d41e --- /dev/null +++ b/desc/rpc/dispute.proto @@ -0,0 +1,137 @@ +syntax = "proto3"; + +option go_package ="./pb"; + +package pb; + +// ------------------------------------ +// Messages +// ------------------------------------ + +//--------------------------------disputes-------------------------------- +message Disputes { + int64 id = 1; + int64 orderId = 2; + int64 initiatorId = 3; + string initiatorName = 4; + int64 respondentId = 5; + string reason = 6; + repeated string evidence = 7; + string status = 8; + string result = 9; + string respondentReason = 10; + repeated string respondentEvidence = 11; + string appealReason = 12; + int64 appealedAt = 13; + int64 resolvedBy = 14; + int64 resolvedAt = 15; + int64 createdAt = 16; + int64 updatedAt = 17; +} + +message AddDisputesReq { + int64 orderId = 1; + int64 initiatorId = 2; + string initiatorName = 3; + int64 respondentId = 4; + string reason = 5; + repeated string evidence = 6; + string status = 7; +} + +message AddDisputesResp { + int64 id = 1; +} + +message UpdateDisputesReq { + int64 id = 1; + optional string status = 2; + optional string result = 3; + optional string respondentReason = 4; + repeated string respondentEvidence = 5; + optional string appealReason = 6; + optional int64 appealedAt = 7; + optional int64 resolvedBy = 8; + optional int64 resolvedAt = 9; +} + +message UpdateDisputesResp { +} + +message DelDisputesReq { + int64 id = 1; +} + +message DelDisputesResp { +} + +message GetDisputesByIdReq { + int64 id = 1; +} + +message GetDisputesByIdResp { + Disputes disputes = 1; +} + +message SearchDisputesReq { + int64 offset = 1; + int64 limit = 2; + optional int64 id = 3; + optional int64 orderId = 4; + optional int64 initiatorId = 5; + optional int64 respondentId = 6; + optional string status = 7; +} + +message SearchDisputesResp { + repeated Disputes disputes = 1; +} + +//--------------------------------disputeTimeline-------------------------------- +message DisputeTimeline { + int64 id = 1; + int64 disputeId = 2; + string eventType = 3; + int64 actorId = 4; + string actorName = 5; + string details = 6; + int64 createdAt = 7; +} + +message AddDisputeTimelineReq { + int64 disputeId = 1; + string eventType = 2; + int64 actorId = 3; + string actorName = 4; + string details = 5; +} + +message AddDisputeTimelineResp { +} + +message SearchDisputeTimelineReq { + int64 offset = 1; + int64 limit = 2; + optional int64 disputeId = 3; +} + +message SearchDisputeTimelineResp { + repeated DisputeTimeline timeline = 1; +} + +// ------------------------------------ +// Rpc Func +// ------------------------------------ + +service disputeService { + //-----------------------disputes----------------------- + rpc AddDisputes(AddDisputesReq) returns (AddDisputesResp); + rpc UpdateDisputes(UpdateDisputesReq) returns (UpdateDisputesResp); + rpc DelDisputes(DelDisputesReq) returns (DelDisputesResp); + rpc GetDisputesById(GetDisputesByIdReq) returns (GetDisputesByIdResp); + rpc SearchDisputes(SearchDisputesReq) returns (SearchDisputesResp); + + //-----------------------disputeTimeline----------------------- + rpc AddDisputeTimeline(AddDisputeTimelineReq) returns (AddDisputeTimelineResp); + rpc SearchDisputeTimeline(SearchDisputeTimelineReq) returns (SearchDisputeTimelineResp); +} diff --git a/desc/rpc/notification.proto b/desc/rpc/notification.proto new file mode 100644 index 0000000..3853323 --- /dev/null +++ b/desc/rpc/notification.proto @@ -0,0 +1,87 @@ +syntax = "proto3"; + +option go_package ="./pb"; + +package pb; + +// ------------------------------------ +// Messages +// ------------------------------------ + +//--------------------------------notifications-------------------------------- +message Notifications { + int64 id = 1; + int64 userId = 2; + string type = 3; + string title = 4; + string content = 5; + bool read = 6; + string link = 7; + int64 createdAt = 8; + int64 updatedAt = 9; +} + +message AddNotificationsReq { + int64 userId = 1; + string type = 2; + string title = 3; + string content = 4; + optional string link = 5; +} + +message AddNotificationsResp { + int64 id = 1; +} + +message UpdateNotificationsReq { + int64 id = 1; + optional bool read = 2; + optional string type = 3; + optional string title = 4; + optional string content = 5; + optional string link = 6; + optional int64 updatedAt = 7; +} + +message UpdateNotificationsResp { +} + +message DelNotificationsReq { + int64 id = 1; +} + +message DelNotificationsResp { +} + +message GetNotificationsByIdReq { + int64 id = 1; +} + +message GetNotificationsByIdResp { + Notifications notifications = 1; +} + +message SearchNotificationsReq { + int64 offset = 1; + int64 limit = 2; + optional int64 id = 3; + optional int64 userId = 4; + optional string type = 5; + optional bool read = 6; +} + +message SearchNotificationsResp { + repeated Notifications notifications = 1; +} + +// ------------------------------------ +// Rpc Func +// ------------------------------------ + +service notificationService { + rpc AddNotifications(AddNotificationsReq) returns (AddNotificationsResp); + rpc UpdateNotifications(UpdateNotificationsReq) returns (UpdateNotificationsResp); + rpc DelNotifications(DelNotificationsReq) returns (DelNotificationsResp); + rpc GetNotificationsById(GetNotificationsByIdReq) returns (GetNotificationsByIdResp); + rpc SearchNotifications(SearchNotificationsReq) returns (SearchNotificationsResp); +} diff --git a/desc/rpc/review.proto b/desc/rpc/review.proto new file mode 100644 index 0000000..37b1aa8 --- /dev/null +++ b/desc/rpc/review.proto @@ -0,0 +1,99 @@ +syntax = "proto3"; + +option go_package ="./pb"; + +package pb; + +// ------------------------------------ +// Messages +// ------------------------------------ + +//--------------------------------reviews-------------------------------- +message Reviews { + int64 id = 1; //id + int64 orderId = 2; //orderId + int64 fromUserId = 3; //fromUserId + string fromUserName = 4; //fromUserName + string fromUserAvatar = 5; //fromUserAvatar + int64 toUserId = 6; //toUserId + int32 rating = 7; //rating + string content = 8; //content + bool sealed = 9; //sealed + int64 createdAt = 10; //createdAt + int64 unsealedAt = 11; //unsealedAt +} + +message AddReviewsReq { + int64 orderId = 1; //orderId + int64 fromUserId = 2; //fromUserId + string fromUserName = 3; //fromUserName + string fromUserAvatar = 4; //fromUserAvatar + int64 toUserId = 5; //toUserId + int32 rating = 6; //rating + string content = 7; //content + bool sealed = 8; //sealed + int64 createdAt = 9; //createdAt +} + +message AddReviewsResp { + int64 id = 1; //id +} + +message UpdateReviewsReq { + int64 id = 1; //id + optional int64 orderId = 2; //orderId + optional int64 fromUserId = 3; //fromUserId + optional string fromUserName = 4; //fromUserName + optional string fromUserAvatar = 5; //fromUserAvatar + optional int64 toUserId = 6; //toUserId + optional int32 rating = 7; //rating + optional string content = 8; //content + optional bool sealed = 9; //sealed + optional int64 createdAt = 10; //createdAt + optional int64 unsealedAt = 11; //unsealedAt +} + +message UpdateReviewsResp { +} + +message DelReviewsReq { + int64 id = 1; //id +} + +message DelReviewsResp { +} + +message GetReviewsByIdReq { + int64 id = 1; //id +} + +message GetReviewsByIdResp { + Reviews reviews = 1; //reviews +} + +message SearchReviewsReq { + int64 offset = 1; //offset + int64 limit = 2; //limit + optional int64 id = 3; //id + optional int64 orderId = 4; //orderId + optional int64 fromUserId = 5; //fromUserId + optional int64 toUserId = 6; //toUserId + optional bool sealed = 7; //sealed +} + +message SearchReviewsResp { + repeated Reviews reviews = 1; //reviews +} + +// ------------------------------------ +// Rpc Func +// ------------------------------------ + +service reviewService { + //-----------------------reviews----------------------- + rpc AddReviews(AddReviewsReq) returns (AddReviewsResp); + rpc UpdateReviews(UpdateReviewsReq) returns (UpdateReviewsResp); + rpc DelReviews(DelReviewsReq) returns (DelReviewsResp); + rpc GetReviewsById(GetReviewsByIdReq) returns (GetReviewsByIdResp); + rpc SearchReviews(SearchReviewsReq) returns (SearchReviewsResp); +} diff --git a/desc/rpc/search.proto b/desc/rpc/search.proto new file mode 100644 index 0000000..dee6eff --- /dev/null +++ b/desc/rpc/search.proto @@ -0,0 +1,67 @@ +syntax = "proto3"; + +option go_package ="./pb"; + +package pb; + +// ------------------------------------ +// Messages +// ------------------------------------ + +//--------------------------------favorites-------------------------------- +message Favorites { + int64 id = 1; + int64 userId = 2; + string targetType = 3; + int64 targetId = 4; + int64 createdAt = 5; +} + +message AddFavoritesReq { + int64 userId = 1; + string targetType = 2; + int64 targetId = 3; +} + +message AddFavoritesResp { + int64 id = 1; +} + +message DelFavoritesReq { + int64 id = 1; +} + +message DelFavoritesResp { +} + +message GetFavoritesByIdReq { + int64 id = 1; +} + +message GetFavoritesByIdResp { + Favorites favorites = 1; +} + +message SearchFavoritesReq { + int64 offset = 1; + int64 limit = 2; + optional int64 id = 3; + optional int64 userId = 4; + optional string targetType = 5; + optional int64 targetId = 6; +} + +message SearchFavoritesResp { + repeated Favorites favorites = 1; +} + +// ------------------------------------ +// Rpc Func +// ------------------------------------ + +service searchService { + rpc AddFavorites(AddFavoritesReq) returns (AddFavoritesResp); + rpc DelFavorites(DelFavoritesReq) returns (DelFavoritesResp); + rpc GetFavoritesById(GetFavoritesByIdReq) returns (GetFavoritesByIdResp); + rpc SearchFavorites(SearchFavoritesReq) returns (SearchFavoritesResp); +} diff --git a/desc/sql/notification/notifications.sql b/desc/sql/notification/notifications.sql new file mode 100644 index 0000000..86bcbdd --- /dev/null +++ b/desc/sql/notification/notifications.sql @@ -0,0 +1,24 @@ +CREATE TABLE notifications +( + id BIGINT PRIMARY KEY, + user_id BIGINT NOT NULL, + type VARCHAR(20) NOT NULL, + title VARCHAR(200) NOT NULL, + content TEXT NOT NULL, + read BOOLEAN NOT NULL DEFAULT FALSE, + link VARCHAR(500), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT chk_notification_type CHECK (type IN ('order', 'community', 'system')) +); + +CREATE INDEX idx_notifications_user_created ON notifications (user_id, created_at DESC); +CREATE INDEX idx_notifications_user_read_created ON notifications (user_id, read, created_at DESC); +CREATE INDEX idx_notifications_user_type_created ON notifications (user_id, type, created_at DESC); + +CREATE TRIGGER trigger_notifications_updated_at + BEFORE UPDATE + ON notifications + FOR EACH ROW + EXECUTE FUNCTION update_updated_at_column(); diff --git a/go.sum b/go.sum index 5babe0f..1e1afa9 100644 --- a/go.sum +++ b/go.sum @@ -162,6 +162,8 @@ github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplb github.com/hashicorp/hcl/v2 v2.18.1 h1:6nxnOJFku1EuSawSD81fuviYUV8DxFr3fp2dUi3ZYSo= github.com/hashicorp/hcl/v2 v2.18.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE= 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= @@ -199,6 +201,8 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM= github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= @@ -215,6 +219,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8m github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= @@ -257,6 +263,8 @@ github.com/quic-go/webtransport-go v0.10.0 h1:LqXXPOXuETY5Xe8ITdGisBzTYmUOy5eSj+ github.com/quic-go/webtransport-go v0.10.0/go.mod h1:LeGIXr5BQKE3UsynwVBeQrU1TPrbh73MGoC6jd+V7ow= github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4= github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/segmentio/kafka-go v0.4.47 h1:IqziR4pA3vrZq7YdRxaT3w1/5fvIH5qpCwstUanQQB0= @@ -267,6 +275,8 @@ github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/pkg/types/TextArray.go b/pkg/types/TextArray.go index d34707c..3bedd2e 100644 --- a/pkg/types/TextArray.go +++ b/pkg/types/TextArray.go @@ -13,6 +13,13 @@ type TextArray pgtype.Array[string] func (s *TextArray) Scan(src any) error { logx.Infof("scan src=%+v", src) + if src == nil { + s.Elements = []string{} + s.Dims = nil + s.Valid = true + return nil + } + var strSrc string switch v := src.(type) { case string: @@ -37,5 +44,8 @@ func (s *TextArray) Scan(src any) error { } func (s TextArray) Value() (driver.Value, error) { + if s.Elements == nil { + return []string{}, nil + } return s.Elements, nil }