From 171526971ed29ff20908b36ce049a31bf0ecee50 Mon Sep 17 00:00:00 2001 From: d_ivahnencko Date: Sat, 1 Oct 2022 21:53:27 +0300 Subject: [PATCH 01/12] Feedbacks were added --- internal/app/app.go | 57 +++++--- internal/controller/http/auth.go | 20 ++- internal/controller/http/interfaces.go | 39 ++++++ internal/controller/http/router.go | 22 ++-- internal/controller/http/student.go | 122 +++++++++--------- internal/controller/http/supervisor.go | 71 +++++----- internal/dto/bid.go | 34 ++--- internal/dto/profile.go | 4 +- internal/dto/relation.go | 16 +++ internal/dto/ssr.go | 16 --- internal/dto/work.go | 26 ++-- internal/entity/auth.go | 12 +- internal/entity/profile.go | 4 +- internal/entity/{ssr.go => relation.go} | 10 +- internal/entity/student.go | 15 +++ internal/entity/user.go | 10 +- internal/entity/work.go | 6 +- internal/{usecase => service}/auth.go | 22 ++-- internal/{usecase => service}/base.go | 2 +- internal/{usecase => service}/bid.go | 48 +++---- internal/{usecase => service}/bid_test.go | 16 +-- internal/{usecase => service}/feedback.go | 6 +- internal/service/interfaces.go | 32 +++++ internal/{usecase => service}/mocks/bid.go | 86 ++++++------ internal/{usecase => service}/profile.go | 22 ++-- .../{usecase/ssr.go => service/relation.go} | 34 ++--- internal/service/repo_pg/auth.go | 63 +++++++++ internal/{usecase => service}/repo_pg/base.go | 0 .../{usecase => service}/repo_pg/feedback.go | 0 internal/service/repo_pg/profile.go | 58 +++++++++ .../ssr.go => service/repo_pg/relation.go} | 62 ++++----- internal/service/repo_pg/student.go | 55 ++++++++ internal/service/repo_pg/user.go | 37 ++++++ internal/{usecase => service}/repo_pg/work.go | 22 ++-- internal/{usecase => service}/work.go | 46 +++---- internal/usecase/interfaces.go | 68 ---------- internal/usecase/repo_pg/auth.go | 31 ----- internal/usecase/repo_pg/profile.go | 58 --------- migrations/20220508102907_create_users.up.sql | 44 ++++--- .../20220509115124_create_students.up.sql | 15 +-- .../20220509192451_create_supervisors.up.sql | 21 ++- .../20220509193416_create_subjects.up.sql | 4 +- migrations/20220509194216_create_works.up.sql | 8 +- .../20220509195738_create_sv_work.up.sql | 15 +-- migrations/20220509200350_create_ssr.up.sql | 12 +- .../20220606071757_create_feedbacks.up.sql | 12 +- swagger/docs.go | 88 ++++++------- swagger/swagger.json | 74 +++++------ swagger/swagger.yaml | 74 +++++------ 49 files changed, 883 insertions(+), 736 deletions(-) create mode 100644 internal/controller/http/interfaces.go create mode 100644 internal/dto/relation.go delete mode 100644 internal/dto/ssr.go rename internal/entity/{ssr.go => relation.go} (83%) create mode 100644 internal/entity/student.go rename internal/{usecase => service}/auth.go (58%) rename internal/{usecase => service}/base.go (89%) rename internal/{usecase => service}/bid.go (59%) rename internal/{usecase => service}/bid_test.go (95%) rename internal/{usecase => service}/feedback.go (89%) create mode 100644 internal/service/interfaces.go rename internal/{usecase => service}/mocks/bid.go (89%) rename internal/{usecase => service}/profile.go (58%) rename internal/{usecase/ssr.go => service/relation.go} (52%) create mode 100644 internal/service/repo_pg/auth.go rename internal/{usecase => service}/repo_pg/base.go (100%) rename internal/{usecase => service}/repo_pg/feedback.go (100%) create mode 100644 internal/service/repo_pg/profile.go rename internal/{usecase/repo_pg/ssr.go => service/repo_pg/relation.go} (61%) create mode 100644 internal/service/repo_pg/student.go create mode 100644 internal/service/repo_pg/user.go rename internal/{usecase => service}/repo_pg/work.go (70%) rename internal/{usecase => service}/work.go (55%) delete mode 100644 internal/usecase/interfaces.go delete mode 100644 internal/usecase/repo_pg/auth.go delete mode 100644 internal/usecase/repo_pg/profile.go diff --git a/internal/app/app.go b/internal/app/app.go index b916ad2..1fb8a4c 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -4,12 +4,13 @@ package app import ( "fmt" "github.com/labstack/echo/v4" - m "github.com/labstack/echo/v4/middleware" + "github.com/labstack/echo/v4/middleware" echoSwagger "github.com/swaggo/echo-swagger" + "net/http" "ssr/config" - "ssr/internal/controller/http" - uc "ssr/internal/usecase" - repo "ssr/internal/usecase/repo_pg" + ctrl "ssr/internal/controller/http" + "ssr/internal/service" + "ssr/internal/service/repo_pg" "ssr/pkg/logger" "ssr/pkg/misc" "ssr/pkg/postgres" @@ -18,10 +19,10 @@ import ( ) func setupMiddlewares(server *echo.Echo, cfg *config.Config) { - server.Use(m.CORS()) - server.Use(m.Logger()) - server.Use(m.Recover()) - server.Use(m.JWTWithConfig(m.JWTConfig{ + server.Use(middleware.CORS()) + server.Use(middleware.Logger()) + server.Use(middleware.Recover()) + server.Use(middleware.JWTWithConfig(middleware.JWTConfig{ Claims: &misc.AppJWTClaims{}, SigningKey: []byte(cfg.SigningKey), ContextKey: "ctx", @@ -34,15 +35,33 @@ func setupMiddlewares(server *echo.Echo, cfg *config.Config) { })) } -func setupUC(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, cfg *config.Config) { - authUC := uc.NewAuth(repo.NewAuthPgRepo(pg, l), l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) - profileUC := uc.NewProfile(repo.NewProfilePgRepo(pg, l), l) - bidUC := uc.NewBid(repo.NewSSRPgRepo(pg, l), l) - workUC := uc.NewWork(repo.NewWorkPgRepo(pg, l), repo.NewSSRPgRepo(pg, l), l) - ssrUC := uc.NewSSR(repo.NewSSRPgRepo(pg, l), l) - feedBackUC := uc.NewFeedback(repo.NewFeedback(pg, l), l) +func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, cfg *config.Config) { + relationRepo := repo_pg.NewRelation(pg, l) + authRepo := repo_pg.NewAuth(pg, l) + profileRepo := repo_pg.NewProfile(pg, l) + workRepo := repo_pg.NewWork(pg, l) + feedbackRepo := repo_pg.NewFeedback(pg, l) - http.NewRouter(server, l, authUC, profileUC, bidUC, bidUC, workUC, workUC, ssrUC, feedBackUC) + authService := service.NewAuth(authRepo, l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) + profileService := service.NewProfile(profileRepo, l) + bidService := service.NewBid(relationRepo, l) + workService := service.NewWork(workRepo, relationRepo, l) + relationService := service.NewRelation(relationRepo, l) + feedbackService := service.NewFeedback(feedbackRepo, l) + + ctrl.NewRouter( + server, + l, + authService, + profileService, + profileService, + bidService, + bidService, + workService, + workService, + relationService, + feedbackService, + ) } func Run(cfg *config.Config) { @@ -57,8 +76,10 @@ func Run(cfg *config.Config) { server := echo.New() setupMiddlewares(server, cfg) - setupUC(server, pg, loggerObject, cfg) + makeInjections(server, pg, loggerObject, cfg) server.GET("/swagger*", echoSwagger.WrapHandler) - server.Logger.Fatal(server.Start(cfg.HTTP.Port)) + if err := server.Start(cfg.HTTP.Port); err != http.ErrServerClosed { + server.Logger.Fatal(err) + } } diff --git a/internal/controller/http/auth.go b/internal/controller/http/auth.go index d60a3f4..374f327 100644 --- a/internal/controller/http/auth.go +++ b/internal/controller/http/auth.go @@ -4,13 +4,12 @@ import ( "fmt" "github.com/labstack/echo/v4" "net/http" - "ssr/internal/usecase" "ssr/pkg/logger" ) -type authRoutes struct { - l logger.Interface - uc usecase.IUsecaseAuth +type auth struct { + l logger.Interface + service AuthService } // ShowAccount godoc @@ -24,13 +23,13 @@ type authRoutes struct { // @Failure 401 // @Failure 500 // @Router /api/auth/login [post] -func (r *authRoutes) login(ctx echo.Context) error { +func (ctrl *auth) login(ctx echo.Context) error { email := ctx.FormValue("username") password := ctx.FormValue("password") - r.l.Debug(fmt.Sprintf("Email %s; Password: %s", email, password)) + ctrl.l.Debug(fmt.Sprintf("Email %s; Password: %s", email, password)) - respDTO, err := r.uc.Login(email, password) + respDTO, err := ctrl.service.Login(email, password) if err != nil { return echo.ErrUnauthorized } @@ -38,13 +37,12 @@ func (r *authRoutes) login(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -func NewAuthRoutes(router *echo.Group, l logger.Interface, uc usecase.IUsecaseAuth) { - ar := &authRoutes{l, uc} +func NewAuthRoutes(router *echo.Group, l logger.Interface, service AuthService) { + ctrl := &auth{l, service} g := router.Group("/auth") - { - g.POST("/login", ar.login) + g.POST("/login", ctrl.login) } } diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go new file mode 100644 index 0000000..9acd07b --- /dev/null +++ b/internal/controller/http/interfaces.go @@ -0,0 +1,39 @@ +package http + +import ( + "ssr/internal/dto" +) + +type ( + AuthService interface { + Login(email, password string) (*dto.LoginResponse, error) + } + StProfileService interface { + GetStudentProfile(email string) (*dto.StProfile, error) + } + SvProfileService interface { + GetSupervisorProfile(email string) (*dto.SvProfile, error) + } + StBidService interface { + GetStudentBids(studentID int) (*dto.StBids, error) + Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) + } + SvBidService interface { + GetSupervisorBids(supervisorID int) (*dto.SvBids, error) + Resolve(data *dto.ResolveBid) error + } + StRelationService interface { + Create(data *dto.CreateSSR) (*dto.StViewRelation, error) + } + StWorkService interface { + GetStudentWorks(studentID int) (*dto.StWorks, error) + GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) + } + SvWorkService interface { + GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) + } + FeedbackService interface { + Add(data *dto.FeedbackReq) (int, error) + GetOnSupervisor(supervisorID int) (*dto.FeedbackPlenty, error) + } +) diff --git a/internal/controller/http/router.go b/internal/controller/http/router.go index fa7484d..e4b9256 100644 --- a/internal/controller/http/router.go +++ b/internal/controller/http/router.go @@ -2,27 +2,27 @@ package http import ( "github.com/labstack/echo/v4" - "ssr/internal/usecase" "ssr/pkg/logger" ) func NewRouter( echo *echo.Echo, l logger.Interface, - auth usecase.IUsecaseAuth, - profile usecase.IUsecaseProfile, - studentBids usecase.IUsecaseStudentBid, - supervisorBids usecase.IUseCaseSupervisorBid, - studentWorks usecase.IStudentWorkUC, - supervisorWorks usecase.ISupervisorWorkUC, - studentRelations usecase.IUseCaseStudentRelation, - feedback usecase.IUsecaseFeedback, + auth AuthService, + stProfile StProfileService, + svProfile SvProfileService, + stBids StBidService, + svBids SvBidService, + stWorks StWorkService, + svWorks SvWorkService, + stRelations StRelationService, + feedback FeedbackService, ) { g := echo.Group("/api") { NewAuthRoutes(g, l, auth) - NewStudentRoutes(g, l, profile, studentBids, studentWorks, studentRelations, feedback) - NewSupervisorRoutes(g, l, profile, supervisorBids, supervisorWorks) + NewStudentRoutes(g, l, stProfile, stBids, stWorks, stRelations, feedback) + NewSupervisorRoutes(g, l, svProfile, svBids, svWorks) } } diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index e2aa220..6b27589 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -6,33 +6,32 @@ import ( "net/http" "ssr/internal/controller/http/middlewares" "ssr/internal/dto" - "ssr/internal/usecase" "ssr/pkg/logger" "ssr/pkg/misc" "strconv" ) -type studentRoutes struct { - l logger.Interface - profileUC usecase.IUsecaseProfile - bidsUC usecase.IUsecaseStudentBid - worksUC usecase.IStudentWorkUC - ssrUC usecase.IUseCaseStudentRelation - feedbackUC usecase.IUsecaseFeedback +type student struct { + l logger.Interface + profileService StProfileService + bidService StBidService + workService StWorkService + relationService StRelationService + feedbackService FeedbackService } // ShowAccount godoc -// @Summary GetUserInfo student's profile +// @Summary GetUserByEmail student's profile // @Tags student // @Produce json -// @Success 200 {object} dto.StudentProfile +// @Success 200 {object} dto.StProfile // @Failure 404 // @Router /api/student/profile [get] // @Security Auth -func (r *studentRoutes) getProfile(ctx echo.Context) error { +func (ctrl *student) getProfile(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - profileDto, err := r.profileUC.GetStudentProfile(email) + profileDto, err := ctrl.profileService.GetStudentProfile(email) if err != nil { return echo.ErrNotFound } @@ -41,21 +40,21 @@ func (r *studentRoutes) getProfile(ctx echo.Context) error { } // ShowAccount godoc -// @Summary GetUserInfo student's bids +// @Summary GetUserByEmail student's bids // @Tags student // @Produce json // @Param student_id query int true "Student ID" -// @Success 200 {object} dto.StudentBids +// @Success 200 {object} dto.StBids // @Failure 404 // @Router /api/student/bid [get] // @Security Auth -func (r *studentRoutes) getBids(ctx echo.Context) error { +func (ctrl *student) getBids(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) studentID, _ := strconv.Atoi(ctx.QueryParam("student_id")) - respDTO, err := r.bidsUC.GetStudentBids(studentID) + respDTO, err := ctrl.bidService.GetStudentBids(studentID) if err != nil { return echo.ErrNotFound } @@ -64,20 +63,20 @@ func (r *studentRoutes) getBids(ctx echo.Context) error { } // ShowAccount godoc -// @Summary GetUserInfo student's works +// @Summary GetUserByEmail student's works // @Tags student // @Param student_id query int true "Student ID" // @Produce json -// @Success 200 {object} dto.StudentWorks +// @Success 200 {object} dto.StWorks // @Router /api/student/work [get] // @Security Auth -func (r *studentRoutes) getWorks(ctx echo.Context) error { +func (ctrl *student) getWorks(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) studentID, _ := strconv.Atoi(ctx.QueryParam("student_id")) - respDTO, err := r.worksUC.GetStudentWorks(studentID) + respDTO, err := ctrl.workService.GetStudentWorks(studentID) if err != nil { return echo.ErrNotFound } @@ -86,20 +85,20 @@ func (r *studentRoutes) getWorks(ctx echo.Context) error { } // ShowAccount godoc -// @Summary GetUserInfo supervisors of the work +// @Summary GetUserByEmail supervisors of the work // @Tags student // @Param work_id query int true "Work ID" // @Produce json -// @Success 200 {object} dto.WorkSupervisorPlenty +// @Success 200 {object} dto.WorkSvPlenty // @Router /api/student/work/supervisor [get] // @Security Auth -func (r *studentRoutes) getSupervisorsOfWork(ctx echo.Context) error { +func (ctrl *student) getSupervisorsOfWork(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) workID, _ := strconv.Atoi(ctx.QueryParam("work_id")) - respDTO, err := r.worksUC.GetWorkSupervisors(workID) + respDTO, err := ctrl.workService.GetWorkSupervisors(workID) if err != nil { return echo.ErrNotFound } @@ -113,19 +112,19 @@ func (r *studentRoutes) getSupervisorsOfWork(ctx echo.Context) error { // @Accept json // @Param ApplyBid body dto.ApplyBid true "bid info" // @Produce json -// @Success 200 {object} dto.ApplyBidResponse +// @Success 200 {object} dto.ApplyBidResp // @Router /api/student/bid [put] // @Security Auth -func (r *studentRoutes) applyBid(ctx echo.Context) error { +func (ctrl *student) applyBid(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) reqDTO := &dto.ApplyBid{} if err := ctx.Bind(reqDTO); err != nil { return echo.ErrBadRequest } - respDTO, err := r.bidsUC.Apply(reqDTO) + respDTO, err := ctrl.bidService.Apply(reqDTO) if err != nil { return echo.ErrInternalServerError } @@ -139,19 +138,19 @@ func (r *studentRoutes) applyBid(ctx echo.Context) error { // @Accept json // @Param ApplyBid body dto.CreateSSR true "ssr info" // @Produce json -// @Success 200 {object} dto.StudentViewSSR +// @Success 200 {object} dto.StViewRelation // @Router /api/student/ssr [post] // @Security Auth -func (r *studentRoutes) createSSR(ctx echo.Context) error { +func (ctrl *student) createSSR(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) reqDTO := &dto.CreateSSR{} if err := ctx.Bind(reqDTO); err != nil { return echo.ErrBadRequest } - respDTO, err := r.ssrUC.Create(reqDTO) + respDTO, err := ctrl.relationService.Create(reqDTO) if err != nil { return echo.ErrInternalServerError } @@ -169,16 +168,16 @@ func (r *studentRoutes) createSSR(ctx echo.Context) error { // @Failure 500 // @Router /api/student/feedback [put] // @Security Auth -func (r *studentRoutes) provideFeedback(ctx echo.Context) error { +func (ctrl *student) provideFeedback(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) reqDTO := &dto.FeedbackReq{} if err := ctx.Bind(reqDTO); err != nil { return echo.ErrBadRequest } - id, err := r.feedbackUC.Add(reqDTO) + id, err := ctrl.feedbackService.Add(reqDTO) if err != nil { return echo.NewHTTPError(http.StatusConflict) } @@ -189,18 +188,18 @@ func (r *studentRoutes) provideFeedback(ctx echo.Context) error { // ShowAccount godoc // @Summary Get feedbacks on the supervisor. // @Tags student -// @Param supervisor_id query int true "Supervisor ID" +// @Param supervisor_id path integer true "Supervisor ID" // @Produce json // @Success 200 {object} dto.FeedbackPlenty // @Router /api/student/feedback [get] // @Security Auth -func (r *studentRoutes) getFeedback(ctx echo.Context) error { +func (ctrl *student) getFeedback(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) + supervisorID, _ := strconv.Atoi(ctx.Param("supervisor_id")) - respDTO, err := r.feedbackUC.GetOnSupervisor(supervisorID) + respDTO, err := ctrl.feedbackService.GetOnSupervisor(supervisorID) if err != nil { return echo.ErrInternalServerError } @@ -211,25 +210,32 @@ func (r *studentRoutes) getFeedback(ctx echo.Context) error { func NewStudentRoutes( router *echo.Group, l logger.Interface, - profileUC usecase.IUsecaseProfile, - bidsUC usecase.IUsecaseStudentBid, - worksUC usecase.IStudentWorkUC, - ssrUC usecase.IUseCaseStudentRelation, - feedbackUC usecase.IUsecaseFeedback, + profileService StProfileService, + bidsService StBidService, + worksService StWorkService, + relationService StRelationService, + feedbackService FeedbackService, ) { - r := &studentRoutes{l, profileUC, bidsUC, worksUC, ssrUC, feedbackUC} + ctrl := &student{ + l, + profileService, + bidsService, + worksService, + relationService, + feedbackService, + } - g := router.Group("/student", middlewares.CheckRole) + student := router.Group("/student", middlewares.CheckRole) { - g.GET("/profile", r.getProfile) - g.GET("/bid", r.getBids) - g.PUT("/bid", r.applyBid) - g.POST("/ssr", r.createSSR) - g.GET("/work", r.getWorks) - g.GET("/work/supervisor", r.getSupervisorsOfWork) - g.GET("/feedback", r.getFeedback) - g.PUT("/feedback", r.provideFeedback) + student.GET("/profile", ctrl.getProfile) + student.GET("/bid", ctrl.getBids) + student.PUT("/bid", ctrl.applyBid) + student.POST("/ssr", ctrl.createSSR) + student.GET("/work", ctrl.getWorks) + student.GET("/work/supervisor_id", ctrl.getSupervisorsOfWork) + student.GET("/feedback/:supervisor_id", ctrl.getFeedback) + student.PUT("/feedback", ctrl.provideFeedback) } } diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index 46f8a71..a619b4e 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -6,33 +6,32 @@ import ( "net/http" "ssr/internal/controller/http/middlewares" "ssr/internal/dto" - "ssr/internal/usecase" "ssr/pkg/logger" "ssr/pkg/misc" "strconv" ) -type supervisorRoutes struct { - l logger.Interface - profileUC usecase.IUsecaseProfile - bidUC usecase.IUseCaseSupervisorBid - workUC usecase.ISupervisorWorkUC +type supervisor struct { + l logger.Interface + profileService SvProfileService + bidService SvBidService + workService SvWorkService } // ShowAccount godoc -// @Summary GetUserInfo supervisor's profile +// @Summary GetUserByEmail supervisor's profile // @Tags supervisor // @Produce json -// @Success 200 {object} dto.SupervisorProfile +// @Success 200 {object} dto.SvProfile // @Router /api/supervisor/profile [get] // @Security Auth -func (r *supervisorRoutes) getProfile(ctx echo.Context) error { +func (ctrl *supervisor) getProfile(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - respDTO, err := r.profileUC.GetSupervisorProfile(email) + respDTO, err := ctrl.profileService.GetSupervisorProfile(email) if err != nil { - r.l.Error(err) + ctrl.l.Error(err) return echo.NewHTTPError(http.StatusInternalServerError, "TODO") } @@ -40,22 +39,22 @@ func (r *supervisorRoutes) getProfile(ctx echo.Context) error { } // ShowAccount godoc -// @Summary GetUserInfo supervisor's works +// @Summary GetUserByEmail supervisor's works // @Tags supervisor // @Param supervisor_id query int true "Supervisor ID" // @Produce json -// @Success 200 {object} dto.SupervisorWorkPlenty +// @Success 200 {object} dto.SvWorkPlenty // @Router /api/supervisor/work [get] // @Security Auth -func (r *supervisorRoutes) getWorks(ctx echo.Context) error { +func (ctrl *supervisor) getWorks(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) - respDTO, err := r.workUC.GetSupervisorWorks(supervisorID) + respDTO, err := ctrl.workService.GetSupervisorWorks(supervisorID) if err != nil { - r.l.Error(err) + ctrl.l.Error(err) return echo.NewHTTPError(http.StatusInternalServerError, "TODO") } @@ -63,22 +62,22 @@ func (r *supervisorRoutes) getWorks(ctx echo.Context) error { } // ShowAccount godoc -// @Summary GetUserInfo supervisor's bids +// @Summary GetUserByEmail supervisor's bids // @Tags supervisor // @Param supervisor_id query int true "Supervisor ID" // @Produce json -// @Success 200 {object} dto.SupervisorBids +// @Success 200 {object} dto.SvBids // @Router /api/supervisor/bid [get] // @Security Auth -func (r *supervisorRoutes) getBids(ctx echo.Context) error { +func (ctrl *supervisor) getBids(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) - respDTO, err := r.bidUC.GetSupervisorBids(supervisorID) + respDTO, err := ctrl.bidService.GetSupervisorBids(supervisorID) if err != nil { - r.l.Error(err) + ctrl.l.Error(err) return echo.NewHTTPError(http.StatusInternalServerError, "TODO") } @@ -93,16 +92,16 @@ func (r *supervisorRoutes) getBids(ctx echo.Context) error { // @Success 200 {object} dto.ResolveBidResp // @Router /api/supervisor/bid/resolve [post] // @Security Auth -func (r *supervisorRoutes) resolveBid(ctx echo.Context) error { +func (ctrl *supervisor) resolveBid(ctx echo.Context) error { email, _ := misc.ExtractCtx(ctx) - r.l.Debug(fmt.Sprintf("Email: %s", email)) + ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) reqDTO := &dto.ResolveBid{} if err := ctx.Bind(reqDTO); err != nil { return echo.ErrBadRequest } - if err := r.bidUC.Resolve(reqDTO); err != nil { + if err := ctrl.bidService.Resolve(reqDTO); err != nil { return echo.NewHTTPError(http.StatusInternalServerError) } @@ -121,20 +120,20 @@ func (r *supervisorRoutes) resolveBid(ctx echo.Context) error { func NewSupervisorRoutes( router *echo.Group, l logger.Interface, - profileUC usecase.IUsecaseProfile, - bidUC usecase.IUseCaseSupervisorBid, - workUC usecase.ISupervisorWorkUC, + profileService SvProfileService, + bidService SvBidService, + workService SvWorkService, ) { - r := &supervisorRoutes{l, profileUC, bidUC, workUC} + ctrl := &supervisor{l, profileService, bidService, workService} g := router.Group("/supervisor", middlewares.CheckRole) { - g.GET("/profile", r.getProfile) - g.GET("/bid", r.getBids) - g.POST("/bid/resolve", r.resolveBid) - g.GET("/work", r.getWorks) - g.GET("/work", r.getWorks) + g.GET("/profile", ctrl.getProfile) + g.GET("/bid", ctrl.getBids) + g.POST("/bid/resolve", ctrl.resolveBid) + g.GET("/work", ctrl.getWorks) + g.GET("/work", ctrl.getWorks) } } diff --git a/internal/dto/bid.go b/internal/dto/bid.go index 06b5ccb..b358f3e 100644 --- a/internal/dto/bid.go +++ b/internal/dto/bid.go @@ -4,28 +4,28 @@ import ( "time" ) -type StudentBid struct { - BidID int `json:"id"` - Status string `json:"status"` - CreatedAt time.Time `json:"createdAt"` - Supervisor SupervisorProfile `json:"supervisor"` - Work Work `json:"work"` +type StBid struct { + BidID int `json:"id"` + Status string `json:"status"` + CreatedAt time.Time `json:"createdAt"` + Supervisor SvProfile `json:"supervisor"` + Work Work `json:"work"` } -type StudentBids struct { - Bids []*StudentBid `json:"bids"` +type StBids struct { + Bids []*StBid `json:"bids"` } -type SupervisorBid struct { - BidID int `json:"id"` - Status string `json:"status"` - CreatedAt time.Time `json:"createdAt"` - Student StudentProfile `json:"student"` - Work Work `json:"work"` +type SvBid struct { + BidID int `json:"id"` + Status string `json:"status"` + CreatedAt time.Time `json:"createdAt"` + Student StProfile `json:"student"` + Work Work `json:"work"` } -type SupervisorBids struct { - Bids []*SupervisorBid `json:"bids"` +type SvBids struct { + Bids []*SvBid `json:"bids"` } type ApplyBid struct { @@ -34,7 +34,7 @@ type ApplyBid struct { WorkID int `json:"workID"` } -type ApplyBidResponse struct { +type ApplyBidResp struct { BidID int `json:"bidID"` } diff --git a/internal/dto/profile.go b/internal/dto/profile.go index d14a36b..fae91bd 100644 --- a/internal/dto/profile.go +++ b/internal/dto/profile.go @@ -11,7 +11,7 @@ type UserInfo struct { AvatarUrl misc.NullString `json:"avatarUrl"` } -type StudentProfile struct { +type StProfile struct { StudentID int `json:"studentID"` Email string `json:"email"` FirstName string `json:"firstName"` @@ -22,7 +22,7 @@ type StudentProfile struct { Department string `json:"department"` } -type SupervisorProfile struct { +type SvProfile struct { SupervisorID int `json:"supervisorID"` Email string `json:"email"` FirstName string `json:"firstName"` diff --git a/internal/dto/relation.go b/internal/dto/relation.go new file mode 100644 index 0000000..db8eaf7 --- /dev/null +++ b/internal/dto/relation.go @@ -0,0 +1,16 @@ +package dto + +import "time" + +type CreateSSR struct { + StudentID int `json:"studentID"` + BidID int `json:"bidID"` +} + +type StViewRelation struct { + RelID int `json:"id"` + Status string `json:"status"` + CreatedAt time.Time `json:"createdAt"` + Supervisor SvProfile `json:"supervisor"` + Work Work `json:"work"` +} diff --git a/internal/dto/ssr.go b/internal/dto/ssr.go deleted file mode 100644 index 2672f85..0000000 --- a/internal/dto/ssr.go +++ /dev/null @@ -1,16 +0,0 @@ -package dto - -import "time" - -type CreateSSR struct { - StudentID int `json:"studentID"` - BidID int `json:"bidID"` -} - -type StudentViewSSR struct { - RelID int `json:"id"` - Status string `json:"status"` - CreatedAt time.Time `json:"createdAt"` - Supervisor SupervisorProfile `json:"supervisor"` - Work Work `json:"work"` -} diff --git a/internal/dto/work.go b/internal/dto/work.go index 6f56097..3299550 100644 --- a/internal/dto/work.go +++ b/internal/dto/work.go @@ -8,7 +8,7 @@ type Work struct { Subject SubjectResp `json:"subject"` } -type StudentWork struct { +type StWork struct { WorkID int `json:"id"` Kind string `json:"kind"` Description string `json:"description"` @@ -16,12 +16,12 @@ type StudentWork struct { IsStarted bool `json:"is_started"` } -type StudentWorks struct { - StudentID int `json:"studentID"` - Works []*StudentWork `json:"works"` +type StWorks struct { + StudentID int `json:"studentID"` + Works []*StWork `json:"works"` } -type SupervisorWork struct { +type SvWork struct { WorkID int `json:"id"` Kind string `json:"kind"` Description string `json:"description"` @@ -29,18 +29,18 @@ type SupervisorWork struct { Head bool `json:"head"` } -type SupervisorWorkPlenty struct { - SupervisorID int `json:"supervisorID"` - Works []*SupervisorWork `json:"works"` +type SvWorkPlenty struct { + SupervisorID int `json:"supervisorID"` + Works []*SvWork `json:"works"` } -type WorkSupervisor struct { - SupervisorProfile +type WorkSv struct { + SvProfile Head bool `json:"head"` Full bool `json:"full"` } -type WorkSupervisorPlenty struct { - WorkID int `json:"workID"` - Supervisors []*WorkSupervisor `json:"supervisors"` +type WorkSvPlenty struct { + WorkID int `json:"workID"` + Supervisors []*WorkSv `json:"supervisors"` } diff --git a/internal/entity/auth.go b/internal/entity/auth.go index 22e1d9d..eac059c 100644 --- a/internal/entity/auth.go +++ b/internal/entity/auth.go @@ -1,14 +1,6 @@ package entity -type UserRole string - -const ( - student UserRole = "student" - supervisor = "supervisor" -) - type Auth struct { - Email string `db:"email"` - Password string `db:"password"` - Role UserRole `db:"role"` + Email string `db:"email"` + Password string `db:"password"` } diff --git a/internal/entity/profile.go b/internal/entity/profile.go index 7f11a4a..cdbb7c6 100644 --- a/internal/entity/profile.go +++ b/internal/entity/profile.go @@ -2,7 +2,7 @@ package entity import "time" -type StudentProfile struct { +type StProfile struct { *User StudentID int `db:"student_id"` StudentCard string `db:"student_card"` @@ -10,7 +10,7 @@ type StudentProfile struct { DepartmentID string `db:"department_id"` } -type SupervisorProfile struct { +type SvProfile struct { *User SupervisorID int `db:"supervisor_id"` Birthdate time.Time `db:"birthdate"` diff --git a/internal/entity/ssr.go b/internal/entity/relation.go similarity index 83% rename from internal/entity/ssr.go rename to internal/entity/relation.go index 790680f..54df3c6 100644 --- a/internal/entity/ssr.go +++ b/internal/entity/relation.go @@ -13,24 +13,24 @@ const ( completed = "done" ) -type WaypointSsr struct { +type WaypointRelation struct { *Waypoint Status string `db:"waypoint_status"` SsrID int `db:"ssr_id"` } -type StudentSsr struct { +type StRelation struct { BidID int `db:"ssr_id"` CreatedAt time.Time `db:"created_at"` Status string `db:"ssr_status"` - *SupervisorProfile + *SvProfile *Work } -type SupervisorSsr struct { +type SvRelation struct { BidID int `db:"ssr_id"` CreatedAt time.Time `db:"created_at"` Status string `db:"ssr_status"` - *StudentProfile + *StProfile *Work } diff --git a/internal/entity/student.go b/internal/entity/student.go new file mode 100644 index 0000000..685cb23 --- /dev/null +++ b/internal/entity/student.go @@ -0,0 +1,15 @@ +package entity + +type Student struct { + UserID int `db:"user_id"` + StudentCard string `db:"student_card"` + Year int + DepartmentID string `db:"department_id"` +} + +type StudentFull struct { + User *User + StudentCard string `db:"student_card"` + Year int + DepartmentID string `db:"department_id"` +} diff --git a/internal/entity/user.go b/internal/entity/user.go index d3b304e..d91c416 100644 --- a/internal/entity/user.go +++ b/internal/entity/user.go @@ -2,10 +2,18 @@ package entity import "database/sql" +type UserRole string + +const ( + student UserRole = "st" + supervisor = "sv" +) + type User struct { UserID int `db:"user_id"` Email string `db:"email"` FirstName string `db:"first_name"` LastName string `db:"last_name"` - Avatar sql.NullString `db:"avatar_url"` + PhotoUrl sql.NullString `db:"photo_url"` + Role UserRole `db:"role"` } diff --git a/internal/entity/work.go b/internal/entity/work.go index 674aedc..d4c0c5a 100644 --- a/internal/entity/work.go +++ b/internal/entity/work.go @@ -13,13 +13,13 @@ type Work struct { Semester int8 } -type WorkOfSupervisor struct { +type SvWork struct { *Work Head bool `db:"head"` } -type SupervisorOfWork struct { - *SupervisorProfile +type WorkSv struct { + *SvProfile Head bool `db:"head"` Full bool `db:"full"` } diff --git a/internal/usecase/auth.go b/internal/service/auth.go similarity index 58% rename from internal/usecase/auth.go rename to internal/service/auth.go index 9a56d96..90b3850 100644 --- a/internal/usecase/auth.go +++ b/internal/service/auth.go @@ -1,4 +1,4 @@ -package usecase +package service import ( "github.com/golang-jwt/jwt" @@ -9,15 +9,15 @@ import ( "time" ) -type Auth struct { +type auth struct { *Base - repo IRepoAuth + repo AuthRepo tokenExp time.Duration signingKey []byte } -func NewAuth(r IRepoAuth, l logger.Interface, tokenExpMinutes int, signingKey []byte) *Auth { - return &Auth{ +func NewAuth(r AuthRepo, l logger.Interface, tokenExpMinutes int, signingKey []byte) *auth { + return &auth{ Base: NewBase(l), repo: r, tokenExp: time.Duration(tokenExpMinutes) * time.Minute, @@ -25,23 +25,23 @@ func NewAuth(r IRepoAuth, l logger.Interface, tokenExpMinutes int, signingKey [] } } -func (uc *Auth) Login(email, password string) (*dto.LoginResponse, error) { - dbData, err := uc.repo.GetUserInfo(email) +func (service *auth) Login(email, password string) (*dto.LoginResponse, error) { + dbData, err := service.repo.GetUserByEmail(email) if err != nil { return nil, err } if err = bcrypt.CompareHashAndPassword([]byte(dbData.Password), []byte(password)); err != nil { - uc.l.Error(err) + service.l.Error(err) return nil, err } - tokenClaims := misc.NewAppJWTClaims(uc.tokenExp, dbData.Email, string(dbData.Role)) + tokenClaims := misc.NewAppJWTClaims(service.tokenExp, dbData.Email, string(dbData.Role)) token := jwt.NewWithClaims(jwt.SigningMethodHS256, tokenClaims) - tokenStr, err := token.SignedString(uc.signingKey) + tokenStr, err := token.SignedString(service.signingKey) if err != nil { - uc.l.Error(err) + service.l.Error(err) return nil, err } diff --git a/internal/usecase/base.go b/internal/service/base.go similarity index 89% rename from internal/usecase/base.go rename to internal/service/base.go index 44996eb..968b4f6 100644 --- a/internal/usecase/base.go +++ b/internal/service/base.go @@ -1,4 +1,4 @@ -package usecase +package service import ( "ssr/pkg/logger" diff --git a/internal/usecase/bid.go b/internal/service/bid.go similarity index 59% rename from internal/usecase/bid.go rename to internal/service/bid.go index 491dacf..3899f09 100644 --- a/internal/usecase/bid.go +++ b/internal/service/bid.go @@ -1,4 +1,4 @@ -package usecase +package service import ( "ssr/internal/dto" @@ -9,30 +9,30 @@ import ( type Bid struct { *Base - repo IRepoSSR + repo RelationRepo } -func NewBid(r IRepoSSR, l logger.Interface) *Bid { +func NewBid(r RelationRepo, l logger.Interface) *Bid { return &Bid{ Base: NewBase(l), repo: r, } } -func (uc *Bid) GetStudentBids(studentID int) (*dto.StudentBids, error) { - dbData, err := uc.repo.GetStudentBids(studentID) +func (service *Bid) GetStudentBids(studentID int) (*dto.StBids, error) { + dbData, err := service.repo.GetStudentBids(studentID) if err != nil { return nil, err } - var resp []*dto.StudentBid + var resp []*dto.StBid for _, db := range dbData { - resp = append(resp, &dto.StudentBid{ + resp = append(resp, &dto.StBid{ BidID: db.BidID, Status: db.Status, CreatedAt: db.CreatedAt, - Supervisor: dto.SupervisorProfile{ + Supervisor: dto.SvProfile{ SupervisorID: db.SupervisorID, Email: db.Email, FirstName: db.FirstName, @@ -41,8 +41,8 @@ func (uc *Bid) GetStudentBids(studentID int) (*dto.StudentBids, error) { Birthdate: misc.Date{ Time: db.Birthdate, }, - AvatarUrl: misc.NullString(db.Avatar), - Department: db.SupervisorProfile.DepartmentID, + AvatarUrl: misc.NullString(db.PhotoUrl), + Department: db.SvProfile.DepartmentID, }, Work: dto.Work{ WorkID: db.WorkID, @@ -58,30 +58,30 @@ func (uc *Bid) GetStudentBids(studentID int) (*dto.StudentBids, error) { }) } - return &dto.StudentBids{Bids: resp}, nil + return &dto.StBids{Bids: resp}, nil } -func (uc *Bid) GetSupervisorBids(supervisorID int) (*dto.SupervisorBids, error) { - dbData, err := uc.repo.GetSupervisorBids(supervisorID) +func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { + dbData, err := service.repo.GetSupervisorBids(supervisorID) if err != nil { return nil, err } - var resp []*dto.SupervisorBid + var resp []*dto.SvBid for _, db := range dbData { - resp = append(resp, &dto.SupervisorBid{ + resp = append(resp, &dto.SvBid{ BidID: db.BidID, Status: db.Status, CreatedAt: db.CreatedAt, - Student: dto.StudentProfile{ + Student: dto.StProfile{ StudentID: db.StudentID, Email: db.Email, FirstName: db.FirstName, LastName: db.LastName, Year: db.Year, - AvatarUrl: misc.NullString(db.Avatar), - Department: db.StudentProfile.DepartmentID, + AvatarUrl: misc.NullString(db.PhotoUrl), + Department: db.StProfile.DepartmentID, }, Work: dto.Work{ WorkID: db.WorkID, @@ -97,19 +97,19 @@ func (uc *Bid) GetSupervisorBids(supervisorID int) (*dto.SupervisorBids, error) }) } - return &dto.SupervisorBids{Bids: resp}, nil + return &dto.SvBids{Bids: resp}, nil } -func (uc *Bid) Apply(data *dto.ApplyBid) (*dto.ApplyBidResponse, error) { - bidID, err := uc.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) +func (service *Bid) Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) { + bidID, err := service.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) if err != nil { return nil, err } - return &dto.ApplyBidResponse{BidID: bidID}, nil + return &dto.ApplyBidResp{BidID: bidID}, nil } -func (uc *Bid) Resolve(data *dto.ResolveBid) error { +func (service *Bid) Resolve(data *dto.ResolveBid) error { var status entity.StatusSSR if data.Accept { @@ -118,6 +118,6 @@ func (uc *Bid) Resolve(data *dto.ResolveBid) error { status = "rejected" } - _, err := uc.repo.UpdateStatus(data.BidID, status) + _, err := service.repo.UpdateStatus(data.BidID, status) return err } diff --git a/internal/usecase/bid_test.go b/internal/service/bid_test.go similarity index 95% rename from internal/usecase/bid_test.go rename to internal/service/bid_test.go index e89378b..c3a1d90 100644 --- a/internal/usecase/bid_test.go +++ b/internal/service/bid_test.go @@ -1,4 +1,4 @@ -package usecase +package service // //import ( @@ -143,13 +143,13 @@ package usecase // BidID: 1, // CreatedAt: time.Time{}, // Status: "wip", -// SupervisorProfile: &entity.SupervisorProfile{ +// SvProfile: &entity.SvProfile{ // User: &entity.User{ // UserID: 2, // Email: "kek@kek.com", // FirstName: "Иван", // LastName: "Иванов", -// Avatar: sql.NullString{}, +// PhotoUrl: sql.NullString{}, // }, // SupervisorID: 1, // Birthdate: time.Time{}, @@ -184,7 +184,7 @@ package usecase // RelID: 1, // Status: "wip", // CreatedAt: time.Time{}, -// Supervisor: dto.SupervisorProfile{ +// Supervisor: dto.SvProfile{ // SupervisorID: 1, // Email: "kek@kek.com", // FirstName: "Иван", @@ -217,13 +217,13 @@ package usecase // BidID: 1, // CreatedAt: time.Time{}, // Status: "wip", -// SupervisorProfile: &entity.SupervisorProfile{ +// SvProfile: &entity.SvProfile{ // User: &entity.User{ // UserID: 2, // Email: "kek@kek.com", // FirstName: "Иван", // LastName: "Иванов", -// Avatar: sql.NullString{}, +// PhotoUrl: sql.NullString{}, // }, // SupervisorID: 1, // Birthdate: time.Time{}, @@ -258,7 +258,7 @@ package usecase // RelID: 1, // Status: "wip", // CreatedAt: time.Time{}, -// Supervisor: dto.SupervisorProfile{ +// Supervisor: dto.SvProfile{ // SupervisorID: 1, // Email: "kek@kek.com", // FirstName: "Иван", @@ -287,7 +287,7 @@ package usecase // t.Run(tt.name, func(t *testing.T) { // ctrl := gomock.NewController(t) // -// u := NewSSR(tt.repository(ctrl)) +// u := NewRelation(tt.repository(ctrl)) // // received, err := u.Create(tt.args.req) // diff --git a/internal/usecase/feedback.go b/internal/service/feedback.go similarity index 89% rename from internal/usecase/feedback.go rename to internal/service/feedback.go index 0f85760..1356435 100644 --- a/internal/usecase/feedback.go +++ b/internal/service/feedback.go @@ -1,4 +1,4 @@ -package usecase +package service import ( "ssr/internal/dto" @@ -7,10 +7,10 @@ import ( type Feedback struct { *Base - repo IRepoFeedback + repo FeedbackRepo } -func NewFeedback(r IRepoFeedback, l logger.Interface) *Feedback { +func NewFeedback(r FeedbackRepo, l logger.Interface) *Feedback { return &Feedback{ Base: NewBase(l), repo: r, diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go new file mode 100644 index 0000000..d304cf7 --- /dev/null +++ b/internal/service/interfaces.go @@ -0,0 +1,32 @@ +package service + +import ( + "ssr/internal/entity" +) + +type ( + AuthRepo interface { + GetUserByEmail(email string) (*entity.Auth, error) + } + ProfileRepo interface { + GetStProfile(email string) (*entity.StProfile, error) + GetSvProfile(email string) (*entity.SvProfile, error) + } + RelationRepo interface { + Create(studentID, supervisorID, workID int) (int, error) + GetStudentBids(studentID int) ([]*entity.StRelation, error) + GetSupervisorBids(studentID int) ([]*entity.SvRelation, error) + GetStudentRelations(studentID int) ([]*entity.StRelation, error) + GetStudentRelation(studentID, ssrID int) (*entity.StRelation, error) + UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) + } + WorkRepo interface { + GetWorksByStudentID(studentID int) ([]*entity.Work, error) + GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) + GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) + } + FeedbackRepo interface { + Create(studentID, supervisorID, workID int, content string) (int, error) + GetBySupervisorID(supervisorID int) ([]*entity.Feedback, error) + } +) diff --git a/internal/usecase/mocks/bid.go b/internal/service/mocks/bid.go similarity index 89% rename from internal/usecase/mocks/bid.go rename to internal/service/mocks/bid.go index 8096230..8c41f73 100644 --- a/internal/usecase/mocks/bid.go +++ b/internal/service/mocks/bid.go @@ -36,9 +36,9 @@ func (m *MockIAuthRepo) EXPECT() *MockIAuthRepoMockRecorder { } // Get mocks base method. -func (m *MockIAuthRepo) GetUserInfo(email string) (*entity.Auth, error) { +func (m *MockIAuthRepo) GetUserByEmail(email string) (*entity.Auth, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUserInfo", email) + ret := m.ctrl.Call(m, "GetUserByEmail", email) ret0, _ := ret[0].(*entity.Auth) ret1, _ := ret[1].(error) return ret0, ret1 @@ -47,7 +47,7 @@ func (m *MockIAuthRepo) GetUserInfo(email string) (*entity.Auth, error) { // Get indicates an expected call of Get. func (mr *MockIAuthRepoMockRecorder) Get(email interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserInfo", reflect.TypeOf((*MockIAuthRepo)(nil).GetUserInfo), email) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByEmail", reflect.TypeOf((*MockIAuthRepo)(nil).GetUserByEmail), email) } // MockIAuthUC is a mock of IAuthUC interface. @@ -112,10 +112,10 @@ func (m *MockIProfileRepo) EXPECT() *MockIProfileRepoMockRecorder { } // GetStudentProfile mocks base method. -func (m *MockIProfileRepo) GetStudentProfile(email string) (*entity.StudentProfile, error) { +func (m *MockIProfileRepo) GetStProfile(email string) (*entity.StProfile, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStudentProfile", email) - ret0, _ := ret[0].(*entity.StudentProfile) + ret := m.ctrl.Call(m, "GetStProfile", email) + ret0, _ := ret[0].(*entity.StProfile) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -123,14 +123,14 @@ func (m *MockIProfileRepo) GetStudentProfile(email string) (*entity.StudentProfi // GetStudentProfile indicates an expected call of GetStudentProfile. func (mr *MockIProfileRepoMockRecorder) GetStudentProfile(email interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentProfile", reflect.TypeOf((*MockIProfileRepo)(nil).GetStudentProfile), email) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStProfile", reflect.TypeOf((*MockIProfileRepo)(nil).GetStProfile), email) } // GetSupervisorProfile mocks base method. -func (m *MockIProfileRepo) GetSupervisorProfile(email string) (*entity.SupervisorProfile, error) { +func (m *MockIProfileRepo) GetSvProfile(email string) (*entity.SvProfile, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSupervisorProfile", email) - ret0, _ := ret[0].(*entity.SupervisorProfile) + ret := m.ctrl.Call(m, "GetSvProfile", email) + ret0, _ := ret[0].(*entity.SvProfile) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -138,7 +138,7 @@ func (m *MockIProfileRepo) GetSupervisorProfile(email string) (*entity.Superviso // GetSupervisorProfile indicates an expected call of GetSupervisorProfile. func (mr *MockIProfileRepoMockRecorder) GetSupervisorProfile(email interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSupervisorProfile", reflect.TypeOf((*MockIProfileRepo)(nil).GetSupervisorProfile), email) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSvProfile", reflect.TypeOf((*MockIProfileRepo)(nil).GetSvProfile), email) } // MockIProfileUC is a mock of IProfileUC interface. @@ -165,10 +165,10 @@ func (m *MockIProfileUC) EXPECT() *MockIProfileUCMockRecorder { } // GetStudentProfile mocks base method. -func (m *MockIProfileUC) GetStudentProfile(email string) (*dto.StudentProfile, error) { +func (m *MockIProfileUC) GetStudentProfile(email string) (*dto.StProfile, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStudentProfile", email) - ret0, _ := ret[0].(*dto.StudentProfile) + ret := m.ctrl.Call(m, "GetStProfile", email) + ret0, _ := ret[0].(*dto.StProfile) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -176,14 +176,14 @@ func (m *MockIProfileUC) GetStudentProfile(email string) (*dto.StudentProfile, e // GetStudentProfile indicates an expected call of GetStudentProfile. func (mr *MockIProfileUCMockRecorder) GetStudentProfile(email interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentProfile", reflect.TypeOf((*MockIProfileUC)(nil).GetStudentProfile), email) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStProfile", reflect.TypeOf((*MockIProfileUC)(nil).GetStudentProfile), email) } // GetSupervisorProfile mocks base method. -func (m *MockIProfileUC) GetSupervisorProfile(email string) (*dto.SupervisorProfile, error) { +func (m *MockIProfileUC) GetSupervisorProfile(email string) (*dto.SvProfile, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSupervisorProfile", email) - ret0, _ := ret[0].(*dto.SupervisorProfile) + ret := m.ctrl.Call(m, "GetSvProfile", email) + ret0, _ := ret[0].(*dto.SvProfile) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -191,7 +191,7 @@ func (m *MockIProfileUC) GetSupervisorProfile(email string) (*dto.SupervisorProf // GetSupervisorProfile indicates an expected call of GetSupervisorProfile. func (mr *MockIProfileUCMockRecorder) GetSupervisorProfile(email interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSupervisorProfile", reflect.TypeOf((*MockIProfileUC)(nil).GetSupervisorProfile), email) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSvProfile", reflect.TypeOf((*MockIProfileUC)(nil).GetSupervisorProfile), email) } // MockIRelRepo is a mock of IRelRepo interface. @@ -233,10 +233,10 @@ func (mr *MockIRelRepoMockRecorder) Create(studentID, supervisorID, workID inter } // GetStudentViewBidPlenty mocks base method. -func (m *MockIRelRepo) GetStudentViewBidPlenty(studentID int) ([]*entity.StudentSsr, error) { +func (m *MockIRelRepo) GetStudentViewBidPlenty(studentID int) ([]*entity.StRelation, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStudentBids", studentID) - ret0, _ := ret[0].([]*entity.StudentSsr) + ret0, _ := ret[0].([]*entity.StRelation) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -248,10 +248,10 @@ func (mr *MockIRelRepoMockRecorder) GetStudentViewBidPlenty(studentID interface{ } // GetStudentViewSSR mocks base method. -func (m *MockIRelRepo) GetStudentViewSSR(studentID, ssrID int) (*entity.StudentSsr, error) { +func (m *MockIRelRepo) GetStudentViewSSR(studentID, ssrID int) (*entity.StRelation, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStudentRelation", studentID, ssrID) - ret0, _ := ret[0].(*entity.StudentSsr) + ret0, _ := ret[0].(*entity.StRelation) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -263,10 +263,10 @@ func (mr *MockIRelRepoMockRecorder) GetStudentViewSSR(studentID, ssrID interface } // GetSupervisorViewBidPlenty mocks base method. -func (m *MockIRelRepo) GetSupervisorViewBidPlenty(studentID int) ([]*entity.SupervisorSsr, error) { +func (m *MockIRelRepo) GetSupervisorViewBidPlenty(studentID int) ([]*entity.SvRelation, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSupervisorBids", studentID) - ret0, _ := ret[0].([]*entity.SupervisorSsr) + ret0, _ := ret[0].([]*entity.SvRelation) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -316,10 +316,10 @@ func (m *MockIStudentBidUC) EXPECT() *MockIStudentBidUCMockRecorder { } // Apply mocks base method. -func (m *MockIStudentBidUC) Apply(data *dto.ApplyBid) (*dto.ApplyBidResponse, error) { +func (m *MockIStudentBidUC) Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Apply", data) - ret0, _ := ret[0].(*dto.ApplyBidResponse) + ret0, _ := ret[0].(*dto.ApplyBidResp) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -331,10 +331,10 @@ func (mr *MockIStudentBidUCMockRecorder) Apply(data interface{}) *gomock.Call { } // GetStudentBids mocks base method. -func (m *MockIStudentBidUC) GetStudentBids(studentID int) (*dto.StudentBids, error) { +func (m *MockIStudentBidUC) GetStudentBids(studentID int) (*dto.StBids, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStudentBids", studentID) - ret0, _ := ret[0].(*dto.StudentBids) + ret0, _ := ret[0].(*dto.StBids) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -369,10 +369,10 @@ func (m *MockISupervisorBidUC) EXPECT() *MockISupervisorBidUCMockRecorder { } // GetSupervisorBids mocks base method. -func (m *MockISupervisorBidUC) GetSupervisorBids(supervisorID int) (*dto.SupervisorBids, error) { +func (m *MockISupervisorBidUC) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSupervisorBids", supervisorID) - ret0, _ := ret[0].(*dto.SupervisorBids) + ret0, _ := ret[0].(*dto.SvBids) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -421,10 +421,10 @@ func (m *MockIStudentRelUC) EXPECT() *MockIStudentRelUCMockRecorder { } // Create mocks base method. -func (m *MockIStudentRelUC) Create(data *dto.CreateSSR) (*dto.StudentViewSSR, error) { +func (m *MockIStudentRelUC) Create(data *dto.CreateSSR) (*dto.StViewRelation, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", data) - ret0, _ := ret[0].(*dto.StudentViewSSR) + ret0, _ := ret[0].(*dto.StViewRelation) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -459,10 +459,10 @@ func (m *MockIWorkRepo) EXPECT() *MockIWorkRepoMockRecorder { } // GetSupervisorsByWorkID mocks base method. -func (m *MockIWorkRepo) GetSupervisorsByWorkID(workID int) ([]*entity.SupervisorOfWork, error) { +func (m *MockIWorkRepo) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSupervisorsByWorkID", workID) - ret0, _ := ret[0].([]*entity.SupervisorOfWork) + ret0, _ := ret[0].([]*entity.WorkSv) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -489,10 +489,10 @@ func (mr *MockIWorkRepoMockRecorder) GetWorksByStudentID(studentID interface{}) } // GetWorksBySupervisorID mocks base method. -func (m *MockIWorkRepo) GetWorksBySupervisorID(supervisorID int) ([]*entity.WorkOfSupervisor, error) { +func (m *MockIWorkRepo) GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetWorksBySupervisorID", supervisorID) - ret0, _ := ret[0].([]*entity.WorkOfSupervisor) + ret0, _ := ret[0].([]*entity.SvWork) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -527,10 +527,10 @@ func (m *MockIStudentWorkUC) EXPECT() *MockIStudentWorkUCMockRecorder { } // GetStudentWorks mocks base method. -func (m *MockIStudentWorkUC) GetStudentWorks(studentID int) (*dto.StudentWorks, error) { +func (m *MockIStudentWorkUC) GetStudentWorks(studentID int) (*dto.StWorks, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStudentWorks", studentID) - ret0, _ := ret[0].(*dto.StudentWorks) + ret0, _ := ret[0].(*dto.StWorks) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -542,10 +542,10 @@ func (mr *MockIStudentWorkUCMockRecorder) GetStudentWorks(studentID interface{}) } // GetWorkSupervisors mocks base method. -func (m *MockIStudentWorkUC) GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error) { +func (m *MockIStudentWorkUC) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetWorkSupervisors", workID) - ret0, _ := ret[0].(*dto.WorkSupervisorPlenty) + ret0, _ := ret[0].(*dto.WorkSvPlenty) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -580,10 +580,10 @@ func (m *MockISupervisorWorkUC) EXPECT() *MockISupervisorWorkUCMockRecorder { } // GetSupervisorWorks mocks base method. -func (m *MockISupervisorWorkUC) GetSupervisorWorks(supervisorID int) (*dto.SupervisorWorkPlenty, error) { +func (m *MockISupervisorWorkUC) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSupervisorWorks", supervisorID) - ret0, _ := ret[0].(*dto.SupervisorWorkPlenty) + ret0, _ := ret[0].(*dto.SvWorkPlenty) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/internal/usecase/profile.go b/internal/service/profile.go similarity index 58% rename from internal/usecase/profile.go rename to internal/service/profile.go index b8e9b66..94fdc41 100644 --- a/internal/usecase/profile.go +++ b/internal/service/profile.go @@ -1,4 +1,4 @@ -package usecase +package service import ( "ssr/internal/dto" @@ -8,46 +8,46 @@ import ( type Profile struct { *Base - repo IRepoProfile + repo ProfileRepo } -func NewProfile(r IRepoProfile, l logger.Interface) *Profile { +func NewProfile(r ProfileRepo, l logger.Interface) *Profile { return &Profile{ Base: NewBase(l), repo: r, } } -func (uc *Profile) GetStudentProfile(email string) (*dto.StudentProfile, error) { - dbData, err := uc.repo.GetStudentProfile(email) +func (uc *Profile) GetStudentProfile(email string) (*dto.StProfile, error) { + dbData, err := uc.repo.GetStProfile(email) if err != nil { return nil, err } - return &dto.StudentProfile{ + return &dto.StProfile{ StudentID: dbData.StudentID, Email: dbData.Email, FirstName: dbData.FirstName, LastName: dbData.LastName, - AvatarUrl: misc.NullString(dbData.Avatar), + AvatarUrl: misc.NullString(dbData.PhotoUrl), Year: dbData.Year, StudentCard: dbData.StudentCard, Department: dbData.DepartmentID, }, nil } -func (uc *Profile) GetSupervisorProfile(email string) (*dto.SupervisorProfile, error) { - dbData, err := uc.repo.GetSupervisorProfile(email) +func (uc *Profile) GetSupervisorProfile(email string) (*dto.SvProfile, error) { + dbData, err := uc.repo.GetSvProfile(email) if err != nil { return nil, err } - return &dto.SupervisorProfile{ + return &dto.SvProfile{ SupervisorID: dbData.SupervisorID, Email: dbData.Email, FirstName: dbData.FirstName, LastName: dbData.LastName, - AvatarUrl: misc.NullString(dbData.Avatar), + AvatarUrl: misc.NullString(dbData.PhotoUrl), About: dbData.About, Birthdate: misc.Date{Time: dbData.Birthdate}, Department: dbData.DepartmentID, diff --git a/internal/usecase/ssr.go b/internal/service/relation.go similarity index 52% rename from internal/usecase/ssr.go rename to internal/service/relation.go index e066e05..b65d5b8 100644 --- a/internal/usecase/ssr.go +++ b/internal/service/relation.go @@ -1,4 +1,4 @@ -package usecase +package service import ( "ssr/internal/dto" @@ -6,20 +6,20 @@ import ( "ssr/pkg/misc" ) -type SSR struct { +type Relation struct { *Base - repo IRepoSSR + repo RelationRepo } -func NewSSR(r IRepoSSR, l logger.Interface) *SSR { - return &SSR{ +func NewRelation(r RelationRepo, l logger.Interface) *Relation { + return &Relation{ Base: NewBase(l), repo: r, } } -func (uc *SSR) CheckIfStudentBeginWork(studentID, workID int) (bool, error) { - relations, err := uc.repo.GetStudentRelations(studentID) +func (service *Relation) CheckIfStudentBeginWork(studentID, workID int) (bool, error) { + relations, err := service.repo.GetStudentRelations(studentID) if err != nil { return false, err } @@ -33,29 +33,29 @@ func (uc *SSR) CheckIfStudentBeginWork(studentID, workID int) (bool, error) { return false, nil } -func (uc *SSR) Create(data *dto.CreateSSR) (*dto.StudentViewSSR, error) { - ssrID, err := uc.repo.UpdateStatus(data.BidID, "wip") +func (service *Relation) Create(data *dto.CreateSSR) (*dto.StViewRelation, error) { + ssrID, err := service.repo.UpdateStatus(data.BidID, "wip") if err != nil { return nil, err } - ssr, err := uc.repo.GetStudentRelation(data.StudentID, ssrID) + ssr, err := service.repo.GetStudentRelation(data.StudentID, ssrID) if err != nil { return nil, err } - return &dto.StudentViewSSR{ + return &dto.StViewRelation{ RelID: ssr.BidID, Status: ssr.Status, CreatedAt: ssr.CreatedAt, - Supervisor: dto.SupervisorProfile{ + Supervisor: dto.SvProfile{ SupervisorID: ssr.SupervisorID, - Email: ssr.SupervisorProfile.Email, - FirstName: ssr.SupervisorProfile.FirstName, - LastName: ssr.SupervisorProfile.LastName, - About: ssr.SupervisorProfile.About, + Email: ssr.SvProfile.Email, + FirstName: ssr.SvProfile.FirstName, + LastName: ssr.SvProfile.LastName, + About: ssr.SvProfile.About, Birthdate: misc.Date{Time: ssr.Birthdate}, - AvatarUrl: misc.NullString(ssr.Avatar), + AvatarUrl: misc.NullString(ssr.PhotoUrl), Department: ssr.DepartmentID, }, Work: dto.Work{ diff --git a/internal/service/repo_pg/auth.go b/internal/service/repo_pg/auth.go new file mode 100644 index 0000000..d05e2d0 --- /dev/null +++ b/internal/service/repo_pg/auth.go @@ -0,0 +1,63 @@ +package repo_pg + +import ( + "fmt" + "ssr/internal/entity" + "ssr/pkg/logger" + "ssr/pkg/postgres" +) + +type Auth struct { + *BasePgRepo +} + +func NewAuth(pg *postgres.Postgres, l logger.Interface) *Auth { + return &Auth{ + BasePgRepo: NewPgRepo(pg, l), + } +} + +func (r *Auth) Create(email, password string, userID int) error { + query := ` + insert into auth (email, password, user_id) + values ($1, $2, $3) + ` + + res, err := r.Conn.Exec(query, email, password, userID) + + fmt.Println(res) //TODO + + if err != nil { + err := fmt.Errorf("Auth->Create->repo.Conn.Exec: %w", err) + r.l.Error(err) // TODO + return err + } + + return nil +} + +func (r *Auth) GetUserByEmail(email string) (*entity.Auth, error) { + auth := entity.Auth{} + + err := r.Conn.Get(&auth, "select * from auth where email = $1", email) + if err != nil { + err := fmt.Errorf("Auth->r.Conn.Get(): %w", err) + r.l.Error(err) + return nil, err + } + + return &auth, nil +} + +func (r *Auth) GetUserByID(userID int) (*entity.Auth, error) { + auth := entity.Auth{} + + err := r.Conn.Get(&auth, "select * from auth where user_id = $1", userID) + if err != nil { + err := fmt.Errorf("Auth->r.Conn.Get(): %w", err) + r.l.Error(err) + return nil, err + } + + return &auth, nil +} diff --git a/internal/usecase/repo_pg/base.go b/internal/service/repo_pg/base.go similarity index 100% rename from internal/usecase/repo_pg/base.go rename to internal/service/repo_pg/base.go diff --git a/internal/usecase/repo_pg/feedback.go b/internal/service/repo_pg/feedback.go similarity index 100% rename from internal/usecase/repo_pg/feedback.go rename to internal/service/repo_pg/feedback.go diff --git a/internal/service/repo_pg/profile.go b/internal/service/repo_pg/profile.go new file mode 100644 index 0000000..2de7cec --- /dev/null +++ b/internal/service/repo_pg/profile.go @@ -0,0 +1,58 @@ +package repo_pg + +import ( + "fmt" + "ssr/internal/entity" + "ssr/pkg/logger" + "ssr/pkg/postgres" +) + +type Profile struct { + *BasePgRepo +} + +func NewProfile(pg *postgres.Postgres, l logger.Interface) *Profile { + return &Profile{ + BasePgRepo: NewPgRepo(pg, l), + } +} + +func (repo *Profile) GetStProfile(email string) (*entity.StProfile, error) { + const query = ` + select * + from users u + join students s using (user_id) + where email = $1 + ` + + student := entity.StProfile{} + + err := repo.Conn.Get(&student, query, email) + if err != nil { + err := fmt.Errorf("Profile->GetStProfile->repo.Conn.Get(): %w", err) + repo.l.Error(err) + return nil, err + } + + return &student, nil +} + +func (repo *Profile) GetSvProfile(email string) (*entity.SvProfile, error) { + const query = ` + select * + from users u + join supervisors s using (user_id) + where email = $1 + ` + + supervisor := entity.SvProfile{} + + err := repo.Conn.Get(&supervisor, query, email) + if err != nil { + err := fmt.Errorf("Profile->GetSvProfile->repo.Conn.Get(): %w", err) + repo.l.Error(err) + return nil, err + } + + return &supervisor, nil +} diff --git a/internal/usecase/repo_pg/ssr.go b/internal/service/repo_pg/relation.go similarity index 61% rename from internal/usecase/repo_pg/ssr.go rename to internal/service/repo_pg/relation.go index c8b93f0..9b75109 100644 --- a/internal/usecase/repo_pg/ssr.go +++ b/internal/service/repo_pg/relation.go @@ -7,17 +7,17 @@ import ( "ssr/pkg/postgres" ) -type SsrPgRepo struct { +type Relation struct { *BasePgRepo } -func NewSSRPgRepo(pg *postgres.Postgres, l logger.Interface) *SsrPgRepo { - return &SsrPgRepo{ +func NewRelation(pg *postgres.Postgres, l logger.Interface) *Relation { + return &Relation{ BasePgRepo: NewPgRepo(pg, l), } } -func (r *SsrPgRepo) GetStudentRelation(studentID, ssrID int) (*entity.StudentSsr, error) { +func (repo *Relation) GetStudentRelation(studentID, ssrID int) (*entity.StRelation, error) { query := ` select ssr.ssr_id, @@ -37,19 +37,19 @@ func (r *SsrPgRepo) GetStudentRelation(studentID, ssrID int) (*entity.StudentSsr join subjects subj using (subject_id) where ssr.ssr_id = $1 and ssr.student_id = $2; ` - ssr := entity.StudentSsr{} + ssr := entity.StRelation{} - err := r.Conn.Get(&ssr, query, ssrID, studentID) + err := repo.Conn.Get(&ssr, query, ssrID, studentID) if err != nil { - err := fmt.Errorf("SsrPgRepo->GetStudentRelation->r.Conn.Get: %w", err) - r.l.Error(err) + err := fmt.Errorf("Relation->GetStudentRelation->repo.Conn.Get: %w", err) + repo.l.Error(err) return nil, err } return &ssr, nil } -func (r *SsrPgRepo) GetStudentBids(studentID int) ([]*entity.StudentSsr, error) { +func (repo *Relation) GetStudentBids(studentID int) ([]*entity.StRelation, error) { query := ` select ssr.ssr_id, @@ -70,19 +70,19 @@ func (r *SsrPgRepo) GetStudentBids(studentID int) ([]*entity.StudentSsr, error) where ssr.status in ('pending','rejected', 'cancelled','accepted') and ssr.student_id = $1; ` - var bids []*entity.StudentSsr + var bids []*entity.StRelation - err := r.Conn.Select(&bids, query, studentID) + err := repo.Conn.Select(&bids, query, studentID) if err != nil { - err := fmt.Errorf("SsrPgRepo->GetStudentBids->r.Conn.Select: %w", err) - r.l.Error(err) + err := fmt.Errorf("Relation->GetStudentBids->repo.Conn.Select: %w", err) + repo.l.Error(err) return nil, err } return bids, nil } -func (r *SsrPgRepo) GetStudentRelations(studentID int) ([]*entity.StudentSsr, error) { +func (repo *Relation) GetStudentRelations(studentID int) ([]*entity.StRelation, error) { query := ` select ssr.ssr_id, @@ -103,19 +103,19 @@ func (r *SsrPgRepo) GetStudentRelations(studentID int) ([]*entity.StudentSsr, er where ssr.status in ('wip', 'done') and ssr.student_id = $1; ` - var bids []*entity.StudentSsr + var bids []*entity.StRelation - err := r.Conn.Select(&bids, query, studentID) + err := repo.Conn.Select(&bids, query, studentID) if err != nil { - err := fmt.Errorf("SsrPgRepo->GetStudentBids->r.Conn.Select: %w", err) - r.l.Error(err) + err := fmt.Errorf("Relation->GetStudentBids->repo.Conn.Select: %w", err) + repo.l.Error(err) return nil, err } return bids, nil } -func (r *SsrPgRepo) GetSupervisorBids(supervisorID int) ([]*entity.SupervisorSsr, error) { +func (repo *Relation) GetSupervisorBids(supervisorID int) ([]*entity.SvRelation, error) { query := ` select ssr.ssr_id, @@ -136,19 +136,19 @@ func (r *SsrPgRepo) GetSupervisorBids(supervisorID int) ([]*entity.SupervisorSsr where ssr.status in ('pending','rejected', 'cancelled','accepted') and ssr.supervisor_id = $1; ` - var bids []*entity.SupervisorSsr + var bids []*entity.SvRelation - err := r.Conn.Select(&bids, query, supervisorID) + err := repo.Conn.Select(&bids, query, supervisorID) if err != nil { - err := fmt.Errorf("SsrPgRepo->GetSupervisorBids->r.Conn.Select: %w", err) - r.l.Error(err) + err := fmt.Errorf("Relation->GetSupervisorBids->repo.Conn.Select: %w", err) + repo.l.Error(err) return nil, err } return bids, nil } -func (r *SsrPgRepo) Create(studentID, supervisorID, workID int) (int, error) { +func (repo *Relation) Create(studentID, supervisorID, workID int) (int, error) { query := ` insert into ssr (student_id, supervisor_id, work_id) values ($1, $2, $3) @@ -156,17 +156,17 @@ func (r *SsrPgRepo) Create(studentID, supervisorID, workID int) (int, error) { ` var bidID int - err := r.Conn.QueryRowx(query, studentID, supervisorID, workID).Scan(&bidID) + err := repo.Conn.QueryRowx(query, studentID, supervisorID, workID).Scan(&bidID) if err != nil { - err := fmt.Errorf("SsrPgRepo->Create->r.Conn.QueryRowx: %w", err) - r.l.Error(err) + err := fmt.Errorf("Relation->Create->repo.Conn.QueryRowx: %w", err) + repo.l.Error(err) return 0, err } return bidID, nil } -func (r *SsrPgRepo) UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) { +func (repo *Relation) UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) { query := ` update ssr set status = $1 where ssr_id = $2 @@ -174,10 +174,10 @@ func (r *SsrPgRepo) UpdateStatus(id int, newStatus entity.StatusSSR) (int, error ` var bidID int - err := r.Conn.QueryRowx(query, newStatus, id).Scan(&bidID) + err := repo.Conn.QueryRowx(query, newStatus, id).Scan(&bidID) if err != nil { - err := fmt.Errorf("SsrPgRepo->UpdateStatus->r.Conn.QueryRowx: %w", err) - r.l.Error(err) + err := fmt.Errorf("Relation->UpdateStatus->repo.Conn.QueryRowx: %w", err) + repo.l.Error(err) return 0, err } diff --git a/internal/service/repo_pg/student.go b/internal/service/repo_pg/student.go new file mode 100644 index 0000000..4e9c71d --- /dev/null +++ b/internal/service/repo_pg/student.go @@ -0,0 +1,55 @@ +package repo_pg + +import ( + "fmt" + "ssr/internal/entity" + "ssr/pkg/logger" + "ssr/pkg/postgres" +) + +type Student struct { + *BasePgRepo +} + +func New(pg *postgres.Postgres, l logger.Interface) *Student { + return &Student{ + BasePgRepo: NewPgRepo(pg, l), + } +} + +func (repo *Student) Get(userID int) (*entity.Student, error) { + const query = ` + select * from users where user_id = $1 + ` + + student := entity.Student{} + + err := repo.Conn.Get(&student, query, userID) + if err != nil { + err := fmt.Errorf("Student->Get->repo.Conn.Get(): %w", err) + repo.l.Error(err) + return nil, err + } + + return &student, nil +} + +func (repo *Student) GetFull(userID int) (*entity.StudentFull, error) { + const query = ` + select * + from users u + join students s using (user_id) + where user_id = $1 + ` + + studentFull := entity.StudentFull{} + + err := repo.Conn.Get(&studentFull, query, userID) + if err != nil { + err := fmt.Errorf("Student->GetFull->repo.Conn.Get(): %w", err) + repo.l.Error(err) + return nil, err + } + + return &studentFull, nil +} diff --git a/internal/service/repo_pg/user.go b/internal/service/repo_pg/user.go new file mode 100644 index 0000000..38e50eb --- /dev/null +++ b/internal/service/repo_pg/user.go @@ -0,0 +1,37 @@ +package repo_pg + +import ( + "fmt" + "ssr/internal/entity" + "ssr/pkg/logger" + "ssr/pkg/postgres" +) + +type User struct { + *BasePgRepo +} + +func New(pg *postgres.Postgres, l logger.Interface) *User { + return &User{ + BasePgRepo: NewPgRepo(pg, l), + } +} + +func (r *Auth) Create(email, firstName, LastName, photoUrl string, role entity.UserRole) error { + query := ` + insert into users (email, first_name, last_name, photo_url, role) + values ($1, $2, $3, $4, $5) + ` + + res, err := r.Conn.Exec(query, email, password, userID) + + fmt.Println(res) //TODO + + if err != nil { + err := fmt.Errorf("Auth->Create->repo.Conn.Exec: %w", err) + r.l.Error(err) // TODO + return err + } + + return nil +} diff --git a/internal/usecase/repo_pg/work.go b/internal/service/repo_pg/work.go similarity index 70% rename from internal/usecase/repo_pg/work.go rename to internal/service/repo_pg/work.go index 8c5a94a..8f3a691 100644 --- a/internal/usecase/repo_pg/work.go +++ b/internal/service/repo_pg/work.go @@ -7,17 +7,17 @@ import ( "ssr/pkg/postgres" ) -type WorkPgRepo struct { +type Work struct { *BasePgRepo } -func NewWorkPgRepo(pg *postgres.Postgres, l logger.Interface) *WorkPgRepo { - return &WorkPgRepo{ +func NewWork(pg *postgres.Postgres, l logger.Interface) *Work { + return &Work{ BasePgRepo: NewPgRepo(pg, l), } } -func (r *WorkPgRepo) GetWorksByStudentID(studentID int) ([]*entity.Work, error) { +func (r *Work) GetWorksByStudentID(studentID int) ([]*entity.Work, error) { const query = ` with const (st_year, st_department_id, curr_month) as ( select s.year, @@ -42,7 +42,7 @@ func (r *WorkPgRepo) GetWorksByStudentID(studentID int) ([]*entity.Work, error) err := r.Conn.Select(&works, query, studentID) if err != nil { - err := fmt.Errorf("WorkPgRepo->GetWorksByStudentID->r.Conn.Select: %w", err) + err := fmt.Errorf("Work->GetWorksByStudentID->r.Conn.Select: %w", err) r.l.Error(err) return nil, err } @@ -50,7 +50,7 @@ func (r *WorkPgRepo) GetWorksByStudentID(studentID int) ([]*entity.Work, error) return works, nil } -func (r *WorkPgRepo) GetWorksBySupervisorID(supervisorID int) ([]*entity.WorkOfSupervisor, error) { +func (r *Work) GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) { const query = ` select w.*, subj.name as subject_name, @@ -63,11 +63,11 @@ func (r *WorkPgRepo) GetWorksBySupervisorID(supervisorID int) ([]*entity.WorkOfS join work_kinds wk using (work_kind_id) where s.supervisor_id = $1; ` - var works []*entity.WorkOfSupervisor + var works []*entity.SvWork err := r.Conn.Select(&works, query, supervisorID) if err != nil { - err := fmt.Errorf("WorkPgRepo->GetWorksBySupervisorID->r.Conn.Select: %w", err) + err := fmt.Errorf("Work->GetWorksBySupervisorID->r.Conn.Select: %w", err) r.l.Error(err) return nil, err } @@ -75,7 +75,7 @@ func (r *WorkPgRepo) GetWorksBySupervisorID(supervisorID int) ([]*entity.WorkOfS return works, nil } -func (r *WorkPgRepo) GetSupervisorsByWorkID(workID int) ([]*entity.SupervisorOfWork, error) { +func (r *Work) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) { const query = ` select u.*, @@ -88,11 +88,11 @@ func (r *WorkPgRepo) GetSupervisorsByWorkID(workID int) ([]*entity.SupervisorOfW where sw.work_id = $1; ` - var supervisors []*entity.SupervisorOfWork + var supervisors []*entity.WorkSv err := r.Conn.Select(&supervisors, query, workID) if err != nil { - err := fmt.Errorf("WorkPgRepo->GetSupervisorsByWorkID->r.Conn.Select: %w", err) + err := fmt.Errorf("Work->GetSupervisorsByWorkID->r.Conn.Select: %w", err) r.l.Error(err) return nil, err } diff --git a/internal/usecase/work.go b/internal/service/work.go similarity index 55% rename from internal/usecase/work.go rename to internal/service/work.go index 6569f60..94ce6c4 100644 --- a/internal/usecase/work.go +++ b/internal/service/work.go @@ -1,4 +1,4 @@ -package usecase +package service import ( "ssr/internal/dto" @@ -9,11 +9,11 @@ import ( type Work struct { *Base - repoWork IRepoWork - repoSsr IRepoSSR + repoWork WorkRepo + repoSsr RelationRepo } -func NewWork(rWork IRepoWork, rSsr IRepoSSR, l logger.Interface) *Work { +func NewWork(rWork WorkRepo, rSsr RelationRepo, l logger.Interface) *Work { return &Work{ Base: NewBase(l), repoWork: rWork, @@ -21,7 +21,7 @@ func NewWork(rWork IRepoWork, rSsr IRepoSSR, l logger.Interface) *Work { } } -func checkIfBegin(relations []*entity.StudentSsr, workID int) bool { +func checkIfBegin(relations []*entity.StRelation, workID int) bool { for _, rel := range relations { if rel.Work.WorkID == workID { return true @@ -31,21 +31,21 @@ func checkIfBegin(relations []*entity.StudentSsr, workID int) bool { return false } -func (uc *Work) GetStudentWorks(studentID int) (*dto.StudentWorks, error) { - dbData, err := uc.repoWork.GetWorksByStudentID(studentID) +func (service *Work) GetStudentWorks(studentID int) (*dto.StWorks, error) { + dbData, err := service.repoWork.GetWorksByStudentID(studentID) if err != nil { return nil, err } - relations, err := uc.repoSsr.GetStudentRelations(studentID) + relations, err := service.repoSsr.GetStudentRelations(studentID) if err != nil { return nil, err } - var resp []*dto.StudentWork + var resp []*dto.StWork for _, db := range dbData { - resp = append(resp, &dto.StudentWork{ + resp = append(resp, &dto.StWork{ WorkID: db.WorkID, Kind: db.WorkKindName, Description: db.Description, @@ -54,22 +54,22 @@ func (uc *Work) GetStudentWorks(studentID int) (*dto.StudentWorks, error) { }) } - return &dto.StudentWorks{ + return &dto.StWorks{ StudentID: studentID, Works: resp, }, nil } -func (uc *Work) GetSupervisorWorks(supervisorID int) (*dto.SupervisorWorkPlenty, error) { - dbData, err := uc.repoWork.GetWorksBySupervisorID(supervisorID) +func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { + dbData, err := service.repoWork.GetWorksBySupervisorID(supervisorID) if err != nil { return nil, err } - var resp []*dto.SupervisorWork + var resp []*dto.SvWork for _, db := range dbData { - resp = append(resp, &dto.SupervisorWork{ + resp = append(resp, &dto.SvWork{ WorkID: db.WorkID, Kind: db.WorkKindName, Description: db.Description, @@ -78,30 +78,30 @@ func (uc *Work) GetSupervisorWorks(supervisorID int) (*dto.SupervisorWorkPlenty, }) } - return &dto.SupervisorWorkPlenty{ + return &dto.SvWorkPlenty{ SupervisorID: supervisorID, Works: resp, }, nil } -func (uc *Work) GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error) { - dbData, err := uc.repoWork.GetSupervisorsByWorkID(workID) +func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { + dbData, err := service.repoWork.GetSupervisorsByWorkID(workID) if err != nil { return nil, err } - var resp []*dto.WorkSupervisor + var resp []*dto.WorkSv for _, db := range dbData { - resp = append(resp, &dto.WorkSupervisor{ - SupervisorProfile: dto.SupervisorProfile{ + resp = append(resp, &dto.WorkSv{ + SvProfile: dto.SvProfile{ SupervisorID: db.SupervisorID, Email: db.Email, FirstName: db.FirstName, LastName: db.LastName, About: db.About, Birthdate: misc.Date{Time: db.Birthdate}, - AvatarUrl: misc.NullString(db.Avatar), + AvatarUrl: misc.NullString(db.PhotoUrl), Department: db.DepartmentID, }, Head: db.Head, @@ -109,7 +109,7 @@ func (uc *Work) GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error }) } - return &dto.WorkSupervisorPlenty{ + return &dto.WorkSvPlenty{ WorkID: workID, Supervisors: resp, }, nil diff --git a/internal/usecase/interfaces.go b/internal/usecase/interfaces.go deleted file mode 100644 index ab5d869..0000000 --- a/internal/usecase/interfaces.go +++ /dev/null @@ -1,68 +0,0 @@ -package usecase - -import ( - "ssr/internal/dto" - "ssr/internal/entity" -) - -type ( - IRepoAuth interface { - GetUserInfo(email string) (*entity.Auth, error) - } - IUsecaseAuth interface { - Login(email, password string) (*dto.LoginResponse, error) - } - - IRepoProfile interface { - GetStudentProfile(email string) (*entity.StudentProfile, error) - GetSupervisorProfile(email string) (*entity.SupervisorProfile, error) - } - IUsecaseProfile interface { - GetStudentProfile(email string) (*dto.StudentProfile, error) - GetSupervisorProfile(email string) (*dto.SupervisorProfile, error) - } - - IRepoSSR interface { - Create(studentID, supervisorID, workID int) (int, error) - GetStudentBids(studentID int) ([]*entity.StudentSsr, error) - GetSupervisorBids(studentID int) ([]*entity.SupervisorSsr, error) - GetStudentRelations(studentID int) ([]*entity.StudentSsr, error) - GetStudentRelation(studentID, ssrID int) (*entity.StudentSsr, error) - UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) - } - - IUsecaseStudentBid interface { - GetStudentBids(studentID int) (*dto.StudentBids, error) - Apply(data *dto.ApplyBid) (*dto.ApplyBidResponse, error) - } - IUseCaseSupervisorBid interface { - GetSupervisorBids(supervisorID int) (*dto.SupervisorBids, error) - Resolve(data *dto.ResolveBid) error - } - - IUseCaseStudentRelation interface { - Create(data *dto.CreateSSR) (*dto.StudentViewSSR, error) - } - - IRepoWork interface { - GetWorksByStudentID(studentID int) ([]*entity.Work, error) - GetWorksBySupervisorID(supervisorID int) ([]*entity.WorkOfSupervisor, error) - GetSupervisorsByWorkID(workID int) ([]*entity.SupervisorOfWork, error) - } - IStudentWorkUC interface { - GetStudentWorks(studentID int) (*dto.StudentWorks, error) - GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error) - } - ISupervisorWorkUC interface { - GetSupervisorWorks(supervisorID int) (*dto.SupervisorWorkPlenty, error) - } - - IUsecaseFeedback interface { - Add(data *dto.FeedbackReq) (int, error) - GetOnSupervisor(supervisorID int) (*dto.FeedbackPlenty, error) - } - IRepoFeedback interface { - Create(studentID, supervisorID, workID int, content string) (int, error) - GetBySupervisorID(supervisorID int) ([]*entity.Feedback, error) - } -) diff --git a/internal/usecase/repo_pg/auth.go b/internal/usecase/repo_pg/auth.go deleted file mode 100644 index 7ed6616..0000000 --- a/internal/usecase/repo_pg/auth.go +++ /dev/null @@ -1,31 +0,0 @@ -package repo_pg - -import ( - "fmt" - "ssr/internal/entity" - "ssr/pkg/logger" - "ssr/pkg/postgres" -) - -type AuthPgRepo struct { - *BasePgRepo -} - -func NewAuthPgRepo(pg *postgres.Postgres, l logger.Interface) *AuthPgRepo { - return &AuthPgRepo{ - BasePgRepo: NewPgRepo(pg, l), - } -} - -func (r *AuthPgRepo) GetUserInfo(email string) (*entity.Auth, error) { - auth := entity.Auth{} - - err := r.Conn.Get(&auth, "select * from auth where email = $1", email) - if err != nil { - err := fmt.Errorf("AuthPgRepo->r.Conn.Get(): %w", err) - r.l.Error(err) - return nil, err - } - - return &auth, nil -} diff --git a/internal/usecase/repo_pg/profile.go b/internal/usecase/repo_pg/profile.go deleted file mode 100644 index fc35131..0000000 --- a/internal/usecase/repo_pg/profile.go +++ /dev/null @@ -1,58 +0,0 @@ -package repo_pg - -import ( - "fmt" - "ssr/internal/entity" - "ssr/pkg/logger" - "ssr/pkg/postgres" -) - -type ProfilePgRepo struct { - *BasePgRepo -} - -func NewProfilePgRepo(pg *postgres.Postgres, l logger.Interface) *ProfilePgRepo { - return &ProfilePgRepo{ - BasePgRepo: NewPgRepo(pg, l), - } -} - -func (r *ProfilePgRepo) GetStudentProfile(email string) (*entity.StudentProfile, error) { - const query = ` - select * - from users u - join students s using (user_id) - where email = $1 - ` - - student := entity.StudentProfile{} - - err := r.Conn.Get(&student, query, email) - if err != nil { - err := fmt.Errorf("ProfilePgRepo->GetStudentProfile->r.Conn.Get(): %w", err) - r.l.Error(err) - return nil, err - } - - return &student, nil -} - -func (r *ProfilePgRepo) GetSupervisorProfile(email string) (*entity.SupervisorProfile, error) { - const query = ` - select * - from users u - join supervisors s using (user_id) - where email = $1 - ` - - supervisor := entity.SupervisorProfile{} - - err := r.Conn.Get(&supervisor, query, email) - if err != nil { - err := fmt.Errorf("ProfilePgRepo->GetSupervisorProfile->r.Conn.Get(): %w", err) - r.l.Error(err) - return nil, err - } - - return &supervisor, nil -} diff --git a/migrations/20220508102907_create_users.up.sql b/migrations/20220508102907_create_users.up.sql index 5ea92e5..f20b2a8 100644 --- a/migrations/20220508102907_create_users.up.sql +++ b/migrations/20220508102907_create_users.up.sql @@ -1,6 +1,6 @@ CREATE TYPE "user_role" AS ENUM ( - 'student', - 'supervisor' + 'st', + 'sv' ); CREATE TABLE "users" @@ -9,31 +9,33 @@ CREATE TABLE "users" "email" varchar unique not null, "first_name" varchar not null, "last_name" varchar not null, - "avatar_url" varchar + "photo_url" varchar, + "role" user_role ); CREATE TABLE "auth" ( "email" varchar PRIMARY KEY, - "password" varchar not null, - "role" user_role + "user_id" int, + "password" varchar not null ); -ALTER TABLE "users" - ADD FOREIGN KEY ("email") REFERENCES "auth" ("email"); +ALTER TABLE "auth" + ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"); -insert into auth (email, password, role) -VALUES ('viktor1970@example.org', '$2b$12$kXlvD8/GSm/ZLEEjPFS0peiPEz.AEh5byuNIqZvFyu7bW6R5RxcJy', 'student'), - ('komarovmina@example.org', '$2b$12$xfWQ1aLcxliWgiNj8pKyOOTqOaUjQV5YMSb7whSNKb.Liejt3ae8u', 'supervisor'), - ('jakov2001@example.org', '$2b$12$qhTeWstBv035IIbUXYM8I.pGnvMS0spDQqUM/OdpIUsmt6cFU.4P2', 'supervisor'), - ('mina1988@example.org', '$2b$12$H7iWpTmqm.2OcsosP8CseOM/XCDP2.y0en.X..nZcbtvQ9EBZ0Pg2', 'supervisor'), - ('ipat1974@example.net', '$2b$12$Zq11QMZNcC/9IxquRrqMwuWh1ijHx.k83McMe6pM2Jtf8LXbZ.a66', 'student'), - ('kopilovfoka@example.org', '$2b$12$MjWCy0Ka0n9QLm12cCJVjuReCykhbBfXck.Jt.VPkYgKQZ/SPwlbK', 'student'); -insert into users (email, first_name, last_name, avatar_url) -VALUES ('viktor1970@example.org', 'Дмитрий', 'Ивахненко', NULL), - ('komarovmina@example.org', 'Наташа', 'Рязанова', NULL), - ('mina1988@example.org', 'Кирилл', 'Тассов', NULL), - ('jakov2001@example.org', 'Андрей', 'Куров', NULL), - ('ipat1974@example.net', 'Максим', 'Борисов', NULL), - ('kopilovfoka@example.org', 'Дмитрий', 'Варин', NULL); +insert into users (email, first_name, last_name, photo_url, role) +VALUES ('viktor1970@example.org', 'Дмитрий', 'Ивахненко', NULL, 'st'), + ('komarovmina@example.org', 'Наташа', 'Рязанова', NULL, 'sv'), + ('mina1988@example.org', 'Кирилл', 'Тассов', NULL, 'sv'), + ('jakov2001@example.org', 'Андрей', 'Куров', NULL, 'sv'), + ('ipat1974@example.net', 'Максим', 'Борисов', NULL, 'st'), + ('kopilovfoka@example.org', 'Дмитрий', 'Варин', NULL, 'st'); + +insert into auth (email, password, user_id) +VALUES ('viktor1970@example.org', '$2b$12$kXlvD8/GSm/ZLEEjPFS0peiPEz.AEh5byuNIqZvFyu7bW6R5RxcJy', 1), + ('komarovmina@example.org', '$2b$12$xfWQ1aLcxliWgiNj8pKyOOTqOaUjQV5YMSb7whSNKb.Liejt3ae8u', 2), + ('jakov2001@example.org', '$2b$12$qhTeWstBv035IIbUXYM8I.pGnvMS0spDQqUM/OdpIUsmt6cFU.4P2', 3), + ('mina1988@example.org', '$2b$12$H7iWpTmqm.2OcsosP8CseOM/XCDP2.y0en.X..nZcbtvQ9EBZ0Pg2', 4), + ('ipat1974@example.net', '$2b$12$Zq11QMZNcC/9IxquRrqMwuWh1ijHx.k83McMe6pM2Jtf8LXbZ.a66', 5), + ('kopilovfoka@example.org', '$2b$12$MjWCy0Ka0n9QLm12cCJVjuReCykhbBfXck.Jt.VPkYgKQZ/SPwlbK', 6); diff --git a/migrations/20220509115124_create_students.up.sql b/migrations/20220509115124_create_students.up.sql index 88c4c92..7285e86 100644 --- a/migrations/20220509115124_create_students.up.sql +++ b/migrations/20220509115124_create_students.up.sql @@ -1,20 +1,17 @@ CREATE TABLE "students" ( - "student_id" bigint unique generated always as identity, + "user_id" bigint primary key unique not null, "student_card" varchar unique not null, "year" int not null, - "user_id" bigint not null, "department_id" varchar not null ); ALTER TABLE "students" - ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"); - -ALTER TABLE "students" + ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"), ADD FOREIGN KEY ("department_id") REFERENCES "departments" ("department_id"); -insert into "students" (student_card, year, user_id, department_id) -VALUES ('ida19u463', 3, 1, 'ИУ7'), - ('bma19u463', 3, 5, 'ИУ7'), - ('vdv19u463', 3, 6, 'ИУ7'); +insert into "students" (user_id, student_card, year, department_id) +VALUES (1, 'ida19u463', 3, 'ИУ7'), + (5, 'bma19u463', 3, 'ИУ7'), + (6, 'vdv19u463', 3, 'ИУ7'); diff --git a/migrations/20220509192451_create_supervisors.up.sql b/migrations/20220509192451_create_supervisors.up.sql index 2166aa8..63d299b 100644 --- a/migrations/20220509192451_create_supervisors.up.sql +++ b/migrations/20220509192451_create_supervisors.up.sql @@ -1,21 +1,18 @@ CREATE TABLE "supervisors" ( - "supervisor_id" bigint unique generated always as identity, - "birthdate" date not null, - "about" varchar not null, - "user_id" bigint not null, - "department_id" varchar not null + "user_id" bigint primary key not null, + "birthdate" date not null, + "about" text not null, + "department_id" varchar not null ); ALTER TABLE "supervisors" - ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"); - -ALTER TABLE "supervisors" + ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"), ADD FOREIGN KEY ("department_id") REFERENCES "departments" ("department_id"); -insert into "supervisors" (birthdate, about, user_id, department_id) -VALUES ('01-01-1956', 'Заслуженный программист СССР. Профессионал.', 2, 'ИУ7'), - ('01-01-1998', 'Лучшие анекдоты тут!', 3, 'ИУ7'), - ('01-01-1801', 'Нуууииитоживашщши слаувваа', 4 , 'ИУ7'); +insert into "supervisors" (user_id, birthdate, about, department_id) +VALUES (2, '01-01-1956', 'Заслуженный программист СССР. Профессионал.', 'ИУ7'), + (3, '01-01-1998', 'Лучшие анекдоты тут!', 'ИУ7'), + (4, '01-01-1801', 'Нуууииитоживашщши слаувваа' , 'ИУ7'); diff --git a/migrations/20220509193416_create_subjects.up.sql b/migrations/20220509193416_create_subjects.up.sql index a3dbb92..79c46d2 100644 --- a/migrations/20220509193416_create_subjects.up.sql +++ b/migrations/20220509193416_create_subjects.up.sql @@ -1,7 +1,7 @@ CREATE TABLE "subjects" ( "subject_id" bigint unique generated always as identity, - "name" varchar primary key, + "title" varchar primary key, "department_id" varchar not null ); @@ -9,7 +9,7 @@ CREATE TABLE "subjects" ALTER TABLE "subjects" ADD FOREIGN KEY ("department_id") REFERENCES "departments" ("department_id"); -insert into subjects (name, department_id) +insert into subjects (title, department_id) VALUES ('Операционные системы', 'ИУ7'), ('Компьютерная графика', 'ИУ7'); diff --git a/migrations/20220509194216_create_works.up.sql b/migrations/20220509194216_create_works.up.sql index 5914c0d..42f0bd8 100644 --- a/migrations/20220509194216_create_works.up.sql +++ b/migrations/20220509194216_create_works.up.sql @@ -1,7 +1,7 @@ CREATE TABLE "work_kinds" ( "work_kind_id" bigint unique generated always as identity, - "name" varchar unique not null + "title" varchar unique not null ); CREATE TABLE "works" @@ -14,13 +14,11 @@ CREATE TABLE "works" ); ALTER TABLE "works" - ADD FOREIGN KEY ("subject_id") REFERENCES "subjects" ("subject_id"); - -ALTER TABLE "works" + ADD FOREIGN KEY ("subject_id") REFERENCES "subjects" ("subject_id"), ADD FOREIGN KEY ("work_kind_id") REFERENCES "work_kinds" ("work_kind_id"); -insert into "work_kinds" (name) +insert into "work_kinds" (title) VALUES ('Курсовая работа'), ('Научно-исследовательская работа'); diff --git a/migrations/20220509195738_create_sv_work.up.sql b/migrations/20220509195738_create_sv_work.up.sql index 5976649..b70735b 100644 --- a/migrations/20220509195738_create_sv_work.up.sql +++ b/migrations/20220509195738_create_sv_work.up.sql @@ -8,16 +8,15 @@ CREATE TABLE "supervisor_work" ALTER TABLE "supervisor_work" - ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"); - -ALTER TABLE "supervisor_work" - ADD FOREIGN KEY ("supervisor_id") REFERENCES "supervisors" ("supervisor_id"); + ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"), + ADD FOREIGN KEY ("supervisor_id") REFERENCES "supervisors" ("user_id"); +CREATE UNIQUE INDEX ON supervisor_work (work_id, supervisor_id); insert into "supervisor_work" (work_id, supervisor_id, is_head) -VALUES (1, 1, true), - (1, 2, false), +VALUES (1, 2, true), (1, 3, false), - (2, 1, false), + (1, 4, false), (2, 2, false), - (2, 3, true); \ No newline at end of file + (2, 3, false), + (2, 4, true); \ No newline at end of file diff --git a/migrations/20220509200350_create_ssr.up.sql b/migrations/20220509200350_create_ssr.up.sql index 2375d46..cd3cf35 100644 --- a/migrations/20220509200350_create_ssr.up.sql +++ b/migrations/20220509200350_create_ssr.up.sql @@ -20,15 +20,9 @@ CREATE TABLE "ssr" ALTER TABLE "ssr" - ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"); - -ALTER TABLE "ssr" - ADD FOREIGN KEY ("supervisor_id") REFERENCES "supervisors" ("supervisor_id"); - -ALTER TABLE "ssr" - ADD FOREIGN KEY ("student_id") REFERENCES "students" ("student_id"); - -ALTER TABLE ssr + ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"), + ADD FOREIGN KEY ("supervisor_id") REFERENCES "supervisors" ("user_id"), + ADD FOREIGN KEY ("student_id") REFERENCES "students" ("user_id"), ADD CONSTRAINT ssr_unique_members_constraint UNIQUE (work_id, supervisor_id, student_id); CREATE INDEX ON "ssr" (status, supervisor_id); diff --git a/migrations/20220606071757_create_feedbacks.up.sql b/migrations/20220606071757_create_feedbacks.up.sql index bffbc15..6ebdbef 100644 --- a/migrations/20220606071757_create_feedbacks.up.sql +++ b/migrations/20220606071757_create_feedbacks.up.sql @@ -10,15 +10,9 @@ CREATE TABLE "feedbacks" ALTER TABLE "feedbacks" - ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"); - -ALTER TABLE "feedbacks" - ADD FOREIGN KEY ("supervisor_id") REFERENCES "supervisors" ("supervisor_id"); - -ALTER TABLE "feedbacks" - ADD FOREIGN KEY ("student_id") REFERENCES "students" ("student_id"); - -ALTER TABLE "feedbacks" + ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"), + ADD FOREIGN KEY ("supervisor_id") REFERENCES "supervisors" ("user_id"), + ADD FOREIGN KEY ("student_id") REFERENCES "students" ("user_id"), ADD CONSTRAINT feedbacks_unique_members_constraint UNIQUE (work_id, student_id); CREATE INDEX ON "feedbacks" (supervisor_id); diff --git a/swagger/docs.go b/swagger/docs.go index 873ba34..e10c641 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -56,10 +56,10 @@ const docTemplate = `{ } }, "401": { - "description": "" + "description": "Unauthorized" }, "500": { - "description": "" + "description": "Internal Server Error" } } } @@ -77,7 +77,7 @@ const docTemplate = `{ "tags": [ "student" ], - "summary": "GetUserInfo student's bids", + "summary": "GetUserByEmail student's bids", "parameters": [ { "type": "integer", @@ -91,11 +91,11 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentBids" + "$ref": "#/definitions/dto.StBids" } }, "404": { - "description": "" + "description": "Not Found" } } }, @@ -130,7 +130,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.ApplyBidResponse" + "$ref": "#/definitions/dto.ApplyBidResp" } } } @@ -155,7 +155,7 @@ const docTemplate = `{ "type": "integer", "description": "Supervisor ID", "name": "supervisor_id", - "in": "query", + "in": "path", "required": true } ], @@ -203,7 +203,7 @@ const docTemplate = `{ } }, "500": { - "description": "" + "description": "Internal Server Error" } } } @@ -221,16 +221,16 @@ const docTemplate = `{ "tags": [ "student" ], - "summary": "GetUserInfo student's profile", + "summary": "GetUserByEmail student's profile", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentProfile" + "$ref": "#/definitions/dto.StProfile" } }, "404": { - "description": "" + "description": "Not Found" } } } @@ -267,7 +267,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentViewSSR" + "$ref": "#/definitions/dto.StViewRelation" } } } @@ -286,7 +286,7 @@ const docTemplate = `{ "tags": [ "student" ], - "summary": "GetUserInfo student's works", + "summary": "GetUserByEmail student's works", "parameters": [ { "type": "integer", @@ -300,7 +300,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentWorks" + "$ref": "#/definitions/dto.StWorks" } } } @@ -319,7 +319,7 @@ const docTemplate = `{ "tags": [ "student" ], - "summary": "GetUserInfo supervisors of the work", + "summary": "GetUserByEmail supervisors of the work", "parameters": [ { "type": "integer", @@ -333,7 +333,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSupervisorPlenty" + "$ref": "#/definitions/dto.WorkSvPlenty" } } } @@ -352,7 +352,7 @@ const docTemplate = `{ "tags": [ "supervisor" ], - "summary": "GetUserInfo supervisor's bids", + "summary": "GetUserByEmail supervisor's bids", "parameters": [ { "type": "integer", @@ -366,7 +366,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SupervisorBids" + "$ref": "#/definitions/dto.SvBids" } } } @@ -420,12 +420,12 @@ const docTemplate = `{ "tags": [ "supervisor" ], - "summary": "GetUserInfo supervisor's profile", + "summary": "GetUserByEmail supervisor's profile", "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SupervisorProfile" + "$ref": "#/definitions/dto.SvProfile" } } } @@ -444,7 +444,7 @@ const docTemplate = `{ "tags": [ "supervisor" ], - "summary": "GetUserInfo supervisor's works", + "summary": "GetUserByEmail supervisor's works", "parameters": [ { "type": "integer", @@ -458,7 +458,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SupervisorWorkPlenty" + "$ref": "#/definitions/dto.SvWorkPlenty" } } } @@ -480,7 +480,7 @@ const docTemplate = `{ } } }, - "dto.ApplyBidResponse": { + "dto.ApplyBidResp": { "type": "object", "properties": { "bidID": { @@ -597,7 +597,7 @@ const docTemplate = `{ } } }, - "dto.StudentBid": { + "dto.StBid": { "type": "object", "properties": { "createdAt": { @@ -610,25 +610,25 @@ const docTemplate = `{ "type": "string" }, "supervisor": { - "$ref": "#/definitions/dto.SupervisorProfile" + "$ref": "#/definitions/dto.SvProfile" }, "work": { "$ref": "#/definitions/dto.Work" } } }, - "dto.StudentBids": { + "dto.StBids": { "type": "object", "properties": { "bids": { "type": "array", "items": { - "$ref": "#/definitions/dto.StudentBid" + "$ref": "#/definitions/dto.StBid" } } } }, - "dto.StudentProfile": { + "dto.StProfile": { "type": "object", "properties": { "avatarUrl": { @@ -657,7 +657,7 @@ const docTemplate = `{ } } }, - "dto.StudentViewSSR": { + "dto.StViewRelation": { "type": "object", "properties": { "createdAt": { @@ -670,14 +670,14 @@ const docTemplate = `{ "type": "string" }, "supervisor": { - "$ref": "#/definitions/dto.SupervisorProfile" + "$ref": "#/definitions/dto.SvProfile" }, "work": { "$ref": "#/definitions/dto.Work" } } }, - "dto.StudentWork": { + "dto.StWork": { "type": "object", "properties": { "description": { @@ -697,7 +697,7 @@ const docTemplate = `{ } } }, - "dto.StudentWorks": { + "dto.StWorks": { "type": "object", "properties": { "studentID": { @@ -706,7 +706,7 @@ const docTemplate = `{ "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.StudentWork" + "$ref": "#/definitions/dto.StWork" } } } @@ -725,7 +725,7 @@ const docTemplate = `{ } } }, - "dto.SupervisorBid": { + "dto.SvBid": { "type": "object", "properties": { "createdAt": { @@ -738,25 +738,25 @@ const docTemplate = `{ "type": "string" }, "student": { - "$ref": "#/definitions/dto.StudentProfile" + "$ref": "#/definitions/dto.StProfile" }, "work": { "$ref": "#/definitions/dto.Work" } } }, - "dto.SupervisorBids": { + "dto.SvBids": { "type": "object", "properties": { "bids": { "type": "array", "items": { - "$ref": "#/definitions/dto.SupervisorBid" + "$ref": "#/definitions/dto.SvBid" } } } }, - "dto.SupervisorProfile": { + "dto.SvProfile": { "type": "object", "properties": { "about": { @@ -785,7 +785,7 @@ const docTemplate = `{ } } }, - "dto.SupervisorWork": { + "dto.SvWork": { "type": "object", "properties": { "description": { @@ -805,7 +805,7 @@ const docTemplate = `{ } } }, - "dto.SupervisorWorkPlenty": { + "dto.SvWorkPlenty": { "type": "object", "properties": { "supervisorID": { @@ -814,7 +814,7 @@ const docTemplate = `{ "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.SupervisorWork" + "$ref": "#/definitions/dto.SvWork" } } } @@ -839,7 +839,7 @@ const docTemplate = `{ } } }, - "dto.WorkSupervisor": { + "dto.WorkSv": { "type": "object", "properties": { "about": { @@ -874,13 +874,13 @@ const docTemplate = `{ } } }, - "dto.WorkSupervisorPlenty": { + "dto.WorkSvPlenty": { "type": "object", "properties": { "supervisors": { "type": "array", "items": { - "$ref": "#/definitions/dto.WorkSupervisor" + "$ref": "#/definitions/dto.WorkSv" } }, "workID": { diff --git a/swagger/swagger.json b/swagger/swagger.json index 5085ee6..4e0a1ec 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -52,10 +52,10 @@ } }, "401": { - "description": "" + "description": "Unauthorized" }, "500": { - "description": "" + "description": "Internal Server Error" } } } @@ -87,11 +87,11 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentBids" + "$ref": "#/definitions/dto.StBids" } }, "404": { - "description": "" + "description": "Not Found" } } }, @@ -126,7 +126,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.ApplyBidResponse" + "$ref": "#/definitions/dto.ApplyBidResp" } } } @@ -151,7 +151,7 @@ "type": "integer", "description": "Supervisor ID", "name": "supervisor_id", - "in": "query", + "in": "path", "required": true } ], @@ -199,7 +199,7 @@ } }, "500": { - "description": "" + "description": "Internal Server Error" } } } @@ -222,11 +222,11 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentProfile" + "$ref": "#/definitions/dto.StProfile" } }, "404": { - "description": "" + "description": "Not Found" } } } @@ -263,7 +263,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentViewSSR" + "$ref": "#/definitions/dto.StViewRelation" } } } @@ -296,7 +296,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StudentWorks" + "$ref": "#/definitions/dto.StWorks" } } } @@ -329,7 +329,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSupervisorPlenty" + "$ref": "#/definitions/dto.WorkSvPlenty" } } } @@ -362,7 +362,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SupervisorBids" + "$ref": "#/definitions/dto.SvBids" } } } @@ -421,7 +421,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SupervisorProfile" + "$ref": "#/definitions/dto.SvProfile" } } } @@ -454,7 +454,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SupervisorWorkPlenty" + "$ref": "#/definitions/dto.SvWorkPlenty" } } } @@ -476,7 +476,7 @@ } } }, - "dto.ApplyBidResponse": { + "dto.ApplyBidResp": { "type": "object", "properties": { "bidID": { @@ -593,7 +593,7 @@ } } }, - "dto.StudentBid": { + "dto.StBid": { "type": "object", "properties": { "createdAt": { @@ -606,25 +606,25 @@ "type": "string" }, "supervisor": { - "$ref": "#/definitions/dto.SupervisorProfile" + "$ref": "#/definitions/dto.SvProfile" }, "work": { "$ref": "#/definitions/dto.Work" } } }, - "dto.StudentBids": { + "dto.StBids": { "type": "object", "properties": { "bids": { "type": "array", "items": { - "$ref": "#/definitions/dto.StudentBid" + "$ref": "#/definitions/dto.StBid" } } } }, - "dto.StudentProfile": { + "dto.StProfile": { "type": "object", "properties": { "avatarUrl": { @@ -653,7 +653,7 @@ } } }, - "dto.StudentViewSSR": { + "dto.StViewRelation": { "type": "object", "properties": { "createdAt": { @@ -666,14 +666,14 @@ "type": "string" }, "supervisor": { - "$ref": "#/definitions/dto.SupervisorProfile" + "$ref": "#/definitions/dto.SvProfile" }, "work": { "$ref": "#/definitions/dto.Work" } } }, - "dto.StudentWork": { + "dto.StWork": { "type": "object", "properties": { "description": { @@ -693,7 +693,7 @@ } } }, - "dto.StudentWorks": { + "dto.StWorks": { "type": "object", "properties": { "studentID": { @@ -702,7 +702,7 @@ "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.StudentWork" + "$ref": "#/definitions/dto.StWork" } } } @@ -721,7 +721,7 @@ } } }, - "dto.SupervisorBid": { + "dto.SvBid": { "type": "object", "properties": { "createdAt": { @@ -734,25 +734,25 @@ "type": "string" }, "student": { - "$ref": "#/definitions/dto.StudentProfile" + "$ref": "#/definitions/dto.StProfile" }, "work": { "$ref": "#/definitions/dto.Work" } } }, - "dto.SupervisorBids": { + "dto.SvBids": { "type": "object", "properties": { "bids": { "type": "array", "items": { - "$ref": "#/definitions/dto.SupervisorBid" + "$ref": "#/definitions/dto.SvBid" } } } }, - "dto.SupervisorProfile": { + "dto.SvProfile": { "type": "object", "properties": { "about": { @@ -781,7 +781,7 @@ } } }, - "dto.SupervisorWork": { + "dto.SvWork": { "type": "object", "properties": { "description": { @@ -801,7 +801,7 @@ } } }, - "dto.SupervisorWorkPlenty": { + "dto.SvWorkPlenty": { "type": "object", "properties": { "supervisorID": { @@ -810,7 +810,7 @@ "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.SupervisorWork" + "$ref": "#/definitions/dto.SvWork" } } } @@ -835,7 +835,7 @@ } } }, - "dto.WorkSupervisor": { + "dto.WorkSv": { "type": "object", "properties": { "about": { @@ -870,13 +870,13 @@ } } }, - "dto.WorkSupervisorPlenty": { + "dto.WorkSvPlenty": { "type": "object", "properties": { "supervisors": { "type": "array", "items": { - "$ref": "#/definitions/dto.WorkSupervisor" + "$ref": "#/definitions/dto.WorkSv" } }, "workID": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index 1e91fe9..679c308 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -9,7 +9,7 @@ definitions: workID: type: integer type: object - dto.ApplyBidResponse: + dto.ApplyBidResp: properties: bidID: type: integer @@ -84,7 +84,7 @@ definitions: new_status: type: string type: object - dto.StudentBid: + dto.StBid: properties: createdAt: type: string @@ -93,18 +93,18 @@ definitions: status: type: string supervisor: - $ref: '#/definitions/dto.SupervisorProfile' + $ref: '#/definitions/dto.SvProfile' work: $ref: '#/definitions/dto.Work' type: object - dto.StudentBids: + dto.StBids: properties: bids: items: - $ref: '#/definitions/dto.StudentBid' + $ref: '#/definitions/dto.StBid' type: array type: object - dto.StudentProfile: + dto.StProfile: properties: avatarUrl: type: string @@ -123,7 +123,7 @@ definitions: year: type: integer type: object - dto.StudentViewSSR: + dto.StViewRelation: properties: createdAt: type: string @@ -132,11 +132,11 @@ definitions: status: type: string supervisor: - $ref: '#/definitions/dto.SupervisorProfile' + $ref: '#/definitions/dto.SvProfile' work: $ref: '#/definitions/dto.Work' type: object - dto.StudentWork: + dto.StWork: properties: description: type: string @@ -149,13 +149,13 @@ definitions: subject: type: string type: object - dto.StudentWorks: + dto.StWorks: properties: studentID: type: integer works: items: - $ref: '#/definitions/dto.StudentWork' + $ref: '#/definitions/dto.StWork' type: array type: object dto.SubjectResp: @@ -167,7 +167,7 @@ definitions: subjectID: type: integer type: object - dto.SupervisorBid: + dto.SvBid: properties: createdAt: type: string @@ -176,18 +176,18 @@ definitions: status: type: string student: - $ref: '#/definitions/dto.StudentProfile' + $ref: '#/definitions/dto.StProfile' work: $ref: '#/definitions/dto.Work' type: object - dto.SupervisorBids: + dto.SvBids: properties: bids: items: - $ref: '#/definitions/dto.SupervisorBid' + $ref: '#/definitions/dto.SvBid' type: array type: object - dto.SupervisorProfile: + dto.SvProfile: properties: about: type: string @@ -206,7 +206,7 @@ definitions: supervisorID: type: integer type: object - dto.SupervisorWork: + dto.SvWork: properties: description: type: string @@ -219,13 +219,13 @@ definitions: subject: type: string type: object - dto.SupervisorWorkPlenty: + dto.SvWorkPlenty: properties: supervisorID: type: integer works: items: - $ref: '#/definitions/dto.SupervisorWork' + $ref: '#/definitions/dto.SvWork' type: array type: object dto.Work: @@ -241,7 +241,7 @@ definitions: subject: $ref: '#/definitions/dto.SubjectResp' type: object - dto.WorkSupervisor: + dto.WorkSv: properties: about: type: string @@ -264,11 +264,11 @@ definitions: supervisorID: type: integer type: object - dto.WorkSupervisorPlenty: + dto.WorkSvPlenty: properties: supervisors: items: - $ref: '#/definitions/dto.WorkSupervisor' + $ref: '#/definitions/dto.WorkSv' type: array workID: type: integer @@ -306,9 +306,9 @@ paths: schema: $ref: '#/definitions/dto.LoginResponse' "401": - description: "" + description: Unauthorized "500": - description: "" + description: Internal Server Error summary: Login into account tags: - auth @@ -326,9 +326,9 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.StudentBids' + $ref: '#/definitions/dto.StBids' "404": - description: "" + description: Not Found security: - Auth: [] summary: GetUserInfo student's bids @@ -350,7 +350,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.ApplyBidResponse' + $ref: '#/definitions/dto.ApplyBidResp' security: - Auth: [] summary: Apply bid @@ -360,7 +360,7 @@ paths: get: parameters: - description: Supervisor ID - in: query + in: path name: supervisor_id required: true type: integer @@ -394,7 +394,7 @@ paths: schema: $ref: '#/definitions/dto.FeedbackAddResp' "500": - description: "" + description: Internal Server Error security: - Auth: [] summary: Provide a feedback @@ -408,9 +408,9 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.StudentProfile' + $ref: '#/definitions/dto.StProfile' "404": - description: "" + description: Not Found security: - Auth: [] summary: GetUserInfo student's profile @@ -433,7 +433,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.StudentViewSSR' + $ref: '#/definitions/dto.StViewRelation' security: - Auth: [] summary: Start SSR @@ -453,7 +453,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.StudentWorks' + $ref: '#/definitions/dto.StWorks' security: - Auth: [] summary: GetUserInfo student's works @@ -473,7 +473,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.WorkSupervisorPlenty' + $ref: '#/definitions/dto.WorkSvPlenty' security: - Auth: [] summary: GetUserInfo supervisors of the work @@ -493,7 +493,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.SupervisorBids' + $ref: '#/definitions/dto.SvBids' security: - Auth: [] summary: GetUserInfo supervisor's bids @@ -528,7 +528,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.SupervisorProfile' + $ref: '#/definitions/dto.SvProfile' security: - Auth: [] summary: GetUserInfo supervisor's profile @@ -548,7 +548,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.SupervisorWorkPlenty' + $ref: '#/definitions/dto.SvWorkPlenty' security: - Auth: [] summary: GetUserInfo supervisor's works From 852e7e1be320e6c84499433962bf2b6942e81ac8 Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Sun, 2 Oct 2022 00:53:53 +0300 Subject: [PATCH 02/12] upgrade: sv and st profiles works --- go.mod | 2 +- internal/app/app.go | 12 +- internal/controller/http/interfaces.go | 4 +- internal/controller/http/middlewares/auth.go | 4 +- internal/controller/http/router.go | 4 +- internal/controller/http/student.go | 7 +- internal/controller/http/supervisor.go | 187 +++++++++--------- internal/dto/auth.go | 6 +- internal/dto/profile.go | 30 ++- internal/entity/auth.go | 6 - internal/entity/supervisor.go | 17 ++ internal/entity/user.go | 15 +- internal/service/auth.go | 12 +- internal/service/bid.go | 14 +- internal/service/bid_test.go | 4 +- internal/service/interfaces.go | 10 +- internal/service/profile.go | 42 ++-- internal/service/relation.go | 15 +- internal/service/repo_pg/auth.go | 63 ------ internal/service/repo_pg/student.go | 18 +- internal/service/repo_pg/supervisor.go | 63 ++++++ internal/service/repo_pg/user.go | 34 +++- internal/service/work.go | 15 +- migrations/20220508102907_create_users.up.sql | 35 +--- pkg/misc/auth.go | 5 +- 25 files changed, 326 insertions(+), 298 deletions(-) delete mode 100644 internal/entity/auth.go create mode 100644 internal/entity/supervisor.go delete mode 100644 internal/service/repo_pg/auth.go create mode 100644 internal/service/repo_pg/supervisor.go diff --git a/go.mod b/go.mod index db20ede..a79bbd7 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module ssr -go 1.17 +go 1.19 require ( github.com/golang-jwt/jwt v3.2.2+incompatible diff --git a/internal/app/app.go b/internal/app/app.go index 1fb8a4c..2678f65 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -37,13 +37,15 @@ func setupMiddlewares(server *echo.Echo, cfg *config.Config) { func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, cfg *config.Config) { relationRepo := repo_pg.NewRelation(pg, l) - authRepo := repo_pg.NewAuth(pg, l) - profileRepo := repo_pg.NewProfile(pg, l) + //profileRepo := repo_pg.NewProfile(pg, l) workRepo := repo_pg.NewWork(pg, l) feedbackRepo := repo_pg.NewFeedback(pg, l) + userRepo := repo_pg.NewUser(pg, l) + studentRepo := repo_pg.NewStudent(pg, l) + supervisorRepo := repo_pg.NewSupervisor(pg, l) - authService := service.NewAuth(authRepo, l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) - profileService := service.NewProfile(profileRepo, l) + authService := service.NewAuth(userRepo, l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) + profileService := service.NewProfile(studentRepo, supervisorRepo, l) bidService := service.NewBid(relationRepo, l) workService := service.NewWork(workRepo, relationRepo, l) relationService := service.NewRelation(relationRepo, l) @@ -56,8 +58,6 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, profileService, profileService, bidService, - bidService, - workService, workService, relationService, feedbackService, diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index 9acd07b..d7f1c22 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -9,10 +9,10 @@ type ( Login(email, password string) (*dto.LoginResponse, error) } StProfileService interface { - GetStudentProfile(email string) (*dto.StProfile, error) + GetStudentProfile(userID int) (*dto.StProfile, error) } SvProfileService interface { - GetSupervisorProfile(email string) (*dto.SvProfile, error) + GetSupervisorProfile(userID int) (*dto.SvProfile, error) } StBidService interface { GetStudentBids(studentID int) (*dto.StBids, error) diff --git a/internal/controller/http/middlewares/auth.go b/internal/controller/http/middlewares/auth.go index a2d3c16..f52b930 100644 --- a/internal/controller/http/middlewares/auth.go +++ b/internal/controller/http/middlewares/auth.go @@ -14,7 +14,9 @@ func CheckRole(next echo.HandlerFunc) echo.HandlerFunc { expRole := split[2] _, recRole := misc.ExtractCtx(c) - if recRole != expRole { + mapping := map[string]string{"st": "student", "sv": "supervisor"} + + if mapping[recRole] != expRole { return echo.ErrForbidden } diff --git a/internal/controller/http/router.go b/internal/controller/http/router.go index e4b9256..33bfd0a 100644 --- a/internal/controller/http/router.go +++ b/internal/controller/http/router.go @@ -12,9 +12,7 @@ func NewRouter( stProfile StProfileService, svProfile SvProfileService, stBids StBidService, - svBids SvBidService, stWorks StWorkService, - svWorks SvWorkService, stRelations StRelationService, feedback FeedbackService, ) { @@ -23,6 +21,6 @@ func NewRouter( { NewAuthRoutes(g, l, auth) NewStudentRoutes(g, l, stProfile, stBids, stWorks, stRelations, feedback) - NewSupervisorRoutes(g, l, svProfile, svBids, svWorks) + NewSupervisorRoutes(g, l, svProfile) } } diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index 6b27589..7891040 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -29,14 +29,15 @@ type student struct { // @Router /api/student/profile [get] // @Security Auth func (ctrl *student) getProfile(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) + rawUserID, _ := misc.ExtractCtx(ctx) + userID, _ := strconv.Atoi(rawUserID) - profileDto, err := ctrl.profileService.GetStudentProfile(email) + profileDTO, err := ctrl.profileService.GetStudentProfile(userID) if err != nil { return echo.ErrNotFound } - return ctx.JSON(http.StatusOK, profileDto) + return ctx.JSON(http.StatusOK, profileDTO) } // ShowAccount godoc diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index a619b4e..a64341d 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -1,11 +1,9 @@ package http import ( - "fmt" "github.com/labstack/echo/v4" "net/http" "ssr/internal/controller/http/middlewares" - "ssr/internal/dto" "ssr/pkg/logger" "ssr/pkg/misc" "strconv" @@ -14,8 +12,8 @@ import ( type supervisor struct { l logger.Interface profileService SvProfileService - bidService SvBidService - workService SvWorkService + //bidService SvBidService + //workService SvWorkService } // ShowAccount godoc @@ -26,33 +24,9 @@ type supervisor struct { // @Router /api/supervisor/profile [get] // @Security Auth func (ctrl *supervisor) getProfile(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - respDTO, err := ctrl.profileService.GetSupervisorProfile(email) - if err != nil { - ctrl.l.Error(err) - return echo.NewHTTPError(http.StatusInternalServerError, "TODO") - } - - return ctx.JSON(http.StatusOK, respDTO) -} - -// ShowAccount godoc -// @Summary GetUserByEmail supervisor's works -// @Tags supervisor -// @Param supervisor_id query int true "Supervisor ID" -// @Produce json -// @Success 200 {object} dto.SvWorkPlenty -// @Router /api/supervisor/work [get] -// @Security Auth -func (ctrl *supervisor) getWorks(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) - - respDTO, err := ctrl.workService.GetSupervisorWorks(supervisorID) + rawUserID, _ := misc.ExtractCtx(ctx) + userID, _ := strconv.Atoi(rawUserID) + respDTO, err := ctrl.profileService.GetSupervisorProfile(userID) if err != nil { ctrl.l.Error(err) return echo.NewHTTPError(http.StatusInternalServerError, "TODO") @@ -61,79 +35,104 @@ func (ctrl *supervisor) getWorks(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -// ShowAccount godoc -// @Summary GetUserByEmail supervisor's bids -// @Tags supervisor -// @Param supervisor_id query int true "Supervisor ID" -// @Produce json -// @Success 200 {object} dto.SvBids -// @Router /api/supervisor/bid [get] -// @Security Auth -func (ctrl *supervisor) getBids(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) - - respDTO, err := ctrl.bidService.GetSupervisorBids(supervisorID) - if err != nil { - ctrl.l.Error(err) - return echo.NewHTTPError(http.StatusInternalServerError, "TODO") - } - - return ctx.JSON(http.StatusOK, respDTO) -} - -// ShowAccount godoc -// @Summary Accept or Decline student's bid -// @Tags supervisor -// @Param ResolveBid body dto.ResolveBid true "bid info" -// @Produce json -// @Success 200 {object} dto.ResolveBidResp -// @Router /api/supervisor/bid/resolve [post] -// @Security Auth -func (ctrl *supervisor) resolveBid(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - reqDTO := &dto.ResolveBid{} - if err := ctx.Bind(reqDTO); err != nil { - return echo.ErrBadRequest - } - - if err := ctrl.bidService.Resolve(reqDTO); err != nil { - return echo.NewHTTPError(http.StatusInternalServerError) - } - - newStatus := "" - if reqDTO.Accept { - newStatus = "accepted" - } else { - newStatus = "rejected" - } - - resp := dto.ResolveBidResp{NewStatus: newStatus} - - return ctx.JSON(http.StatusOK, resp) -} - +// // ShowAccount godoc +// // @Summary GetUserByEmail supervisor's works +// // @Tags supervisor +// // @Param supervisor_id query int true "Supervisor ID" +// // @Produce json +// // @Success 200 {object} dto.SvWorkPlenty +// // @Router /api/supervisor/work [get] +// // @Security Auth +// +// func (ctrl *supervisor) getWorks(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) +// +// respDTO, err := ctrl.workService.GetSupervisorWorks(supervisorID) +// if err != nil { +// ctrl.l.Error(err) +// return echo.NewHTTPError(http.StatusInternalServerError, "TODO") +// } +// +// return ctx.JSON(http.StatusOK, respDTO) +// } +// +// // ShowAccount godoc +// // @Summary GetUserByEmail supervisor's bids +// // @Tags supervisor +// // @Param supervisor_id query int true "Supervisor ID" +// // @Produce json +// // @Success 200 {object} dto.SvBids +// // @Router /api/supervisor/bid [get] +// // @Security Auth +// +// func (ctrl *supervisor) getBids(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) +// +// respDTO, err := ctrl.bidService.GetSupervisorBids(supervisorID) +// if err != nil { +// ctrl.l.Error(err) +// return echo.NewHTTPError(http.StatusInternalServerError, "TODO") +// } +// +// return ctx.JSON(http.StatusOK, respDTO) +// } +// +// // ShowAccount godoc +// // @Summary Accept or Decline student's bid +// // @Tags supervisor +// // @Param ResolveBid body dto.ResolveBid true "bid info" +// // @Produce json +// // @Success 200 {object} dto.ResolveBidResp +// // @Router /api/supervisor/bid/resolve [post] +// // @Security Auth +// +// func (ctrl *supervisor) resolveBid(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// reqDTO := &dto.ResolveBid{} +// if err := ctx.Bind(reqDTO); err != nil { +// return echo.ErrBadRequest +// } +// +// if err := ctrl.bidService.Resolve(reqDTO); err != nil { +// return echo.NewHTTPError(http.StatusInternalServerError) +// } +// +// newStatus := "" +// if reqDTO.Accept { +// newStatus = "accepted" +// } else { +// newStatus = "rejected" +// } +// +// resp := dto.ResolveBidResp{NewStatus: newStatus} +// +// return ctx.JSON(http.StatusOK, resp) +// } func NewSupervisorRoutes( router *echo.Group, l logger.Interface, profileService SvProfileService, - bidService SvBidService, - workService SvWorkService, + // bidService SvBidService, + // workService SvWorkService, ) { - ctrl := &supervisor{l, profileService, bidService, workService} + ctrl := &supervisor{l, profileService} g := router.Group("/supervisor", middlewares.CheckRole) { g.GET("/profile", ctrl.getProfile) - g.GET("/bid", ctrl.getBids) - g.POST("/bid/resolve", ctrl.resolveBid) - g.GET("/work", ctrl.getWorks) - g.GET("/work", ctrl.getWorks) + //g.GET("/bid", ctrl.getBids) + //g.POST("/bid/resolve", ctrl.resolveBid) + //g.GET("/work", ctrl.getWorks) + //g.GET("/work", ctrl.getWorks) } } diff --git a/internal/dto/auth.go b/internal/dto/auth.go index 01a42d6..dd03faf 100644 --- a/internal/dto/auth.go +++ b/internal/dto/auth.go @@ -1,7 +1,7 @@ package dto type LoginResponse struct { - Token string `json:"token"` - Email string `json:"email"` - Role string `json:"role"` + Token string `json:"token"` + UserID int `json:"user-id"` + Role string `json:"role"` } diff --git a/internal/dto/profile.go b/internal/dto/profile.go index fae91bd..3da29ec 100644 --- a/internal/dto/profile.go +++ b/internal/dto/profile.go @@ -12,23 +12,21 @@ type UserInfo struct { } type StProfile struct { - StudentID int `json:"studentID"` - Email string `json:"email"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - AvatarUrl misc.NullString `json:"avatarUrl" swaggertype:"string"` - Year int `json:"year"` - StudentCard string `json:"studentCard"` - Department string `json:"department"` + Email string `json:"email"` + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + PhotoUrl string `json:"photoUrl"` + Year int `json:"year"` + StudentCard string `json:"studentCard"` + Department string `json:"department"` } type SvProfile struct { - SupervisorID int `json:"supervisorID"` - Email string `json:"email"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - About string `json:"about"` - Birthdate misc.Date `json:"birthdate" swaggertype:"string"` - AvatarUrl misc.NullString `json:"avatarUrl" swaggertype:"string"` - Department string `json:"department"` + Email string `json:"email"` + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + About string `json:"about"` + Birthdate misc.Date `json:"birthdate" swaggertype:"string"` + PhotoUrl string `json:"avatarUrl"` + Department string `json:"department"` } diff --git a/internal/entity/auth.go b/internal/entity/auth.go deleted file mode 100644 index eac059c..0000000 --- a/internal/entity/auth.go +++ /dev/null @@ -1,6 +0,0 @@ -package entity - -type Auth struct { - Email string `db:"email"` - Password string `db:"password"` -} diff --git a/internal/entity/supervisor.go b/internal/entity/supervisor.go new file mode 100644 index 0000000..1219d75 --- /dev/null +++ b/internal/entity/supervisor.go @@ -0,0 +1,17 @@ +package entity + +import "time" + +type Supervisor struct { + UserID int `db:"user_id"` + Birthdate string + About int + DepartmentID string `db:"department_id"` +} + +type SupervisorFull struct { + User *User + Birthdate time.Time + About string + DepartmentID string `db:"department_id"` +} diff --git a/internal/entity/user.go b/internal/entity/user.go index d91c416..fd0044c 100644 --- a/internal/entity/user.go +++ b/internal/entity/user.go @@ -1,7 +1,5 @@ package entity -import "database/sql" - type UserRole string const ( @@ -10,10 +8,11 @@ const ( ) type User struct { - UserID int `db:"user_id"` - Email string `db:"email"` - FirstName string `db:"first_name"` - LastName string `db:"last_name"` - PhotoUrl sql.NullString `db:"photo_url"` - Role UserRole `db:"role"` + UserID int `db:"user_id"` + Email string `db:"email"` + FirstName string `db:"first_name"` + LastName string `db:"last_name"` + PhotoUrl string `db:"photo_url"` + Role UserRole `db:"role"` + Password string `db:"password"` } diff --git a/internal/service/auth.go b/internal/service/auth.go index 90b3850..ffb8edd 100644 --- a/internal/service/auth.go +++ b/internal/service/auth.go @@ -11,12 +11,12 @@ import ( type auth struct { *Base - repo AuthRepo + repo UserRepo tokenExp time.Duration signingKey []byte } -func NewAuth(r AuthRepo, l logger.Interface, tokenExpMinutes int, signingKey []byte) *auth { +func NewAuth(r UserRepo, l logger.Interface, tokenExpMinutes int, signingKey []byte) *auth { return &auth{ Base: NewBase(l), repo: r, @@ -36,7 +36,7 @@ func (service *auth) Login(email, password string) (*dto.LoginResponse, error) { return nil, err } - tokenClaims := misc.NewAppJWTClaims(service.tokenExp, dbData.Email, string(dbData.Role)) + tokenClaims := misc.NewAppJWTClaims(service.tokenExp, dbData.UserID, string(dbData.Role)) token := jwt.NewWithClaims(jwt.SigningMethodHS256, tokenClaims) tokenStr, err := token.SignedString(service.signingKey) @@ -46,8 +46,8 @@ func (service *auth) Login(email, password string) (*dto.LoginResponse, error) { } return &dto.LoginResponse{ - Token: tokenStr, - Email: dbData.Email, - Role: string(dbData.Role), + Token: tokenStr, + UserID: dbData.UserID, + Role: string(dbData.Role), }, nil } diff --git a/internal/service/bid.go b/internal/service/bid.go index 3899f09..20ac0a0 100644 --- a/internal/service/bid.go +++ b/internal/service/bid.go @@ -33,15 +33,14 @@ func (service *Bid) GetStudentBids(studentID int) (*dto.StBids, error) { Status: db.Status, CreatedAt: db.CreatedAt, Supervisor: dto.SvProfile{ - SupervisorID: db.SupervisorID, - Email: db.Email, - FirstName: db.FirstName, - LastName: db.LastName, - About: db.About, + Email: db.Email, + FirstName: db.FirstName, + LastName: db.LastName, + About: db.About, Birthdate: misc.Date{ Time: db.Birthdate, }, - AvatarUrl: misc.NullString(db.PhotoUrl), + PhotoUrl: db.PhotoUrl, Department: db.SvProfile.DepartmentID, }, Work: dto.Work{ @@ -75,12 +74,11 @@ func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { Status: db.Status, CreatedAt: db.CreatedAt, Student: dto.StProfile{ - StudentID: db.StudentID, Email: db.Email, FirstName: db.FirstName, LastName: db.LastName, Year: db.Year, - AvatarUrl: misc.NullString(db.PhotoUrl), + PhotoUrl: db.PhotoUrl, Department: db.StProfile.DepartmentID, }, Work: dto.Work{ diff --git a/internal/service/bid_test.go b/internal/service/bid_test.go index c3a1d90..88c0c06 100644 --- a/internal/service/bid_test.go +++ b/internal/service/bid_test.go @@ -191,7 +191,7 @@ package service // LastName: "Иванов", // About: "Обо мне", // Birthdate: misc.Date{}, -// AvatarUrl: misc.NullString{}, +// PhotoUrl: misc.NullString{}, // Department: "ИУ7", // }, // Work: dto.Work{ @@ -265,7 +265,7 @@ package service // LastName: "Иванов", // About: "Обо мне", // Birthdate: misc.Date{}, -// AvatarUrl: misc.NullString{}, +// PhotoUrl: misc.NullString{}, // Department: "ИУ7", // }, // Work: dto.Work{ diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index d304cf7..48658f7 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -5,8 +5,14 @@ import ( ) type ( - AuthRepo interface { - GetUserByEmail(email string) (*entity.Auth, error) + UserRepo interface { + GetUserByEmail(email string) (*entity.User, error) + } + StudentRepo interface { + GetFullStudent(userID int) (*entity.StudentFull, error) + } + SupervisorRepo interface { + GetFullSupervisor(userID int) (*entity.SupervisorFull, error) } ProfileRepo interface { GetStProfile(email string) (*entity.StProfile, error) diff --git a/internal/service/profile.go b/internal/service/profile.go index 94fdc41..d4abf00 100644 --- a/internal/service/profile.go +++ b/internal/service/profile.go @@ -8,48 +8,48 @@ import ( type Profile struct { *Base - repo ProfileRepo + stRepo StudentRepo + svRepo SupervisorRepo } -func NewProfile(r ProfileRepo, l logger.Interface) *Profile { +func NewProfile(stRepo StudentRepo, svRepo SupervisorRepo, l logger.Interface) *Profile { return &Profile{ - Base: NewBase(l), - repo: r, + Base: NewBase(l), + stRepo: stRepo, + svRepo: svRepo, } } -func (uc *Profile) GetStudentProfile(email string) (*dto.StProfile, error) { - dbData, err := uc.repo.GetStProfile(email) +func (uc *Profile) GetStudentProfile(userID int) (*dto.StProfile, error) { + dbData, err := uc.stRepo.GetFullStudent(userID) if err != nil { return nil, err } return &dto.StProfile{ - StudentID: dbData.StudentID, - Email: dbData.Email, - FirstName: dbData.FirstName, - LastName: dbData.LastName, - AvatarUrl: misc.NullString(dbData.PhotoUrl), + Email: dbData.User.Email, + FirstName: dbData.User.FirstName, + LastName: dbData.User.LastName, + PhotoUrl: dbData.User.PhotoUrl, Year: dbData.Year, StudentCard: dbData.StudentCard, Department: dbData.DepartmentID, }, nil } -func (uc *Profile) GetSupervisorProfile(email string) (*dto.SvProfile, error) { - dbData, err := uc.repo.GetSvProfile(email) +func (uc *Profile) GetSupervisorProfile(userID int) (*dto.SvProfile, error) { + dbData, err := uc.svRepo.GetFullSupervisor(userID) if err != nil { return nil, err } return &dto.SvProfile{ - SupervisorID: dbData.SupervisorID, - Email: dbData.Email, - FirstName: dbData.FirstName, - LastName: dbData.LastName, - AvatarUrl: misc.NullString(dbData.PhotoUrl), - About: dbData.About, - Birthdate: misc.Date{Time: dbData.Birthdate}, - Department: dbData.DepartmentID, + Email: dbData.User.Email, + FirstName: dbData.User.FirstName, + LastName: dbData.User.LastName, + PhotoUrl: dbData.User.PhotoUrl, + About: dbData.About, + Birthdate: misc.Date{Time: dbData.Birthdate}, + Department: dbData.DepartmentID, }, nil } diff --git a/internal/service/relation.go b/internal/service/relation.go index b65d5b8..4e8bd0a 100644 --- a/internal/service/relation.go +++ b/internal/service/relation.go @@ -49,14 +49,13 @@ func (service *Relation) Create(data *dto.CreateSSR) (*dto.StViewRelation, error Status: ssr.Status, CreatedAt: ssr.CreatedAt, Supervisor: dto.SvProfile{ - SupervisorID: ssr.SupervisorID, - Email: ssr.SvProfile.Email, - FirstName: ssr.SvProfile.FirstName, - LastName: ssr.SvProfile.LastName, - About: ssr.SvProfile.About, - Birthdate: misc.Date{Time: ssr.Birthdate}, - AvatarUrl: misc.NullString(ssr.PhotoUrl), - Department: ssr.DepartmentID, + Email: ssr.SvProfile.Email, + FirstName: ssr.SvProfile.FirstName, + LastName: ssr.SvProfile.LastName, + About: ssr.SvProfile.About, + Birthdate: misc.Date{Time: ssr.Birthdate}, + PhotoUrl: ssr.PhotoUrl, + Department: ssr.DepartmentID, }, Work: dto.Work{ WorkID: ssr.WorkID, diff --git a/internal/service/repo_pg/auth.go b/internal/service/repo_pg/auth.go deleted file mode 100644 index d05e2d0..0000000 --- a/internal/service/repo_pg/auth.go +++ /dev/null @@ -1,63 +0,0 @@ -package repo_pg - -import ( - "fmt" - "ssr/internal/entity" - "ssr/pkg/logger" - "ssr/pkg/postgres" -) - -type Auth struct { - *BasePgRepo -} - -func NewAuth(pg *postgres.Postgres, l logger.Interface) *Auth { - return &Auth{ - BasePgRepo: NewPgRepo(pg, l), - } -} - -func (r *Auth) Create(email, password string, userID int) error { - query := ` - insert into auth (email, password, user_id) - values ($1, $2, $3) - ` - - res, err := r.Conn.Exec(query, email, password, userID) - - fmt.Println(res) //TODO - - if err != nil { - err := fmt.Errorf("Auth->Create->repo.Conn.Exec: %w", err) - r.l.Error(err) // TODO - return err - } - - return nil -} - -func (r *Auth) GetUserByEmail(email string) (*entity.Auth, error) { - auth := entity.Auth{} - - err := r.Conn.Get(&auth, "select * from auth where email = $1", email) - if err != nil { - err := fmt.Errorf("Auth->r.Conn.Get(): %w", err) - r.l.Error(err) - return nil, err - } - - return &auth, nil -} - -func (r *Auth) GetUserByID(userID int) (*entity.Auth, error) { - auth := entity.Auth{} - - err := r.Conn.Get(&auth, "select * from auth where user_id = $1", userID) - if err != nil { - err := fmt.Errorf("Auth->r.Conn.Get(): %w", err) - r.l.Error(err) - return nil, err - } - - return &auth, nil -} diff --git a/internal/service/repo_pg/student.go b/internal/service/repo_pg/student.go index 4e9c71d..8c3c434 100644 --- a/internal/service/repo_pg/student.go +++ b/internal/service/repo_pg/student.go @@ -11,15 +11,15 @@ type Student struct { *BasePgRepo } -func New(pg *postgres.Postgres, l logger.Interface) *Student { +func NewStudent(pg *postgres.Postgres, l logger.Interface) *Student { return &Student{ BasePgRepo: NewPgRepo(pg, l), } } -func (repo *Student) Get(userID int) (*entity.Student, error) { +func (repo *Student) GetStudent(userID int) (*entity.Student, error) { const query = ` - select * from users where user_id = $1 + select * from students where user_id = $1 ` student := entity.Student{} @@ -34,9 +34,17 @@ func (repo *Student) Get(userID int) (*entity.Student, error) { return &student, nil } -func (repo *Student) GetFull(userID int) (*entity.StudentFull, error) { +func (repo *Student) GetFullStudent(userID int) (*entity.StudentFull, error) { const query = ` - select * + select + s.student_card, + s.department_id, + s.year, + u.email as "user.email", + u.first_name as "user.first_name", + u.last_name as "user.last_name", + u.photo_url as "user.photo_url", + u.user_id as "user.user_id" from users u join students s using (user_id) where user_id = $1 diff --git a/internal/service/repo_pg/supervisor.go b/internal/service/repo_pg/supervisor.go new file mode 100644 index 0000000..0e49159 --- /dev/null +++ b/internal/service/repo_pg/supervisor.go @@ -0,0 +1,63 @@ +package repo_pg + +import ( + "fmt" + "ssr/internal/entity" + "ssr/pkg/logger" + "ssr/pkg/postgres" +) + +type Supervisor struct { + *BasePgRepo +} + +func NewSupervisor(pg *postgres.Postgres, l logger.Interface) *Supervisor { + return &Supervisor{ + BasePgRepo: NewPgRepo(pg, l), + } +} + +func (repo *Supervisor) GetSupervisor(userID int) (*entity.Supervisor, error) { + const query = ` + select * from supervisors where user_id = $1 + ` + + supervisor := entity.Supervisor{} + + err := repo.Conn.Get(&supervisor, query, userID) + if err != nil { + err := fmt.Errorf("Supervisor->Get->repo.Conn.Get(): %w", err) + repo.l.Error(err) + return nil, err + } + + return &supervisor, nil +} + +func (repo *Supervisor) GetFullSupervisor(userID int) (*entity.SupervisorFull, error) { + const query = ` + select + s.about, + s.department_id, + s.birthdate, + u.email as "user.email", + u.first_name as "user.first_name", + u.last_name as "user.last_name", + u.photo_url as "user.photo_url", + u.user_id as "user.user_id" + from users u + join supervisors s using (user_id) + where user_id = $1 + ` + + supervisorFull := entity.SupervisorFull{} + + err := repo.Conn.Get(&supervisorFull, query, userID) + if err != nil { + err := fmt.Errorf("Supervisor->GetFull->repo.Conn.Get(): %w", err) + repo.l.Error(err) + return nil, err + } + + return &supervisorFull, nil +} diff --git a/internal/service/repo_pg/user.go b/internal/service/repo_pg/user.go index 38e50eb..3ae9fc9 100644 --- a/internal/service/repo_pg/user.go +++ b/internal/service/repo_pg/user.go @@ -11,19 +11,19 @@ type User struct { *BasePgRepo } -func New(pg *postgres.Postgres, l logger.Interface) *User { +func NewUser(pg *postgres.Postgres, l logger.Interface) *User { return &User{ BasePgRepo: NewPgRepo(pg, l), } } -func (r *Auth) Create(email, firstName, LastName, photoUrl string, role entity.UserRole) error { +func (r *User) CreateUser(email, password, firstName, lastName, photoUrl string, role entity.UserRole) error { query := ` - insert into users (email, first_name, last_name, photo_url, role) + insert into users (email, password, first_name, last_name, photo_url, role) values ($1, $2, $3, $4, $5) ` - res, err := r.Conn.Exec(query, email, password, userID) + res, err := r.Conn.Exec(query, email, password, firstName, lastName, photoUrl, role) fmt.Println(res) //TODO @@ -35,3 +35,29 @@ func (r *Auth) Create(email, firstName, LastName, photoUrl string, role entity.U return nil } + +func (r *User) GetUserByEmail(email string) (*entity.User, error) { + user := entity.User{} + + err := r.Conn.Get(&user, "select * from users where email = $1", email) + if err != nil { + err := fmt.Errorf("User->r.Conn.Get(): %w", err) + r.l.Error(err) + return nil, err + } + + return &user, nil +} + +func (r *User) GetUserByID(userID int) (*entity.User, error) { + auth := entity.User{} + + err := r.Conn.Get(&auth, "select * from user where user_id = $1", userID) + if err != nil { + err := fmt.Errorf("User->r.Conn.Get(): %w", err) + r.l.Error(err) + return nil, err + } + + return &auth, nil +} diff --git a/internal/service/work.go b/internal/service/work.go index 94ce6c4..86d7ca8 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -95,14 +95,13 @@ func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { for _, db := range dbData { resp = append(resp, &dto.WorkSv{ SvProfile: dto.SvProfile{ - SupervisorID: db.SupervisorID, - Email: db.Email, - FirstName: db.FirstName, - LastName: db.LastName, - About: db.About, - Birthdate: misc.Date{Time: db.Birthdate}, - AvatarUrl: misc.NullString(db.PhotoUrl), - Department: db.DepartmentID, + Email: db.Email, + FirstName: db.FirstName, + LastName: db.LastName, + About: db.About, + Birthdate: misc.Date{Time: db.Birthdate}, + PhotoUrl: db.PhotoUrl, + Department: db.DepartmentID, }, Head: db.Head, Full: db.Full, diff --git a/migrations/20220508102907_create_users.up.sql b/migrations/20220508102907_create_users.up.sql index f20b2a8..f533eca 100644 --- a/migrations/20220508102907_create_users.up.sql +++ b/migrations/20220508102907_create_users.up.sql @@ -9,33 +9,16 @@ CREATE TABLE "users" "email" varchar unique not null, "first_name" varchar not null, "last_name" varchar not null, - "photo_url" varchar, - "role" user_role -); - -CREATE TABLE "auth" -( - "email" varchar PRIMARY KEY, - "user_id" int, + "photo_url" varchar not null, + "role" user_role not null, "password" varchar not null ); -ALTER TABLE "auth" - ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"); - - -insert into users (email, first_name, last_name, photo_url, role) -VALUES ('viktor1970@example.org', 'Дмитрий', 'Ивахненко', NULL, 'st'), - ('komarovmina@example.org', 'Наташа', 'Рязанова', NULL, 'sv'), - ('mina1988@example.org', 'Кирилл', 'Тассов', NULL, 'sv'), - ('jakov2001@example.org', 'Андрей', 'Куров', NULL, 'sv'), - ('ipat1974@example.net', 'Максим', 'Борисов', NULL, 'st'), - ('kopilovfoka@example.org', 'Дмитрий', 'Варин', NULL, 'st'); -insert into auth (email, password, user_id) -VALUES ('viktor1970@example.org', '$2b$12$kXlvD8/GSm/ZLEEjPFS0peiPEz.AEh5byuNIqZvFyu7bW6R5RxcJy', 1), - ('komarovmina@example.org', '$2b$12$xfWQ1aLcxliWgiNj8pKyOOTqOaUjQV5YMSb7whSNKb.Liejt3ae8u', 2), - ('jakov2001@example.org', '$2b$12$qhTeWstBv035IIbUXYM8I.pGnvMS0spDQqUM/OdpIUsmt6cFU.4P2', 3), - ('mina1988@example.org', '$2b$12$H7iWpTmqm.2OcsosP8CseOM/XCDP2.y0en.X..nZcbtvQ9EBZ0Pg2', 4), - ('ipat1974@example.net', '$2b$12$Zq11QMZNcC/9IxquRrqMwuWh1ijHx.k83McMe6pM2Jtf8LXbZ.a66', 5), - ('kopilovfoka@example.org', '$2b$12$MjWCy0Ka0n9QLm12cCJVjuReCykhbBfXck.Jt.VPkYgKQZ/SPwlbK', 6); +insert into users (email, first_name, last_name, photo_url, role, password) +VALUES ('viktor1970@example.org', 'Дмитрий', 'Ивахненко', '', 'st', '$2b$12$kXlvD8/GSm/ZLEEjPFS0peiPEz.AEh5byuNIqZvFyu7bW6R5RxcJy'), + ('komarovmina@example.org', 'Наташа', 'Рязанова', '', 'sv', '$2b$12$xfWQ1aLcxliWgiNj8pKyOOTqOaUjQV5YMSb7whSNKb.Liejt3ae8u'), + ('mina1988@example.org', 'Кирилл', 'Тассов', '', 'sv', '$2b$12$qhTeWstBv035IIbUXYM8I.pGnvMS0spDQqUM/OdpIUsmt6cFU.4P2'), + ('jakov2001@example.org', 'Андрей', 'Куров', '', 'sv', '$2b$12$H7iWpTmqm.2OcsosP8CseOM/XCDP2.y0en.X..nZcbtvQ9EBZ0Pg2'), + ('ipat1974@example.net', 'Максим', 'Борисов', '', 'st', '$2b$12$Zq11QMZNcC/9IxquRrqMwuWh1ijHx.k83McMe6pM2Jtf8LXbZ.a66'), + ('kopilovfoka@example.org', 'Дмитрий', 'Варин', '', 'st', '$2b$12$MjWCy0Ka0n9QLm12cCJVjuReCykhbBfXck.Jt.VPkYgKQZ/SPwlbK'); diff --git a/pkg/misc/auth.go b/pkg/misc/auth.go index 0af3a40..83ab487 100644 --- a/pkg/misc/auth.go +++ b/pkg/misc/auth.go @@ -3,6 +3,7 @@ package misc import ( "github.com/golang-jwt/jwt" "github.com/labstack/echo/v4" + "strconv" "time" ) @@ -11,11 +12,11 @@ type AppJWTClaims struct { Role string } -func NewAppJWTClaims(exp time.Duration, sub, role string) *AppJWTClaims { +func NewAppJWTClaims(exp time.Duration, sub int, role string) *AppJWTClaims { return &AppJWTClaims{ StandardClaims: jwt.StandardClaims{ ExpiresAt: time.Now().Add(exp).Unix(), - Subject: sub, + Subject: strconv.Itoa(sub), }, Role: role, } From 3564f5afcec5f0882c8e1872ef57b9422ac85b91 Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Sun, 2 Oct 2022 02:00:09 +0300 Subject: [PATCH 03/12] upgrade: paritially works students works --- internal/app/app.go | 2 +- internal/controller/http/interfaces.go | 4 +- internal/controller/http/student.go | 32 ++-- internal/dto/bid.go | 4 +- internal/dto/relation.go | 2 +- internal/dto/work.go | 42 ++--- internal/entity/subject.go | 6 +- internal/entity/work.go | 8 +- internal/service/bid.go | 19 +- internal/service/interfaces.go | 7 +- internal/service/mocks/bid.go | 10 +- internal/service/relation.go | 5 +- internal/service/repo_pg/work.go | 58 ++++-- internal/service/work.go | 166 ++++++++++-------- .../20220509115124_create_students.up.sql | 6 +- .../20220509193416_create_subjects.up.sql | 6 +- migrations/20220509194216_create_works.up.sql | 8 +- 17 files changed, 218 insertions(+), 167 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index 2678f65..820e577 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -47,7 +47,7 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, authService := service.NewAuth(userRepo, l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) profileService := service.NewProfile(studentRepo, supervisorRepo, l) bidService := service.NewBid(relationRepo, l) - workService := service.NewWork(workRepo, relationRepo, l) + workService := service.NewWork(workRepo, relationRepo, studentRepo, l) relationService := service.NewRelation(relationRepo, l) feedbackService := service.NewFeedback(feedbackRepo, l) diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index d7f1c22..06f7dd0 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -26,8 +26,8 @@ type ( Create(data *dto.CreateSSR) (*dto.StViewRelation, error) } StWorkService interface { - GetStudentWorks(studentID int) (*dto.StWorks, error) - GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) + GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) + //GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) } SvWorkService interface { GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index 7891040..49e78c8 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -68,7 +68,7 @@ func (ctrl *student) getBids(ctx echo.Context) error { // @Tags student // @Param student_id query int true "Student ID" // @Produce json -// @Success 200 {object} dto.StWorks +// @Success 200 {object} dto.StWorkPlenty // @Router /api/student/work [get] // @Security Auth func (ctrl *student) getWorks(ctx echo.Context) error { @@ -88,24 +88,24 @@ func (ctrl *student) getWorks(ctx echo.Context) error { // ShowAccount godoc // @Summary GetUserByEmail supervisors of the work // @Tags student -// @Param work_id query int true "Work ID" +// @Param work_id query int true "WorkResp ID" // @Produce json // @Success 200 {object} dto.WorkSvPlenty // @Router /api/student/work/supervisor [get] // @Security Auth -func (ctrl *student) getSupervisorsOfWork(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - workID, _ := strconv.Atoi(ctx.QueryParam("work_id")) - - respDTO, err := ctrl.workService.GetWorkSupervisors(workID) - if err != nil { - return echo.ErrNotFound - } - - return ctx.JSON(http.StatusOK, respDTO) -} +//func (ctrl *student) getSupervisorsOfWork(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// workID, _ := strconv.Atoi(ctx.QueryParam("work_id")) +// +// respDTO, err := ctrl.workService.GetWorkSupervisors(workID) +// if err != nil { +// return echo.ErrNotFound +// } +// +// return ctx.JSON(http.StatusOK, respDTO) +//} // ShowAccount godoc // @Summary Apply bid @@ -234,7 +234,7 @@ func NewStudentRoutes( student.PUT("/bid", ctrl.applyBid) student.POST("/ssr", ctrl.createSSR) student.GET("/work", ctrl.getWorks) - student.GET("/work/supervisor_id", ctrl.getSupervisorsOfWork) + //student.GET("/work/supervisor_id", ctrl.getSupervisorsOfWork) student.GET("/feedback/:supervisor_id", ctrl.getFeedback) student.PUT("/feedback", ctrl.provideFeedback) } diff --git a/internal/dto/bid.go b/internal/dto/bid.go index b358f3e..691c737 100644 --- a/internal/dto/bid.go +++ b/internal/dto/bid.go @@ -9,7 +9,7 @@ type StBid struct { Status string `json:"status"` CreatedAt time.Time `json:"createdAt"` Supervisor SvProfile `json:"supervisor"` - Work Work `json:"work"` + Work WorkResp `json:"work"` } type StBids struct { @@ -21,7 +21,7 @@ type SvBid struct { Status string `json:"status"` CreatedAt time.Time `json:"createdAt"` Student StProfile `json:"student"` - Work Work `json:"work"` + Work WorkResp `json:"work"` } type SvBids struct { diff --git a/internal/dto/relation.go b/internal/dto/relation.go index db8eaf7..025208d 100644 --- a/internal/dto/relation.go +++ b/internal/dto/relation.go @@ -12,5 +12,5 @@ type StViewRelation struct { Status string `json:"status"` CreatedAt time.Time `json:"createdAt"` Supervisor SvProfile `json:"supervisor"` - Work Work `json:"work"` + Work WorkResp `json:"work"` } diff --git a/internal/dto/work.go b/internal/dto/work.go index 3299550..4f28e51 100644 --- a/internal/dto/work.go +++ b/internal/dto/work.go @@ -1,46 +1,42 @@ package dto -type Work struct { - WorkID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Semester int8 `json:"semester"` - Subject SubjectResp `json:"subject"` +type WorkKindResp struct { + ID int `json:"id"` + Name string `json:"name"` +} + +type WorkResp struct { + WorkID int `json:"id"` + Description string `json:"description"` + Semester int8 `json:"semester"` + Subject SubjectResp `json:"subject"` + Kind WorkKindResp `json:"kind"` } type StWork struct { - WorkID int `json:"id"` - Kind string `json:"kind"` - Description string `json:"description"` - Subject string `json:"subject"` - IsStarted bool `json:"is_started"` + Work *WorkResp `json:"work"` + IsStarted bool `json:"is_started"` } -type StWorks struct { - StudentID int `json:"studentID"` - Works []*StWork `json:"works"` +type StWorkPlenty struct { + Works []*StWork `json:"works"` } type SvWork struct { - WorkID int `json:"id"` - Kind string `json:"kind"` - Description string `json:"description"` - Subject string `json:"subject"` - Head bool `json:"head"` + Work *WorkSv `json:"work"` + Head bool `json:"head"` } type SvWorkPlenty struct { - SupervisorID int `json:"supervisorID"` - Works []*SvWork `json:"works"` + Works []*SvWork `json:"works"` } type WorkSv struct { - SvProfile + *SvProfile Head bool `json:"head"` Full bool `json:"full"` } type WorkSvPlenty struct { - WorkID int `json:"workID"` Supervisors []*WorkSv `json:"supervisors"` } diff --git a/internal/entity/subject.go b/internal/entity/subject.go index 9f8242d..29944fe 100644 --- a/internal/entity/subject.go +++ b/internal/entity/subject.go @@ -1,7 +1,7 @@ package entity type Subject struct { - SubjectID int `db:"subject_id"` - SubjectName string `db:"subject_name"` - DepartmentID string `db:"subject_department_id"` + SubjectID int `db:"subject_id"` + Name string + DepartmentID string `db:"department_id"` } diff --git a/internal/entity/work.go b/internal/entity/work.go index d4c0c5a..c7fc3bc 100644 --- a/internal/entity/work.go +++ b/internal/entity/work.go @@ -1,13 +1,13 @@ package entity type WorkKind struct { - WorkKindID int `db:"work_kind_id"` - WorkKindName string `db:"work_kind_name"` + WorkKindID int `db:"work_kind_id"` + Name string } type Work struct { - *WorkKind - *Subject + *WorkKind `db:"work_kind"` + *Subject `db:"subject"` WorkID int `db:"work_id"` Description string Semester int8 diff --git a/internal/service/bid.go b/internal/service/bid.go index 20ac0a0..8d02d2a 100644 --- a/internal/service/bid.go +++ b/internal/service/bid.go @@ -43,14 +43,17 @@ func (service *Bid) GetStudentBids(studentID int) (*dto.StBids, error) { PhotoUrl: db.PhotoUrl, Department: db.SvProfile.DepartmentID, }, - Work: dto.Work{ + Work: dto.WorkResp{ WorkID: db.WorkID, - Name: db.WorkKind.WorkKindName, Description: db.Work.Description, Semester: db.Work.Semester, + Kind: dto.WorkKindResp{ + ID: db.WorkKind.WorkKindID, + Name: db.WorkKind.Name, + }, Subject: dto.SubjectResp{ SubjectID: db.SubjectID, - Name: db.Subject.SubjectName, + Name: db.Subject.Name, Department: db.Subject.DepartmentID, }, }, @@ -81,14 +84,16 @@ func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { PhotoUrl: db.PhotoUrl, Department: db.StProfile.DepartmentID, }, - Work: dto.Work{ - WorkID: db.WorkID, - Name: db.WorkKind.WorkKindName, + Work: dto.WorkResp{ Description: db.Work.Description, Semester: db.Work.Semester, + Kind: dto.WorkKindResp{ + ID: db.WorkKind.WorkKindID, + Name: db.WorkKind.Name, + }, Subject: dto.SubjectResp{ SubjectID: db.SubjectID, - Name: db.Subject.SubjectName, + Name: db.Subject.Name, Department: db.Subject.DepartmentID, }, }, diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index 48658f7..c94eeee 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -10,6 +10,7 @@ type ( } StudentRepo interface { GetFullStudent(userID int) (*entity.StudentFull, error) + GetStudent(userID int) (*entity.Student, error) } SupervisorRepo interface { GetFullSupervisor(userID int) (*entity.SupervisorFull, error) @@ -27,9 +28,9 @@ type ( UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) } WorkRepo interface { - GetWorksByStudentID(studentID int) ([]*entity.Work, error) - GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) - GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) + GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) + //GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) + //GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) } FeedbackRepo interface { Create(studentID, supervisorID, workID int, content string) (int, error) diff --git a/internal/service/mocks/bid.go b/internal/service/mocks/bid.go index 8c41f73..5d5a349 100644 --- a/internal/service/mocks/bid.go +++ b/internal/service/mocks/bid.go @@ -474,9 +474,9 @@ func (mr *MockIWorkRepoMockRecorder) GetSupervisorsByWorkID(workID interface{}) } // GetWorksByStudentID mocks base method. -func (m *MockIWorkRepo) GetWorksByStudentID(studentID int) ([]*entity.Work, error) { +func (m *MockIWorkRepo) GetStudentWorks(studentID int) ([]*entity.Work, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetWorksByStudentID", studentID) + ret := m.ctrl.Call(m, "GetStudentWorks", studentID) ret0, _ := ret[0].([]*entity.Work) ret1, _ := ret[1].(error) return ret0, ret1 @@ -485,7 +485,7 @@ func (m *MockIWorkRepo) GetWorksByStudentID(studentID int) ([]*entity.Work, erro // GetWorksByStudentID indicates an expected call of GetWorksByStudentID. func (mr *MockIWorkRepoMockRecorder) GetWorksByStudentID(studentID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWorksByStudentID", reflect.TypeOf((*MockIWorkRepo)(nil).GetWorksByStudentID), studentID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentWorks", reflect.TypeOf((*MockIWorkRepo)(nil).GetStudentWorks), studentID) } // GetWorksBySupervisorID mocks base method. @@ -527,10 +527,10 @@ func (m *MockIStudentWorkUC) EXPECT() *MockIStudentWorkUCMockRecorder { } // GetStudentWorks mocks base method. -func (m *MockIStudentWorkUC) GetStudentWorks(studentID int) (*dto.StWorks, error) { +func (m *MockIStudentWorkUC) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStudentWorks", studentID) - ret0, _ := ret[0].(*dto.StWorks) + ret0, _ := ret[0].(*dto.StWorkPlenty) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/internal/service/relation.go b/internal/service/relation.go index 4e8bd0a..dd80524 100644 --- a/internal/service/relation.go +++ b/internal/service/relation.go @@ -57,14 +57,13 @@ func (service *Relation) Create(data *dto.CreateSSR) (*dto.StViewRelation, error PhotoUrl: ssr.PhotoUrl, Department: ssr.DepartmentID, }, - Work: dto.Work{ + Work: dto.WorkResp{ WorkID: ssr.WorkID, - Name: ssr.Work.WorkKindName, Description: ssr.Work.Description, Semester: ssr.Work.Semester, Subject: dto.SubjectResp{ SubjectID: ssr.SubjectID, - Name: ssr.SubjectName, + Name: ssr.Subject.Name, Department: ssr.DepartmentID, }, }, diff --git a/internal/service/repo_pg/work.go b/internal/service/repo_pg/work.go index 8f3a691..9bd001a 100644 --- a/internal/service/repo_pg/work.go +++ b/internal/service/repo_pg/work.go @@ -17,32 +17,23 @@ func NewWork(pg *postgres.Postgres, l logger.Interface) *Work { } } -func (r *Work) GetWorksByStudentID(studentID int) ([]*entity.Work, error) { +func (r *Work) GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) { const query = ` - with const (st_year, st_department_id, curr_month) as ( - select s.year, - s.department_id, - extract('month' from current_date) - from students s - where student_id = $1 - ) - select w.*, - wk.name as work_kind_name, - subj.name as subject_name + select w.work_id, description, semester, + wk.name as "work_kind.name", + subj.name as "subject.name", + subj.department_id as "subject.department_id" from works w join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) - join const c on true - where (((curr_month between 2 and 8) and (semester = st_year * 2)) - or (semester = st_year * 2 - 1)) - and subj.department_id = c.st_department_id; + where subj.department_id = $1 and w.semester = $2; ` var works []*entity.Work - err := r.Conn.Select(&works, query, studentID) + err := r.Conn.Select(&works, query, departmentID, semester) if err != nil { - err := fmt.Errorf("Work->GetWorksByStudentID->r.Conn.Select: %w", err) + err := fmt.Errorf("Work->GetStudentWorks->r.Conn.Select: %w", err) r.l.Error(err) return nil, err } @@ -50,6 +41,39 @@ func (r *Work) GetWorksByStudentID(studentID int) ([]*entity.Work, error) { return works, nil } +//func (r *Work) GetStudentWorks(studentID int) ([]*entity.Work, error) { +// const query = ` +// with const (st_year, st_department_id, curr_month) as ( +// select s.year, +// s.department_id, +// extract('month' from current_date) +// from students s +// where user_id = $1 +// ) +// select w.*, +// wk.name as "work_kind.name", +// subj.name as "subject.name" +// from works w +// join work_kinds wk using (work_kind_id) +// join subjects subj using (subject_id) +// join const c on true +// where (((curr_month between 2 and 8) and (semester = st_year * 2)) +// or (semester = st_year * 2 - 1)) +// and subj.department_id = c.st_department_id; +// ` +// +// var works []*entity.Work +// +// err := r.Conn.Select(&works, query, studentID) +// if err != nil { +// err := fmt.Errorf("Work->GetStudentWorks->r.Conn.Select: %w", err) +// r.l.Error(err) +// return nil, err +// } +// +// return works, nil +//} + func (r *Work) GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) { const query = ` select w.*, diff --git a/internal/service/work.go b/internal/service/work.go index 86d7ca8..ab24243 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -4,24 +4,26 @@ import ( "ssr/internal/dto" "ssr/internal/entity" "ssr/pkg/logger" - "ssr/pkg/misc" + "time" ) type Work struct { *Base - repoWork WorkRepo - repoSsr RelationRepo + workRepo WorkRepo + ssrRepo RelationRepo + stRepo StudentRepo } -func NewWork(rWork WorkRepo, rSsr RelationRepo, l logger.Interface) *Work { +func NewWork(workRepo WorkRepo, ssrRepo RelationRepo, stRepo StudentRepo, l logger.Interface) *Work { return &Work{ Base: NewBase(l), - repoWork: rWork, - repoSsr: rSsr, + workRepo: workRepo, + ssrRepo: ssrRepo, + stRepo: stRepo, } } -func checkIfBegin(relations []*entity.StRelation, workID int) bool { +func (service *Work) checkIfBegin(relations []*entity.StRelation, workID int) bool { for _, rel := range relations { if rel.Work.WorkID == workID { return true @@ -31,85 +33,109 @@ func checkIfBegin(relations []*entity.StRelation, workID int) bool { return false } -func (service *Work) GetStudentWorks(studentID int) (*dto.StWorks, error) { - dbData, err := service.repoWork.GetWorksByStudentID(studentID) - if err != nil { - return nil, err - } - - relations, err := service.repoSsr.GetStudentRelations(studentID) - if err != nil { - return nil, err - } - - var resp []*dto.StWork - - for _, db := range dbData { - resp = append(resp, &dto.StWork{ - WorkID: db.WorkID, - Kind: db.WorkKindName, - Description: db.Description, - Subject: db.SubjectName, - IsStarted: checkIfBegin(relations, db.WorkID), - }) +func (service *Work) recognizeSemester(studentYear int) int { + month := time.Now().Month() + if time.February <= month && month <= time.August { + return studentYear * 2 + } else { + return studentYear*2 - 1 } - - return &dto.StWorks{ - StudentID: studentID, - Works: resp, - }, nil } -func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { - dbData, err := service.repoWork.GetWorksBySupervisorID(supervisorID) +func (service *Work) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { + studentData, err := service.stRepo.GetStudent(studentID) if err != nil { return nil, err } - var resp []*dto.SvWork - - for _, db := range dbData { - resp = append(resp, &dto.SvWork{ - WorkID: db.WorkID, - Kind: db.WorkKindName, - Description: db.Description, - Subject: db.SubjectName, - Head: db.Head, - }) - } - - return &dto.SvWorkPlenty{ - SupervisorID: supervisorID, - Works: resp, - }, nil -} + semester := service.recognizeSemester(studentData.Year) -func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { - dbData, err := service.repoWork.GetSupervisorsByWorkID(workID) + worksData, err := service.workRepo.GetStudentWorks(studentData.DepartmentID, semester) if err != nil { return nil, err } - var resp []*dto.WorkSv + //relationsData, err := service.ssrRepo.GetStudentRelations(studentID) + //if err != nil { + // return nil, err + //} + + var resp []*dto.StWork - for _, db := range dbData { - resp = append(resp, &dto.WorkSv{ - SvProfile: dto.SvProfile{ - Email: db.Email, - FirstName: db.FirstName, - LastName: db.LastName, - About: db.About, - Birthdate: misc.Date{Time: db.Birthdate}, - PhotoUrl: db.PhotoUrl, - Department: db.DepartmentID, + for _, work := range worksData { + resp = append(resp, &dto.StWork{ + Work: &dto.WorkResp{ + WorkID: work.WorkID, + Description: work.Description, + Semester: work.Semester, + Subject: dto.SubjectResp{ + Name: work.Subject.Name, + Department: work.Subject.DepartmentID, + }, + Kind: dto.WorkKindResp{ + Name: work.WorkKind.Name, + }, + //IsStarted: service.checkIfBegin(relations, work.WorkID), TODO }, - Head: db.Head, - Full: db.Full, }) } - return &dto.WorkSvPlenty{ - WorkID: workID, - Supervisors: resp, + return &dto.StWorkPlenty{ + Works: resp, }, nil } + +// +//func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { +// dbData, err := service.workRepo.GetWorksBySupervisorID(supervisorID) +// if err != nil { +// return nil, err +// } +// +// var resp []*dto.SvWork +// +// for _, db := range dbData { +// resp = append(resp, &dto.SvWork{ +// WorkID: db.WorkID, +// Kind: db.WorkKindName, +// Description: db.Description, +// Subject: db.SubjectName, +// Head: db.Head, +// }) +// } +// +// return &dto.SvWorkPlenty{ +// SupervisorID: supervisorID, +// Works: resp, +// }, nil +//} +// +//func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { +// dbData, err := service.workRepo.GetSupervisorsByWorkID(workID) +// if err != nil { +// return nil, err +// } +// +// var resp []*dto.WorkSv +// +// for _, db := range dbData { +// resp = append(resp, &dto.WorkSv{ +// SvProfile: dto.SvProfile{ +// Email: db.Email, +// FirstName: db.FirstName, +// LastName: db.LastName, +// About: db.About, +// Birthdate: misc.Date{Time: db.Birthdate}, +// PhotoUrl: db.PhotoUrl, +// Department: db.DepartmentID, +// }, +// Head: db.Head, +// Full: db.Full, +// }) +// } +// +// return &dto.WorkSvPlenty{ +// WorkID: workID, +// Supervisors: resp, +// }, nil +//} diff --git a/migrations/20220509115124_create_students.up.sql b/migrations/20220509115124_create_students.up.sql index 7285e86..438a2d8 100644 --- a/migrations/20220509115124_create_students.up.sql +++ b/migrations/20220509115124_create_students.up.sql @@ -12,6 +12,6 @@ ALTER TABLE "students" insert into "students" (user_id, student_card, year, department_id) -VALUES (1, 'ida19u463', 3, 'ИУ7'), - (5, 'bma19u463', 3, 'ИУ7'), - (6, 'vdv19u463', 3, 'ИУ7'); +VALUES (1, 'ida19u463', 4, 'ИУ7'), + (5, 'bma19u463', 4, 'ИУ7'), + (6, 'vdv19u463', 4, 'ИУ7'); diff --git a/migrations/20220509193416_create_subjects.up.sql b/migrations/20220509193416_create_subjects.up.sql index 79c46d2..e682483 100644 --- a/migrations/20220509193416_create_subjects.up.sql +++ b/migrations/20220509193416_create_subjects.up.sql @@ -1,7 +1,7 @@ CREATE TABLE "subjects" ( "subject_id" bigint unique generated always as identity, - "title" varchar primary key, + "name" varchar primary key, "department_id" varchar not null ); @@ -9,7 +9,7 @@ CREATE TABLE "subjects" ALTER TABLE "subjects" ADD FOREIGN KEY ("department_id") REFERENCES "departments" ("department_id"); -insert into subjects (title, department_id) +insert into subjects (name, department_id) VALUES ('Операционные системы', 'ИУ7'), - ('Компьютерная графика', 'ИУ7'); + ('НИР', 'ИУ7'); diff --git a/migrations/20220509194216_create_works.up.sql b/migrations/20220509194216_create_works.up.sql index 42f0bd8..718ffba 100644 --- a/migrations/20220509194216_create_works.up.sql +++ b/migrations/20220509194216_create_works.up.sql @@ -1,7 +1,7 @@ CREATE TABLE "work_kinds" ( "work_kind_id" bigint unique generated always as identity, - "title" varchar unique not null + "name" varchar unique not null ); CREATE TABLE "works" @@ -18,10 +18,10 @@ ALTER TABLE "works" ADD FOREIGN KEY ("work_kind_id") REFERENCES "work_kinds" ("work_kind_id"); -insert into "work_kinds" (title) +insert into "work_kinds" (name) VALUES ('Курсовая работа'), ('Научно-исследовательская работа'); insert into "works" (work_kind_id, description, semester, subject_id) -VALUES (1, 'Только для истинных профессионалов', 6, 1), - (2, 'Брезенхем за 20 минту', 6, 2); \ No newline at end of file +VALUES (1, 'Только для истинных профессионалов', 7, 1), + (2, 'Готовься к ВКР', 7, 2); \ No newline at end of file From 12e08069d43793b14ecec8323f0be722748abc82 Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Sun, 2 Oct 2022 15:40:07 +0300 Subject: [PATCH 04/12] upgrade: swagger works --- cmd/app/main.go | 5 +- internal/app/app.go | 22 +- internal/controller/http/middlewares/auth.go | 20 +- internal/controller/http/router.go | 14 +- internal/controller/http/student.go | 281 ++++---- internal/controller/http/supervisor.go | 64 +- internal/dto/auth.go | 7 +- internal/dto/subject.go | 2 +- internal/dto/work.go | 19 +- internal/entity/work.go | 3 +- internal/service/auth.go | 15 +- internal/service/bid_test.go | 303 --------- internal/service/interfaces.go | 2 +- internal/service/mocks/bid.go | 595 ----------------- internal/service/repo_pg/work.go | 56 +- internal/service/work.go | 64 +- swagger/docs.go | 658 ++----------------- swagger/swagger.json | 658 ++----------------- swagger/swagger.yaml | 437 +----------- 19 files changed, 388 insertions(+), 2837 deletions(-) delete mode 100644 internal/service/bid_test.go delete mode 100644 internal/service/mocks/bid.go diff --git a/cmd/app/main.go b/cmd/app/main.go index a0a020f..c30519a 100644 --- a/cmd/app/main.go +++ b/cmd/app/main.go @@ -18,9 +18,8 @@ import ( // @BasePath / // @schemes http -// @securitydefinitions.apikey Auth -// @in header -// @name Authorization +// @securitydefinitions.oauth2.password OAuth2Password +// @tokenUrl http://localhost:8080/api/v1/auth/login func main() { cfg, err := config.NewConfig() if err != nil { diff --git a/internal/app/app.go b/internal/app/app.go index 820e577..3afcc1b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -5,34 +5,19 @@ import ( "fmt" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" - echoSwagger "github.com/swaggo/echo-swagger" "net/http" "ssr/config" ctrl "ssr/internal/controller/http" "ssr/internal/service" "ssr/internal/service/repo_pg" "ssr/pkg/logger" - "ssr/pkg/misc" "ssr/pkg/postgres" - _ "ssr/swagger" - "strings" ) -func setupMiddlewares(server *echo.Echo, cfg *config.Config) { +func setupMiddlewares(server *echo.Echo) { server.Use(middleware.CORS()) server.Use(middleware.Logger()) server.Use(middleware.Recover()) - server.Use(middleware.JWTWithConfig(middleware.JWTConfig{ - Claims: &misc.AppJWTClaims{}, - SigningKey: []byte(cfg.SigningKey), - ContextKey: "ctx", - Skipper: func(c echo.Context) bool { - // Skip middleware if 'login' or 'swagger' - path := c.Request().URL.Path - split := strings.Split(path, "/") - return split[2] == "auth" || split[1] == "swagger" - }, - })) } func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, cfg *config.Config) { @@ -54,11 +39,13 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, ctrl.NewRouter( server, l, + cfg, authService, profileService, profileService, bidService, workService, + workService, relationService, feedbackService, ) @@ -75,10 +62,9 @@ func Run(cfg *config.Config) { defer pg.Close() server := echo.New() - setupMiddlewares(server, cfg) + setupMiddlewares(server) makeInjections(server, pg, loggerObject, cfg) - server.GET("/swagger*", echoSwagger.WrapHandler) if err := server.Start(cfg.HTTP.Port); err != http.ErrServerClosed { server.Logger.Fatal(err) } diff --git a/internal/controller/http/middlewares/auth.go b/internal/controller/http/middlewares/auth.go index f52b930..a0dc950 100644 --- a/internal/controller/http/middlewares/auth.go +++ b/internal/controller/http/middlewares/auth.go @@ -2,6 +2,8 @@ package middlewares import ( "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" + "ssr/config" "ssr/pkg/misc" "strings" ) @@ -10,11 +12,15 @@ func CheckRole(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { split := strings.Split(c.Request().URL.Path, "/") - // /api//... -> ["", "api", "" , ...] - expRole := split[2] + // /api//... -> ["", "api", "vNo", "" , ...] + + if len(split) < 4 { + return echo.ErrForbidden + } + expRole := split[3] _, recRole := misc.ExtractCtx(c) - mapping := map[string]string{"st": "student", "sv": "supervisor"} + mapping := map[string]string{"st": "students", "sv": "supervisors"} if mapping[recRole] != expRole { return echo.ErrForbidden @@ -27,3 +33,11 @@ func CheckRole(next echo.HandlerFunc) echo.HandlerFunc { return nil } } + +func MakeAuthMiddleware(config *config.Config) echo.MiddlewareFunc { + return middleware.JWTWithConfig(middleware.JWTConfig{ + Claims: &misc.AppJWTClaims{}, + SigningKey: []byte(config.SigningKey), + ContextKey: "ctx", + }) +} diff --git a/internal/controller/http/router.go b/internal/controller/http/router.go index 33bfd0a..28b883b 100644 --- a/internal/controller/http/router.go +++ b/internal/controller/http/router.go @@ -2,25 +2,31 @@ package http import ( "github.com/labstack/echo/v4" + echoSwagger "github.com/swaggo/echo-swagger" + "ssr/config" "ssr/pkg/logger" + _ "ssr/swagger" ) func NewRouter( - echo *echo.Echo, + server *echo.Echo, l logger.Interface, + config *config.Config, auth AuthService, stProfile StProfileService, svProfile SvProfileService, stBids StBidService, stWorks StWorkService, + svWorks SvWorkService, stRelations StRelationService, feedback FeedbackService, ) { - g := echo.Group("/api") + g := server.Group("/api/v1") + g.GET("/swagger/*", echoSwagger.WrapHandler) { NewAuthRoutes(g, l, auth) - NewStudentRoutes(g, l, stProfile, stBids, stWorks, stRelations, feedback) - NewSupervisorRoutes(g, l, svProfile) + NewStudentRoutes(g, l, config, stProfile, stBids, stWorks, stRelations, feedback) + NewSupervisorRoutes(g, l, config, svProfile, svWorks) } } diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index 49e78c8..256d166 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -1,13 +1,11 @@ package http import ( - "fmt" "github.com/labstack/echo/v4" "net/http" + "ssr/config" "ssr/internal/controller/http/middlewares" - "ssr/internal/dto" "ssr/pkg/logger" - "ssr/pkg/misc" "strconv" ) @@ -21,18 +19,18 @@ type student struct { } // ShowAccount godoc -// @Summary GetUserByEmail student's profile +// @Summary Get student's profile // @Tags student // @Produce json +// @Param student_id path int true "Student ID" // @Success 200 {object} dto.StProfile // @Failure 404 -// @Router /api/student/profile [get] -// @Security Auth +// @Router /api/v1/students/{student_id}/profile [get] +// @Security OAuth2Password func (ctrl *student) getProfile(ctx echo.Context) error { - rawUserID, _ := misc.ExtractCtx(ctx) - userID, _ := strconv.Atoi(rawUserID) + studentID, _ := strconv.Atoi(ctx.Param("student_id")) - profileDTO, err := ctrl.profileService.GetStudentProfile(userID) + profileDTO, err := ctrl.profileService.GetStudentProfile(studentID) if err != nil { return echo.ErrNotFound } @@ -40,42 +38,36 @@ func (ctrl *student) getProfile(ctx echo.Context) error { return ctx.JSON(http.StatusOK, profileDTO) } -// ShowAccount godoc -// @Summary GetUserByEmail student's bids -// @Tags student -// @Produce json -// @Param student_id query int true "Student ID" -// @Success 200 {object} dto.StBids -// @Failure 404 -// @Router /api/student/bid [get] -// @Security Auth -func (ctrl *student) getBids(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - studentID, _ := strconv.Atoi(ctx.QueryParam("student_id")) - - respDTO, err := ctrl.bidService.GetStudentBids(studentID) - if err != nil { - return echo.ErrNotFound - } - - return ctx.JSON(http.StatusOK, respDTO) -} +//// ShowAccount godoc +//// @Summary GetUserByEmail student's bids +//// @Tags student +//// @Produce json +//// @Param student_id path int true "Student ID" +//// @Success 200 {object} dto.StBids +//// @Failure 404 +//// @Router /api/students/{student_id}/bids [get] +//// @Security Authorization +//func (ctrl *student) getBids(ctx echo.Context) error { +// studentID, _ := strconv.Atoi(ctx.Param("student_id")) +// +// respDTO, err := ctrl.bidService.GetStudentBids(studentID) +// if err != nil { +// return echo.ErrNotFound +// } +// +// return ctx.JSON(http.StatusOK, respDTO) +//} // ShowAccount godoc -// @Summary GetUserByEmail student's works +// @Summary Get student's works // @Tags student -// @Param student_id query int true "Student ID" +// @Param student_id path int true "Student ID" // @Produce json // @Success 200 {object} dto.StWorkPlenty -// @Router /api/student/work [get] -// @Security Auth +// @Router /api/v1/students/{student_id}/works [get] +// @Security OAuth2Password func (ctrl *student) getWorks(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - studentID, _ := strconv.Atoi(ctx.QueryParam("student_id")) + studentID, _ := strconv.Atoi(ctx.Param("student_id")) respDTO, err := ctrl.workService.GetStudentWorks(studentID) if err != nil { @@ -107,110 +99,111 @@ func (ctrl *student) getWorks(ctx echo.Context) error { // return ctx.JSON(http.StatusOK, respDTO) //} -// ShowAccount godoc -// @Summary Apply bid -// @Tags student -// @Accept json -// @Param ApplyBid body dto.ApplyBid true "bid info" -// @Produce json -// @Success 200 {object} dto.ApplyBidResp -// @Router /api/student/bid [put] -// @Security Auth -func (ctrl *student) applyBid(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - reqDTO := &dto.ApplyBid{} - if err := ctx.Bind(reqDTO); err != nil { - return echo.ErrBadRequest - } - - respDTO, err := ctrl.bidService.Apply(reqDTO) - if err != nil { - return echo.ErrInternalServerError - } - - return ctx.JSON(http.StatusCreated, respDTO) -} - -// ShowAccount godoc -// @Summary Start SSR -// @Tags student -// @Accept json -// @Param ApplyBid body dto.CreateSSR true "ssr info" -// @Produce json -// @Success 200 {object} dto.StViewRelation -// @Router /api/student/ssr [post] -// @Security Auth -func (ctrl *student) createSSR(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - reqDTO := &dto.CreateSSR{} - if err := ctx.Bind(reqDTO); err != nil { - return echo.ErrBadRequest - } - - respDTO, err := ctrl.relationService.Create(reqDTO) - if err != nil { - return echo.ErrInternalServerError - } - - return ctx.JSON(http.StatusCreated, respDTO) -} - -// ShowAccount godoc -// @Summary Provide a feedback -// @Tags student -// @Accept json -// @Param Feedback body dto.FeedbackReq true "feedback info" -// @Produce json -// @Success 201 {object} dto.FeedbackAddResp -// @Failure 500 -// @Router /api/student/feedback [put] -// @Security Auth -func (ctrl *student) provideFeedback(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) - - reqDTO := &dto.FeedbackReq{} - if err := ctx.Bind(reqDTO); err != nil { - return echo.ErrBadRequest - } - - id, err := ctrl.feedbackService.Add(reqDTO) - if err != nil { - return echo.NewHTTPError(http.StatusConflict) - } - - return ctx.JSON(http.StatusCreated, dto.FeedbackAddResp{FeedbackID: id}) -} - -// ShowAccount godoc -// @Summary Get feedbacks on the supervisor. -// @Tags student -// @Param supervisor_id path integer true "Supervisor ID" -// @Produce json -// @Success 200 {object} dto.FeedbackPlenty -// @Router /api/student/feedback [get] -// @Security Auth -func (ctrl *student) getFeedback(ctx echo.Context) error { - email, _ := misc.ExtractCtx(ctx) - ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +//// ShowAccount godoc +//// @Summary Apply bid +//// @Tags student +//// @Accept json +//// @Param ApplyBid body dto.ApplyBid true "bid info" +//// @Produce json +//// @Success 200 {object} dto.ApplyBidResp +//// @Router /api/student/bid [put] +//// @Security Auth +//func (ctrl *student) applyBid(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// reqDTO := &dto.ApplyBid{} +// if err := ctx.Bind(reqDTO); err != nil { +// return echo.ErrBadRequest +// } +// +// respDTO, err := ctrl.bidService.Apply(reqDTO) +// if err != nil { +// return echo.ErrInternalServerError +// } +// +// return ctx.JSON(http.StatusCreated, respDTO) +//} - supervisorID, _ := strconv.Atoi(ctx.Param("supervisor_id")) +//// ShowAccount godoc +//// @Summary Start SSR +//// @Tags student +//// @Accept json +//// @Param ApplyBid body dto.CreateSSR true "ssr info" +//// @Produce json +//// @Success 200 {object} dto.StViewRelation +//// @Router /api/student/ssr [post] +//// @Security Auth +//func (ctrl *student) createSSR(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// reqDTO := &dto.CreateSSR{} +// if err := ctx.Bind(reqDTO); err != nil { +// return echo.ErrBadRequest +// } +// +// respDTO, err := ctrl.relationService.Create(reqDTO) +// if err != nil { +// return echo.ErrInternalServerError +// } +// +// return ctx.JSON(http.StatusCreated, respDTO) +//} - respDTO, err := ctrl.feedbackService.GetOnSupervisor(supervisorID) - if err != nil { - return echo.ErrInternalServerError - } +//// ShowAccount godoc +//// @Summary Provide a feedback +//// @Tags student +//// @Accept json +//// @Param Feedback body dto.FeedbackReq true "feedback info" +//// @Produce json +//// @Success 201 {object} dto.FeedbackAddResp +//// @Failure 500 +//// @Router /api/student/feedback [put] +//// @Security Authorization +//func (ctrl *student) provideFeedback(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// reqDTO := &dto.FeedbackReq{} +// if err := ctx.Bind(reqDTO); err != nil { +// return echo.ErrBadRequest +// } +// +// id, err := ctrl.feedbackService.Add(reqDTO) +// if err != nil { +// return echo.NewHTTPError(http.StatusConflict) +// } +// +// return ctx.JSON(http.StatusCreated, dto.FeedbackAddResp{FeedbackID: id}) +//} - return ctx.JSON(http.StatusOK, respDTO) -} +//// ShowAccount godoc +//// @Summary Get feedbacks on the supervisor. +//// @Tags student +//// @Param supervisor_id path integer true "Supervisor ID" +//// @Produce json +//// @Success 200 {object} dto.FeedbackPlenty +//// @Router /api/student/feedback [get] +//// @Security Auth +//func (ctrl *student) getFeedback(ctx echo.Context) error { +// email, _ := misc.ExtractCtx(ctx) +// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) +// +// supervisorID, _ := strconv.Atoi(ctx.Param("supervisor_id")) +// +// respDTO, err := ctrl.feedbackService.GetOnSupervisor(supervisorID) +// if err != nil { +// return echo.ErrInternalServerError +// } +// +// return ctx.JSON(http.StatusOK, respDTO) +//} func NewStudentRoutes( router *echo.Group, l logger.Interface, + config *config.Config, profileService StProfileService, bidsService StBidService, worksService StWorkService, @@ -226,17 +219,17 @@ func NewStudentRoutes( feedbackService, } - student := router.Group("/student", middlewares.CheckRole) + student := router.Group("/students", middlewares.MakeAuthMiddleware(config), middlewares.CheckRole) { - student.GET("/profile", ctrl.getProfile) - student.GET("/bid", ctrl.getBids) - student.PUT("/bid", ctrl.applyBid) - student.POST("/ssr", ctrl.createSSR) - student.GET("/work", ctrl.getWorks) + student.GET("/:student_id/profile", ctrl.getProfile) + student.GET("/:student_id/works", ctrl.getWorks) + //student.GET("/bid", ctrl.getBids) + //student.PUT("/bid", ctrl.applyBid) + //student.POST("/ssr", ctrl.createSSR) //student.GET("/work/supervisor_id", ctrl.getSupervisorsOfWork) - student.GET("/feedback/:supervisor_id", ctrl.getFeedback) - student.PUT("/feedback", ctrl.provideFeedback) + //student.GET("/feedback/:supervisor_id", ctrl.getFeedback) + //student.PUT("/feedback", ctrl.provideFeedback) } } diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index a64341d..006b5c4 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -3,9 +3,9 @@ package http import ( "github.com/labstack/echo/v4" "net/http" + "ssr/config" "ssr/internal/controller/http/middlewares" "ssr/pkg/logger" - "ssr/pkg/misc" "strconv" ) @@ -13,20 +13,21 @@ type supervisor struct { l logger.Interface profileService SvProfileService //bidService SvBidService - //workService SvWorkService + workService SvWorkService } // ShowAccount godoc -// @Summary GetUserByEmail supervisor's profile +// @Summary Get supervisor's profile // @Tags supervisor // @Produce json +// @Param supervisor_id path int true "Supervisor ID" // @Success 200 {object} dto.SvProfile -// @Router /api/supervisor/profile [get] -// @Security Auth +// @Router /api/v1/supervisors/{supervisor_id}/profile [get] +// @Security OAuth2Password func (ctrl *supervisor) getProfile(ctx echo.Context) error { - rawUserID, _ := misc.ExtractCtx(ctx) - userID, _ := strconv.Atoi(rawUserID) - respDTO, err := ctrl.profileService.GetSupervisorProfile(userID) + supervisorID, _ := strconv.Atoi(ctx.Param("student_id")) + + respDTO, err := ctrl.profileService.GetSupervisorProfile(supervisorID) if err != nil { ctrl.l.Error(err) return echo.NewHTTPError(http.StatusInternalServerError, "TODO") @@ -36,29 +37,25 @@ func (ctrl *supervisor) getProfile(ctx echo.Context) error { } // // ShowAccount godoc -// // @Summary GetUserByEmail supervisor's works +// // @Summary Get supervisor's works // // @Tags supervisor -// // @Param supervisor_id query int true "Supervisor ID" +// // @Param supervisor_id path int true "Supervisor ID" // // @Produce json // // @Success 200 {object} dto.SvWorkPlenty -// // @Router /api/supervisor/work [get] -// // @Security Auth -// -// func (ctrl *supervisor) getWorks(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) -// -// respDTO, err := ctrl.workService.GetSupervisorWorks(supervisorID) -// if err != nil { -// ctrl.l.Error(err) -// return echo.NewHTTPError(http.StatusInternalServerError, "TODO") -// } -// -// return ctx.JSON(http.StatusOK, respDTO) -// } -// +// // @Router /api/v1/supervisors/{supervisor_id}/work [get] +// // @Security OAuth2Password +func (ctrl *supervisor) getWorks(ctx echo.Context) error { + supervisorID, _ := strconv.Atoi(ctx.Param("student_id")) + + respDTO, err := ctrl.workService.GetSupervisorWorks(supervisorID) + if err != nil { + ctrl.l.Error(err) + return echo.NewHTTPError(http.StatusInternalServerError, "TODO") + } + + return ctx.JSON(http.StatusOK, respDTO) +} + // // ShowAccount godoc // // @Summary GetUserByEmail supervisor's bids // // @Tags supervisor @@ -119,20 +116,21 @@ func (ctrl *supervisor) getProfile(ctx echo.Context) error { func NewSupervisorRoutes( router *echo.Group, l logger.Interface, + config *config.Config, profileService SvProfileService, // bidService SvBidService, - // workService SvWorkService, + workService SvWorkService, ) { - ctrl := &supervisor{l, profileService} + ctrl := &supervisor{l, profileService, workService} - g := router.Group("/supervisor", middlewares.CheckRole) + g := router.Group("/supervisors", middlewares.MakeAuthMiddleware(config), middlewares.CheckRole) { - g.GET("/profile", ctrl.getProfile) + g.GET("/supervisor_id/profile", ctrl.getProfile) + g.GET("/supervisor_id/works", ctrl.getWorks) //g.GET("/bid", ctrl.getBids) //g.POST("/bid/resolve", ctrl.resolveBid) //g.GET("/work", ctrl.getWorks) - //g.GET("/work", ctrl.getWorks) } } diff --git a/internal/dto/auth.go b/internal/dto/auth.go index dd03faf..df6d6e7 100644 --- a/internal/dto/auth.go +++ b/internal/dto/auth.go @@ -1,7 +1,8 @@ package dto type LoginResponse struct { - Token string `json:"token"` - UserID int `json:"user-id"` - Role string `json:"role"` + Token string `json:"access_token"` + TokenType string `json:"token_type"` + UserID int `json:"user_id"` + Role string `json:"role"` } diff --git a/internal/dto/subject.go b/internal/dto/subject.go index d3aa69d..c922bba 100644 --- a/internal/dto/subject.go +++ b/internal/dto/subject.go @@ -1,7 +1,7 @@ package dto type SubjectResp struct { - SubjectID int `json:"subjectID"` + SubjectID int `json:"id"` Name string `json:"name"` Department string `json:"department"` } diff --git a/internal/dto/work.go b/internal/dto/work.go index 4f28e51..e893e41 100644 --- a/internal/dto/work.go +++ b/internal/dto/work.go @@ -13,26 +13,27 @@ type WorkResp struct { Kind WorkKindResp `json:"kind"` } -type StWork struct { - Work *WorkResp `json:"work"` - IsStarted bool `json:"is_started"` +type StWorkResp struct { + Work WorkResp `json:"work"` + IsStarted bool `json:"is_started"` } type StWorkPlenty struct { - Works []*StWork `json:"works"` + Works []*StWorkResp `json:"works"` } -type SvWork struct { - Work *WorkSv `json:"work"` - Head bool `json:"head"` +type SvWorkResp struct { + Work WorkResp `json:"work"` + IsHead bool `json:"is_head"` + IsFull bool `json:"is_full"` } type SvWorkPlenty struct { - Works []*SvWork `json:"works"` + Works []*SvWorkResp `json:"works"` } type WorkSv struct { - *SvProfile + SvProfile Head bool `json:"head"` Full bool `json:"full"` } diff --git a/internal/entity/work.go b/internal/entity/work.go index c7fc3bc..4f53ddf 100644 --- a/internal/entity/work.go +++ b/internal/entity/work.go @@ -15,7 +15,8 @@ type Work struct { type SvWork struct { *Work - Head bool `db:"head"` + IsHead bool `db:"is_head"` + IsFull bool `db:"is_full"` } type WorkSv struct { diff --git a/internal/service/auth.go b/internal/service/auth.go index ffb8edd..8b36f37 100644 --- a/internal/service/auth.go +++ b/internal/service/auth.go @@ -9,15 +9,15 @@ import ( "time" ) -type auth struct { +type Auth struct { *Base repo UserRepo tokenExp time.Duration signingKey []byte } -func NewAuth(r UserRepo, l logger.Interface, tokenExpMinutes int, signingKey []byte) *auth { - return &auth{ +func NewAuth(r UserRepo, l logger.Interface, tokenExpMinutes int, signingKey []byte) *Auth { + return &Auth{ Base: NewBase(l), repo: r, tokenExp: time.Duration(tokenExpMinutes) * time.Minute, @@ -25,7 +25,7 @@ func NewAuth(r UserRepo, l logger.Interface, tokenExpMinutes int, signingKey []b } } -func (service *auth) Login(email, password string) (*dto.LoginResponse, error) { +func (service *Auth) Login(email, password string) (*dto.LoginResponse, error) { dbData, err := service.repo.GetUserByEmail(email) if err != nil { return nil, err @@ -46,8 +46,9 @@ func (service *auth) Login(email, password string) (*dto.LoginResponse, error) { } return &dto.LoginResponse{ - Token: tokenStr, - UserID: dbData.UserID, - Role: string(dbData.Role), + Token: tokenStr, + TokenType: "Bearer", + UserID: dbData.UserID, + Role: string(dbData.Role), }, nil } diff --git a/internal/service/bid_test.go b/internal/service/bid_test.go deleted file mode 100644 index 88c0c06..0000000 --- a/internal/service/bid_test.go +++ /dev/null @@ -1,303 +0,0 @@ -package service - -// -//import ( -// "database/sql" -// "github.com/golang/mock/gomock" -// "reflect" -// "ssr/internal/dto" -// "ssr/internal/entity" -// "ssr/internal/usecase/mocks" -// "ssr/pkg/misc" -// "testing" -// "time" -//) -// -//func TestBidUseCase_Apply(t *testing.T) { -// type args struct { -// bid *dto.ApplyBid -// } -// tests := []struct { -// name string -// repository func(ctrl *gomock.Controller) *mocks.MockIRelRepo -// args args -// want *dto.ApplyBidResponse -// wantErr bool -// }{ -// { -// name: "success apply", -// repository: func(ctrl *gomock.Controller) *mocks.MockIRelRepo { -// m := mocks.NewMockIRelRepo(ctrl) -// m.EXPECT().Create(1, 1, 1).Return(1, nil) -// -// return m -// }, -// args: args{ -// bid: &dto.ApplyBid{ -// StudentID: 1, -// SupervisorID: 1, -// WorkID: 1, -// }, -// }, -// want: &dto.ApplyBidResponse{BidID: 1}, -// wantErr: false, -// }, -// } -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// ctrl := gomock.NewController(t) -// -// u := NewBid(tt.repository(ctrl)) -// -// received, err := u.Apply(tt.args.bid) -// -// if (err != nil) != tt.wantErr { -// t.Errorf("Bid() error = %v, wantErr %v", err, tt.wantErr) -// return -// } -// if !reflect.DeepEqual(received, tt.want) { -// t.Errorf("Bid() got = %v, want %v", received, tt.want) -// } -// }) -// } -//} -// -//func TestBidUseCase_Resolve(t *testing.T) { -// type args struct { -// bid *dto.ResolveBid -// } -// tests := []struct { -// name string -// repository func(ctrl *gomock.Controller) *mocks.MockIRelRepo -// args args -// wantErr bool -// }{ -// { -// name: "accept success", -// repository: func(ctrl *gomock.Controller) *mocks.MockIRelRepo { -// m := mocks.NewMockIRelRepo(ctrl) -// m.EXPECT().UpdateStatus(1, entity.StatusSSR("accepted")).Return(1, nil) -// -// return m -// }, -// args: args{ -// bid: &dto.ResolveBid{ -// SupervisorID: 1, -// BidID: 1, -// Accept: true, -// }, -// }, -// wantErr: false, -// }, -// { -// name: "reject success", -// repository: func(ctrl *gomock.Controller) *mocks.MockIRelRepo { -// m := mocks.NewMockIRelRepo(ctrl) -// m.EXPECT().UpdateStatus(1, entity.StatusSSR("rejected")).Return(1, nil) -// -// return m -// }, -// args: args{ -// bid: &dto.ResolveBid{ -// SupervisorID: 1, -// BidID: 1, -// Accept: false, -// }, -// }, -// wantErr: false, -// }, -// } -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// ctrl := gomock.NewController(t) -// -// u := NewBid(tt.repository(ctrl)) -// -// err := u.Resolve(tt.args.bid) -// -// if (err != nil) != tt.wantErr { -// t.Errorf("Bid() error = %v, wantErr %v", err, tt.wantErr) -// return -// } -// }) -// } -//} -// -//func TestSSRUseCase_Create(t *testing.T) { -// type args struct { -// req *dto.CreateSSR -// } -// tests := []struct { -// name string -// repository func(ctrl *gomock.Controller) *mocks.MockIRelRepo -// args args -// want *dto.StudentViewSSR -// wantErr bool -// }{ -// { -// name: "success ssr create", -// repository: func(ctrl *gomock.Controller) *mocks.MockIRelRepo { -// m := mocks.NewMockIRelRepo(ctrl) -// m.EXPECT().UpdateStatus(1, entity.StatusSSR("wip")).Return(1, nil) -// m.EXPECT().GetStudentViewSSR(1, 1).Return(&entity.StudentSsr{ -// BidID: 1, -// CreatedAt: time.Time{}, -// Status: "wip", -// SvProfile: &entity.SvProfile{ -// User: &entity.User{ -// UserID: 2, -// Email: "kek@kek.com", -// FirstName: "Иван", -// LastName: "Иванов", -// PhotoUrl: sql.NullString{}, -// }, -// SupervisorID: 1, -// Birthdate: time.Time{}, -// About: "Обо мне", -// DepartmentID: "ИУ7", -// }, -// Work: &entity.Work{ -// WorkKind: &entity.WorkKind{ -// WorkKindID: 1, -// WorkKindName: "Курсовая работа", -// }, -// Subject: &entity.Subject{ -// SubjectID: 1, -// SubjectName: "Операционные системы", -// DepartmentID: "ИУ7", -// }, -// WorkID: 1, -// Description: "Работа для профи!", -// Semester: 7, -// }, -// }, nil) -// -// return m -// }, -// args: args{ -// req: &dto.CreateSSR{ -// StudentID: 1, -// BidID: 1, -// }, -// }, -// want: &dto.StudentViewSSR{ -// RelID: 1, -// Status: "wip", -// CreatedAt: time.Time{}, -// Supervisor: dto.SvProfile{ -// SupervisorID: 1, -// Email: "kek@kek.com", -// FirstName: "Иван", -// LastName: "Иванов", -// About: "Обо мне", -// Birthdate: misc.Date{}, -// PhotoUrl: misc.NullString{}, -// Department: "ИУ7", -// }, -// Work: dto.Work{ -// WorkID: 1, -// Name: "Курсовая работа", -// Description: "Работа для профи!", -// Semester: 7, -// Subject: dto.SubjectResp{ -// SubjectID: 1, -// Name: "Операционные системы", -// Department: "ИУ7", -// }, -// }, -// }, -// wantErr: false, -// }, -// { -// name: "success ssr create", -// repository: func(ctrl *gomock.Controller) *mocks.MockIRelRepo { -// m := mocks.NewMockIRelRepo(ctrl) -// m.EXPECT().UpdateStatus(1, entity.StatusSSR("wip")).Return(1, nil) -// m.EXPECT().GetStudentViewSSR(1, 1).Return(&entity.StudentSsr{ -// BidID: 1, -// CreatedAt: time.Time{}, -// Status: "wip", -// SvProfile: &entity.SvProfile{ -// User: &entity.User{ -// UserID: 2, -// Email: "kek@kek.com", -// FirstName: "Иван", -// LastName: "Иванов", -// PhotoUrl: sql.NullString{}, -// }, -// SupervisorID: 1, -// Birthdate: time.Time{}, -// About: "Обо мне", -// DepartmentID: "ИУ7", -// }, -// Work: &entity.Work{ -// WorkKind: &entity.WorkKind{ -// WorkKindID: 1, -// WorkKindName: "Курсовая работа", -// }, -// Subject: &entity.Subject{ -// SubjectID: 1, -// SubjectName: "Операционные системы", -// DepartmentID: "ИУ7", -// }, -// WorkID: 1, -// Description: "Работа для профи!", -// Semester: 7, -// }, -// }, nil) -// -// return m -// }, -// args: args{ -// req: &dto.CreateSSR{ -// StudentID: 1, -// BidID: 1, -// }, -// }, -// want: &dto.StudentViewSSR{ -// RelID: 1, -// Status: "wip", -// CreatedAt: time.Time{}, -// Supervisor: dto.SvProfile{ -// SupervisorID: 1, -// Email: "kek@kek.com", -// FirstName: "Иван", -// LastName: "Иванов", -// About: "Обо мне", -// Birthdate: misc.Date{}, -// PhotoUrl: misc.NullString{}, -// Department: "ИУ7", -// }, -// Work: dto.Work{ -// WorkID: 1, -// Name: "Курсовая работа", -// Description: "Работа для профи!", -// Semester: 7, -// Subject: dto.SubjectResp{ -// SubjectID: 1, -// Name: "Операционные системы", -// Department: "ИУ7", -// }, -// }, -// }, -// wantErr: false, -// }, -// } -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// ctrl := gomock.NewController(t) -// -// u := NewRelation(tt.repository(ctrl)) -// -// received, err := u.Create(tt.args.req) -// -// if (err != nil) != tt.wantErr { -// t.Errorf("Bid() error = %v, wantErr %v", err, tt.wantErr) -// return -// } -// if !reflect.DeepEqual(received, tt.want) { -// t.Errorf("Bid() got = %v, want %v", received, tt.want) -// } -// }) -// } -//} diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index c94eeee..9d57f14 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -29,7 +29,7 @@ type ( } WorkRepo interface { GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) - //GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) + GetSupervisorWorks(supervisorID int) ([]*entity.SvWork, error) //GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) } FeedbackRepo interface { diff --git a/internal/service/mocks/bid.go b/internal/service/mocks/bid.go deleted file mode 100644 index 5d5a349..0000000 --- a/internal/service/mocks/bid.go +++ /dev/null @@ -1,595 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: internal/usecase/interfaces.go - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - dto "ssr/internal/dto" - entity "ssr/internal/entity" - - gomock "github.com/golang/mock/gomock" -) - -// MockIAuthRepo is a mock of IAuthRepo interface. -type MockIAuthRepo struct { - ctrl *gomock.Controller - recorder *MockIAuthRepoMockRecorder -} - -// MockIAuthRepoMockRecorder is the mock recorder for MockIAuthRepo. -type MockIAuthRepoMockRecorder struct { - mock *MockIAuthRepo -} - -// NewMockIAuthRepo creates a new mock instance. -func NewMockIAuthRepo(ctrl *gomock.Controller) *MockIAuthRepo { - mock := &MockIAuthRepo{ctrl: ctrl} - mock.recorder = &MockIAuthRepoMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIAuthRepo) EXPECT() *MockIAuthRepoMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockIAuthRepo) GetUserByEmail(email string) (*entity.Auth, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUserByEmail", email) - ret0, _ := ret[0].(*entity.Auth) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockIAuthRepoMockRecorder) Get(email interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByEmail", reflect.TypeOf((*MockIAuthRepo)(nil).GetUserByEmail), email) -} - -// MockIAuthUC is a mock of IAuthUC interface. -type MockIAuthUC struct { - ctrl *gomock.Controller - recorder *MockIAuthUCMockRecorder -} - -// MockIAuthUCMockRecorder is the mock recorder for MockIAuthUC. -type MockIAuthUCMockRecorder struct { - mock *MockIAuthUC -} - -// NewMockIAuthUC creates a new mock instance. -func NewMockIAuthUC(ctrl *gomock.Controller) *MockIAuthUC { - mock := &MockIAuthUC{ctrl: ctrl} - mock.recorder = &MockIAuthUCMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIAuthUC) EXPECT() *MockIAuthUCMockRecorder { - return m.recorder -} - -// Login mocks base method. -func (m *MockIAuthUC) Login(email, password string) (*dto.LoginResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Login", email, password) - ret0, _ := ret[0].(*dto.LoginResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Login indicates an expected call of Login. -func (mr *MockIAuthUCMockRecorder) Login(email, password interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Login", reflect.TypeOf((*MockIAuthUC)(nil).Login), email, password) -} - -// MockIProfileRepo is a mock of IProfileRepo interface. -type MockIProfileRepo struct { - ctrl *gomock.Controller - recorder *MockIProfileRepoMockRecorder -} - -// MockIProfileRepoMockRecorder is the mock recorder for MockIProfileRepo. -type MockIProfileRepoMockRecorder struct { - mock *MockIProfileRepo -} - -// NewMockIProfileRepo creates a new mock instance. -func NewMockIProfileRepo(ctrl *gomock.Controller) *MockIProfileRepo { - mock := &MockIProfileRepo{ctrl: ctrl} - mock.recorder = &MockIProfileRepoMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIProfileRepo) EXPECT() *MockIProfileRepoMockRecorder { - return m.recorder -} - -// GetStudentProfile mocks base method. -func (m *MockIProfileRepo) GetStProfile(email string) (*entity.StProfile, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStProfile", email) - ret0, _ := ret[0].(*entity.StProfile) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStudentProfile indicates an expected call of GetStudentProfile. -func (mr *MockIProfileRepoMockRecorder) GetStudentProfile(email interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStProfile", reflect.TypeOf((*MockIProfileRepo)(nil).GetStProfile), email) -} - -// GetSupervisorProfile mocks base method. -func (m *MockIProfileRepo) GetSvProfile(email string) (*entity.SvProfile, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSvProfile", email) - ret0, _ := ret[0].(*entity.SvProfile) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSupervisorProfile indicates an expected call of GetSupervisorProfile. -func (mr *MockIProfileRepoMockRecorder) GetSupervisorProfile(email interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSvProfile", reflect.TypeOf((*MockIProfileRepo)(nil).GetSvProfile), email) -} - -// MockIProfileUC is a mock of IProfileUC interface. -type MockIProfileUC struct { - ctrl *gomock.Controller - recorder *MockIProfileUCMockRecorder -} - -// MockIProfileUCMockRecorder is the mock recorder for MockIProfileUC. -type MockIProfileUCMockRecorder struct { - mock *MockIProfileUC -} - -// NewMockIProfileUC creates a new mock instance. -func NewMockIProfileUC(ctrl *gomock.Controller) *MockIProfileUC { - mock := &MockIProfileUC{ctrl: ctrl} - mock.recorder = &MockIProfileUCMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIProfileUC) EXPECT() *MockIProfileUCMockRecorder { - return m.recorder -} - -// GetStudentProfile mocks base method. -func (m *MockIProfileUC) GetStudentProfile(email string) (*dto.StProfile, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStProfile", email) - ret0, _ := ret[0].(*dto.StProfile) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStudentProfile indicates an expected call of GetStudentProfile. -func (mr *MockIProfileUCMockRecorder) GetStudentProfile(email interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStProfile", reflect.TypeOf((*MockIProfileUC)(nil).GetStudentProfile), email) -} - -// GetSupervisorProfile mocks base method. -func (m *MockIProfileUC) GetSupervisorProfile(email string) (*dto.SvProfile, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSvProfile", email) - ret0, _ := ret[0].(*dto.SvProfile) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSupervisorProfile indicates an expected call of GetSupervisorProfile. -func (mr *MockIProfileUCMockRecorder) GetSupervisorProfile(email interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSvProfile", reflect.TypeOf((*MockIProfileUC)(nil).GetSupervisorProfile), email) -} - -// MockIRelRepo is a mock of IRelRepo interface. -type MockIRelRepo struct { - ctrl *gomock.Controller - recorder *MockIRelRepoMockRecorder -} - -// MockIRelRepoMockRecorder is the mock recorder for MockIRelRepo. -type MockIRelRepoMockRecorder struct { - mock *MockIRelRepo -} - -// NewMockIRelRepo creates a new mock instance. -func NewMockIRelRepo(ctrl *gomock.Controller) *MockIRelRepo { - mock := &MockIRelRepo{ctrl: ctrl} - mock.recorder = &MockIRelRepoMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIRelRepo) EXPECT() *MockIRelRepoMockRecorder { - return m.recorder -} - -// Create mocks base method. -func (m *MockIRelRepo) Create(studentID, supervisorID, workID int) (int, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Create", studentID, supervisorID, workID) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Create indicates an expected call of Create. -func (mr *MockIRelRepoMockRecorder) Create(studentID, supervisorID, workID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockIRelRepo)(nil).Create), studentID, supervisorID, workID) -} - -// GetStudentViewBidPlenty mocks base method. -func (m *MockIRelRepo) GetStudentViewBidPlenty(studentID int) ([]*entity.StRelation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStudentBids", studentID) - ret0, _ := ret[0].([]*entity.StRelation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStudentViewBidPlenty indicates an expected call of GetStudentViewBidPlenty. -func (mr *MockIRelRepoMockRecorder) GetStudentViewBidPlenty(studentID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentBids", reflect.TypeOf((*MockIRelRepo)(nil).GetStudentViewBidPlenty), studentID) -} - -// GetStudentViewSSR mocks base method. -func (m *MockIRelRepo) GetStudentViewSSR(studentID, ssrID int) (*entity.StRelation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStudentRelation", studentID, ssrID) - ret0, _ := ret[0].(*entity.StRelation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStudentViewSSR indicates an expected call of GetStudentViewSSR. -func (mr *MockIRelRepoMockRecorder) GetStudentViewSSR(studentID, ssrID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentRelation", reflect.TypeOf((*MockIRelRepo)(nil).GetStudentViewSSR), studentID, ssrID) -} - -// GetSupervisorViewBidPlenty mocks base method. -func (m *MockIRelRepo) GetSupervisorViewBidPlenty(studentID int) ([]*entity.SvRelation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSupervisorBids", studentID) - ret0, _ := ret[0].([]*entity.SvRelation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSupervisorViewBidPlenty indicates an expected call of GetSupervisorViewBidPlenty. -func (mr *MockIRelRepoMockRecorder) GetSupervisorViewBidPlenty(studentID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSupervisorBids", reflect.TypeOf((*MockIRelRepo)(nil).GetSupervisorViewBidPlenty), studentID) -} - -// UpdateStatus mocks base method. -func (m *MockIRelRepo) UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateStatus", id, newStatus) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateStatus indicates an expected call of UpdateStatus. -func (mr *MockIRelRepoMockRecorder) UpdateStatus(id, newStatus interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStatus", reflect.TypeOf((*MockIRelRepo)(nil).UpdateStatus), id, newStatus) -} - -// MockIStudentBidUC is a mock of IStudentBidUC interface. -type MockIStudentBidUC struct { - ctrl *gomock.Controller - recorder *MockIStudentBidUCMockRecorder -} - -// MockIStudentBidUCMockRecorder is the mock recorder for MockIStudentBidUC. -type MockIStudentBidUCMockRecorder struct { - mock *MockIStudentBidUC -} - -// NewMockIStudentBidUC creates a new mock instance. -func NewMockIStudentBidUC(ctrl *gomock.Controller) *MockIStudentBidUC { - mock := &MockIStudentBidUC{ctrl: ctrl} - mock.recorder = &MockIStudentBidUCMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIStudentBidUC) EXPECT() *MockIStudentBidUCMockRecorder { - return m.recorder -} - -// Apply mocks base method. -func (m *MockIStudentBidUC) Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Apply", data) - ret0, _ := ret[0].(*dto.ApplyBidResp) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Apply indicates an expected call of Apply. -func (mr *MockIStudentBidUCMockRecorder) Apply(data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockIStudentBidUC)(nil).Apply), data) -} - -// GetStudentBids mocks base method. -func (m *MockIStudentBidUC) GetStudentBids(studentID int) (*dto.StBids, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStudentBids", studentID) - ret0, _ := ret[0].(*dto.StBids) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStudentBids indicates an expected call of GetStudentBids. -func (mr *MockIStudentBidUCMockRecorder) GetStudentBids(studentID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentBids", reflect.TypeOf((*MockIStudentBidUC)(nil).GetStudentBids), studentID) -} - -// MockISupervisorBidUC is a mock of ISupervisorBidUC interface. -type MockISupervisorBidUC struct { - ctrl *gomock.Controller - recorder *MockISupervisorBidUCMockRecorder -} - -// MockISupervisorBidUCMockRecorder is the mock recorder for MockISupervisorBidUC. -type MockISupervisorBidUCMockRecorder struct { - mock *MockISupervisorBidUC -} - -// NewMockISupervisorBidUC creates a new mock instance. -func NewMockISupervisorBidUC(ctrl *gomock.Controller) *MockISupervisorBidUC { - mock := &MockISupervisorBidUC{ctrl: ctrl} - mock.recorder = &MockISupervisorBidUCMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockISupervisorBidUC) EXPECT() *MockISupervisorBidUCMockRecorder { - return m.recorder -} - -// GetSupervisorBids mocks base method. -func (m *MockISupervisorBidUC) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSupervisorBids", supervisorID) - ret0, _ := ret[0].(*dto.SvBids) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSupervisorBids indicates an expected call of GetSupervisorBids. -func (mr *MockISupervisorBidUCMockRecorder) GetSupervisorBids(supervisorID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSupervisorBids", reflect.TypeOf((*MockISupervisorBidUC)(nil).GetSupervisorBids), supervisorID) -} - -// Resolve mocks base method. -func (m *MockISupervisorBidUC) Resolve(data *dto.ResolveBid) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Resolve", data) - ret0, _ := ret[0].(error) - return ret0 -} - -// Resolve indicates an expected call of Resolve. -func (mr *MockISupervisorBidUCMockRecorder) Resolve(data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Resolve", reflect.TypeOf((*MockISupervisorBidUC)(nil).Resolve), data) -} - -// MockIStudentRelUC is a mock of IStudentRelUC interface. -type MockIStudentRelUC struct { - ctrl *gomock.Controller - recorder *MockIStudentRelUCMockRecorder -} - -// MockIStudentRelUCMockRecorder is the mock recorder for MockIStudentRelUC. -type MockIStudentRelUCMockRecorder struct { - mock *MockIStudentRelUC -} - -// NewMockIStudentRelUC creates a new mock instance. -func NewMockIStudentRelUC(ctrl *gomock.Controller) *MockIStudentRelUC { - mock := &MockIStudentRelUC{ctrl: ctrl} - mock.recorder = &MockIStudentRelUCMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIStudentRelUC) EXPECT() *MockIStudentRelUCMockRecorder { - return m.recorder -} - -// Create mocks base method. -func (m *MockIStudentRelUC) Create(data *dto.CreateSSR) (*dto.StViewRelation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Create", data) - ret0, _ := ret[0].(*dto.StViewRelation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Create indicates an expected call of Create. -func (mr *MockIStudentRelUCMockRecorder) Create(data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockIStudentRelUC)(nil).Create), data) -} - -// MockIWorkRepo is a mock of IWorkRepo interface. -type MockIWorkRepo struct { - ctrl *gomock.Controller - recorder *MockIWorkRepoMockRecorder -} - -// MockIWorkRepoMockRecorder is the mock recorder for MockIWorkRepo. -type MockIWorkRepoMockRecorder struct { - mock *MockIWorkRepo -} - -// NewMockIWorkRepo creates a new mock instance. -func NewMockIWorkRepo(ctrl *gomock.Controller) *MockIWorkRepo { - mock := &MockIWorkRepo{ctrl: ctrl} - mock.recorder = &MockIWorkRepoMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIWorkRepo) EXPECT() *MockIWorkRepoMockRecorder { - return m.recorder -} - -// GetSupervisorsByWorkID mocks base method. -func (m *MockIWorkRepo) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSupervisorsByWorkID", workID) - ret0, _ := ret[0].([]*entity.WorkSv) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSupervisorsByWorkID indicates an expected call of GetSupervisorsByWorkID. -func (mr *MockIWorkRepoMockRecorder) GetSupervisorsByWorkID(workID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSupervisorsByWorkID", reflect.TypeOf((*MockIWorkRepo)(nil).GetSupervisorsByWorkID), workID) -} - -// GetWorksByStudentID mocks base method. -func (m *MockIWorkRepo) GetStudentWorks(studentID int) ([]*entity.Work, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStudentWorks", studentID) - ret0, _ := ret[0].([]*entity.Work) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetWorksByStudentID indicates an expected call of GetWorksByStudentID. -func (mr *MockIWorkRepoMockRecorder) GetWorksByStudentID(studentID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentWorks", reflect.TypeOf((*MockIWorkRepo)(nil).GetStudentWorks), studentID) -} - -// GetWorksBySupervisorID mocks base method. -func (m *MockIWorkRepo) GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetWorksBySupervisorID", supervisorID) - ret0, _ := ret[0].([]*entity.SvWork) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetWorksBySupervisorID indicates an expected call of GetWorksBySupervisorID. -func (mr *MockIWorkRepoMockRecorder) GetWorksBySupervisorID(supervisorID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWorksBySupervisorID", reflect.TypeOf((*MockIWorkRepo)(nil).GetWorksBySupervisorID), supervisorID) -} - -// MockIStudentWorkUC is a mock of IStudentWorkUC interface. -type MockIStudentWorkUC struct { - ctrl *gomock.Controller - recorder *MockIStudentWorkUCMockRecorder -} - -// MockIStudentWorkUCMockRecorder is the mock recorder for MockIStudentWorkUC. -type MockIStudentWorkUCMockRecorder struct { - mock *MockIStudentWorkUC -} - -// NewMockIStudentWorkUC creates a new mock instance. -func NewMockIStudentWorkUC(ctrl *gomock.Controller) *MockIStudentWorkUC { - mock := &MockIStudentWorkUC{ctrl: ctrl} - mock.recorder = &MockIStudentWorkUCMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIStudentWorkUC) EXPECT() *MockIStudentWorkUCMockRecorder { - return m.recorder -} - -// GetStudentWorks mocks base method. -func (m *MockIStudentWorkUC) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStudentWorks", studentID) - ret0, _ := ret[0].(*dto.StWorkPlenty) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStudentWorks indicates an expected call of GetStudentWorks. -func (mr *MockIStudentWorkUCMockRecorder) GetStudentWorks(studentID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStudentWorks", reflect.TypeOf((*MockIStudentWorkUC)(nil).GetStudentWorks), studentID) -} - -// GetWorkSupervisors mocks base method. -func (m *MockIStudentWorkUC) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetWorkSupervisors", workID) - ret0, _ := ret[0].(*dto.WorkSvPlenty) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetWorkSupervisors indicates an expected call of GetWorkSupervisors. -func (mr *MockIStudentWorkUCMockRecorder) GetWorkSupervisors(workID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWorkSupervisors", reflect.TypeOf((*MockIStudentWorkUC)(nil).GetWorkSupervisors), workID) -} - -// MockISupervisorWorkUC is a mock of ISupervisorWorkUC interface. -type MockISupervisorWorkUC struct { - ctrl *gomock.Controller - recorder *MockISupervisorWorkUCMockRecorder -} - -// MockISupervisorWorkUCMockRecorder is the mock recorder for MockISupervisorWorkUC. -type MockISupervisorWorkUCMockRecorder struct { - mock *MockISupervisorWorkUC -} - -// NewMockISupervisorWorkUC creates a new mock instance. -func NewMockISupervisorWorkUC(ctrl *gomock.Controller) *MockISupervisorWorkUC { - mock := &MockISupervisorWorkUC{ctrl: ctrl} - mock.recorder = &MockISupervisorWorkUCMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockISupervisorWorkUC) EXPECT() *MockISupervisorWorkUCMockRecorder { - return m.recorder -} - -// GetSupervisorWorks mocks base method. -func (m *MockISupervisorWorkUC) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSupervisorWorks", supervisorID) - ret0, _ := ret[0].(*dto.SvWorkPlenty) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSupervisorWorks indicates an expected call of GetSupervisorWorks. -func (mr *MockISupervisorWorkUCMockRecorder) GetSupervisorWorks(supervisorID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSupervisorWorks", reflect.TypeOf((*MockISupervisorWorkUC)(nil).GetSupervisorWorks), supervisorID) -} diff --git a/internal/service/repo_pg/work.go b/internal/service/repo_pg/work.go index 9bd001a..74cb2ac 100644 --- a/internal/service/repo_pg/work.go +++ b/internal/service/repo_pg/work.go @@ -19,8 +19,10 @@ func NewWork(pg *postgres.Postgres, l logger.Interface) *Work { func (r *Work) GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) { const query = ` - select w.work_id, description, semester, + select w.work_id, w.description, w.semester, wk.name as "work_kind.name", + wk.work_kind_id as "work_kind.work_kind_id", + subj.subject_id as "subject.subject_id", subj.name as "subject.name", subj.department_id as "subject.department_id" from works w @@ -41,57 +43,27 @@ func (r *Work) GetStudentWorks(departmentID string, semester int) ([]*entity.Wor return works, nil } -//func (r *Work) GetStudentWorks(studentID int) ([]*entity.Work, error) { -// const query = ` -// with const (st_year, st_department_id, curr_month) as ( -// select s.year, -// s.department_id, -// extract('month' from current_date) -// from students s -// where user_id = $1 -// ) -// select w.*, -// wk.name as "work_kind.name", -// subj.name as "subject.name" -// from works w -// join work_kinds wk using (work_kind_id) -// join subjects subj using (subject_id) -// join const c on true -// where (((curr_month between 2 and 8) and (semester = st_year * 2)) -// or (semester = st_year * 2 - 1)) -// and subj.department_id = c.st_department_id; -// ` -// -// var works []*entity.Work -// -// err := r.Conn.Select(&works, query, studentID) -// if err != nil { -// err := fmt.Errorf("Work->GetStudentWorks->r.Conn.Select: %w", err) -// r.l.Error(err) -// return nil, err -// } -// -// return works, nil -//} - -func (r *Work) GetWorksBySupervisorID(supervisorID int) ([]*entity.SvWork, error) { +func (r *Work) GetSupervisorWorks(supervisorID int) ([]*entity.SvWork, error) { const query = ` - select w.*, - subj.name as subject_name, - wk.name as work_kind_name, - sw.is_head as head + select w.work_id, w.description, w.semester, + wk.name as "work_kind.name", + wk.work_kind_id as "work_kind.work_kind_id", + subj.subject_id as "subject.subject_id", + subj.name as "subject.name", + subj.department_id as "subject.department_id", + sw.is_head, + sw.is_full from works w join supervisor_work sw using (work_id) - join supervisors s using (supervisor_id) join subjects subj using (subject_id) join work_kinds wk using (work_kind_id) - where s.supervisor_id = $1; + where sw.supervisor_id = $1; ` var works []*entity.SvWork err := r.Conn.Select(&works, query, supervisorID) if err != nil { - err := fmt.Errorf("Work->GetWorksBySupervisorID->r.Conn.Select: %w", err) + err := fmt.Errorf("Work->GetSupervisorWorks->r.Conn.Select: %w", err) r.l.Error(err) return nil, err } diff --git a/internal/service/work.go b/internal/service/work.go index ab24243..6c0c932 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -60,11 +60,11 @@ func (service *Work) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { // return nil, err //} - var resp []*dto.StWork + var resp []*dto.StWorkResp for _, work := range worksData { - resp = append(resp, &dto.StWork{ - Work: &dto.WorkResp{ + resp = append(resp, &dto.StWorkResp{ + Work: dto.WorkResp{ WorkID: work.WorkID, Description: work.Description, Semester: work.Semester, @@ -85,30 +85,40 @@ func (service *Work) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { }, nil } -// -//func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { -// dbData, err := service.workRepo.GetWorksBySupervisorID(supervisorID) -// if err != nil { -// return nil, err -// } -// -// var resp []*dto.SvWork -// -// for _, db := range dbData { -// resp = append(resp, &dto.SvWork{ -// WorkID: db.WorkID, -// Kind: db.WorkKindName, -// Description: db.Description, -// Subject: db.SubjectName, -// Head: db.Head, -// }) -// } -// -// return &dto.SvWorkPlenty{ -// SupervisorID: supervisorID, -// Works: resp, -// }, nil -//} +func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { + worksData, err := service.workRepo.GetSupervisorWorks(supervisorID) + if err != nil { + return nil, err + } + + var resp []*dto.SvWorkResp + + for _, db := range worksData { + resp = append(resp, &dto.SvWorkResp{ + Work: dto.WorkResp{ + WorkID: db.WorkID, + Description: db.Description, + Semester: db.Semester, + Subject: dto.SubjectResp{ + SubjectID: db.Subject.SubjectID, + Name: db.Subject.Name, + Department: db.Subject.DepartmentID, + }, + Kind: dto.WorkKindResp{ + ID: db.WorkKind.WorkKindID, + Name: db.WorkKind.Name, + }, + }, + IsHead: db.IsHead, + IsFull: db.IsFull, + }) + } + + return &dto.SvWorkPlenty{ + Works: resp, + }, nil +} + // //func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { // dbData, err := service.workRepo.GetSupervisorsByWorkID(workID) diff --git a/swagger/docs.go b/swagger/docs.go index e10c641..ec8df58 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -64,11 +64,11 @@ const docTemplate = `{ } } }, - "/api/student/bid": { + "/api/v1/students/{student_id}/profile": { "get": { "security": [ { - "Auth": [] + "OAuth2Password": [] } ], "produces": [ @@ -77,151 +77,16 @@ const docTemplate = `{ "tags": [ "student" ], - "summary": "GetUserByEmail student's bids", + "summary": "Get student's profile", "parameters": [ { "type": "integer", "description": "Student ID", "name": "student_id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.StBids" - } - }, - "404": { - "description": "Not Found" - } - } - }, - "put": { - "security": [ - { - "Auth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Apply bid", - "parameters": [ - { - "description": "bid info", - "name": "ApplyBid", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.ApplyBid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.ApplyBidResp" - } - } - } - } - }, - "/api/student/feedback": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Get feedbacks on the supervisor.", - "parameters": [ - { - "type": "integer", - "description": "Supervisor ID", - "name": "supervisor_id", "in": "path", "required": true } ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.FeedbackPlenty" - } - } - } - }, - "put": { - "security": [ - { - "Auth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Provide a feedback", - "parameters": [ - { - "description": "feedback info", - "name": "Feedback", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.FeedbackReq" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/dto.FeedbackAddResp" - } - }, - "500": { - "description": "Internal Server Error" - } - } - } - }, - "/api/student/profile": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "GetUserByEmail student's profile", "responses": { "200": { "description": "OK", @@ -235,49 +100,11 @@ const docTemplate = `{ } } }, - "/api/student/ssr": { - "post": { - "security": [ - { - "Auth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Start SSR", - "parameters": [ - { - "description": "ssr info", - "name": "ApplyBid", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.CreateSSR" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.StViewRelation" - } - } - } - } - }, - "/api/student/work": { + "/api/v1/students/{student_id}/works": { "get": { "security": [ { - "Auth": [] + "OAuth2Password": [] } ], "produces": [ @@ -286,46 +113,13 @@ const docTemplate = `{ "tags": [ "student" ], - "summary": "GetUserByEmail student's works", + "summary": "Get student's works", "parameters": [ { "type": "integer", "description": "Student ID", "name": "student_id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.StWorks" - } - } - } - } - }, - "/api/student/work/supervisor": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "GetUserByEmail supervisors of the work", - "parameters": [ - { - "type": "integer", - "description": "Work ID", - "name": "work_id", - "in": "query", + "in": "path", "required": true } ], @@ -333,17 +127,17 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSvPlenty" + "$ref": "#/definitions/dto.StWorkPlenty" } } } } }, - "/api/supervisor/bid": { + "/api/v1/supervisors/{supervisor_id}/profile": { "get": { "security": [ { - "Auth": [] + "OAuth2Password": [] } ], "produces": [ @@ -352,75 +146,16 @@ const docTemplate = `{ "tags": [ "supervisor" ], - "summary": "GetUserByEmail supervisor's bids", + "summary": "Get supervisor's profile", "parameters": [ { "type": "integer", "description": "Supervisor ID", "name": "supervisor_id", - "in": "query", + "in": "path", "required": true } ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.SvBids" - } - } - } - } - }, - "/api/supervisor/bid/resolve": { - "post": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "supervisor" - ], - "summary": "Accept or Decline student's bid", - "parameters": [ - { - "description": "bid info", - "name": "ResolveBid", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.ResolveBid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.ResolveBidResp" - } - } - } - } - }, - "/api/supervisor/profile": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "supervisor" - ], - "summary": "GetUserByEmail supervisor's profile", "responses": { "200": { "description": "OK", @@ -430,210 +165,29 @@ const docTemplate = `{ } } } - }, - "/api/supervisor/work": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "supervisor" - ], - "summary": "GetUserByEmail supervisor's works", - "parameters": [ - { - "type": "integer", - "description": "Supervisor ID", - "name": "supervisor_id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.SvWorkPlenty" - } - } - } - } } }, "definitions": { - "dto.ApplyBid": { - "type": "object", - "properties": { - "studentID": { - "type": "integer" - }, - "supervisorID": { - "type": "integer" - }, - "workID": { - "type": "integer" - } - } - }, - "dto.ApplyBidResp": { - "type": "object", - "properties": { - "bidID": { - "type": "integer" - } - } - }, - "dto.CreateSSR": { - "type": "object", - "properties": { - "bidID": { - "type": "integer" - }, - "studentID": { - "type": "integer" - } - } - }, - "dto.FeedbackAddResp": { - "type": "object", - "properties": { - "feedback_id": { - "type": "integer" - } - } - }, - "dto.FeedbackPlenty": { - "type": "object", - "properties": { - "feedbacks": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.FeedbackResp" - } - } - } - }, - "dto.FeedbackReq": { - "type": "object", - "properties": { - "content": { - "type": "string" - }, - "studentID": { - "type": "integer" - }, - "supervisorID": { - "type": "integer" - }, - "workID": { - "type": "integer" - } - } - }, - "dto.FeedbackResp": { - "type": "object", - "properties": { - "content": { - "type": "string" - }, - "studentID": { - "type": "integer" - }, - "student_full_name": { - "type": "string" - }, - "supervisorID": { - "type": "integer" - }, - "workID": { - "type": "integer" - }, - "work_kind": { - "type": "string" - }, - "work_subject": { - "type": "string" - } - } - }, "dto.LoginResponse": { "type": "object", "properties": { - "email": { + "access_token": { "type": "string" }, "role": { "type": "string" }, - "token": { + "token_type": { "type": "string" - } - } - }, - "dto.ResolveBid": { - "type": "object", - "properties": { - "accept": { - "type": "boolean" - }, - "bidID": { - "type": "integer" }, - "supervisorID": { + "user_id": { "type": "integer" } } }, - "dto.ResolveBidResp": { - "type": "object", - "properties": { - "new_status": { - "type": "string" - } - } - }, - "dto.StBid": { - "type": "object", - "properties": { - "createdAt": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "status": { - "type": "string" - }, - "supervisor": { - "$ref": "#/definitions/dto.SvProfile" - }, - "work": { - "$ref": "#/definitions/dto.Work" - } - } - }, - "dto.StBids": { - "type": "object", - "properties": { - "bids": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.StBid" - } - } - } - }, "dto.StProfile": { "type": "object", "properties": { - "avatarUrl": { - "type": "string" - }, "department": { "type": "string" }, @@ -646,113 +200,50 @@ const docTemplate = `{ "lastName": { "type": "string" }, - "studentCard": { - "type": "string" - }, - "studentID": { - "type": "integer" - }, - "year": { - "type": "integer" - } - } - }, - "dto.StViewRelation": { - "type": "object", - "properties": { - "createdAt": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "status": { + "photoUrl": { "type": "string" }, - "supervisor": { - "$ref": "#/definitions/dto.SvProfile" - }, - "work": { - "$ref": "#/definitions/dto.Work" - } - } - }, - "dto.StWork": { - "type": "object", - "properties": { - "description": { + "studentCard": { "type": "string" }, - "id": { + "year": { "type": "integer" - }, - "is_started": { - "type": "boolean" - }, - "kind": { - "type": "string" - }, - "subject": { - "type": "string" } } }, - "dto.StWorks": { + "dto.StWorkPlenty": { "type": "object", "properties": { - "studentID": { - "type": "integer" - }, "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.StWork" + "$ref": "#/definitions/dto.StWorkResp" } } } }, - "dto.SubjectResp": { + "dto.StWorkResp": { "type": "object", "properties": { - "department": { - "type": "string" - }, - "name": { - "type": "string" + "is_started": { + "type": "boolean" }, - "subjectID": { - "type": "integer" + "work": { + "$ref": "#/definitions/dto.WorkResp" } } }, - "dto.SvBid": { + "dto.SubjectResp": { "type": "object", "properties": { - "createdAt": { + "department": { "type": "string" }, "id": { "type": "integer" }, - "status": { + "name": { "type": "string" - }, - "student": { - "$ref": "#/definitions/dto.StProfile" - }, - "work": { - "$ref": "#/definitions/dto.Work" - } - } - }, - "dto.SvBids": { - "type": "object", - "properties": { - "bids": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.SvBid" - } } } }, @@ -779,47 +270,21 @@ const docTemplate = `{ }, "lastName": { "type": "string" - }, - "supervisorID": { - "type": "integer" } } }, - "dto.SvWork": { + "dto.WorkKindResp": { "type": "object", "properties": { - "description": { - "type": "string" - }, - "head": { - "type": "boolean" - }, "id": { "type": "integer" }, - "kind": { - "type": "string" - }, - "subject": { + "name": { "type": "string" } } }, - "dto.SvWorkPlenty": { - "type": "object", - "properties": { - "supervisorID": { - "type": "integer" - }, - "works": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.SvWork" - } - } - } - }, - "dto.Work": { + "dto.WorkResp": { "type": "object", "properties": { "description": { @@ -828,8 +293,8 @@ const docTemplate = `{ "id": { "type": "integer" }, - "name": { - "type": "string" + "kind": { + "$ref": "#/definitions/dto.WorkKindResp" }, "semester": { "type": "integer" @@ -838,62 +303,13 @@ const docTemplate = `{ "$ref": "#/definitions/dto.SubjectResp" } } - }, - "dto.WorkSv": { - "type": "object", - "properties": { - "about": { - "type": "string" - }, - "avatarUrl": { - "type": "string" - }, - "birthdate": { - "type": "string" - }, - "department": { - "type": "string" - }, - "email": { - "type": "string" - }, - "firstName": { - "type": "string" - }, - "full": { - "type": "boolean" - }, - "head": { - "type": "boolean" - }, - "lastName": { - "type": "string" - }, - "supervisorID": { - "type": "integer" - } - } - }, - "dto.WorkSvPlenty": { - "type": "object", - "properties": { - "supervisors": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.WorkSv" - } - }, - "workID": { - "type": "integer" - } - } } }, "securityDefinitions": { - "Auth": { - "type": "apiKey", - "name": "Authorization", - "in": "header" + "OAuth2Password": { + "type": "oauth2", + "flow": "password", + "tokenUrl": "http://localhost:8080/api/v1/auth/login" } } }` diff --git a/swagger/swagger.json b/swagger/swagger.json index 4e0a1ec..9575bfd 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -60,11 +60,11 @@ } } }, - "/api/student/bid": { + "/api/v1/students/{student_id}/profile": { "get": { "security": [ { - "Auth": [] + "OAuth2Password": [] } ], "produces": [ @@ -73,151 +73,16 @@ "tags": [ "student" ], - "summary": "GetUserInfo student's bids", + "summary": "Get student's profile", "parameters": [ { "type": "integer", "description": "Student ID", "name": "student_id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.StBids" - } - }, - "404": { - "description": "Not Found" - } - } - }, - "put": { - "security": [ - { - "Auth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Apply bid", - "parameters": [ - { - "description": "bid info", - "name": "ApplyBid", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.ApplyBid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.ApplyBidResp" - } - } - } - } - }, - "/api/student/feedback": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Get feedbacks on the supervisor.", - "parameters": [ - { - "type": "integer", - "description": "Supervisor ID", - "name": "supervisor_id", "in": "path", "required": true } ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.FeedbackPlenty" - } - } - } - }, - "put": { - "security": [ - { - "Auth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Provide a feedback", - "parameters": [ - { - "description": "feedback info", - "name": "Feedback", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.FeedbackReq" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "$ref": "#/definitions/dto.FeedbackAddResp" - } - }, - "500": { - "description": "Internal Server Error" - } - } - } - }, - "/api/student/profile": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "GetUserInfo student's profile", "responses": { "200": { "description": "OK", @@ -231,49 +96,11 @@ } } }, - "/api/student/ssr": { - "post": { - "security": [ - { - "Auth": [] - } - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "Start SSR", - "parameters": [ - { - "description": "ssr info", - "name": "ApplyBid", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.CreateSSR" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.StViewRelation" - } - } - } - } - }, - "/api/student/work": { + "/api/v1/students/{student_id}/works": { "get": { "security": [ { - "Auth": [] + "OAuth2Password": [] } ], "produces": [ @@ -282,46 +109,13 @@ "tags": [ "student" ], - "summary": "GetUserInfo student's works", + "summary": "Get student's works", "parameters": [ { "type": "integer", "description": "Student ID", "name": "student_id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.StWorks" - } - } - } - } - }, - "/api/student/work/supervisor": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "student" - ], - "summary": "GetUserInfo supervisors of the work", - "parameters": [ - { - "type": "integer", - "description": "Work ID", - "name": "work_id", - "in": "query", + "in": "path", "required": true } ], @@ -329,17 +123,17 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSvPlenty" + "$ref": "#/definitions/dto.StWorkPlenty" } } } } }, - "/api/supervisor/bid": { + "/api/v1/supervisors/{supervisor_id}/profile": { "get": { "security": [ { - "Auth": [] + "OAuth2Password": [] } ], "produces": [ @@ -348,75 +142,16 @@ "tags": [ "supervisor" ], - "summary": "GetUserInfo supervisor's bids", + "summary": "Get supervisor's profile", "parameters": [ { "type": "integer", "description": "Supervisor ID", "name": "supervisor_id", - "in": "query", + "in": "path", "required": true } ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.SvBids" - } - } - } - } - }, - "/api/supervisor/bid/resolve": { - "post": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "supervisor" - ], - "summary": "Accept or Decline student's bid", - "parameters": [ - { - "description": "bid info", - "name": "ResolveBid", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/dto.ResolveBid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.ResolveBidResp" - } - } - } - } - }, - "/api/supervisor/profile": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "supervisor" - ], - "summary": "GetUserInfo supervisor's profile", "responses": { "200": { "description": "OK", @@ -426,210 +161,29 @@ } } } - }, - "/api/supervisor/work": { - "get": { - "security": [ - { - "Auth": [] - } - ], - "produces": [ - "application/json" - ], - "tags": [ - "supervisor" - ], - "summary": "GetUserInfo supervisor's works", - "parameters": [ - { - "type": "integer", - "description": "Supervisor ID", - "name": "supervisor_id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/dto.SvWorkPlenty" - } - } - } - } } }, "definitions": { - "dto.ApplyBid": { - "type": "object", - "properties": { - "studentID": { - "type": "integer" - }, - "supervisorID": { - "type": "integer" - }, - "workID": { - "type": "integer" - } - } - }, - "dto.ApplyBidResp": { - "type": "object", - "properties": { - "bidID": { - "type": "integer" - } - } - }, - "dto.CreateSSR": { - "type": "object", - "properties": { - "bidID": { - "type": "integer" - }, - "studentID": { - "type": "integer" - } - } - }, - "dto.FeedbackAddResp": { - "type": "object", - "properties": { - "feedback_id": { - "type": "integer" - } - } - }, - "dto.FeedbackPlenty": { - "type": "object", - "properties": { - "feedbacks": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.FeedbackResp" - } - } - } - }, - "dto.FeedbackReq": { - "type": "object", - "properties": { - "content": { - "type": "string" - }, - "studentID": { - "type": "integer" - }, - "supervisorID": { - "type": "integer" - }, - "workID": { - "type": "integer" - } - } - }, - "dto.FeedbackResp": { - "type": "object", - "properties": { - "content": { - "type": "string" - }, - "studentID": { - "type": "integer" - }, - "student_full_name": { - "type": "string" - }, - "supervisorID": { - "type": "integer" - }, - "workID": { - "type": "integer" - }, - "work_kind": { - "type": "string" - }, - "work_subject": { - "type": "string" - } - } - }, "dto.LoginResponse": { "type": "object", "properties": { - "email": { + "access_token": { "type": "string" }, "role": { "type": "string" }, - "token": { + "token_type": { "type": "string" - } - } - }, - "dto.ResolveBid": { - "type": "object", - "properties": { - "accept": { - "type": "boolean" - }, - "bidID": { - "type": "integer" }, - "supervisorID": { + "user_id": { "type": "integer" } } }, - "dto.ResolveBidResp": { - "type": "object", - "properties": { - "new_status": { - "type": "string" - } - } - }, - "dto.StBid": { - "type": "object", - "properties": { - "createdAt": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "status": { - "type": "string" - }, - "supervisor": { - "$ref": "#/definitions/dto.SvProfile" - }, - "work": { - "$ref": "#/definitions/dto.Work" - } - } - }, - "dto.StBids": { - "type": "object", - "properties": { - "bids": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.StBid" - } - } - } - }, "dto.StProfile": { "type": "object", "properties": { - "avatarUrl": { - "type": "string" - }, "department": { "type": "string" }, @@ -642,113 +196,50 @@ "lastName": { "type": "string" }, - "studentCard": { - "type": "string" - }, - "studentID": { - "type": "integer" - }, - "year": { - "type": "integer" - } - } - }, - "dto.StViewRelation": { - "type": "object", - "properties": { - "createdAt": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "status": { + "photoUrl": { "type": "string" }, - "supervisor": { - "$ref": "#/definitions/dto.SvProfile" - }, - "work": { - "$ref": "#/definitions/dto.Work" - } - } - }, - "dto.StWork": { - "type": "object", - "properties": { - "description": { + "studentCard": { "type": "string" }, - "id": { + "year": { "type": "integer" - }, - "is_started": { - "type": "boolean" - }, - "kind": { - "type": "string" - }, - "subject": { - "type": "string" } } }, - "dto.StWorks": { + "dto.StWorkPlenty": { "type": "object", "properties": { - "studentID": { - "type": "integer" - }, "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.StWork" + "$ref": "#/definitions/dto.StWorkResp" } } } }, - "dto.SubjectResp": { + "dto.StWorkResp": { "type": "object", "properties": { - "department": { - "type": "string" - }, - "name": { - "type": "string" + "is_started": { + "type": "boolean" }, - "subjectID": { - "type": "integer" + "work": { + "$ref": "#/definitions/dto.WorkResp" } } }, - "dto.SvBid": { + "dto.SubjectResp": { "type": "object", "properties": { - "createdAt": { + "department": { "type": "string" }, "id": { "type": "integer" }, - "status": { + "name": { "type": "string" - }, - "student": { - "$ref": "#/definitions/dto.StProfile" - }, - "work": { - "$ref": "#/definitions/dto.Work" - } - } - }, - "dto.SvBids": { - "type": "object", - "properties": { - "bids": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.SvBid" - } } } }, @@ -775,47 +266,21 @@ }, "lastName": { "type": "string" - }, - "supervisorID": { - "type": "integer" } } }, - "dto.SvWork": { + "dto.WorkKindResp": { "type": "object", "properties": { - "description": { - "type": "string" - }, - "head": { - "type": "boolean" - }, "id": { "type": "integer" }, - "kind": { - "type": "string" - }, - "subject": { + "name": { "type": "string" } } }, - "dto.SvWorkPlenty": { - "type": "object", - "properties": { - "supervisorID": { - "type": "integer" - }, - "works": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.SvWork" - } - } - } - }, - "dto.Work": { + "dto.WorkResp": { "type": "object", "properties": { "description": { @@ -824,8 +289,8 @@ "id": { "type": "integer" }, - "name": { - "type": "string" + "kind": { + "$ref": "#/definitions/dto.WorkKindResp" }, "semester": { "type": "integer" @@ -834,62 +299,13 @@ "$ref": "#/definitions/dto.SubjectResp" } } - }, - "dto.WorkSv": { - "type": "object", - "properties": { - "about": { - "type": "string" - }, - "avatarUrl": { - "type": "string" - }, - "birthdate": { - "type": "string" - }, - "department": { - "type": "string" - }, - "email": { - "type": "string" - }, - "firstName": { - "type": "string" - }, - "full": { - "type": "boolean" - }, - "head": { - "type": "boolean" - }, - "lastName": { - "type": "string" - }, - "supervisorID": { - "type": "integer" - } - } - }, - "dto.WorkSvPlenty": { - "type": "object", - "properties": { - "supervisors": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.WorkSv" - } - }, - "workID": { - "type": "integer" - } - } } }, "securityDefinitions": { - "Auth": { - "type": "apiKey", - "name": "Authorization", - "in": "header" + "OAuth2Password": { + "type": "oauth2", + "flow": "password", + "tokenUrl": "http://localhost:8080/api/v1/auth/login" } } } \ No newline at end of file diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index 679c308..8b74af4 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -1,113 +1,18 @@ basePath: / definitions: - dto.ApplyBid: - properties: - studentID: - type: integer - supervisorID: - type: integer - workID: - type: integer - type: object - dto.ApplyBidResp: - properties: - bidID: - type: integer - type: object - dto.CreateSSR: - properties: - bidID: - type: integer - studentID: - type: integer - type: object - dto.FeedbackAddResp: - properties: - feedback_id: - type: integer - type: object - dto.FeedbackPlenty: - properties: - feedbacks: - items: - $ref: '#/definitions/dto.FeedbackResp' - type: array - type: object - dto.FeedbackReq: - properties: - content: - type: string - studentID: - type: integer - supervisorID: - type: integer - workID: - type: integer - type: object - dto.FeedbackResp: - properties: - content: - type: string - student_full_name: - type: string - studentID: - type: integer - supervisorID: - type: integer - work_kind: - type: string - work_subject: - type: string - workID: - type: integer - type: object dto.LoginResponse: properties: - email: + access_token: type: string role: type: string - token: - type: string - type: object - dto.ResolveBid: - properties: - accept: - type: boolean - bidID: - type: integer - supervisorID: - type: integer - type: object - dto.ResolveBidResp: - properties: - new_status: - type: string - type: object - dto.StBid: - properties: - createdAt: + token_type: type: string - id: + user_id: type: integer - status: - type: string - supervisor: - $ref: '#/definitions/dto.SvProfile' - work: - $ref: '#/definitions/dto.Work' - type: object - dto.StBids: - properties: - bids: - items: - $ref: '#/definitions/dto.StBid' - type: array type: object dto.StProfile: properties: - avatarUrl: - type: string department: type: string email: @@ -116,76 +21,35 @@ definitions: type: string lastName: type: string + photoUrl: + type: string studentCard: type: string - studentID: - type: integer year: type: integer type: object - dto.StViewRelation: + dto.StWorkPlenty: properties: - createdAt: - type: string - id: - type: integer - status: - type: string - supervisor: - $ref: '#/definitions/dto.SvProfile' - work: - $ref: '#/definitions/dto.Work' + works: + items: + $ref: '#/definitions/dto.StWorkResp' + type: array type: object - dto.StWork: + dto.StWorkResp: properties: - description: - type: string - id: - type: integer is_started: type: boolean - kind: - type: string - subject: - type: string - type: object - dto.StWorks: - properties: - studentID: - type: integer - works: - items: - $ref: '#/definitions/dto.StWork' - type: array + work: + $ref: '#/definitions/dto.WorkResp' type: object dto.SubjectResp: properties: department: type: string - name: - type: string - subjectID: - type: integer - type: object - dto.SvBid: - properties: - createdAt: - type: string id: type: integer - status: + name: type: string - student: - $ref: '#/definitions/dto.StProfile' - work: - $ref: '#/definitions/dto.Work' - type: object - dto.SvBids: - properties: - bids: - items: - $ref: '#/definitions/dto.SvBid' - type: array type: object dto.SvProfile: properties: @@ -203,76 +67,27 @@ definitions: type: string lastName: type: string - supervisorID: - type: integer type: object - dto.SvWork: + dto.WorkKindResp: properties: - description: - type: string - head: - type: boolean id: type: integer - kind: - type: string - subject: + name: type: string type: object - dto.SvWorkPlenty: - properties: - supervisorID: - type: integer - works: - items: - $ref: '#/definitions/dto.SvWork' - type: array - type: object - dto.Work: + dto.WorkResp: properties: description: type: string id: type: integer - name: - type: string + kind: + $ref: '#/definitions/dto.WorkKindResp' semester: type: integer subject: $ref: '#/definitions/dto.SubjectResp' type: object - dto.WorkSv: - properties: - about: - type: string - avatarUrl: - type: string - birthdate: - type: string - department: - type: string - email: - type: string - firstName: - type: string - full: - type: boolean - head: - type: boolean - lastName: - type: string - supervisorID: - type: integer - type: object - dto.WorkSvPlenty: - properties: - supervisors: - items: - $ref: '#/definitions/dto.WorkSv' - type: array - workID: - type: integer - type: object host: localhost:8080 info: contact: @@ -312,98 +127,16 @@ paths: summary: Login into account tags: - auth - /api/student/bid: + /api/v1/students/{student_id}/profile: get: parameters: - description: Student ID - in: query - name: student_id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.StBids' - "404": - description: Not Found - security: - - Auth: [] - summary: GetUserInfo student's bids - tags: - - student - put: - consumes: - - application/json - parameters: - - description: bid info - in: body - name: ApplyBid - required: true - schema: - $ref: '#/definitions/dto.ApplyBid' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.ApplyBidResp' - security: - - Auth: [] - summary: Apply bid - tags: - - student - /api/student/feedback: - get: - parameters: - - description: Supervisor ID in: path - name: supervisor_id + name: student_id required: true type: integer produces: - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.FeedbackPlenty' - security: - - Auth: [] - summary: Get feedbacks on the supervisor. - tags: - - student - put: - consumes: - - application/json - parameters: - - description: feedback info - in: body - name: Feedback - required: true - schema: - $ref: '#/definitions/dto.FeedbackReq' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/dto.FeedbackAddResp' - "500": - description: Internal Server Error - security: - - Auth: [] - summary: Provide a feedback - tags: - - student - /api/student/profile: - get: - produces: - - application/json responses: "200": description: OK @@ -412,38 +145,15 @@ paths: "404": description: Not Found security: - - Auth: [] - summary: GetUserInfo student's profile + - OAuth2Password: [] + summary: Get student's profile tags: - student - /api/student/ssr: - post: - consumes: - - application/json - parameters: - - description: ssr info - in: body - name: ApplyBid - required: true - schema: - $ref: '#/definitions/dto.CreateSSR' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.StViewRelation' - security: - - Auth: [] - summary: Start SSR - tags: - - student - /api/student/work: + /api/v1/students/{student_id}/works: get: parameters: - description: Student ID - in: query + in: path name: student_id required: true type: integer @@ -453,112 +163,37 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.StWorks' - security: - - Auth: [] - summary: GetUserInfo student's works - tags: - - student - /api/student/work/supervisor: - get: - parameters: - - description: Work ID - in: query - name: work_id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.WorkSvPlenty' + $ref: '#/definitions/dto.StWorkPlenty' security: - - Auth: [] - summary: GetUserInfo supervisors of the work + - OAuth2Password: [] + summary: Get student's works tags: - student - /api/supervisor/bid: + /api/v1/supervisors/{supervisor_id}/profile: get: parameters: - description: Supervisor ID - in: query + in: path name: supervisor_id required: true type: integer produces: - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.SvBids' - security: - - Auth: [] - summary: GetUserInfo supervisor's bids - tags: - - supervisor - /api/supervisor/bid/resolve: - post: - parameters: - - description: bid info - in: body - name: ResolveBid - required: true - schema: - $ref: '#/definitions/dto.ResolveBid' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.ResolveBidResp' - security: - - Auth: [] - summary: Accept or Decline student's bid - tags: - - supervisor - /api/supervisor/profile: - get: - produces: - - application/json responses: "200": description: OK schema: $ref: '#/definitions/dto.SvProfile' security: - - Auth: [] - summary: GetUserInfo supervisor's profile - tags: - - supervisor - /api/supervisor/work: - get: - parameters: - - description: Supervisor ID - in: query - name: supervisor_id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/dto.SvWorkPlenty' - security: - - Auth: [] - summary: GetUserInfo supervisor's works + - OAuth2Password: [] + summary: Get supervisor's profile tags: - supervisor schemes: - http securityDefinitions: - Auth: - in: header - name: Authorization - type: apiKey + OAuth2Password: + flow: password + tokenUrl: http://localhost:8080/api/v1/auth/login + type: oauth2 swagger: "2.0" From d49550e3b0935ba32f365264af13b632059518e9 Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Sun, 2 Oct 2022 15:44:42 +0300 Subject: [PATCH 05/12] upgrade: swagger works --- internal/controller/http/supervisor.go | 24 +++++------ swagger/docs.go | 58 ++++++++++++++++++++++++++ swagger/swagger.json | 58 ++++++++++++++++++++++++++ swagger/swagger.yaml | 36 ++++++++++++++++ 4 files changed, 164 insertions(+), 12 deletions(-) diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index 006b5c4..cd2508b 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -25,7 +25,7 @@ type supervisor struct { // @Router /api/v1/supervisors/{supervisor_id}/profile [get] // @Security OAuth2Password func (ctrl *supervisor) getProfile(ctx echo.Context) error { - supervisorID, _ := strconv.Atoi(ctx.Param("student_id")) + supervisorID, _ := strconv.Atoi(ctx.Param("supervisor_id")) respDTO, err := ctrl.profileService.GetSupervisorProfile(supervisorID) if err != nil { @@ -36,16 +36,16 @@ func (ctrl *supervisor) getProfile(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -// // ShowAccount godoc -// // @Summary Get supervisor's works -// // @Tags supervisor -// // @Param supervisor_id path int true "Supervisor ID" -// // @Produce json -// // @Success 200 {object} dto.SvWorkPlenty -// // @Router /api/v1/supervisors/{supervisor_id}/work [get] -// // @Security OAuth2Password +// ShowAccount godoc +// @Summary Get supervisor's works +// @Tags supervisor +// @Param supervisor_id path int true "Supervisor ID" +// @Produce json +// @Success 200 {object} dto.SvWorkPlenty +// @Router /api/v1/supervisors/{supervisor_id}/works [get] +// @Security OAuth2Password func (ctrl *supervisor) getWorks(ctx echo.Context) error { - supervisorID, _ := strconv.Atoi(ctx.Param("student_id")) + supervisorID, _ := strconv.Atoi(ctx.Param("supervisor_id")) respDTO, err := ctrl.workService.GetSupervisorWorks(supervisorID) if err != nil { @@ -126,8 +126,8 @@ func NewSupervisorRoutes( g := router.Group("/supervisors", middlewares.MakeAuthMiddleware(config), middlewares.CheckRole) { - g.GET("/supervisor_id/profile", ctrl.getProfile) - g.GET("/supervisor_id/works", ctrl.getWorks) + g.GET("/:supervisor_id/profile", ctrl.getProfile) + g.GET("/:supervisor_id/works", ctrl.getWorks) //g.GET("/bid", ctrl.getBids) //g.POST("/bid/resolve", ctrl.resolveBid) //g.GET("/work", ctrl.getWorks) diff --git a/swagger/docs.go b/swagger/docs.go index ec8df58..10a10b8 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -165,6 +165,39 @@ const docTemplate = `{ } } } + }, + "/api/v1/supervisors/{supervisor_id}/works": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "supervisor" + ], + "summary": "Get supervisor's works", + "parameters": [ + { + "type": "integer", + "description": "Supervisor ID", + "name": "supervisor_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.SvWorkPlenty" + } + } + } + } } }, "definitions": { @@ -273,6 +306,31 @@ const docTemplate = `{ } } }, + "dto.SvWorkPlenty": { + "type": "object", + "properties": { + "works": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.SvWorkResp" + } + } + } + }, + "dto.SvWorkResp": { + "type": "object", + "properties": { + "is_full": { + "type": "boolean" + }, + "is_head": { + "type": "boolean" + }, + "work": { + "$ref": "#/definitions/dto.WorkResp" + } + } + }, "dto.WorkKindResp": { "type": "object", "properties": { diff --git a/swagger/swagger.json b/swagger/swagger.json index 9575bfd..f90ca47 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -161,6 +161,39 @@ } } } + }, + "/api/v1/supervisors/{supervisor_id}/works": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "supervisor" + ], + "summary": "Get supervisor's works", + "parameters": [ + { + "type": "integer", + "description": "Supervisor ID", + "name": "supervisor_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.SvWorkPlenty" + } + } + } + } } }, "definitions": { @@ -269,6 +302,31 @@ } } }, + "dto.SvWorkPlenty": { + "type": "object", + "properties": { + "works": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.SvWorkResp" + } + } + } + }, + "dto.SvWorkResp": { + "type": "object", + "properties": { + "is_full": { + "type": "boolean" + }, + "is_head": { + "type": "boolean" + }, + "work": { + "$ref": "#/definitions/dto.WorkResp" + } + } + }, "dto.WorkKindResp": { "type": "object", "properties": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index 8b74af4..bbe3163 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -68,6 +68,22 @@ definitions: lastName: type: string type: object + dto.SvWorkPlenty: + properties: + works: + items: + $ref: '#/definitions/dto.SvWorkResp' + type: array + type: object + dto.SvWorkResp: + properties: + is_full: + type: boolean + is_head: + type: boolean + work: + $ref: '#/definitions/dto.WorkResp' + type: object dto.WorkKindResp: properties: id: @@ -189,6 +205,26 @@ paths: summary: Get supervisor's profile tags: - supervisor + /api/v1/supervisors/{supervisor_id}/works: + get: + parameters: + - description: Supervisor ID + in: path + name: supervisor_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/dto.SvWorkPlenty' + security: + - OAuth2Password: [] + summary: Get supervisor's works + tags: + - supervisor schemes: - http securityDefinitions: From 1427a403b9455aa01899a7afc064fa2dac201fce Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Sun, 2 Oct 2022 17:02:34 +0300 Subject: [PATCH 06/12] upgrade: supervisors of the works is working now --- internal/app/app.go | 2 - internal/controller/http/interfaces.go | 9 ++- internal/controller/http/router.go | 11 ++-- internal/controller/http/student.go | 32 ++--------- internal/controller/http/supervisor.go | 8 +-- internal/controller/http/works.go | 53 ++++++++++++++++++ internal/dto/work.go | 4 +- internal/entity/supervisor.go | 2 +- internal/entity/work.go | 6 +- internal/service/interfaces.go | 2 +- internal/service/repo_pg/work.go | 19 ++++--- internal/service/work.go | 59 ++++++++++---------- swagger/docs.go | 76 ++++++++++++++++++++++++++ swagger/swagger.json | 76 ++++++++++++++++++++++++++ swagger/swagger.yaml | 48 ++++++++++++++++ 15 files changed, 319 insertions(+), 88 deletions(-) create mode 100644 internal/controller/http/works.go diff --git a/internal/app/app.go b/internal/app/app.go index 3afcc1b..b957ffa 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -42,10 +42,8 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, cfg, authService, profileService, - profileService, bidService, workService, - workService, relationService, feedbackService, ) diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index 06f7dd0..74d06c3 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -8,8 +8,9 @@ type ( AuthService interface { Login(email, password string) (*dto.LoginResponse, error) } - StProfileService interface { + ProfileService interface { GetStudentProfile(userID int) (*dto.StProfile, error) + GetSupervisorProfile(userID int) (*dto.SvProfile, error) } SvProfileService interface { GetSupervisorProfile(userID int) (*dto.SvProfile, error) @@ -25,12 +26,10 @@ type ( StRelationService interface { Create(data *dto.CreateSSR) (*dto.StViewRelation, error) } - StWorkService interface { + WorkService interface { GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) - //GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) - } - SvWorkService interface { GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) + GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) } FeedbackService interface { Add(data *dto.FeedbackReq) (int, error) diff --git a/internal/controller/http/router.go b/internal/controller/http/router.go index 28b883b..a48623e 100644 --- a/internal/controller/http/router.go +++ b/internal/controller/http/router.go @@ -13,11 +13,9 @@ func NewRouter( l logger.Interface, config *config.Config, auth AuthService, - stProfile StProfileService, - svProfile SvProfileService, + profiles ProfileService, stBids StBidService, - stWorks StWorkService, - svWorks SvWorkService, + works WorkService, stRelations StRelationService, feedback FeedbackService, ) { @@ -26,7 +24,8 @@ func NewRouter( { NewAuthRoutes(g, l, auth) - NewStudentRoutes(g, l, config, stProfile, stBids, stWorks, stRelations, feedback) - NewSupervisorRoutes(g, l, config, svProfile, svWorks) + NewStudentRoutes(g, l, config, profiles, stBids, works, stRelations, feedback) + NewSupervisorRoutes(g, l, config, profiles, works) + NewWorksRoutes(g, l, config, works) } } diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index 256d166..f9b27cf 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -11,9 +11,9 @@ import ( type student struct { l logger.Interface - profileService StProfileService + profileService ProfileService bidService StBidService - workService StWorkService + workService WorkService relationService StRelationService feedbackService FeedbackService } @@ -77,28 +77,6 @@ func (ctrl *student) getWorks(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -// ShowAccount godoc -// @Summary GetUserByEmail supervisors of the work -// @Tags student -// @Param work_id query int true "WorkResp ID" -// @Produce json -// @Success 200 {object} dto.WorkSvPlenty -// @Router /api/student/work/supervisor [get] -// @Security Auth -//func (ctrl *student) getSupervisorsOfWork(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// workID, _ := strconv.Atoi(ctx.QueryParam("work_id")) -// -// respDTO, err := ctrl.workService.GetWorkSupervisors(workID) -// if err != nil { -// return echo.ErrNotFound -// } -// -// return ctx.JSON(http.StatusOK, respDTO) -//} - //// ShowAccount godoc //// @Summary Apply bid //// @Tags student @@ -204,9 +182,9 @@ func NewStudentRoutes( router *echo.Group, l logger.Interface, config *config.Config, - profileService StProfileService, + profileService ProfileService, bidsService StBidService, - worksService StWorkService, + worksService WorkService, relationService StRelationService, feedbackService FeedbackService, ) { @@ -227,7 +205,7 @@ func NewStudentRoutes( //student.GET("/bid", ctrl.getBids) //student.PUT("/bid", ctrl.applyBid) //student.POST("/ssr", ctrl.createSSR) - //student.GET("/work/supervisor_id", ctrl.getSupervisorsOfWork) + //student.GET("/work/supervisor_id", ctrl.getSupervisors) //student.GET("/feedback/:supervisor_id", ctrl.getFeedback) //student.PUT("/feedback", ctrl.provideFeedback) } diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index cd2508b..671d833 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -11,9 +11,9 @@ import ( type supervisor struct { l logger.Interface - profileService SvProfileService + profileService ProfileService //bidService SvBidService - workService SvWorkService + workService WorkService } // ShowAccount godoc @@ -117,9 +117,9 @@ func NewSupervisorRoutes( router *echo.Group, l logger.Interface, config *config.Config, - profileService SvProfileService, + profileService ProfileService, // bidService SvBidService, - workService SvWorkService, + workService WorkService, ) { ctrl := &supervisor{l, profileService, workService} diff --git a/internal/controller/http/works.go b/internal/controller/http/works.go new file mode 100644 index 0000000..3a03254 --- /dev/null +++ b/internal/controller/http/works.go @@ -0,0 +1,53 @@ +package http + +import ( + "github.com/labstack/echo/v4" + "net/http" + "ssr/config" + "ssr/internal/controller/http/middlewares" + "ssr/pkg/logger" + "strconv" +) + +type works struct { + l logger.Interface + workService WorkService +} + +// ShowAccount godoc +// @Summary Get supervisors of the work +// @Tags works +// @Param work_id path int true "Work ID" +// @Produce json +// @Success 200 {object} dto.WorkSvPlenty +// @Router /api/v1/works/{work_id}/supervisors [get] +// @Security OAuth2Password +func (ctrl *works) getSupervisors(ctx echo.Context) error { + workID, _ := strconv.Atoi(ctx.Param("work_id")) + + respDTO, err := ctrl.workService.GetWorkSupervisors(workID) + if err != nil { + return echo.ErrNotFound + } + + return ctx.JSON(http.StatusOK, respDTO) +} + +func NewWorksRoutes( + router *echo.Group, + l logger.Interface, + config *config.Config, + worksService WorkService, +) { + ctrl := &works{ + l, + worksService, + } + + works := router.Group("/works", middlewares.MakeAuthMiddleware(config)) + + { + works.GET("/:work_id/supervisors", ctrl.getSupervisors) + } + +} diff --git a/internal/dto/work.go b/internal/dto/work.go index e893e41..0206005 100644 --- a/internal/dto/work.go +++ b/internal/dto/work.go @@ -34,8 +34,8 @@ type SvWorkPlenty struct { type WorkSv struct { SvProfile - Head bool `json:"head"` - Full bool `json:"full"` + IsHead bool `json:"head"` + IsFull bool `json:"full"` } type WorkSvPlenty struct { diff --git a/internal/entity/supervisor.go b/internal/entity/supervisor.go index 1219d75..ab9335b 100644 --- a/internal/entity/supervisor.go +++ b/internal/entity/supervisor.go @@ -10,7 +10,7 @@ type Supervisor struct { } type SupervisorFull struct { - User *User + User *User `db:"user"` Birthdate time.Time About string DepartmentID string `db:"department_id"` diff --git a/internal/entity/work.go b/internal/entity/work.go index 4f53ddf..69c9fcd 100644 --- a/internal/entity/work.go +++ b/internal/entity/work.go @@ -20,7 +20,7 @@ type SvWork struct { } type WorkSv struct { - *SvProfile - Head bool `db:"head"` - Full bool `db:"full"` + *SupervisorFull `db:"sv"` + IsHead bool `db:"is_head"` + IsFull bool `db:"is_full"` } diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index 9d57f14..df09f4d 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -30,7 +30,7 @@ type ( WorkRepo interface { GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) GetSupervisorWorks(supervisorID int) ([]*entity.SvWork, error) - //GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) + GetWorkSupervisors(workID int) ([]*entity.WorkSv, error) } FeedbackRepo interface { Create(studentID, supervisorID, workID int, content string) (int, error) diff --git a/internal/service/repo_pg/work.go b/internal/service/repo_pg/work.go index 74cb2ac..350bd04 100644 --- a/internal/service/repo_pg/work.go +++ b/internal/service/repo_pg/work.go @@ -71,15 +71,20 @@ func (r *Work) GetSupervisorWorks(supervisorID int) ([]*entity.SvWork, error) { return works, nil } -func (r *Work) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) { +func (r *Work) GetWorkSupervisors(workID int) ([]*entity.WorkSv, error) { const query = ` select - u.*, - sv.*, - sw.is_full as "full", - sw.is_head as head + sv.about as "sv.about", + sv.birthdate as "sv.birthdate", + sv.department_id as "sv.department_id", + u.email as "sv.user.email", + u.first_name as "sv.user.first_name", + u.last_name as "sv.user.last_name", + u.photo_url as "sv.user.photo_url", + sw.is_full as is_full, + sw.is_head as is_head from supervisors sv - join supervisor_work sw using (supervisor_id) + join supervisor_work sw on sv.user_id = sw.supervisor_id join users u using (user_id) where sw.work_id = $1; ` @@ -88,7 +93,7 @@ func (r *Work) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSv, error) { err := r.Conn.Select(&supervisors, query, workID) if err != nil { - err := fmt.Errorf("Work->GetSupervisorsByWorkID->r.Conn.Select: %w", err) + err := fmt.Errorf("Work->GetWorkSupervisors->r.Conn.Select: %w", err) r.l.Error(err) return nil, err } diff --git a/internal/service/work.go b/internal/service/work.go index 6c0c932..b3c64cd 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -4,6 +4,7 @@ import ( "ssr/internal/dto" "ssr/internal/entity" "ssr/pkg/logger" + "ssr/pkg/misc" "time" ) @@ -119,33 +120,31 @@ func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, er }, nil } -// -//func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { -// dbData, err := service.workRepo.GetSupervisorsByWorkID(workID) -// if err != nil { -// return nil, err -// } -// -// var resp []*dto.WorkSv -// -// for _, db := range dbData { -// resp = append(resp, &dto.WorkSv{ -// SvProfile: dto.SvProfile{ -// Email: db.Email, -// FirstName: db.FirstName, -// LastName: db.LastName, -// About: db.About, -// Birthdate: misc.Date{Time: db.Birthdate}, -// PhotoUrl: db.PhotoUrl, -// Department: db.DepartmentID, -// }, -// Head: db.Head, -// Full: db.Full, -// }) -// } -// -// return &dto.WorkSvPlenty{ -// WorkID: workID, -// Supervisors: resp, -// }, nil -//} +func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { + supervisorsData, err := service.workRepo.GetWorkSupervisors(workID) + if err != nil { + return nil, err + } + + var resp []*dto.WorkSv + + for _, db := range supervisorsData { + resp = append(resp, &dto.WorkSv{ + SvProfile: dto.SvProfile{ + Email: db.User.Email, + FirstName: db.User.FirstName, + LastName: db.User.LastName, + About: db.SupervisorFull.About, + Birthdate: misc.Date{Time: db.SupervisorFull.Birthdate}, + PhotoUrl: db.User.PhotoUrl, + Department: db.DepartmentID, + }, + IsHead: db.IsHead, + IsFull: db.IsFull, + }) + } + + return &dto.WorkSvPlenty{ + Supervisors: resp, + }, nil +} diff --git a/swagger/docs.go b/swagger/docs.go index 10a10b8..9e6c2cf 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -198,6 +198,39 @@ const docTemplate = `{ } } } + }, + "/api/v1/works/{work_id}/supervisors": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "works" + ], + "summary": "Get supervisors of the work", + "parameters": [ + { + "type": "integer", + "description": "Work ID", + "name": "work_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.WorkSvPlenty" + } + } + } + } } }, "definitions": { @@ -361,6 +394,49 @@ const docTemplate = `{ "$ref": "#/definitions/dto.SubjectResp" } } + }, + "dto.WorkSv": { + "type": "object", + "properties": { + "about": { + "type": "string" + }, + "avatarUrl": { + "type": "string" + }, + "birthdate": { + "type": "string" + }, + "department": { + "type": "string" + }, + "email": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "full": { + "type": "boolean" + }, + "head": { + "type": "boolean" + }, + "lastName": { + "type": "string" + } + } + }, + "dto.WorkSvPlenty": { + "type": "object", + "properties": { + "supervisors": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.WorkSv" + } + } + } } }, "securityDefinitions": { diff --git a/swagger/swagger.json b/swagger/swagger.json index f90ca47..e2390a1 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -194,6 +194,39 @@ } } } + }, + "/api/v1/works/{work_id}/supervisors": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "works" + ], + "summary": "Get supervisors of the work", + "parameters": [ + { + "type": "integer", + "description": "Work ID", + "name": "work_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.WorkSvPlenty" + } + } + } + } } }, "definitions": { @@ -357,6 +390,49 @@ "$ref": "#/definitions/dto.SubjectResp" } } + }, + "dto.WorkSv": { + "type": "object", + "properties": { + "about": { + "type": "string" + }, + "avatarUrl": { + "type": "string" + }, + "birthdate": { + "type": "string" + }, + "department": { + "type": "string" + }, + "email": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "full": { + "type": "boolean" + }, + "head": { + "type": "boolean" + }, + "lastName": { + "type": "string" + } + } + }, + "dto.WorkSvPlenty": { + "type": "object", + "properties": { + "supervisors": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.WorkSv" + } + } + } } }, "securityDefinitions": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index bbe3163..aa186f2 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -104,6 +104,34 @@ definitions: subject: $ref: '#/definitions/dto.SubjectResp' type: object + dto.WorkSv: + properties: + about: + type: string + avatarUrl: + type: string + birthdate: + type: string + department: + type: string + email: + type: string + firstName: + type: string + full: + type: boolean + head: + type: boolean + lastName: + type: string + type: object + dto.WorkSvPlenty: + properties: + supervisors: + items: + $ref: '#/definitions/dto.WorkSv' + type: array + type: object host: localhost:8080 info: contact: @@ -225,6 +253,26 @@ paths: summary: Get supervisor's works tags: - supervisor + /api/v1/works/{work_id}/supervisors: + get: + parameters: + - description: Work ID + in: path + name: work_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/dto.WorkSvPlenty' + security: + - OAuth2Password: [] + summary: Get supervisors of the work + tags: + - works schemes: - http securityDefinitions: From f92b4212421dffca48c3bed406eae03c06447964 Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Sun, 2 Oct 2022 17:46:17 +0300 Subject: [PATCH 07/12] upgrade: student's relation list was added --- internal/app/app.go | 3 +- internal/controller/http/interfaces.go | 12 +- internal/controller/http/router.go | 5 +- internal/controller/http/student.go | 59 +++++----- internal/controller/http/supervisor.go | 8 +- internal/dto/bid.go | 8 +- internal/dto/subject.go | 2 +- internal/entity/relation.go | 16 +-- internal/entity/supervisor.go | 2 +- internal/entity/work.go | 12 +- internal/service/bid.go | 49 +------- internal/service/interfaces.go | 3 +- internal/service/relation.go | 117 ++++++++++++++------ internal/service/repo_pg/relation.go | 96 +++++++++------- internal/service/work.go | 4 +- migrations/20220509200350_create_ssr.up.sql | 4 + swagger/docs.go | 67 +++++++++++ swagger/swagger.json | 67 +++++++++++ swagger/swagger.yaml | 42 +++++++ 19 files changed, 381 insertions(+), 195 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index b957ffa..9d227a2 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -31,7 +31,7 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, authService := service.NewAuth(userRepo, l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) profileService := service.NewProfile(studentRepo, supervisorRepo, l) - bidService := service.NewBid(relationRepo, l) + //bidService := service.NewBid(relationRepo, l) workService := service.NewWork(workRepo, relationRepo, studentRepo, l) relationService := service.NewRelation(relationRepo, l) feedbackService := service.NewFeedback(feedbackRepo, l) @@ -42,7 +42,6 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, cfg, authService, profileService, - bidService, workService, relationService, feedbackService, diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index 74d06c3..026a3df 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -15,17 +15,17 @@ type ( SvProfileService interface { GetSupervisorProfile(userID int) (*dto.SvProfile, error) } - StBidService interface { - GetStudentBids(studentID int) (*dto.StBids, error) - Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) + StRelationsService interface { + GetStudentRelations(studentID int) (*dto.StRelationPlenty, error) + //Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) } SvBidService interface { GetSupervisorBids(supervisorID int) (*dto.SvBids, error) Resolve(data *dto.ResolveBid) error } - StRelationService interface { - Create(data *dto.CreateSSR) (*dto.StViewRelation, error) - } + //StRelationService interface { + // Create(data *dto.CreateSSR) (*dto.StViewRelation, error) + //} WorkService interface { GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) diff --git a/internal/controller/http/router.go b/internal/controller/http/router.go index a48623e..831555e 100644 --- a/internal/controller/http/router.go +++ b/internal/controller/http/router.go @@ -14,9 +14,8 @@ func NewRouter( config *config.Config, auth AuthService, profiles ProfileService, - stBids StBidService, works WorkService, - stRelations StRelationService, + stRelations StRelationsService, feedback FeedbackService, ) { g := server.Group("/api/v1") @@ -24,7 +23,7 @@ func NewRouter( { NewAuthRoutes(g, l, auth) - NewStudentRoutes(g, l, config, profiles, stBids, works, stRelations, feedback) + NewStudentRoutes(g, l, config, profiles, works, stRelations, feedback) NewSupervisorRoutes(g, l, config, profiles, works) NewWorksRoutes(g, l, config, works) } diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index f9b27cf..ae93be7 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -10,12 +10,11 @@ import ( ) type student struct { - l logger.Interface - profileService ProfileService - bidService StBidService - workService WorkService - relationService StRelationService - feedbackService FeedbackService + l logger.Interface + profileService ProfileService + workService WorkService + relationsService StRelationsService + feedbackService FeedbackService } // ShowAccount godoc @@ -38,26 +37,6 @@ func (ctrl *student) getProfile(ctx echo.Context) error { return ctx.JSON(http.StatusOK, profileDTO) } -//// ShowAccount godoc -//// @Summary GetUserByEmail student's bids -//// @Tags student -//// @Produce json -//// @Param student_id path int true "Student ID" -//// @Success 200 {object} dto.StBids -//// @Failure 404 -//// @Router /api/students/{student_id}/bids [get] -//// @Security Authorization -//func (ctrl *student) getBids(ctx echo.Context) error { -// studentID, _ := strconv.Atoi(ctx.Param("student_id")) -// -// respDTO, err := ctrl.bidService.GetStudentBids(studentID) -// if err != nil { -// return echo.ErrNotFound -// } -// -// return ctx.JSON(http.StatusOK, respDTO) -//} - // ShowAccount godoc // @Summary Get student's works // @Tags student @@ -77,6 +56,26 @@ func (ctrl *student) getWorks(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } +// ShowAccount godoc +// @Summary Get student's bids +// @Tags student +// @Produce json +// @Param student_id path int true "Student ID" +// @Success 200 {object} dto.StRelationPlenty +// @Failure 404 +// @Router /api/v1/students/{student_id}/relations [get] +// @Security OAuth2Password +func (ctrl *student) getRelations(ctx echo.Context) error { + studentID, _ := strconv.Atoi(ctx.Param("student_id")) + + respDTO, err := ctrl.relationsService.GetStudentRelations(studentID) + if err != nil { + return echo.ErrNotFound + } + + return ctx.JSON(http.StatusOK, respDTO) +} + //// ShowAccount godoc //// @Summary Apply bid //// @Tags student @@ -95,7 +94,7 @@ func (ctrl *student) getWorks(ctx echo.Context) error { // return echo.ErrBadRequest // } // -// respDTO, err := ctrl.bidService.Apply(reqDTO) +// respDTO, err := ctrl.relationsService.Apply(reqDTO) // if err != nil { // return echo.ErrInternalServerError // } @@ -183,15 +182,13 @@ func NewStudentRoutes( l logger.Interface, config *config.Config, profileService ProfileService, - bidsService StBidService, worksService WorkService, - relationService StRelationService, + relationService StRelationsService, feedbackService FeedbackService, ) { ctrl := &student{ l, profileService, - bidsService, worksService, relationService, feedbackService, @@ -202,7 +199,7 @@ func NewStudentRoutes( { student.GET("/:student_id/profile", ctrl.getProfile) student.GET("/:student_id/works", ctrl.getWorks) - //student.GET("/bid", ctrl.getBids) + student.GET("/:student_id/relations", ctrl.getRelations) //student.PUT("/bid", ctrl.applyBid) //student.POST("/ssr", ctrl.createSSR) //student.GET("/work/supervisor_id", ctrl.getSupervisors) diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index 671d833..97c8133 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -12,7 +12,7 @@ import ( type supervisor struct { l logger.Interface profileService ProfileService - //bidService SvBidService + //relationsService SvBidService workService WorkService } @@ -71,7 +71,7 @@ func (ctrl *supervisor) getWorks(ctx echo.Context) error { // // supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) // -// respDTO, err := ctrl.bidService.GetSupervisorBids(supervisorID) +// respDTO, err := ctrl.relationsService.GetSupervisorBids(supervisorID) // if err != nil { // ctrl.l.Error(err) // return echo.NewHTTPError(http.StatusInternalServerError, "TODO") @@ -98,7 +98,7 @@ func (ctrl *supervisor) getWorks(ctx echo.Context) error { // return echo.ErrBadRequest // } // -// if err := ctrl.bidService.Resolve(reqDTO); err != nil { +// if err := ctrl.relationsService.Resolve(reqDTO); err != nil { // return echo.NewHTTPError(http.StatusInternalServerError) // } // @@ -118,7 +118,7 @@ func NewSupervisorRoutes( l logger.Interface, config *config.Config, profileService ProfileService, - // bidService SvBidService, + // relationsService SvBidService, workService WorkService, ) { ctrl := &supervisor{l, profileService, workService} diff --git a/internal/dto/bid.go b/internal/dto/bid.go index 691c737..3538a22 100644 --- a/internal/dto/bid.go +++ b/internal/dto/bid.go @@ -4,16 +4,16 @@ import ( "time" ) -type StBid struct { +type StRelationResp struct { BidID int `json:"id"` Status string `json:"status"` - CreatedAt time.Time `json:"createdAt"` + CreatedAt time.Time `json:"created_at"` Supervisor SvProfile `json:"supervisor"` Work WorkResp `json:"work"` } -type StBids struct { - Bids []*StBid `json:"bids"` +type StRelationPlenty struct { + Relations []*StRelationResp `json:"relations"` } type SvBid struct { diff --git a/internal/dto/subject.go b/internal/dto/subject.go index c922bba..258b5fe 100644 --- a/internal/dto/subject.go +++ b/internal/dto/subject.go @@ -1,7 +1,7 @@ package dto type SubjectResp struct { - SubjectID int `json:"id"` + ID int `json:"id"` Name string `json:"name"` Department string `json:"department"` } diff --git a/internal/entity/relation.go b/internal/entity/relation.go index 54df3c6..238e9ec 100644 --- a/internal/entity/relation.go +++ b/internal/entity/relation.go @@ -20,17 +20,17 @@ type WaypointRelation struct { } type StRelation struct { - BidID int `db:"ssr_id"` - CreatedAt time.Time `db:"created_at"` - Status string `db:"ssr_status"` - *SvProfile - *Work + RelationID int `db:"ssr_id"` + CreatedAt time.Time `db:"created_at"` + Status string `db:"status"` + SupervisorFull `db:"sv"` + Work `db:"work"` } type SvRelation struct { - BidID int `db:"ssr_id"` - CreatedAt time.Time `db:"created_at"` - Status string `db:"ssr_status"` + RelationID int `db:"ssr_id"` + CreatedAt time.Time `db:"created_at"` + Status string `db:"ssr_status"` *StProfile *Work } diff --git a/internal/entity/supervisor.go b/internal/entity/supervisor.go index ab9335b..ab275b0 100644 --- a/internal/entity/supervisor.go +++ b/internal/entity/supervisor.go @@ -10,7 +10,7 @@ type Supervisor struct { } type SupervisorFull struct { - User *User `db:"user"` + User User `db:"user"` Birthdate time.Time About string DepartmentID string `db:"department_id"` diff --git a/internal/entity/work.go b/internal/entity/work.go index 69c9fcd..524f2d7 100644 --- a/internal/entity/work.go +++ b/internal/entity/work.go @@ -6,21 +6,21 @@ type WorkKind struct { } type Work struct { - *WorkKind `db:"work_kind"` - *Subject `db:"subject"` + WorkKind `db:"work_kind"` + Subject `db:"subject"` WorkID int `db:"work_id"` Description string Semester int8 } type SvWork struct { - *Work + Work IsHead bool `db:"is_head"` IsFull bool `db:"is_full"` } type WorkSv struct { - *SupervisorFull `db:"sv"` - IsHead bool `db:"is_head"` - IsFull bool `db:"is_full"` + SupervisorFull `db:"sv"` + IsHead bool `db:"is_head"` + IsFull bool `db:"is_full"` } diff --git a/internal/service/bid.go b/internal/service/bid.go index 8d02d2a..9e4c594 100644 --- a/internal/service/bid.go +++ b/internal/service/bid.go @@ -4,7 +4,6 @@ import ( "ssr/internal/dto" "ssr/internal/entity" "ssr/pkg/logger" - "ssr/pkg/misc" ) type Bid struct { @@ -19,50 +18,6 @@ func NewBid(r RelationRepo, l logger.Interface) *Bid { } } -func (service *Bid) GetStudentBids(studentID int) (*dto.StBids, error) { - dbData, err := service.repo.GetStudentBids(studentID) - if err != nil { - return nil, err - } - - var resp []*dto.StBid - - for _, db := range dbData { - resp = append(resp, &dto.StBid{ - BidID: db.BidID, - Status: db.Status, - CreatedAt: db.CreatedAt, - Supervisor: dto.SvProfile{ - Email: db.Email, - FirstName: db.FirstName, - LastName: db.LastName, - About: db.About, - Birthdate: misc.Date{ - Time: db.Birthdate, - }, - PhotoUrl: db.PhotoUrl, - Department: db.SvProfile.DepartmentID, - }, - Work: dto.WorkResp{ - WorkID: db.WorkID, - Description: db.Work.Description, - Semester: db.Work.Semester, - Kind: dto.WorkKindResp{ - ID: db.WorkKind.WorkKindID, - Name: db.WorkKind.Name, - }, - Subject: dto.SubjectResp{ - SubjectID: db.SubjectID, - Name: db.Subject.Name, - Department: db.Subject.DepartmentID, - }, - }, - }) - } - - return &dto.StBids{Bids: resp}, nil -} - func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { dbData, err := service.repo.GetSupervisorBids(supervisorID) if err != nil { @@ -73,7 +28,7 @@ func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { for _, db := range dbData { resp = append(resp, &dto.SvBid{ - BidID: db.BidID, + BidID: db.RelationID, Status: db.Status, CreatedAt: db.CreatedAt, Student: dto.StProfile{ @@ -92,7 +47,7 @@ func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { Name: db.WorkKind.Name, }, Subject: dto.SubjectResp{ - SubjectID: db.SubjectID, + ID: db.SubjectID, Name: db.Subject.Name, Department: db.Subject.DepartmentID, }, diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index df09f4d..9bf6e1d 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -21,9 +21,8 @@ type ( } RelationRepo interface { Create(studentID, supervisorID, workID int) (int, error) - GetStudentBids(studentID int) ([]*entity.StRelation, error) - GetSupervisorBids(studentID int) ([]*entity.SvRelation, error) GetStudentRelations(studentID int) ([]*entity.StRelation, error) + GetSupervisorBids(studentID int) ([]*entity.SvRelation, error) GetStudentRelation(studentID, ssrID int) (*entity.StRelation, error) UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) } diff --git a/internal/service/relation.go b/internal/service/relation.go index dd80524..7a4e780 100644 --- a/internal/service/relation.go +++ b/internal/service/relation.go @@ -18,6 +18,50 @@ func NewRelation(r RelationRepo, l logger.Interface) *Relation { } } +func (service *Relation) GetStudentRelations(studentID int) (*dto.StRelationPlenty, error) { + dbData, err := service.repo.GetStudentRelations(studentID) + if err != nil { + return nil, err + } + + var resp []*dto.StRelationResp + + for _, db := range dbData { + resp = append(resp, &dto.StRelationResp{ + BidID: db.RelationID, + Status: db.Status, + CreatedAt: db.CreatedAt, + Supervisor: dto.SvProfile{ + Email: db.User.Email, + FirstName: db.User.FirstName, + LastName: db.User.LastName, + About: db.SupervisorFull.About, + Birthdate: misc.Date{ + Time: db.Birthdate, + }, + PhotoUrl: db.User.PhotoUrl, + Department: db.SupervisorFull.DepartmentID, + }, + Work: dto.WorkResp{ + WorkID: db.WorkID, + Description: db.Work.Description, + Semester: db.Work.Semester, + Kind: dto.WorkKindResp{ + ID: db.WorkKind.WorkKindID, + Name: db.WorkKind.Name, + }, + Subject: dto.SubjectResp{ + ID: db.SubjectID, + Name: db.Subject.Name, + Department: db.Subject.DepartmentID, + }, + }, + }) + } + + return &dto.StRelationPlenty{Relations: resp}, nil +} + func (service *Relation) CheckIfStudentBeginWork(studentID, workID int) (bool, error) { relations, err := service.repo.GetStudentRelations(studentID) if err != nil { @@ -33,39 +77,40 @@ func (service *Relation) CheckIfStudentBeginWork(studentID, workID int) (bool, e return false, nil } -func (service *Relation) Create(data *dto.CreateSSR) (*dto.StViewRelation, error) { - ssrID, err := service.repo.UpdateStatus(data.BidID, "wip") - if err != nil { - return nil, err - } - - ssr, err := service.repo.GetStudentRelation(data.StudentID, ssrID) - if err != nil { - return nil, err - } - - return &dto.StViewRelation{ - RelID: ssr.BidID, - Status: ssr.Status, - CreatedAt: ssr.CreatedAt, - Supervisor: dto.SvProfile{ - Email: ssr.SvProfile.Email, - FirstName: ssr.SvProfile.FirstName, - LastName: ssr.SvProfile.LastName, - About: ssr.SvProfile.About, - Birthdate: misc.Date{Time: ssr.Birthdate}, - PhotoUrl: ssr.PhotoUrl, - Department: ssr.DepartmentID, - }, - Work: dto.WorkResp{ - WorkID: ssr.WorkID, - Description: ssr.Work.Description, - Semester: ssr.Work.Semester, - Subject: dto.SubjectResp{ - SubjectID: ssr.SubjectID, - Name: ssr.Subject.Name, - Department: ssr.DepartmentID, - }, - }, - }, nil -} +// +//func (service *Relation) Create(data *dto.CreateSSR) (*dto.StViewRelation, error) { +// ssrID, err := service.repo.UpdateStatus(data.BidID, "wip") +// if err != nil { +// return nil, err +// } +// +// ssr, err := service.repo.GetStudentRelation(data.StudentID, ssrID) +// if err != nil { +// return nil, err +// } +// +// return &dto.StViewRelation{ +// RelID: ssr.RelationID, +// Status: ssr.Status, +// CreatedAt: ssr.CreatedAt, +// Supervisor: dto.SvProfile{ +// Email: ssr.SvProfile.Email, +// FirstName: ssr.SvProfile.FirstName, +// LastName: ssr.SvProfile.LastName, +// About: ssr.SvProfile.About, +// Birthdate: misc.Date{Time: ssr.Birthdate}, +// PhotoUrl: ssr.PhotoUrl, +// Department: ssr.DepartmentID, +// }, +// Work: dto.WorkResp{ +// WorkID: ssr.WorkID, +// Description: ssr.Work.Description, +// Semester: ssr.Work.Semester, +// Subject: dto.SubjectResp{ +// ID: ssr.ID, +// Name: ssr.Subject.Name, +// Department: ssr.DepartmentID, +// }, +// }, +// }, nil +//} diff --git a/internal/service/repo_pg/relation.go b/internal/service/repo_pg/relation.go index 9b75109..394c0c1 100644 --- a/internal/service/repo_pg/relation.go +++ b/internal/service/repo_pg/relation.go @@ -49,65 +49,42 @@ func (repo *Relation) GetStudentRelation(studentID, ssrID int) (*entity.StRelati return &ssr, nil } -func (repo *Relation) GetStudentBids(studentID int) ([]*entity.StRelation, error) { - query := ` - select - ssr.ssr_id, - ssr.status as ssr_status, - ssr.created_at, - sv.*, - u.*, - w.*, - wk.name as work_kind_name, - subj.name as subject_name, - subj.department_id as subject_department_id - from ssr - join supervisors sv using (supervisor_id) - join users u using (user_id) - join works w using (work_id) - join work_kinds wk using (work_kind_id) - join subjects subj using (subject_id) - where ssr.status in ('pending','rejected', 'cancelled','accepted') and ssr.student_id = $1; - ` - - var bids []*entity.StRelation - - err := repo.Conn.Select(&bids, query, studentID) - if err != nil { - err := fmt.Errorf("Relation->GetStudentBids->repo.Conn.Select: %w", err) - repo.l.Error(err) - return nil, err - } - - return bids, nil -} - func (repo *Relation) GetStudentRelations(studentID int) ([]*entity.StRelation, error) { query := ` select ssr.ssr_id, - ssr.status as ssr_status, + ssr.status, ssr.created_at, - sv.*, - u.*, - w.*, - wk.name as work_kind_name, - subj.name as subject_name, - subj.department_id as subject_department_id + sv.birthdate as "sv.birthdate", + sv.about as "sv.about", + sv.department_id as "sv.department_id", + u.email as "sv.user.email", + u.first_name as "sv.user.first_name", + u.last_name as "sv.user.last_name", + u.photo_url as "sv.user.photo_url", + u.user_id as "sv.user.user_id", + w.semester as "work.semester", + w.description as "work.description", + w.work_id as "work.work_id", + wk.name as "work.work_kind.name", + wk.work_kind_id as "work.work_kind.work_kind_id", + subj.subject_id as "work.subject.subject_id", + subj.name as "work.subject.name", + subj.department_id as "work.subject.department_id" from ssr - join supervisors sv using (supervisor_id) + join supervisors sv on ssr.supervisor_id = sv.user_id join users u using (user_id) join works w using (work_id) join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) - where ssr.status in ('wip', 'done') and ssr.student_id = $1; + where ssr.student_id = $1; ` var bids []*entity.StRelation err := repo.Conn.Select(&bids, query, studentID) if err != nil { - err := fmt.Errorf("Relation->GetStudentBids->repo.Conn.Select: %w", err) + err := fmt.Errorf("Relation->GetStudentRelations->repo.Conn.Select: %w", err) repo.l.Error(err) return nil, err } @@ -115,6 +92,39 @@ func (repo *Relation) GetStudentRelations(studentID int) ([]*entity.StRelation, return bids, nil } +//func (repo *Relation) GetStudentRelations(studentID int) ([]*entity.StRelation, error) { +// query := ` +// select +// ssr.ssr_id, +// ssr.status as ssr_status, +// ssr.created_at, +// sv.*, +// u.*, +// w.*, +// wk.name as work_kind_name, +// subj.name as subject_name, +// subj.department_id as subject_department_id +// from ssr +// join supervisors sv using (supervisor_id) +// join users u using (user_id) +// join works w using (work_id) +// join work_kinds wk using (work_kind_id) +// join subjects subj using (subject_id) +// where ssr.status in ('wip', 'done') and ssr.student_id = $1; +// ` +// +// var bids []*entity.StRelation +// +// err := repo.Conn.Select(&bids, query, studentID) +// if err != nil { +// err := fmt.Errorf("Relation->GetStudentRelations->repo.Conn.Select: %w", err) +// repo.l.Error(err) +// return nil, err +// } +// +// return bids, nil +//} + func (repo *Relation) GetSupervisorBids(supervisorID int) ([]*entity.SvRelation, error) { query := ` select diff --git a/internal/service/work.go b/internal/service/work.go index b3c64cd..5386348 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -70,10 +70,12 @@ func (service *Work) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { Description: work.Description, Semester: work.Semester, Subject: dto.SubjectResp{ + ID: work.Subject.SubjectID, Name: work.Subject.Name, Department: work.Subject.DepartmentID, }, Kind: dto.WorkKindResp{ + ID: work.WorkKind.WorkKindID, Name: work.WorkKind.Name, }, //IsStarted: service.checkIfBegin(relations, work.WorkID), TODO @@ -101,7 +103,7 @@ func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, er Description: db.Description, Semester: db.Semester, Subject: dto.SubjectResp{ - SubjectID: db.Subject.SubjectID, + ID: db.Subject.SubjectID, Name: db.Subject.Name, Department: db.Subject.DepartmentID, }, diff --git a/migrations/20220509200350_create_ssr.up.sql b/migrations/20220509200350_create_ssr.up.sql index cd3cf35..95de616 100644 --- a/migrations/20220509200350_create_ssr.up.sql +++ b/migrations/20220509200350_create_ssr.up.sql @@ -28,3 +28,7 @@ ALTER TABLE "ssr" CREATE INDEX ON "ssr" (status, supervisor_id); CREATE INDEX ON "ssr" (status, student_id); CREATE INDEX ON "ssr" (status, work_id); + + +insert into ssr(status, created_at, supervisor_id, work_id, student_id) + VALUES ('pending', '2022-09-01', 2, 1, 1) diff --git a/swagger/docs.go b/swagger/docs.go index 9e6c2cf..a6d0e0c 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -100,6 +100,42 @@ const docTemplate = `{ } } }, + "/api/v1/students/{student_id}/relations": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "student" + ], + "summary": "Get student's bids", + "parameters": [ + { + "type": "integer", + "description": "Student ID", + "name": "student_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.StRelationPlenty" + } + }, + "404": { + "description": "Not Found" + } + } + } + }, "/api/v1/students/{student_id}/works": { "get": { "security": [ @@ -277,6 +313,37 @@ const docTemplate = `{ } } }, + "dto.StRelationPlenty": { + "type": "object", + "properties": { + "relations": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.StRelationResp" + } + } + } + }, + "dto.StRelationResp": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "status": { + "type": "string" + }, + "supervisor": { + "$ref": "#/definitions/dto.SvProfile" + }, + "work": { + "$ref": "#/definitions/dto.WorkResp" + } + } + }, "dto.StWorkPlenty": { "type": "object", "properties": { diff --git a/swagger/swagger.json b/swagger/swagger.json index e2390a1..b2e021c 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -96,6 +96,42 @@ } } }, + "/api/v1/students/{student_id}/relations": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "student" + ], + "summary": "Get student's bids", + "parameters": [ + { + "type": "integer", + "description": "Student ID", + "name": "student_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.StRelationPlenty" + } + }, + "404": { + "description": "Not Found" + } + } + } + }, "/api/v1/students/{student_id}/works": { "get": { "security": [ @@ -273,6 +309,37 @@ } } }, + "dto.StRelationPlenty": { + "type": "object", + "properties": { + "relations": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.StRelationResp" + } + } + } + }, + "dto.StRelationResp": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "status": { + "type": "string" + }, + "supervisor": { + "$ref": "#/definitions/dto.SvProfile" + }, + "work": { + "$ref": "#/definitions/dto.WorkResp" + } + } + }, "dto.StWorkPlenty": { "type": "object", "properties": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index aa186f2..5581738 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -28,6 +28,26 @@ definitions: year: type: integer type: object + dto.StRelationPlenty: + properties: + relations: + items: + $ref: '#/definitions/dto.StRelationResp' + type: array + type: object + dto.StRelationResp: + properties: + created_at: + type: string + id: + type: integer + status: + type: string + supervisor: + $ref: '#/definitions/dto.SvProfile' + work: + $ref: '#/definitions/dto.WorkResp' + type: object dto.StWorkPlenty: properties: works: @@ -193,6 +213,28 @@ paths: summary: Get student's profile tags: - student + /api/v1/students/{student_id}/relations: + get: + parameters: + - description: Student ID + in: path + name: student_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/dto.StRelationPlenty' + "404": + description: Not Found + security: + - OAuth2Password: [] + summary: Get student's bids + tags: + - student /api/v1/students/{student_id}/works: get: parameters: From 794fdf0f1b2c6f7ac31ee949d75d88f31178812f Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Sun, 2 Oct 2022 21:36:24 +0300 Subject: [PATCH 08/12] upgrade: relation creation working now --- internal/controller/http/interfaces.go | 11 ++--- internal/controller/http/relation.go | 58 ++++++++++++++++++++++++ internal/controller/http/router.go | 5 ++- internal/controller/http/student.go | 32 ++------------ internal/dto/bid.go | 12 ++--- internal/dto/work.go | 2 +- internal/service/bid.go | 43 +++++++++--------- internal/service/relation.go | 14 ++++-- internal/service/repo_pg/feedback.go | 2 +- internal/service/repo_pg/relation.go | 8 ++-- internal/service/repo_pg/user.go | 2 +- swagger/docs.go | 61 ++++++++++++++++++++++++++ swagger/swagger.json | 61 ++++++++++++++++++++++++++ swagger/swagger.yaml | 38 ++++++++++++++++ 14 files changed, 273 insertions(+), 76 deletions(-) create mode 100644 internal/controller/http/relation.go diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index 026a3df..0d12b1c 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -15,17 +15,14 @@ type ( SvProfileService interface { GetSupervisorProfile(userID int) (*dto.SvProfile, error) } - StRelationsService interface { - GetStudentRelations(studentID int) (*dto.StRelationPlenty, error) - //Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) - } SvBidService interface { GetSupervisorBids(supervisorID int) (*dto.SvBids, error) Resolve(data *dto.ResolveBid) error } - //StRelationService interface { - // Create(data *dto.CreateSSR) (*dto.StViewRelation, error) - //} + RelationsService interface { + GetStudentRelations(studentID int) (*dto.StRelationPlenty, error) + Create(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) + } WorkService interface { GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) diff --git a/internal/controller/http/relation.go b/internal/controller/http/relation.go new file mode 100644 index 0000000..cbaeec9 --- /dev/null +++ b/internal/controller/http/relation.go @@ -0,0 +1,58 @@ +package http + +import ( + "github.com/labstack/echo/v4" + "net/http" + "ssr/config" + "ssr/internal/controller/http/middlewares" + "ssr/internal/dto" + "ssr/pkg/logger" +) + +type relation struct { + l logger.Interface + relationService RelationsService +} + +// ShowAccount godoc +// @Summary Create relation +// @Tags relation +// @Accept json +// @Param CreateRelation body dto.RelationCreateReq true "Relation data" +// @Produce json +// @Success 200 {object} dto.RelationCreateResp +// @Router /api/v1/relations/ [post] +// @Security OAuth2Password +func (ctrl *relation) create(ctx echo.Context) error { + reqDTO := &dto.RelationCreateReq{} + + if err := ctx.Bind(reqDTO); err != nil { + return echo.ErrBadRequest + } + + respDTO, err := ctrl.relationService.Create(reqDTO) + if err != nil { + return echo.ErrInternalServerError + } + + return ctx.JSON(http.StatusCreated, respDTO) +} + +func NewRelationRoutes( + router *echo.Group, + l logger.Interface, + config *config.Config, + relationsService RelationsService, +) { + ctrl := &relation{ + l, + relationsService, + } + + relations := router.Group("/relations", middlewares.MakeAuthMiddleware(config)) + + { + relations.POST("/", ctrl.create) + } + +} diff --git a/internal/controller/http/router.go b/internal/controller/http/router.go index 831555e..bc86443 100644 --- a/internal/controller/http/router.go +++ b/internal/controller/http/router.go @@ -15,7 +15,7 @@ func NewRouter( auth AuthService, profiles ProfileService, works WorkService, - stRelations StRelationsService, + relations RelationsService, feedback FeedbackService, ) { g := server.Group("/api/v1") @@ -23,8 +23,9 @@ func NewRouter( { NewAuthRoutes(g, l, auth) - NewStudentRoutes(g, l, config, profiles, works, stRelations, feedback) + NewStudentRoutes(g, l, config, profiles, works, relations, feedback) NewSupervisorRoutes(g, l, config, profiles, works) NewWorksRoutes(g, l, config, works) + NewRelationRoutes(g, l, config, relations) } } diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index ae93be7..33bbe51 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -13,7 +13,7 @@ type student struct { l logger.Interface profileService ProfileService workService WorkService - relationsService StRelationsService + relationsService RelationsService feedbackService FeedbackService } @@ -76,32 +76,6 @@ func (ctrl *student) getRelations(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -//// ShowAccount godoc -//// @Summary Apply bid -//// @Tags student -//// @Accept json -//// @Param ApplyBid body dto.ApplyBid true "bid info" -//// @Produce json -//// @Success 200 {object} dto.ApplyBidResp -//// @Router /api/student/bid [put] -//// @Security Auth -//func (ctrl *student) applyBid(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// reqDTO := &dto.ApplyBid{} -// if err := ctx.Bind(reqDTO); err != nil { -// return echo.ErrBadRequest -// } -// -// respDTO, err := ctrl.relationsService.Apply(reqDTO) -// if err != nil { -// return echo.ErrInternalServerError -// } -// -// return ctx.JSON(http.StatusCreated, respDTO) -//} - //// ShowAccount godoc //// @Summary Start SSR //// @Tags student @@ -120,7 +94,7 @@ func (ctrl *student) getRelations(ctx echo.Context) error { // return echo.ErrBadRequest // } // -// respDTO, err := ctrl.relationService.Create(reqDTO) +// respDTO, err := ctrl.relationService.Accept(reqDTO) // if err != nil { // return echo.ErrInternalServerError // } @@ -183,7 +157,7 @@ func NewStudentRoutes( config *config.Config, profileService ProfileService, worksService WorkService, - relationService StRelationsService, + relationService RelationsService, feedbackService FeedbackService, ) { ctrl := &student{ diff --git a/internal/dto/bid.go b/internal/dto/bid.go index 3538a22..b0ef9a1 100644 --- a/internal/dto/bid.go +++ b/internal/dto/bid.go @@ -28,14 +28,14 @@ type SvBids struct { Bids []*SvBid `json:"bids"` } -type ApplyBid struct { - StudentID int `json:"studentID"` - SupervisorID int `json:"supervisorID"` - WorkID int `json:"workID"` +type RelationCreateReq struct { + StudentID int `json:"student_id"` + SupervisorID int `json:"supervisor_id"` + WorkID int `json:"work_id"` } -type ApplyBidResp struct { - BidID int `json:"bidID"` +type RelationCreateResp struct { + RelationID int `json:"relation_id"` } type ResolveBid struct { diff --git a/internal/dto/work.go b/internal/dto/work.go index 0206005..015003a 100644 --- a/internal/dto/work.go +++ b/internal/dto/work.go @@ -15,7 +15,7 @@ type WorkResp struct { type StWorkResp struct { Work WorkResp `json:"work"` - IsStarted bool `json:"is_started"` + IsStarted bool `json:"is_started"` // TODO } type StWorkPlenty struct { diff --git a/internal/service/bid.go b/internal/service/bid.go index 9e4c594..e1d3804 100644 --- a/internal/service/bid.go +++ b/internal/service/bid.go @@ -2,7 +2,6 @@ package service import ( "ssr/internal/dto" - "ssr/internal/entity" "ssr/pkg/logger" ) @@ -58,24 +57,24 @@ func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { return &dto.SvBids{Bids: resp}, nil } -func (service *Bid) Apply(data *dto.ApplyBid) (*dto.ApplyBidResp, error) { - bidID, err := service.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) - if err != nil { - return nil, err - } - - return &dto.ApplyBidResp{BidID: bidID}, nil -} - -func (service *Bid) Resolve(data *dto.ResolveBid) error { - var status entity.StatusSSR - - if data.Accept { - status = "accepted" - } else { - status = "rejected" - } - - _, err := service.repo.UpdateStatus(data.BidID, status) - return err -} +//func (service *Bid) Apply(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) { +// bidID, err := service.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) +// if err != nil { +// return nil, err +// } +// +// return &dto.RelationCreateResp{BidID: bidID}, nil +//} +// +//func (service *Bid) Resolve(data *dto.ResolveBid) error { +// var status entity.StatusSSR +// +// if data.Accept { +// status = "accepted" +// } else { +// status = "rejected" +// } +// +// _, err := service.repo.UpdateStatus(data.BidID, status) +// return err +//} diff --git a/internal/service/relation.go b/internal/service/relation.go index 7a4e780..7beb08b 100644 --- a/internal/service/relation.go +++ b/internal/service/relation.go @@ -77,8 +77,16 @@ func (service *Relation) CheckIfStudentBeginWork(studentID, workID int) (bool, e return false, nil } -// -//func (service *Relation) Create(data *dto.CreateSSR) (*dto.StViewRelation, error) { +func (service *Relation) Create(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) { + relationID, err := service.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) + if err != nil { + return nil, err + } + + return &dto.RelationCreateResp{RelationID: relationID}, nil +} + +//func (service *Relation) Accept(data *dto.CreateSSR) (*dto.StViewRelation, error) { // ssrID, err := service.repo.UpdateStatus(data.BidID, "wip") // if err != nil { // return nil, err @@ -107,7 +115,7 @@ func (service *Relation) CheckIfStudentBeginWork(studentID, workID int) (bool, e // Description: ssr.Work.Description, // Semester: ssr.Work.Semester, // Subject: dto.SubjectResp{ -// ID: ssr.ID, +// ID: ssr.ID, // Name: ssr.Subject.Name, // Department: ssr.DepartmentID, // }, diff --git a/internal/service/repo_pg/feedback.go b/internal/service/repo_pg/feedback.go index 9bd41e1..e6c4156 100644 --- a/internal/service/repo_pg/feedback.go +++ b/internal/service/repo_pg/feedback.go @@ -27,7 +27,7 @@ func (f *Feedback) Create(studentID, supervisorID, workID int, content string) ( var feedbackID int err := f.Conn.QueryRowx(query, studentID, supervisorID, workID, content).Scan(&feedbackID) if err != nil { - err := fmt.Errorf("repo_pg.Feedback->Create->r.Conn.QueryRowx: %w", err) + err := fmt.Errorf("repo_pg.Feedback->Accept->r.Conn.QueryRowx: %w", err) f.l.Error(err) return 0, err } diff --git a/internal/service/repo_pg/relation.go b/internal/service/repo_pg/relation.go index 394c0c1..8e7b1e6 100644 --- a/internal/service/repo_pg/relation.go +++ b/internal/service/repo_pg/relation.go @@ -165,15 +165,15 @@ func (repo *Relation) Create(studentID, supervisorID, workID int) (int, error) { returning ssr_id; ` - var bidID int - err := repo.Conn.QueryRowx(query, studentID, supervisorID, workID).Scan(&bidID) + var relationID int + err := repo.Conn.QueryRowx(query, studentID, supervisorID, workID).Scan(&relationID) if err != nil { - err := fmt.Errorf("Relation->Create->repo.Conn.QueryRowx: %w", err) + err := fmt.Errorf("RelationRepo->Create->repo.Conn.QueryRowx: %w", err) repo.l.Error(err) return 0, err } - return bidID, nil + return relationID, nil } func (repo *Relation) UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) { diff --git a/internal/service/repo_pg/user.go b/internal/service/repo_pg/user.go index 3ae9fc9..bdbae3d 100644 --- a/internal/service/repo_pg/user.go +++ b/internal/service/repo_pg/user.go @@ -28,7 +28,7 @@ func (r *User) CreateUser(email, password, firstName, lastName, photoUrl string, fmt.Println(res) //TODO if err != nil { - err := fmt.Errorf("Auth->Create->repo.Conn.Exec: %w", err) + err := fmt.Errorf("Auth->Accept->repo.Conn.Exec: %w", err) r.l.Error(err) // TODO return err } diff --git a/swagger/docs.go b/swagger/docs.go index a6d0e0c..d917416 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -64,6 +64,44 @@ const docTemplate = `{ } } }, + "/api/v1/relations/": { + "post": { + "security": [ + { + "OAuth2Password": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "relation" + ], + "summary": "Create relation", + "parameters": [ + { + "description": "Relation data", + "name": "CreateRelation", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/dto.RelationCreateReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.RelationCreateResp" + } + } + } + } + }, "/api/v1/students/{student_id}/profile": { "get": { "security": [ @@ -287,6 +325,28 @@ const docTemplate = `{ } } }, + "dto.RelationCreateReq": { + "type": "object", + "properties": { + "student_id": { + "type": "integer" + }, + "supervisor_id": { + "type": "integer" + }, + "work_id": { + "type": "integer" + } + } + }, + "dto.RelationCreateResp": { + "type": "object", + "properties": { + "relation_id": { + "type": "integer" + } + } + }, "dto.StProfile": { "type": "object", "properties": { @@ -359,6 +419,7 @@ const docTemplate = `{ "type": "object", "properties": { "is_started": { + "description": "TODO", "type": "boolean" }, "work": { diff --git a/swagger/swagger.json b/swagger/swagger.json index b2e021c..673765b 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -60,6 +60,44 @@ } } }, + "/api/v1/relations/": { + "post": { + "security": [ + { + "OAuth2Password": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "relation" + ], + "summary": "Create relation", + "parameters": [ + { + "description": "Relation data", + "name": "CreateRelation", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/dto.RelationCreateReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.RelationCreateResp" + } + } + } + } + }, "/api/v1/students/{student_id}/profile": { "get": { "security": [ @@ -283,6 +321,28 @@ } } }, + "dto.RelationCreateReq": { + "type": "object", + "properties": { + "student_id": { + "type": "integer" + }, + "supervisor_id": { + "type": "integer" + }, + "work_id": { + "type": "integer" + } + } + }, + "dto.RelationCreateResp": { + "type": "object", + "properties": { + "relation_id": { + "type": "integer" + } + } + }, "dto.StProfile": { "type": "object", "properties": { @@ -355,6 +415,7 @@ "type": "object", "properties": { "is_started": { + "description": "TODO", "type": "boolean" }, "work": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index 5581738..d94b92d 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -11,6 +11,20 @@ definitions: user_id: type: integer type: object + dto.RelationCreateReq: + properties: + student_id: + type: integer + supervisor_id: + type: integer + work_id: + type: integer + type: object + dto.RelationCreateResp: + properties: + relation_id: + type: integer + type: object dto.StProfile: properties: department: @@ -58,6 +72,7 @@ definitions: dto.StWorkResp: properties: is_started: + description: TODO type: boolean work: $ref: '#/definitions/dto.WorkResp' @@ -191,6 +206,29 @@ paths: summary: Login into account tags: - auth + /api/v1/relations/: + post: + consumes: + - application/json + parameters: + - description: Relation data + in: body + name: CreateRelation + required: true + schema: + $ref: '#/definitions/dto.RelationCreateReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/dto.RelationCreateResp' + security: + - OAuth2Password: [] + summary: Create relation + tags: + - relation /api/v1/students/{student_id}/profile: get: parameters: From bc36c0a776ceab3b5843966acde33eea134b5640 Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Mon, 3 Oct 2022 08:55:44 +0300 Subject: [PATCH 09/12] upgrade: short versions were added and refactoring for reduce size of dtos --- internal/controller/http/auth.go | 4 +- internal/controller/http/interfaces.go | 21 +- internal/controller/http/relation.go | 63 ++++- internal/controller/http/student.go | 26 +- internal/controller/http/supervisor.go | 6 +- internal/controller/http/works.go | 2 +- internal/dto/bid.go | 49 ---- internal/dto/profile.go | 32 --- internal/dto/relation.go | 16 -- internal/dto/relations.go | 40 +++ internal/dto/students.go | 18 ++ internal/dto/{subject.go => subjects.go} | 0 internal/dto/supervisors.go | 30 +++ internal/dto/work.go | 43 ---- internal/dto/work_kinds.go | 6 + internal/dto/works_common.go | 15 ++ internal/dto/works_student_view.go | 14 ++ internal/dto/works_supervisor_view.go | 17 ++ internal/entity/relation.go | 37 +-- internal/entity/student.go | 9 +- internal/entity/supervisor.go | 10 +- internal/entity/user.go | 16 +- internal/entity/work.go | 6 +- internal/service/bid.go | 135 +++++----- internal/service/interfaces.go | 15 +- internal/service/profile.go | 10 +- internal/service/relation.go | 156 ++++++++---- internal/service/repo_pg/relation.go | 201 ++++++++------- internal/service/repo_pg/student.go | 18 +- internal/service/repo_pg/supervisor.go | 12 +- internal/service/repo_pg/user.go | 12 +- internal/service/work.go | 72 +++--- swagger/docs.go | 298 ++++++++++++++++------- swagger/swagger.json | 298 ++++++++++++++++------- swagger/swagger.yaml | 231 ++++++++++++------ 35 files changed, 1187 insertions(+), 751 deletions(-) delete mode 100644 internal/dto/bid.go delete mode 100644 internal/dto/profile.go delete mode 100644 internal/dto/relation.go create mode 100644 internal/dto/relations.go create mode 100644 internal/dto/students.go rename internal/dto/{subject.go => subjects.go} (100%) create mode 100644 internal/dto/supervisors.go delete mode 100644 internal/dto/work.go create mode 100644 internal/dto/work_kinds.go create mode 100644 internal/dto/works_common.go create mode 100644 internal/dto/works_student_view.go create mode 100644 internal/dto/works_supervisor_view.go diff --git a/internal/controller/http/auth.go b/internal/controller/http/auth.go index 374f327..4373510 100644 --- a/internal/controller/http/auth.go +++ b/internal/controller/http/auth.go @@ -17,8 +17,8 @@ type auth struct { // @Tags auth // @Accept x-www-form-urlencoded // @Produce json -// @Param username formData string true "User email" -// @Param password formData string true "User password" +// @Param username formData string true "UserFull email" +// @Param password formData string true "UserFull password" // @Success 200 {object} dto.LoginResponse // @Failure 401 // @Failure 500 diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index 0d12b1c..8765e27 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -9,24 +9,19 @@ type ( Login(email, password string) (*dto.LoginResponse, error) } ProfileService interface { - GetStudentProfile(userID int) (*dto.StProfile, error) - GetSupervisorProfile(userID int) (*dto.SvProfile, error) - } - SvProfileService interface { - GetSupervisorProfile(userID int) (*dto.SvProfile, error) - } - SvBidService interface { - GetSupervisorBids(supervisorID int) (*dto.SvBids, error) - Resolve(data *dto.ResolveBid) error + GetStudentProfile(userID int) (*dto.Student, error) + GetSupervisorProfile(userID int) (*dto.Supervisor, error) } RelationsService interface { - GetStudentRelations(studentID int) (*dto.StRelationPlenty, error) + GetPlenty(studentID, supervisorID int) (*dto.RelationPlenty, error) Create(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) + Update(data *dto.RelationUpdateReq) (*dto.RelationResp, error) + Get(RelationID int) (*dto.RelationResp, error) } WorkService interface { - GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) - GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) - GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) + GetStudentWorks(studentID int) (*dto.StudentViewWorkPlenty, error) + GetSupervisorWorks(supervisorID int) (*dto.SupervisorViewWorkPlenty, error) + GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error) } FeedbackService interface { Add(data *dto.FeedbackReq) (int, error) diff --git a/internal/controller/http/relation.go b/internal/controller/http/relation.go index cbaeec9..2efac99 100644 --- a/internal/controller/http/relation.go +++ b/internal/controller/http/relation.go @@ -7,6 +7,7 @@ import ( "ssr/internal/controller/http/middlewares" "ssr/internal/dto" "ssr/pkg/logger" + "strconv" ) type relation struct { @@ -20,7 +21,7 @@ type relation struct { // @Accept json // @Param CreateRelation body dto.RelationCreateReq true "Relation data" // @Produce json -// @Success 200 {object} dto.RelationCreateResp +// @Success 201 {object} dto.RelationCreateResp // @Router /api/v1/relations/ [post] // @Security OAuth2Password func (ctrl *relation) create(ctx echo.Context) error { @@ -38,6 +39,64 @@ func (ctrl *relation) create(ctx echo.Context) error { return ctx.JSON(http.StatusCreated, respDTO) } +// ShowAccount godoc +// @Summary Update relation +// @Tags relation +// @Accept json +// @Param CreateRelation body dto.RelationUpdateReq true "Relation data" +// @Produce json +// @Success 200 {object} dto.RelationResp +// @Router /api/v1/relations/ [patch] +// @Security OAuth2Password +func (ctrl *relation) update(ctx echo.Context) error { + reqDTO := &dto.RelationUpdateReq{} + + if err := ctx.Bind(reqDTO); err != nil { + return echo.ErrBadRequest + } + + respDTO, err := ctrl.relationService.Update(reqDTO) + if err != nil { + return echo.ErrInternalServerError + } + + return ctx.JSON(http.StatusCreated, respDTO) +} + +// ShowAccount godoc +// @Summary Get relations +// @Tags relation +// @Produce json +// @Param student_id query int false "Student ID" +// @Param supervisor_id query int false "Supervisor ID" +// @Success 200 {object} dto.RelationPlenty +// @Failure 404 +// @Router /api/v1/relations/ [get] +// @Security OAuth2Password +func (ctrl *relation) getPlenty(ctx echo.Context) error { + studentID, _ := strconv.Atoi(ctx.QueryParam("student_id")) + supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) + + if studentID < 0 || supervisorID < 0 { + return echo.NewHTTPError(400, map[string]string{"err": "Bad request", "msg": "Parameter (student_id, supervisor_id) must be positive"}) + } + + if studentID == 0 && supervisorID == 0 { + return echo.NewHTTPError(400, map[string]string{"err": "Bad request", "msg": "Must be passed at least one parameter (student_id, supervisor_id)"}) + } + + if studentID != 0 && supervisorID != 0 { + return echo.NewHTTPError(400, map[string]string{"err": "Bad request", "msg": "Must be passed only on parameter (student_id, supervisor_id)"}) + } + + respDTO, err := ctrl.relationService.GetPlenty(studentID, supervisorID) + if err != nil { + return err + } + + return ctx.JSON(http.StatusOK, respDTO) +} + func NewRelationRoutes( router *echo.Group, l logger.Interface, @@ -52,7 +111,9 @@ func NewRelationRoutes( relations := router.Group("/relations", middlewares.MakeAuthMiddleware(config)) { + relations.GET("/", ctrl.getPlenty) relations.POST("/", ctrl.create) + relations.PATCH("/", ctrl.update) } } diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index 33bbe51..fa81fc8 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -22,7 +22,7 @@ type student struct { // @Tags student // @Produce json // @Param student_id path int true "Student ID" -// @Success 200 {object} dto.StProfile +// @Success 200 {object} dto.Student // @Failure 404 // @Router /api/v1/students/{student_id}/profile [get] // @Security OAuth2Password @@ -42,7 +42,7 @@ func (ctrl *student) getProfile(ctx echo.Context) error { // @Tags student // @Param student_id path int true "Student ID" // @Produce json -// @Success 200 {object} dto.StWorkPlenty +// @Success 200 {object} dto.StudentViewWorkPlenty // @Router /api/v1/students/{student_id}/works [get] // @Security OAuth2Password func (ctrl *student) getWorks(ctx echo.Context) error { @@ -56,26 +56,6 @@ func (ctrl *student) getWorks(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -// ShowAccount godoc -// @Summary Get student's bids -// @Tags student -// @Produce json -// @Param student_id path int true "Student ID" -// @Success 200 {object} dto.StRelationPlenty -// @Failure 404 -// @Router /api/v1/students/{student_id}/relations [get] -// @Security OAuth2Password -func (ctrl *student) getRelations(ctx echo.Context) error { - studentID, _ := strconv.Atoi(ctx.Param("student_id")) - - respDTO, err := ctrl.relationsService.GetStudentRelations(studentID) - if err != nil { - return echo.ErrNotFound - } - - return ctx.JSON(http.StatusOK, respDTO) -} - //// ShowAccount godoc //// @Summary Start SSR //// @Tags student @@ -173,7 +153,7 @@ func NewStudentRoutes( { student.GET("/:student_id/profile", ctrl.getProfile) student.GET("/:student_id/works", ctrl.getWorks) - student.GET("/:student_id/relations", ctrl.getRelations) + //student.GET("/:student_id/relations", ctrl.get) //student.PUT("/bid", ctrl.applyBid) //student.POST("/ssr", ctrl.createSSR) //student.GET("/work/supervisor_id", ctrl.getSupervisors) diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index 97c8133..85f84d6 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -21,7 +21,7 @@ type supervisor struct { // @Tags supervisor // @Produce json // @Param supervisor_id path int true "Supervisor ID" -// @Success 200 {object} dto.SvProfile +// @Success 200 {object} dto.Supervisor // @Router /api/v1/supervisors/{supervisor_id}/profile [get] // @Security OAuth2Password func (ctrl *supervisor) getProfile(ctx echo.Context) error { @@ -41,7 +41,7 @@ func (ctrl *supervisor) getProfile(ctx echo.Context) error { // @Tags supervisor // @Param supervisor_id path int true "Supervisor ID" // @Produce json -// @Success 200 {object} dto.SvWorkPlenty +// @Success 200 {object} dto.SupervisorViewWorkPlenty // @Router /api/v1/supervisors/{supervisor_id}/works [get] // @Security OAuth2Password func (ctrl *supervisor) getWorks(ctx echo.Context) error { @@ -71,7 +71,7 @@ func (ctrl *supervisor) getWorks(ctx echo.Context) error { // // supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) // -// respDTO, err := ctrl.relationsService.GetSupervisorBids(supervisorID) +// respDTO, err := ctrl.relationsService.GetSupervisorRelations(supervisorID) // if err != nil { // ctrl.l.Error(err) // return echo.NewHTTPError(http.StatusInternalServerError, "TODO") diff --git a/internal/controller/http/works.go b/internal/controller/http/works.go index 3a03254..fa2d5f4 100644 --- a/internal/controller/http/works.go +++ b/internal/controller/http/works.go @@ -19,7 +19,7 @@ type works struct { // @Tags works // @Param work_id path int true "Work ID" // @Produce json -// @Success 200 {object} dto.WorkSvPlenty +// @Success 200 {object} dto.WorkSupervisorPlenty // @Router /api/v1/works/{work_id}/supervisors [get] // @Security OAuth2Password func (ctrl *works) getSupervisors(ctx echo.Context) error { diff --git a/internal/dto/bid.go b/internal/dto/bid.go deleted file mode 100644 index b0ef9a1..0000000 --- a/internal/dto/bid.go +++ /dev/null @@ -1,49 +0,0 @@ -package dto - -import ( - "time" -) - -type StRelationResp struct { - BidID int `json:"id"` - Status string `json:"status"` - CreatedAt time.Time `json:"created_at"` - Supervisor SvProfile `json:"supervisor"` - Work WorkResp `json:"work"` -} - -type StRelationPlenty struct { - Relations []*StRelationResp `json:"relations"` -} - -type SvBid struct { - BidID int `json:"id"` - Status string `json:"status"` - CreatedAt time.Time `json:"createdAt"` - Student StProfile `json:"student"` - Work WorkResp `json:"work"` -} - -type SvBids struct { - Bids []*SvBid `json:"bids"` -} - -type RelationCreateReq struct { - StudentID int `json:"student_id"` - SupervisorID int `json:"supervisor_id"` - WorkID int `json:"work_id"` -} - -type RelationCreateResp struct { - RelationID int `json:"relation_id"` -} - -type ResolveBid struct { - SupervisorID int `json:"supervisorID"` - BidID int `json:"bidID"` - Accept bool `json:"accept"` -} - -type ResolveBidResp struct { - NewStatus string `json:"new_status"` -} diff --git a/internal/dto/profile.go b/internal/dto/profile.go deleted file mode 100644 index 3da29ec..0000000 --- a/internal/dto/profile.go +++ /dev/null @@ -1,32 +0,0 @@ -package dto - -import ( - "ssr/pkg/misc" -) - -type UserInfo struct { - Email string `json:"email"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - AvatarUrl misc.NullString `json:"avatarUrl"` -} - -type StProfile struct { - Email string `json:"email"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - PhotoUrl string `json:"photoUrl"` - Year int `json:"year"` - StudentCard string `json:"studentCard"` - Department string `json:"department"` -} - -type SvProfile struct { - Email string `json:"email"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - About string `json:"about"` - Birthdate misc.Date `json:"birthdate" swaggertype:"string"` - PhotoUrl string `json:"avatarUrl"` - Department string `json:"department"` -} diff --git a/internal/dto/relation.go b/internal/dto/relation.go deleted file mode 100644 index 025208d..0000000 --- a/internal/dto/relation.go +++ /dev/null @@ -1,16 +0,0 @@ -package dto - -import "time" - -type CreateSSR struct { - StudentID int `json:"studentID"` - BidID int `json:"bidID"` -} - -type StViewRelation struct { - RelID int `json:"id"` - Status string `json:"status"` - CreatedAt time.Time `json:"createdAt"` - Supervisor SvProfile `json:"supervisor"` - Work WorkResp `json:"work"` -} diff --git a/internal/dto/relations.go b/internal/dto/relations.go new file mode 100644 index 0000000..a8c60f2 --- /dev/null +++ b/internal/dto/relations.go @@ -0,0 +1,40 @@ +package dto + +import ( + "ssr/internal/entity" +) + +type RelationCreateReq struct { + StudentID int `json:"student_id"` + SupervisorID int `json:"supervisor_id"` + WorkID int `json:"work_id"` +} + +type RelationResp struct { + RelationID int `json:"relation_id"` + Work WorkResp `json:"work"` + Status string `json:"status"` + Supervisor Supervisor `json:"supervisor"` + Student Student `json:"student"` +} + +type RelationShortResp struct { + RelationID int `json:"relation_id"` + Work WorkShortResp `json:"work"` + Status string `json:"status"` + Supervisor SupervisorShort `json:"supervisor"` + Student StudentShort `json:"student"` +} + +type RelationCreateResp struct { + RelationID int `json:"relation_id"` +} + +type RelationUpdateReq struct { + RelationID int `json:"relation_id"` + Status entity.StatusSSR `json:"status"` +} + +type RelationPlenty struct { + Relations []*RelationShortResp `json:"relations"` +} diff --git a/internal/dto/students.go b/internal/dto/students.go new file mode 100644 index 0000000..82afa16 --- /dev/null +++ b/internal/dto/students.go @@ -0,0 +1,18 @@ +package dto + +type Student struct { + UserID int `json:"user_id"` + Email string `json:"email"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + PhotoUrl string `json:"photo_url"` + Year int `json:"year"` + StudentCard string `json:"student_card"` + Department string `json:"department"` +} + +type StudentShort struct { + UserID int `json:"user_id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` +} diff --git a/internal/dto/subject.go b/internal/dto/subjects.go similarity index 100% rename from internal/dto/subject.go rename to internal/dto/subjects.go diff --git a/internal/dto/supervisors.go b/internal/dto/supervisors.go new file mode 100644 index 0000000..94556e0 --- /dev/null +++ b/internal/dto/supervisors.go @@ -0,0 +1,30 @@ +package dto + +import "ssr/pkg/misc" + +type Supervisor struct { + UserID int `json:"user_id"` + Email string `json:"email"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + About string `json:"about"` + Birthdate misc.Date `json:"birthdate" swaggertype:"string"` + PhotoUrl string `json:"photo_url"` + Department string `json:"department"` +} + +type SupervisorShort struct { + UserID int `json:"user_id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` +} + +type WorkSupervisorShort struct { + SupervisorShort + IsHead bool `json:"head"` + IsFull bool `json:"full"` +} + +type WorkSupervisorPlenty struct { + Supervisors []*WorkSupervisorShort `json:"supervisors"` +} diff --git a/internal/dto/work.go b/internal/dto/work.go deleted file mode 100644 index 015003a..0000000 --- a/internal/dto/work.go +++ /dev/null @@ -1,43 +0,0 @@ -package dto - -type WorkKindResp struct { - ID int `json:"id"` - Name string `json:"name"` -} - -type WorkResp struct { - WorkID int `json:"id"` - Description string `json:"description"` - Semester int8 `json:"semester"` - Subject SubjectResp `json:"subject"` - Kind WorkKindResp `json:"kind"` -} - -type StWorkResp struct { - Work WorkResp `json:"work"` - IsStarted bool `json:"is_started"` // TODO -} - -type StWorkPlenty struct { - Works []*StWorkResp `json:"works"` -} - -type SvWorkResp struct { - Work WorkResp `json:"work"` - IsHead bool `json:"is_head"` - IsFull bool `json:"is_full"` -} - -type SvWorkPlenty struct { - Works []*SvWorkResp `json:"works"` -} - -type WorkSv struct { - SvProfile - IsHead bool `json:"head"` - IsFull bool `json:"full"` -} - -type WorkSvPlenty struct { - Supervisors []*WorkSv `json:"supervisors"` -} diff --git a/internal/dto/work_kinds.go b/internal/dto/work_kinds.go new file mode 100644 index 0000000..5a2f9b1 --- /dev/null +++ b/internal/dto/work_kinds.go @@ -0,0 +1,6 @@ +package dto + +type WorkKindResp struct { + ID int `json:"id"` + Name string `json:"name"` +} diff --git a/internal/dto/works_common.go b/internal/dto/works_common.go new file mode 100644 index 0000000..1434ab5 --- /dev/null +++ b/internal/dto/works_common.go @@ -0,0 +1,15 @@ +package dto + +type WorkResp struct { + WorkID int `json:"id"` + Description string `json:"description"` + Semester int8 `json:"semester"` + Subject SubjectResp `json:"subject"` + Kind WorkKindResp `json:"kind"` +} + +type WorkShortResp struct { + WorkID int `json:"id"` + Subject SubjectResp `json:"subject"` + Kind WorkKindResp `json:"kind"` +} diff --git a/internal/dto/works_student_view.go b/internal/dto/works_student_view.go new file mode 100644 index 0000000..d7a004a --- /dev/null +++ b/internal/dto/works_student_view.go @@ -0,0 +1,14 @@ +package dto + +type StudentViewWorkResp struct { + Work WorkResp `json:"work"` + IsStarted bool `json:"is_started"` // TODO +} + +type StudentViewWorkShortResp struct { + Work WorkShortResp `json:"work"` +} + +type StudentViewWorkPlenty struct { + Works []*StudentViewWorkShortResp `json:"works"` +} diff --git a/internal/dto/works_supervisor_view.go b/internal/dto/works_supervisor_view.go new file mode 100644 index 0000000..98a5e92 --- /dev/null +++ b/internal/dto/works_supervisor_view.go @@ -0,0 +1,17 @@ +package dto + +type SupervisorViewWorkResp struct { + Work WorkResp `json:"work"` + IsHead bool `json:"is_head"` + IsFull bool `json:"is_full"` +} + +type SupervisorViewWorkShortResp struct { + Work WorkShortResp `json:"work"` + IsHead bool `json:"is_head"` + IsFull bool `json:"is_full"` +} + +type SupervisorViewWorkPlenty struct { + Works []*SupervisorViewWorkShortResp `json:"works"` +} diff --git a/internal/entity/relation.go b/internal/entity/relation.go index 238e9ec..eb47391 100644 --- a/internal/entity/relation.go +++ b/internal/entity/relation.go @@ -5,12 +5,12 @@ import "time" type StatusSSR string const ( - bidPending StatusSSR = "pending" - bidDeclined = "rejected" - bidCancelled = "cancelled" - bidAccepted = "accepted" - inProgress = "wip" - completed = "done" + Pending StatusSSR = "pending" + Rejected = "rejected" + Cancelled = "cancelled" + Accepted = "accepted" + Wip = "wip" + Completed = "done" ) type WaypointRelation struct { @@ -19,18 +19,19 @@ type WaypointRelation struct { SsrID int `db:"ssr_id"` } -type StRelation struct { - RelationID int `db:"ssr_id"` - CreatedAt time.Time `db:"created_at"` - Status string `db:"status"` - SupervisorFull `db:"sv"` - Work `db:"work"` -} - -type SvRelation struct { +type Relation struct { RelationID int `db:"ssr_id"` CreatedAt time.Time `db:"created_at"` - Status string `db:"ssr_status"` - *StProfile - *Work + Status string `db:"status"` + Supervisor `db:"sv"` + Student `db:"st"` + Work `db:"work"` +} + +type RelationShort struct { + RelationID int `db:"ssr_id"` + Status string `db:"status"` + SupervisorShort `db:"sv"` + StudentShort `db:"st"` + Work `db:"work"` } diff --git a/internal/entity/student.go b/internal/entity/student.go index 685cb23..48e15a8 100644 --- a/internal/entity/student.go +++ b/internal/entity/student.go @@ -1,14 +1,13 @@ package entity -type Student struct { - UserID int `db:"user_id"` - StudentCard string `db:"student_card"` +type StudentShort struct { + User UserShort `db:"user"` Year int DepartmentID string `db:"department_id"` } -type StudentFull struct { - User *User +type Student struct { + User User StudentCard string `db:"student_card"` Year int DepartmentID string `db:"department_id"` diff --git a/internal/entity/supervisor.go b/internal/entity/supervisor.go index ab275b0..e45bbe3 100644 --- a/internal/entity/supervisor.go +++ b/internal/entity/supervisor.go @@ -2,14 +2,12 @@ package entity import "time" -type Supervisor struct { - UserID int `db:"user_id"` - Birthdate string - About int - DepartmentID string `db:"department_id"` +type SupervisorShort struct { + User UserShort `db:"user"` + DepartmentID string `db:"department_id"` } -type SupervisorFull struct { +type Supervisor struct { User User `db:"user"` Birthdate time.Time About string diff --git a/internal/entity/user.go b/internal/entity/user.go index fd0044c..7ca3c6e 100644 --- a/internal/entity/user.go +++ b/internal/entity/user.go @@ -7,7 +7,7 @@ const ( supervisor = "sv" ) -type User struct { +type UserFull struct { UserID int `db:"user_id"` Email string `db:"email"` FirstName string `db:"first_name"` @@ -16,3 +16,17 @@ type User struct { Role UserRole `db:"role"` Password string `db:"password"` } + +type User struct { + UserID int `db:"user_id"` + Email string `db:"email"` + FirstName string `db:"first_name"` + LastName string `db:"last_name"` + PhotoUrl string `db:"photo_url"` +} + +type UserShort struct { + UserID int `db:"user_id"` + FirstName string `db:"first_name"` + LastName string `db:"last_name"` +} diff --git a/internal/entity/work.go b/internal/entity/work.go index 524f2d7..9a4da7d 100644 --- a/internal/entity/work.go +++ b/internal/entity/work.go @@ -20,7 +20,7 @@ type SvWork struct { } type WorkSv struct { - SupervisorFull `db:"sv"` - IsHead bool `db:"is_head"` - IsFull bool `db:"is_full"` + Supervisor `db:"sv"` + IsHead bool `db:"is_head"` + IsFull bool `db:"is_full"` } diff --git a/internal/service/bid.go b/internal/service/bid.go index e1d3804..b4414f8 100644 --- a/internal/service/bid.go +++ b/internal/service/bid.go @@ -1,80 +1,75 @@ package service -import ( - "ssr/internal/dto" - "ssr/pkg/logger" -) - -type Bid struct { - *Base - repo RelationRepo -} - -func NewBid(r RelationRepo, l logger.Interface) *Bid { - return &Bid{ - Base: NewBase(l), - repo: r, - } -} - -func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { - dbData, err := service.repo.GetSupervisorBids(supervisorID) - if err != nil { - return nil, err - } - - var resp []*dto.SvBid - - for _, db := range dbData { - resp = append(resp, &dto.SvBid{ - BidID: db.RelationID, - Status: db.Status, - CreatedAt: db.CreatedAt, - Student: dto.StProfile{ - Email: db.Email, - FirstName: db.FirstName, - LastName: db.LastName, - Year: db.Year, - PhotoUrl: db.PhotoUrl, - Department: db.StProfile.DepartmentID, - }, - Work: dto.WorkResp{ - Description: db.Work.Description, - Semester: db.Work.Semester, - Kind: dto.WorkKindResp{ - ID: db.WorkKind.WorkKindID, - Name: db.WorkKind.Name, - }, - Subject: dto.SubjectResp{ - ID: db.SubjectID, - Name: db.Subject.Name, - Department: db.Subject.DepartmentID, - }, - }, - }) - } - - return &dto.SvBids{Bids: resp}, nil -} - -//func (service *Bid) Apply(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) { -// bidID, err := service.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) +//type Bid struct { +// *Base +// repo RelationRepo +//} +// +//func NewBid(r RelationRepo, l logger.Interface) *Bid { +// return &Bid{ +// Base: NewBase(l), +// repo: r, +// } +//} +// +//func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { +// dbData, err := service.repo.GetSupervisorRelations(supervisorID) // if err != nil { // return nil, err // } // -// return &dto.RelationCreateResp{BidID: bidID}, nil -//} -// -//func (service *Bid) Resolve(data *dto.ResolveBid) error { -// var status entity.StatusSSR +// var resp []*dto.SvBid // -// if data.Accept { -// status = "accepted" -// } else { -// status = "rejected" +// for _, db := range dbData { +// resp = append(resp, &dto.SvBid{ +// BidID: db.RelationID, +// Status: db.Status, +// CreatedAt: db.CreatedAt, +// Student: dto.Student{ +// Email: db.Email, +// FirstName: db.FirstName, +// LastName: db.LastName, +// Year: db.Year, +// PhotoUrl: db.PhotoUrl, +// Department: db.StProfile.DepartmentID, +// }, +// Work: dto.WorkResp{ +// Description: db.Work.Description, +// Semester: db.Work.Semester, +// Kind: dto.WorkKindResp{ +// ID: db.WorkKind.WorkKindID, +// Name: db.WorkKind.Name, +// }, +// Subject: dto.SubjectResp{ +// ID: db.SubjectID, +// Name: db.Subject.Name, +// Department: db.Subject.DepartmentID, +// }, +// }, +// }) // } // -// _, err := service.repo.UpdateStatus(data.BidID, status) -// return err +// return &dto.SvBids{Bids: resp}, nil //} +// +////func (service *Bid) Apply(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) { +//// bidID, err := service.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) +//// if err != nil { +//// return nil, err +//// } +//// +//// return &dto.RelationCreateResp{BidID: bidID}, nil +////} +//// +////func (service *Bid) Resolve(data *dto.ResolveBid) error { +//// var status entity.StatusSSR +//// +//// if data.Accept { +//// status = "accepted" +//// } else { +//// status = "rejected" +//// } +//// +//// _, err := service.repo.Update(data.BidID, status) +//// return err +////} diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index 9bf6e1d..c81afb2 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -6,14 +6,14 @@ import ( type ( UserRepo interface { - GetUserByEmail(email string) (*entity.User, error) + GetUserByEmail(email string) (*entity.UserFull, error) } StudentRepo interface { - GetFullStudent(userID int) (*entity.StudentFull, error) GetStudent(userID int) (*entity.Student, error) + GetStudentShort(userID int) (*entity.StudentShort, error) } SupervisorRepo interface { - GetFullSupervisor(userID int) (*entity.SupervisorFull, error) + GetFullSupervisor(userID int) (*entity.Supervisor, error) } ProfileRepo interface { GetStProfile(email string) (*entity.StProfile, error) @@ -21,10 +21,11 @@ type ( } RelationRepo interface { Create(studentID, supervisorID, workID int) (int, error) - GetStudentRelations(studentID int) ([]*entity.StRelation, error) - GetSupervisorBids(studentID int) ([]*entity.SvRelation, error) - GetStudentRelation(studentID, ssrID int) (*entity.StRelation, error) - UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) + GetRelationsByStudentID(studentID int) ([]*entity.RelationShort, error) + GetRelationsBySupervisorID(supervisorID int) ([]*entity.RelationShort, error) + Get(id int) (*entity.Relation, error) + Update(id int, status entity.StatusSSR) (int, error) + GetRelationStatus(studentID, workID int) (entity.StatusSSR, error) } WorkRepo interface { GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) diff --git a/internal/service/profile.go b/internal/service/profile.go index d4abf00..11bb01e 100644 --- a/internal/service/profile.go +++ b/internal/service/profile.go @@ -20,13 +20,13 @@ func NewProfile(stRepo StudentRepo, svRepo SupervisorRepo, l logger.Interface) * } } -func (uc *Profile) GetStudentProfile(userID int) (*dto.StProfile, error) { - dbData, err := uc.stRepo.GetFullStudent(userID) +func (uc *Profile) GetStudentProfile(userID int) (*dto.Student, error) { + dbData, err := uc.stRepo.GetStudent(userID) if err != nil { return nil, err } - return &dto.StProfile{ + return &dto.Student{ Email: dbData.User.Email, FirstName: dbData.User.FirstName, LastName: dbData.User.LastName, @@ -37,13 +37,13 @@ func (uc *Profile) GetStudentProfile(userID int) (*dto.StProfile, error) { }, nil } -func (uc *Profile) GetSupervisorProfile(userID int) (*dto.SvProfile, error) { +func (uc *Profile) GetSupervisorProfile(userID int) (*dto.Supervisor, error) { dbData, err := uc.svRepo.GetFullSupervisor(userID) if err != nil { return nil, err } - return &dto.SvProfile{ + return &dto.Supervisor{ Email: dbData.User.Email, FirstName: dbData.User.FirstName, LastName: dbData.User.LastName, diff --git a/internal/service/relation.go b/internal/service/relation.go index 7beb08b..42cb59b 100644 --- a/internal/service/relation.go +++ b/internal/service/relation.go @@ -2,6 +2,7 @@ package service import ( "ssr/internal/dto" + "ssr/internal/entity" "ssr/pkg/logger" "ssr/pkg/misc" ) @@ -18,34 +19,38 @@ func NewRelation(r RelationRepo, l logger.Interface) *Relation { } } -func (service *Relation) GetStudentRelations(studentID int) (*dto.StRelationPlenty, error) { - dbData, err := service.repo.GetStudentRelations(studentID) +func (service *Relation) GetPlenty(studentID, supervisorID int) (*dto.RelationPlenty, error) { + var relations []*entity.RelationShort + var err error + + if studentID != 0 { + relations, err = service.repo.GetRelationsByStudentID(studentID) + } else { + relations, err = service.repo.GetRelationsBySupervisorID(supervisorID) + } + if err != nil { return nil, err } - var resp []*dto.StRelationResp - - for _, db := range dbData { - resp = append(resp, &dto.StRelationResp{ - BidID: db.RelationID, - Status: db.Status, - CreatedAt: db.CreatedAt, - Supervisor: dto.SvProfile{ - Email: db.User.Email, - FirstName: db.User.FirstName, - LastName: db.User.LastName, - About: db.SupervisorFull.About, - Birthdate: misc.Date{ - Time: db.Birthdate, - }, - PhotoUrl: db.User.PhotoUrl, - Department: db.SupervisorFull.DepartmentID, + var resp []*dto.RelationShortResp + + for _, db := range relations { + resp = append(resp, &dto.RelationShortResp{ + RelationID: db.RelationID, + Status: db.Status, + Supervisor: dto.SupervisorShort{ + UserID: db.SupervisorShort.User.UserID, + FirstName: db.SupervisorShort.User.FirstName, + LastName: db.SupervisorShort.User.LastName, }, - Work: dto.WorkResp{ - WorkID: db.WorkID, - Description: db.Work.Description, - Semester: db.Work.Semester, + Student: dto.StudentShort{ + UserID: db.StudentShort.User.UserID, + FirstName: db.StudentShort.User.FirstName, + LastName: db.StudentShort.User.LastName, + }, + Work: dto.WorkShortResp{ + WorkID: db.WorkID, Kind: dto.WorkKindResp{ ID: db.WorkKind.WorkKindID, Name: db.WorkKind.Name, @@ -59,22 +64,53 @@ func (service *Relation) GetStudentRelations(studentID int) (*dto.StRelationPlen }) } - return &dto.StRelationPlenty{Relations: resp}, nil + return &dto.RelationPlenty{Relations: resp}, nil } -func (service *Relation) CheckIfStudentBeginWork(studentID, workID int) (bool, error) { - relations, err := service.repo.GetStudentRelations(studentID) +func (service *Relation) Get(id int) (*dto.RelationResp, error) { + rel, err := service.repo.Get(id) if err != nil { - return false, err - } - - for _, rel := range relations { - if rel.Work.WorkID == workID { - return true, nil - } + return nil, err } - return false, nil + return &dto.RelationResp{ + RelationID: rel.RelationID, + Status: rel.Status, + Supervisor: dto.Supervisor{ + UserID: rel.Supervisor.User.UserID, + Email: rel.Supervisor.User.Email, + FirstName: rel.Supervisor.User.FirstName, + LastName: rel.Supervisor.User.LastName, + About: rel.Supervisor.About, + Birthdate: misc.Date{Time: rel.Supervisor.Birthdate}, + PhotoUrl: rel.Supervisor.User.PhotoUrl, + Department: rel.Supervisor.DepartmentID, + }, + Work: dto.WorkResp{ + WorkID: rel.WorkID, + Kind: dto.WorkKindResp{ + ID: rel.WorkKind.WorkKindID, + Name: rel.WorkKind.Name, + }, + Subject: dto.SubjectResp{ + ID: rel.SubjectID, + Name: rel.Subject.Name, + Department: rel.Subject.DepartmentID, + }, + Description: rel.Work.Description, + Semester: rel.Work.Semester, + }, + Student: dto.Student{ + UserID: rel.Student.User.UserID, + Email: rel.Student.User.Email, + FirstName: rel.Student.User.FirstName, + LastName: rel.Student.User.LastName, + PhotoUrl: rel.Student.User.PhotoUrl, + Year: rel.Student.Year, + StudentCard: rel.Student.StudentCard, + Department: rel.Student.DepartmentID, + }, + }, nil } func (service *Relation) Create(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) { @@ -86,13 +122,51 @@ func (service *Relation) Create(data *dto.RelationCreateReq) (*dto.RelationCreat return &dto.RelationCreateResp{RelationID: relationID}, nil } +func (service *Relation) Update(data *dto.RelationUpdateReq) (*dto.RelationResp, error) { + relationID, err := service.repo.Update(data.RelationID, data.Status) + if err != nil { + return nil, err + } + + relation, err := service.repo.Get(relationID) + + return &dto.RelationResp{ + RelationID: relation.RelationID, + Work: dto.WorkResp{ + WorkID: relation.Work.WorkID, + Description: relation.Work.Description, + Semester: relation.Semester, + Subject: dto.SubjectResp{ + ID: relation.Subject.SubjectID, + Name: relation.Subject.Name, + Department: relation.Subject.DepartmentID, + }, + Kind: dto.WorkKindResp{ + ID: relation.WorkKind.WorkKindID, + Name: relation.WorkKind.Name, + }, + }, + Student: dto.Student{ + UserID: relation.Student.User.UserID, + Email: relation.Student.User.Email, + FirstName: relation.Student.User.FirstName, + LastName: relation.Student.User.LastName, + PhotoUrl: relation.Student.User.PhotoUrl, + Year: relation.Student.Year, + StudentCard: relation.Student.StudentCard, + Department: relation.Student.DepartmentID, + }, + Status: relation.Status, + }, nil +} + //func (service *Relation) Accept(data *dto.CreateSSR) (*dto.StViewRelation, error) { -// ssrID, err := service.repo.UpdateStatus(data.BidID, "wip") +// ssrID, err := service.repo.Update(data.BidID, "wip") // if err != nil { // return nil, err // } // -// ssr, err := service.repo.GetStudentRelation(data.StudentID, ssrID) +// ssr, err := service.repo.Get(data.StudentID, ssrID) // if err != nil { // return nil, err // } @@ -101,11 +175,11 @@ func (service *Relation) Create(data *dto.RelationCreateReq) (*dto.RelationCreat // RelID: ssr.RelationID, // Status: ssr.Status, // CreatedAt: ssr.CreatedAt, -// Supervisor: dto.SvProfile{ -// Email: ssr.SvProfile.Email, -// FirstName: ssr.SvProfile.FirstName, -// LastName: ssr.SvProfile.LastName, -// About: ssr.SvProfile.About, +// Supervisor: dto.Supervisor{ +// Email: ssr.Supervisor.Email, +// FirstName: ssr.Supervisor.FirstName, +// LastName: ssr.Supervisor.LastName, +// About: ssr.Supervisor.About, // Birthdate: misc.Date{Time: ssr.Birthdate}, // PhotoUrl: ssr.PhotoUrl, // Department: ssr.DepartmentID, diff --git a/internal/service/repo_pg/relation.go b/internal/service/repo_pg/relation.go index 8e7b1e6..0a11be0 100644 --- a/internal/service/repo_pg/relation.go +++ b/internal/service/repo_pg/relation.go @@ -17,145 +17,158 @@ func NewRelation(pg *postgres.Postgres, l logger.Interface) *Relation { } } -func (repo *Relation) GetStudentRelation(studentID, ssrID int) (*entity.StRelation, error) { +func (repo *Relation) Get(id int) (*entity.Relation, error) { query := ` select ssr.ssr_id, - ssr.status as ssr_status, + ssr.status, ssr.created_at, - sv.*, - u.*, - w.*, - wk.name as work_kind_name, - subj.name as subject_name, - subj.department_id as subject_department_id - from ssr - join supervisors sv using (supervisor_id) - join users u using (user_id) + + sv.department_id as "sv.department_id", + sv.birthdate as "sv.birthdate", + sv.about as "sv.about", + + svu.user_id as "sv.user.user_id", + svu.email as "sv.user.email", + svu.last_name as "sv.user.last_name", + svu.first_name as "sv.user.first_name", + + st.year as "st.year", + st.department_id as "st.department_id", + + stu.user_id as "st.user.user_id", + stu.email as "st.user.email", + stu.last_name as "st.user.last_name", + stu.first_name as "st.user.first_name", + + w.semester as "work.semester", + w.description as "work.description", + w.work_id as "work.work_id", + wk.name as "work.work_kind.name", + wk.work_kind_id as "work.work_kind.work_kind_id", + + subj.subject_id as "work.subject.subject_id", + subj.name as "work.subject.name", + subj.department_id as "work.subject.department_id" + from ssr + join supervisors sv on ssr.supervisor_id = sv.user_id + join students st on ssr.student_id = st.user_id + join users stu on st.user_id = stu.user_id + join users svu on sv.user_id = svu.user_id join works w using (work_id) join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) - where ssr.ssr_id = $1 and ssr.student_id = $2; + where ssr.ssr_id = $1; ` - ssr := entity.StRelation{} - err := repo.Conn.Get(&ssr, query, ssrID, studentID) + relation := entity.Relation{} + + err := repo.Conn.Get(&relation, query, id) if err != nil { - err := fmt.Errorf("Relation->GetStudentRelation->repo.Conn.Get: %w", err) + err := fmt.Errorf("Relation->Get->repo.Conn.Get: %w", err) repo.l.Error(err) return nil, err } - return &ssr, nil + return &relation, nil } -func (repo *Relation) GetStudentRelations(studentID int) ([]*entity.StRelation, error) { +func (repo *Relation) GetRelationsBySupervisorID(supervisorID int) ([]*entity.RelationShort, error) { query := ` select ssr.ssr_id, ssr.status, - ssr.created_at, - sv.birthdate as "sv.birthdate", - sv.about as "sv.about", + sv.department_id as "sv.department_id", - u.email as "sv.user.email", - u.first_name as "sv.user.first_name", - u.last_name as "sv.user.last_name", - u.photo_url as "sv.user.photo_url", - u.user_id as "sv.user.user_id", + svu.user_id as "sv.user.user_id", + svu.last_name as "sv.user.last_name", + svu.first_name as "sv.user.first_name", + + st.year as "st.year", + st.department_id as "st.department_id", + stu.user_id as "st.user.user_id", + stu.last_name as "st.user.last_name", + stu.first_name as "st.user.first_name", + w.semester as "work.semester", w.description as "work.description", w.work_id as "work.work_id", wk.name as "work.work_kind.name", wk.work_kind_id as "work.work_kind.work_kind_id", + subj.subject_id as "work.subject.subject_id", subj.name as "work.subject.name", subj.department_id as "work.subject.department_id" from ssr join supervisors sv on ssr.supervisor_id = sv.user_id - join users u using (user_id) + join students st on ssr.student_id = st.user_id + join users stu on st.user_id = stu.user_id + join users svu on sv.user_id = svu.user_id join works w using (work_id) join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) - where ssr.student_id = $1; + where ssr.supervisor_id = $1; ` - var bids []*entity.StRelation + var relations []*entity.RelationShort - err := repo.Conn.Select(&bids, query, studentID) + err := repo.Conn.Select(&relations, query, supervisorID) if err != nil { - err := fmt.Errorf("Relation->GetStudentRelations->repo.Conn.Select: %w", err) + err := fmt.Errorf("Relation->GetRelations->repo.Conn.Select: %w", err) repo.l.Error(err) return nil, err } - return bids, nil + return relations, nil } -//func (repo *Relation) GetStudentRelations(studentID int) ([]*entity.StRelation, error) { -// query := ` -// select -// ssr.ssr_id, -// ssr.status as ssr_status, -// ssr.created_at, -// sv.*, -// u.*, -// w.*, -// wk.name as work_kind_name, -// subj.name as subject_name, -// subj.department_id as subject_department_id -// from ssr -// join supervisors sv using (supervisor_id) -// join users u using (user_id) -// join works w using (work_id) -// join work_kinds wk using (work_kind_id) -// join subjects subj using (subject_id) -// where ssr.status in ('wip', 'done') and ssr.student_id = $1; -// ` -// -// var bids []*entity.StRelation -// -// err := repo.Conn.Select(&bids, query, studentID) -// if err != nil { -// err := fmt.Errorf("Relation->GetStudentRelations->repo.Conn.Select: %w", err) -// repo.l.Error(err) -// return nil, err -// } -// -// return bids, nil -//} - -func (repo *Relation) GetSupervisorBids(supervisorID int) ([]*entity.SvRelation, error) { +func (repo *Relation) GetRelationsByStudentID(studentID int) ([]*entity.RelationShort, error) { query := ` select ssr.ssr_id, - ssr.status as ssr_status, - ssr.created_at, - st.*, - u.*, - w.*, - wk.name as work_kind_name, - subj.name as subject_name, - subj.department_id as subject_department_id + ssr.status, + + sv.department_id as "sv.department_id", + svu.user_id as "sv.user.user_id", + svu.last_name as "sv.user.last_name", + svu.first_name as "sv.user.first_name", + + st.year as "st.year", + st.department_id as "st.department_id", + stu.user_id as "st.user.user_id", + stu.last_name as "st.user.last_name", + stu.first_name as "st.user.first_name", + + w.semester as "work.semester", + w.description as "work.description", + w.work_id as "work.work_id", + wk.name as "work.work_kind.name", + wk.work_kind_id as "work.work_kind.work_kind_id", + + subj.subject_id as "work.subject.subject_id", + subj.name as "work.subject.name", + subj.department_id as "work.subject.department_id" from ssr - join students st using (student_id) - join users u using (user_id) + join supervisors sv on ssr.supervisor_id = sv.user_id + join students st on ssr.student_id = st.user_id + join users stu on st.user_id = stu.user_id + join users svu on sv.user_id = svu.user_id join works w using (work_id) join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) - where ssr.status in ('pending','rejected', 'cancelled','accepted') and ssr.supervisor_id = $1; + where ssr.student_id = $1; ` - var bids []*entity.SvRelation + var relations []*entity.RelationShort - err := repo.Conn.Select(&bids, query, supervisorID) + err := repo.Conn.Select(&relations, query, studentID) if err != nil { - err := fmt.Errorf("Relation->GetSupervisorBids->repo.Conn.Select: %w", err) + err := fmt.Errorf("Relation->GetRelations->repo.Conn.Select: %w", err) repo.l.Error(err) return nil, err } - return bids, nil + return relations, nil } func (repo *Relation) Create(studentID, supervisorID, workID int) (int, error) { @@ -176,20 +189,38 @@ func (repo *Relation) Create(studentID, supervisorID, workID int) (int, error) { return relationID, nil } -func (repo *Relation) UpdateStatus(id int, newStatus entity.StatusSSR) (int, error) { +func (repo *Relation) Update(id int, status entity.StatusSSR) (int, error) { query := ` update ssr set status = $1 where ssr_id = $2 returning ssr_id; ` - var bidID int - err := repo.Conn.QueryRowx(query, newStatus, id).Scan(&bidID) + var relationID int + err := repo.Conn.QueryRowx(query, status, id).Scan(&relationID) if err != nil { - err := fmt.Errorf("Relation->UpdateStatus->repo.Conn.QueryRowx: %w", err) + err := fmt.Errorf("Relation->Update->repo.Conn.QueryRowx: %w", err) repo.l.Error(err) return 0, err } - return bidID, nil + return relationID, nil +} + +func (repo *Relation) GetRelationStatus(studentID, workID int) (entity.StatusSSR, error) { + const query = ` + select ssr.status + from ssr where ssr.student_id = $1 and ssr.work_id = $2; + ` + + var status entity.StatusSSR + + err := repo.Conn.Get(&status, query, studentID, workID) + if err != nil { + err := fmt.Errorf("Relation->GetRelationStatus->r.Conn.Select: %w", err) + repo.l.Error(err) + return "", err + } + + return status, nil } diff --git a/internal/service/repo_pg/student.go b/internal/service/repo_pg/student.go index 8c3c434..8adae87 100644 --- a/internal/service/repo_pg/student.go +++ b/internal/service/repo_pg/student.go @@ -17,12 +17,20 @@ func NewStudent(pg *postgres.Postgres, l logger.Interface) *Student { } } -func (repo *Student) GetStudent(userID int) (*entity.Student, error) { +func (repo *Student) GetStudentShort(userID int) (*entity.StudentShort, error) { const query = ` - select * from students where user_id = $1 + select + s.year, + s.department_id, + u.last_name as "user.last_name", + u.first_name as "user.first_name", + u.user_id as "user.user_id" + from students s + join users u on s.user_id = u.user_id + where u.user_id = $1 ` - student := entity.Student{} + student := entity.StudentShort{} err := repo.Conn.Get(&student, query, userID) if err != nil { @@ -34,7 +42,7 @@ func (repo *Student) GetStudent(userID int) (*entity.Student, error) { return &student, nil } -func (repo *Student) GetFullStudent(userID int) (*entity.StudentFull, error) { +func (repo *Student) GetStudent(userID int) (*entity.Student, error) { const query = ` select s.student_card, @@ -50,7 +58,7 @@ func (repo *Student) GetFullStudent(userID int) (*entity.StudentFull, error) { where user_id = $1 ` - studentFull := entity.StudentFull{} + studentFull := entity.Student{} err := repo.Conn.Get(&studentFull, query, userID) if err != nil { diff --git a/internal/service/repo_pg/supervisor.go b/internal/service/repo_pg/supervisor.go index 0e49159..aaafc76 100644 --- a/internal/service/repo_pg/supervisor.go +++ b/internal/service/repo_pg/supervisor.go @@ -17,16 +17,16 @@ func NewSupervisor(pg *postgres.Postgres, l logger.Interface) *Supervisor { } } -func (repo *Supervisor) GetSupervisor(userID int) (*entity.Supervisor, error) { +func (repo *Supervisor) GetSupervisor(userID int) (*entity.SupervisorShort, error) { const query = ` select * from supervisors where user_id = $1 ` - supervisor := entity.Supervisor{} + supervisor := entity.SupervisorShort{} err := repo.Conn.Get(&supervisor, query, userID) if err != nil { - err := fmt.Errorf("Supervisor->Get->repo.Conn.Get(): %w", err) + err := fmt.Errorf("SupervisorShort->Get->repo.Conn.Get(): %w", err) repo.l.Error(err) return nil, err } @@ -34,7 +34,7 @@ func (repo *Supervisor) GetSupervisor(userID int) (*entity.Supervisor, error) { return &supervisor, nil } -func (repo *Supervisor) GetFullSupervisor(userID int) (*entity.SupervisorFull, error) { +func (repo *Supervisor) GetFullSupervisor(userID int) (*entity.Supervisor, error) { const query = ` select s.about, @@ -50,11 +50,11 @@ func (repo *Supervisor) GetFullSupervisor(userID int) (*entity.SupervisorFull, e where user_id = $1 ` - supervisorFull := entity.SupervisorFull{} + supervisorFull := entity.Supervisor{} err := repo.Conn.Get(&supervisorFull, query, userID) if err != nil { - err := fmt.Errorf("Supervisor->GetFull->repo.Conn.Get(): %w", err) + err := fmt.Errorf("SupervisorShort->GetFull->repo.Conn.Get(): %w", err) repo.l.Error(err) return nil, err } diff --git a/internal/service/repo_pg/user.go b/internal/service/repo_pg/user.go index bdbae3d..c066c42 100644 --- a/internal/service/repo_pg/user.go +++ b/internal/service/repo_pg/user.go @@ -36,12 +36,12 @@ func (r *User) CreateUser(email, password, firstName, lastName, photoUrl string, return nil } -func (r *User) GetUserByEmail(email string) (*entity.User, error) { - user := entity.User{} +func (r *User) GetUserByEmail(email string) (*entity.UserFull, error) { + user := entity.UserFull{} err := r.Conn.Get(&user, "select * from users where email = $1", email) if err != nil { - err := fmt.Errorf("User->r.Conn.Get(): %w", err) + err := fmt.Errorf("UserFull->r.Conn.Get(): %w", err) r.l.Error(err) return nil, err } @@ -49,12 +49,12 @@ func (r *User) GetUserByEmail(email string) (*entity.User, error) { return &user, nil } -func (r *User) GetUserByID(userID int) (*entity.User, error) { - auth := entity.User{} +func (r *User) GetUserByID(userID int) (*entity.UserFull, error) { + auth := entity.UserFull{} err := r.Conn.Get(&auth, "select * from user where user_id = $1", userID) if err != nil { - err := fmt.Errorf("User->r.Conn.Get(): %w", err) + err := fmt.Errorf("UserFull->r.Conn.Get(): %w", err) r.l.Error(err) return nil, err } diff --git a/internal/service/work.go b/internal/service/work.go index 5386348..834cacd 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -4,27 +4,26 @@ import ( "ssr/internal/dto" "ssr/internal/entity" "ssr/pkg/logger" - "ssr/pkg/misc" "time" ) type Work struct { *Base - workRepo WorkRepo - ssrRepo RelationRepo - stRepo StudentRepo + workRepo WorkRepo + relationRepo RelationRepo + stRepo StudentRepo } func NewWork(workRepo WorkRepo, ssrRepo RelationRepo, stRepo StudentRepo, l logger.Interface) *Work { return &Work{ - Base: NewBase(l), - workRepo: workRepo, - ssrRepo: ssrRepo, - stRepo: stRepo, + Base: NewBase(l), + workRepo: workRepo, + relationRepo: ssrRepo, + stRepo: stRepo, } } -func (service *Work) checkIfBegin(relations []*entity.StRelation, workID int) bool { +func (service *Work) checkIfBegin(relations []*entity.Relation, workID int) bool { for _, rel := range relations { if rel.Work.WorkID == workID { return true @@ -43,8 +42,8 @@ func (service *Work) recognizeSemester(studentYear int) int { } } -func (service *Work) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { - studentData, err := service.stRepo.GetStudent(studentID) +func (service *Work) GetStudentWorks(studentID int) (*dto.StudentViewWorkPlenty, error) { + studentData, err := service.stRepo.GetStudentShort(studentID) if err != nil { return nil, err } @@ -56,19 +55,12 @@ func (service *Work) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { return nil, err } - //relationsData, err := service.ssrRepo.GetStudentRelations(studentID) - //if err != nil { - // return nil, err - //} - - var resp []*dto.StWorkResp + var resp []*dto.StudentViewWorkShortResp for _, work := range worksData { - resp = append(resp, &dto.StWorkResp{ - Work: dto.WorkResp{ - WorkID: work.WorkID, - Description: work.Description, - Semester: work.Semester, + resp = append(resp, &dto.StudentViewWorkShortResp{ + Work: dto.WorkShortResp{ + WorkID: work.WorkID, Subject: dto.SubjectResp{ ID: work.Subject.SubjectID, Name: work.Subject.Name, @@ -78,30 +70,27 @@ func (service *Work) GetStudentWorks(studentID int) (*dto.StWorkPlenty, error) { ID: work.WorkKind.WorkKindID, Name: work.WorkKind.Name, }, - //IsStarted: service.checkIfBegin(relations, work.WorkID), TODO }, }) } - return &dto.StWorkPlenty{ + return &dto.StudentViewWorkPlenty{ Works: resp, }, nil } -func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, error) { +func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SupervisorViewWorkPlenty, error) { worksData, err := service.workRepo.GetSupervisorWorks(supervisorID) if err != nil { return nil, err } - var resp []*dto.SvWorkResp + var resp []*dto.SupervisorViewWorkShortResp for _, db := range worksData { - resp = append(resp, &dto.SvWorkResp{ - Work: dto.WorkResp{ - WorkID: db.WorkID, - Description: db.Description, - Semester: db.Semester, + resp = append(resp, &dto.SupervisorViewWorkShortResp{ + Work: dto.WorkShortResp{ + WorkID: db.WorkID, Subject: dto.SubjectResp{ ID: db.Subject.SubjectID, Name: db.Subject.Name, @@ -117,36 +106,31 @@ func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SvWorkPlenty, er }) } - return &dto.SvWorkPlenty{ + return &dto.SupervisorViewWorkPlenty{ Works: resp, }, nil } -func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSvPlenty, error) { +func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error) { supervisorsData, err := service.workRepo.GetWorkSupervisors(workID) if err != nil { return nil, err } - var resp []*dto.WorkSv + var resp []*dto.WorkSupervisorShort for _, db := range supervisorsData { - resp = append(resp, &dto.WorkSv{ - SvProfile: dto.SvProfile{ - Email: db.User.Email, - FirstName: db.User.FirstName, - LastName: db.User.LastName, - About: db.SupervisorFull.About, - Birthdate: misc.Date{Time: db.SupervisorFull.Birthdate}, - PhotoUrl: db.User.PhotoUrl, - Department: db.DepartmentID, + resp = append(resp, &dto.WorkSupervisorShort{ + SupervisorShort: dto.SupervisorShort{ + FirstName: db.User.FirstName, + LastName: db.User.LastName, }, IsHead: db.IsHead, IsFull: db.IsFull, }) } - return &dto.WorkSvPlenty{ + return &dto.WorkSupervisorPlenty{ Supervisors: resp, }, nil } diff --git a/swagger/docs.go b/swagger/docs.go index d917416..6e0cd41 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -35,14 +35,14 @@ const docTemplate = `{ "parameters": [ { "type": "string", - "description": "User email", + "description": "UserFull email", "name": "username", "in": "formData", "required": true }, { "type": "string", - "description": "User password", + "description": "UserFull password", "name": "password", "in": "formData", "required": true @@ -65,6 +65,45 @@ const docTemplate = `{ } }, "/api/v1/relations/": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "relation" + ], + "summary": "Get relations", + "parameters": [ + { + "type": "integer", + "description": "Student ID", + "name": "student_id", + "in": "query" + }, + { + "type": "integer", + "description": "Supervisor ID", + "name": "supervisor_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.RelationPlenty" + } + }, + "404": { + "description": "Not Found" + } + } + }, "post": { "security": [ { @@ -93,52 +132,52 @@ const docTemplate = `{ } ], "responses": { - "200": { - "description": "OK", + "201": { + "description": "Created", "schema": { "$ref": "#/definitions/dto.RelationCreateResp" } } } - } - }, - "/api/v1/students/{student_id}/profile": { - "get": { + }, + "patch": { "security": [ { "OAuth2Password": [] } ], + "consumes": [ + "application/json" + ], "produces": [ "application/json" ], "tags": [ - "student" + "relation" ], - "summary": "Get student's profile", + "summary": "Update relation", "parameters": [ { - "type": "integer", - "description": "Student ID", - "name": "student_id", - "in": "path", - "required": true + "description": "Relation data", + "name": "CreateRelation", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/dto.RelationUpdateReq" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StProfile" + "$ref": "#/definitions/dto.RelationResp" } - }, - "404": { - "description": "Not Found" } } } }, - "/api/v1/students/{student_id}/relations": { + "/api/v1/students/{student_id}/profile": { "get": { "security": [ { @@ -151,7 +190,7 @@ const docTemplate = `{ "tags": [ "student" ], - "summary": "Get student's bids", + "summary": "Get student's profile", "parameters": [ { "type": "integer", @@ -165,7 +204,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StRelationPlenty" + "$ref": "#/definitions/dto.Student" } }, "404": { @@ -201,7 +240,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StWorkPlenty" + "$ref": "#/definitions/dto.StudentViewWorkPlenty" } } } @@ -234,7 +273,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SvProfile" + "$ref": "#/definitions/dto.Supervisor" } } } @@ -267,7 +306,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SvWorkPlenty" + "$ref": "#/definitions/dto.SupervisorViewWorkPlenty" } } } @@ -300,7 +339,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSvPlenty" + "$ref": "#/definitions/dto.WorkSupervisorPlenty" } } } @@ -347,75 +386,129 @@ const docTemplate = `{ } } }, - "dto.StProfile": { + "dto.RelationPlenty": { "type": "object", "properties": { - "department": { - "type": "string" + "relations": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.RelationShortResp" + } + } + } + }, + "dto.RelationResp": { + "type": "object", + "properties": { + "relation_id": { + "type": "integer" }, - "email": { + "status": { "type": "string" }, - "firstName": { - "type": "string" + "student": { + "$ref": "#/definitions/dto.Student" }, - "lastName": { - "type": "string" + "supervisor": { + "$ref": "#/definitions/dto.Supervisor" }, - "photoUrl": { - "type": "string" + "work": { + "$ref": "#/definitions/dto.WorkResp" + } + } + }, + "dto.RelationShortResp": { + "type": "object", + "properties": { + "relation_id": { + "type": "integer" }, - "studentCard": { + "status": { "type": "string" }, - "year": { + "student": { + "$ref": "#/definitions/dto.StudentShort" + }, + "student_id": { + "type": "integer" + }, + "supervisor": { + "$ref": "#/definitions/dto.SupervisorShort" + }, + "supervisor_id": { "type": "integer" + }, + "work": { + "$ref": "#/definitions/dto.WorkShortResp" } } }, - "dto.StRelationPlenty": { + "dto.RelationUpdateReq": { "type": "object", "properties": { - "relations": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.StRelationResp" - } + "relation_id": { + "type": "integer" + }, + "status": { + "type": "string" } } }, - "dto.StRelationResp": { + "dto.Student": { "type": "object", "properties": { - "created_at": { + "department": { "type": "string" }, - "id": { + "email": { + "type": "string" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "photo_url": { + "type": "string" + }, + "student_card": { + "type": "string" + }, + "user_id": { "type": "integer" }, - "status": { + "year": { + "type": "integer" + } + } + }, + "dto.StudentShort": { + "type": "object", + "properties": { + "first_name": { "type": "string" }, - "supervisor": { - "$ref": "#/definitions/dto.SvProfile" + "last_name": { + "type": "string" }, - "work": { - "$ref": "#/definitions/dto.WorkResp" + "user_id": { + "type": "integer" } } }, - "dto.StWorkPlenty": { + "dto.StudentViewWorkPlenty": { "type": "object", "properties": { "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.StWorkResp" + "$ref": "#/definitions/dto.StudentViewWorkShortResp" } } } }, - "dto.StWorkResp": { + "dto.StudentViewWorkShortResp": { "type": "object", "properties": { "is_started": { @@ -423,7 +516,7 @@ const docTemplate = `{ "type": "boolean" }, "work": { - "$ref": "#/definitions/dto.WorkResp" + "$ref": "#/definitions/dto.WorkShortResp" } } }, @@ -441,15 +534,12 @@ const docTemplate = `{ } } }, - "dto.SvProfile": { + "dto.Supervisor": { "type": "object", "properties": { "about": { "type": "string" }, - "avatarUrl": { - "type": "string" - }, "birthdate": { "type": "string" }, @@ -459,26 +549,46 @@ const docTemplate = `{ "email": { "type": "string" }, - "firstName": { + "first_name": { + "type": "string" + }, + "last_name": { "type": "string" }, - "lastName": { + "photo_url": { "type": "string" + }, + "user_id": { + "type": "integer" } } }, - "dto.SvWorkPlenty": { + "dto.SupervisorShort": { + "type": "object", + "properties": { + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "user_id": { + "type": "integer" + } + } + }, + "dto.SupervisorViewWorkPlenty": { "type": "object", "properties": { "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.SvWorkResp" + "$ref": "#/definitions/dto.SupervisorViewWorkShortResp" } } } }, - "dto.SvWorkResp": { + "dto.SupervisorViewWorkShortResp": { "type": "object", "properties": { "is_full": { @@ -488,7 +598,7 @@ const docTemplate = `{ "type": "boolean" }, "work": { - "$ref": "#/definitions/dto.WorkResp" + "$ref": "#/definitions/dto.WorkShortResp" } } }, @@ -523,48 +633,50 @@ const docTemplate = `{ } } }, - "dto.WorkSv": { + "dto.WorkShortResp": { "type": "object", "properties": { - "about": { - "type": "string" - }, - "avatarUrl": { - "type": "string" - }, - "birthdate": { - "type": "string" - }, - "department": { - "type": "string" - }, - "email": { - "type": "string" - }, - "firstName": { - "type": "string" - }, - "full": { - "type": "boolean" + "id": { + "type": "integer" }, - "head": { - "type": "boolean" + "kind": { + "$ref": "#/definitions/dto.WorkKindResp" }, - "lastName": { - "type": "string" + "subject": { + "$ref": "#/definitions/dto.SubjectResp" } } }, - "dto.WorkSvPlenty": { + "dto.WorkSupervisorPlenty": { "type": "object", "properties": { "supervisors": { "type": "array", "items": { - "$ref": "#/definitions/dto.WorkSv" + "$ref": "#/definitions/dto.WorkSupervisorShort" } } } + }, + "dto.WorkSupervisorShort": { + "type": "object", + "properties": { + "first_name": { + "type": "string" + }, + "full": { + "type": "boolean" + }, + "head": { + "type": "boolean" + }, + "last_name": { + "type": "string" + }, + "user_id": { + "type": "integer" + } + } } }, "securityDefinitions": { diff --git a/swagger/swagger.json b/swagger/swagger.json index 673765b..621a378 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -31,14 +31,14 @@ "parameters": [ { "type": "string", - "description": "User email", + "description": "UserFull email", "name": "username", "in": "formData", "required": true }, { "type": "string", - "description": "User password", + "description": "UserFull password", "name": "password", "in": "formData", "required": true @@ -61,6 +61,45 @@ } }, "/api/v1/relations/": { + "get": { + "security": [ + { + "OAuth2Password": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "relation" + ], + "summary": "Get relations", + "parameters": [ + { + "type": "integer", + "description": "Student ID", + "name": "student_id", + "in": "query" + }, + { + "type": "integer", + "description": "Supervisor ID", + "name": "supervisor_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/dto.RelationPlenty" + } + }, + "404": { + "description": "Not Found" + } + } + }, "post": { "security": [ { @@ -89,52 +128,52 @@ } ], "responses": { - "200": { - "description": "OK", + "201": { + "description": "Created", "schema": { "$ref": "#/definitions/dto.RelationCreateResp" } } } - } - }, - "/api/v1/students/{student_id}/profile": { - "get": { + }, + "patch": { "security": [ { "OAuth2Password": [] } ], + "consumes": [ + "application/json" + ], "produces": [ "application/json" ], "tags": [ - "student" + "relation" ], - "summary": "Get student's profile", + "summary": "Update relation", "parameters": [ { - "type": "integer", - "description": "Student ID", - "name": "student_id", - "in": "path", - "required": true + "description": "Relation data", + "name": "CreateRelation", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/dto.RelationUpdateReq" + } } ], "responses": { "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StProfile" + "$ref": "#/definitions/dto.RelationResp" } - }, - "404": { - "description": "Not Found" } } } }, - "/api/v1/students/{student_id}/relations": { + "/api/v1/students/{student_id}/profile": { "get": { "security": [ { @@ -147,7 +186,7 @@ "tags": [ "student" ], - "summary": "Get student's bids", + "summary": "Get student's profile", "parameters": [ { "type": "integer", @@ -161,7 +200,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StRelationPlenty" + "$ref": "#/definitions/dto.Student" } }, "404": { @@ -197,7 +236,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.StWorkPlenty" + "$ref": "#/definitions/dto.StudentViewWorkPlenty" } } } @@ -230,7 +269,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SvProfile" + "$ref": "#/definitions/dto.Supervisor" } } } @@ -263,7 +302,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.SvWorkPlenty" + "$ref": "#/definitions/dto.SupervisorViewWorkPlenty" } } } @@ -296,7 +335,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSvPlenty" + "$ref": "#/definitions/dto.WorkSupervisorPlenty" } } } @@ -343,75 +382,129 @@ } } }, - "dto.StProfile": { + "dto.RelationPlenty": { "type": "object", "properties": { - "department": { - "type": "string" + "relations": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.RelationShortResp" + } + } + } + }, + "dto.RelationResp": { + "type": "object", + "properties": { + "relation_id": { + "type": "integer" }, - "email": { + "status": { "type": "string" }, - "firstName": { - "type": "string" + "student": { + "$ref": "#/definitions/dto.Student" }, - "lastName": { - "type": "string" + "supervisor": { + "$ref": "#/definitions/dto.Supervisor" }, - "photoUrl": { - "type": "string" + "work": { + "$ref": "#/definitions/dto.WorkResp" + } + } + }, + "dto.RelationShortResp": { + "type": "object", + "properties": { + "relation_id": { + "type": "integer" }, - "studentCard": { + "status": { "type": "string" }, - "year": { + "student": { + "$ref": "#/definitions/dto.StudentShort" + }, + "student_id": { + "type": "integer" + }, + "supervisor": { + "$ref": "#/definitions/dto.SupervisorShort" + }, + "supervisor_id": { "type": "integer" + }, + "work": { + "$ref": "#/definitions/dto.WorkShortResp" } } }, - "dto.StRelationPlenty": { + "dto.RelationUpdateReq": { "type": "object", "properties": { - "relations": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.StRelationResp" - } + "relation_id": { + "type": "integer" + }, + "status": { + "type": "string" } } }, - "dto.StRelationResp": { + "dto.Student": { "type": "object", "properties": { - "created_at": { + "department": { "type": "string" }, - "id": { + "email": { + "type": "string" + }, + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "photo_url": { + "type": "string" + }, + "student_card": { + "type": "string" + }, + "user_id": { "type": "integer" }, - "status": { + "year": { + "type": "integer" + } + } + }, + "dto.StudentShort": { + "type": "object", + "properties": { + "first_name": { "type": "string" }, - "supervisor": { - "$ref": "#/definitions/dto.SvProfile" + "last_name": { + "type": "string" }, - "work": { - "$ref": "#/definitions/dto.WorkResp" + "user_id": { + "type": "integer" } } }, - "dto.StWorkPlenty": { + "dto.StudentViewWorkPlenty": { "type": "object", "properties": { "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.StWorkResp" + "$ref": "#/definitions/dto.StudentViewWorkShortResp" } } } }, - "dto.StWorkResp": { + "dto.StudentViewWorkShortResp": { "type": "object", "properties": { "is_started": { @@ -419,7 +512,7 @@ "type": "boolean" }, "work": { - "$ref": "#/definitions/dto.WorkResp" + "$ref": "#/definitions/dto.WorkShortResp" } } }, @@ -437,15 +530,12 @@ } } }, - "dto.SvProfile": { + "dto.Supervisor": { "type": "object", "properties": { "about": { "type": "string" }, - "avatarUrl": { - "type": "string" - }, "birthdate": { "type": "string" }, @@ -455,26 +545,46 @@ "email": { "type": "string" }, - "firstName": { + "first_name": { + "type": "string" + }, + "last_name": { "type": "string" }, - "lastName": { + "photo_url": { "type": "string" + }, + "user_id": { + "type": "integer" } } }, - "dto.SvWorkPlenty": { + "dto.SupervisorShort": { + "type": "object", + "properties": { + "first_name": { + "type": "string" + }, + "last_name": { + "type": "string" + }, + "user_id": { + "type": "integer" + } + } + }, + "dto.SupervisorViewWorkPlenty": { "type": "object", "properties": { "works": { "type": "array", "items": { - "$ref": "#/definitions/dto.SvWorkResp" + "$ref": "#/definitions/dto.SupervisorViewWorkShortResp" } } } }, - "dto.SvWorkResp": { + "dto.SupervisorViewWorkShortResp": { "type": "object", "properties": { "is_full": { @@ -484,7 +594,7 @@ "type": "boolean" }, "work": { - "$ref": "#/definitions/dto.WorkResp" + "$ref": "#/definitions/dto.WorkShortResp" } } }, @@ -519,48 +629,50 @@ } } }, - "dto.WorkSv": { + "dto.WorkShortResp": { "type": "object", "properties": { - "about": { - "type": "string" - }, - "avatarUrl": { - "type": "string" - }, - "birthdate": { - "type": "string" - }, - "department": { - "type": "string" - }, - "email": { - "type": "string" - }, - "firstName": { - "type": "string" - }, - "full": { - "type": "boolean" + "id": { + "type": "integer" }, - "head": { - "type": "boolean" + "kind": { + "$ref": "#/definitions/dto.WorkKindResp" }, - "lastName": { - "type": "string" + "subject": { + "$ref": "#/definitions/dto.SubjectResp" } } }, - "dto.WorkSvPlenty": { + "dto.WorkSupervisorPlenty": { "type": "object", "properties": { "supervisors": { "type": "array", "items": { - "$ref": "#/definitions/dto.WorkSv" + "$ref": "#/definitions/dto.WorkSupervisorShort" } } } + }, + "dto.WorkSupervisorShort": { + "type": "object", + "properties": { + "first_name": { + "type": "string" + }, + "full": { + "type": "boolean" + }, + "head": { + "type": "boolean" + }, + "last_name": { + "type": "string" + }, + "user_id": { + "type": "integer" + } + } } }, "securityDefinitions": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index d94b92d..e3a9389 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -25,57 +25,92 @@ definitions: relation_id: type: integer type: object - dto.StProfile: + dto.RelationPlenty: + properties: + relations: + items: + $ref: '#/definitions/dto.RelationShortResp' + type: array + type: object + dto.RelationResp: + properties: + relation_id: + type: integer + status: + type: string + student: + $ref: '#/definitions/dto.Student' + supervisor: + $ref: '#/definitions/dto.Supervisor' + work: + $ref: '#/definitions/dto.WorkResp' + type: object + dto.RelationShortResp: + properties: + relation_id: + type: integer + status: + type: string + student: + $ref: '#/definitions/dto.StudentShort' + student_id: + type: integer + supervisor: + $ref: '#/definitions/dto.SupervisorShort' + supervisor_id: + type: integer + work: + $ref: '#/definitions/dto.WorkShortResp' + type: object + dto.RelationUpdateReq: + properties: + relation_id: + type: integer + status: + type: string + type: object + dto.Student: properties: department: type: string email: type: string - firstName: + first_name: type: string - lastName: + last_name: type: string - photoUrl: + photo_url: type: string - studentCard: + student_card: type: string + user_id: + type: integer year: type: integer type: object - dto.StRelationPlenty: + dto.StudentShort: properties: - relations: - items: - $ref: '#/definitions/dto.StRelationResp' - type: array - type: object - dto.StRelationResp: - properties: - created_at: + first_name: type: string - id: - type: integer - status: + last_name: type: string - supervisor: - $ref: '#/definitions/dto.SvProfile' - work: - $ref: '#/definitions/dto.WorkResp' + user_id: + type: integer type: object - dto.StWorkPlenty: + dto.StudentViewWorkPlenty: properties: works: items: - $ref: '#/definitions/dto.StWorkResp' + $ref: '#/definitions/dto.StudentViewWorkShortResp' type: array type: object - dto.StWorkResp: + dto.StudentViewWorkShortResp: properties: is_started: description: TODO type: boolean work: - $ref: '#/definitions/dto.WorkResp' + $ref: '#/definitions/dto.WorkShortResp' type: object dto.SubjectResp: properties: @@ -86,38 +121,49 @@ definitions: name: type: string type: object - dto.SvProfile: + dto.Supervisor: properties: about: type: string - avatarUrl: - type: string birthdate: type: string department: type: string email: type: string - firstName: + first_name: + type: string + last_name: + type: string + photo_url: + type: string + user_id: + type: integer + type: object + dto.SupervisorShort: + properties: + first_name: type: string - lastName: + last_name: type: string + user_id: + type: integer type: object - dto.SvWorkPlenty: + dto.SupervisorViewWorkPlenty: properties: works: items: - $ref: '#/definitions/dto.SvWorkResp' + $ref: '#/definitions/dto.SupervisorViewWorkShortResp' type: array type: object - dto.SvWorkResp: + dto.SupervisorViewWorkShortResp: properties: is_full: type: boolean is_head: type: boolean work: - $ref: '#/definitions/dto.WorkResp' + $ref: '#/definitions/dto.WorkShortResp' type: object dto.WorkKindResp: properties: @@ -139,33 +185,34 @@ definitions: subject: $ref: '#/definitions/dto.SubjectResp' type: object - dto.WorkSv: + dto.WorkShortResp: properties: - about: - type: string - avatarUrl: - type: string - birthdate: - type: string - department: - type: string - email: - type: string - firstName: + id: + type: integer + kind: + $ref: '#/definitions/dto.WorkKindResp' + subject: + $ref: '#/definitions/dto.SubjectResp' + type: object + dto.WorkSupervisorPlenty: + properties: + supervisors: + items: + $ref: '#/definitions/dto.WorkSupervisorShort' + type: array + type: object + dto.WorkSupervisorShort: + properties: + first_name: type: string full: type: boolean head: type: boolean - lastName: + last_name: type: string - type: object - dto.WorkSvPlenty: - properties: - supervisors: - items: - $ref: '#/definitions/dto.WorkSv' - type: array + user_id: + type: integer type: object host: localhost:8080 info: @@ -182,12 +229,12 @@ paths: consumes: - application/x-www-form-urlencoded parameters: - - description: User email + - description: UserFull email in: formData name: username required: true type: string - - description: User password + - description: UserFull password in: formData name: password required: true @@ -207,7 +254,31 @@ paths: tags: - auth /api/v1/relations/: - post: + get: + parameters: + - description: Student ID + in: query + name: student_id + type: integer + - description: Supervisor ID + in: query + name: supervisor_id + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/dto.RelationPlenty' + "404": + description: Not Found + security: + - OAuth2Password: [] + summary: Get relations + tags: + - relation + patch: consumes: - application/json parameters: @@ -216,42 +287,42 @@ paths: name: CreateRelation required: true schema: - $ref: '#/definitions/dto.RelationCreateReq' + $ref: '#/definitions/dto.RelationUpdateReq' produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/dto.RelationCreateResp' + $ref: '#/definitions/dto.RelationResp' security: - OAuth2Password: [] - summary: Create relation + summary: Update relation tags: - relation - /api/v1/students/{student_id}/profile: - get: + post: + consumes: + - application/json parameters: - - description: Student ID - in: path - name: student_id + - description: Relation data + in: body + name: CreateRelation required: true - type: integer + schema: + $ref: '#/definitions/dto.RelationCreateReq' produces: - application/json responses: - "200": - description: OK + "201": + description: Created schema: - $ref: '#/definitions/dto.StProfile' - "404": - description: Not Found + $ref: '#/definitions/dto.RelationCreateResp' security: - OAuth2Password: [] - summary: Get student's profile + summary: Create relation tags: - - student - /api/v1/students/{student_id}/relations: + - relation + /api/v1/students/{student_id}/profile: get: parameters: - description: Student ID @@ -265,12 +336,12 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.StRelationPlenty' + $ref: '#/definitions/dto.Student' "404": description: Not Found security: - OAuth2Password: [] - summary: Get student's bids + summary: Get student's profile tags: - student /api/v1/students/{student_id}/works: @@ -287,7 +358,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.StWorkPlenty' + $ref: '#/definitions/dto.StudentViewWorkPlenty' security: - OAuth2Password: [] summary: Get student's works @@ -307,7 +378,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.SvProfile' + $ref: '#/definitions/dto.Supervisor' security: - OAuth2Password: [] summary: Get supervisor's profile @@ -327,7 +398,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.SvWorkPlenty' + $ref: '#/definitions/dto.SupervisorViewWorkPlenty' security: - OAuth2Password: [] summary: Get supervisor's works @@ -347,7 +418,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.WorkSvPlenty' + $ref: '#/definitions/dto.WorkSupervisorPlenty' security: - OAuth2Password: [] summary: Get supervisors of the work From d857c49bd8c2b7e554ffaf5998bb412c73bd645b Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Mon, 3 Oct 2022 12:51:36 +0300 Subject: [PATCH 10/12] upgrade: waypoints works --- internal/app/app.go | 3 +- internal/controller/http/interfaces.go | 3 +- internal/controller/http/student.go | 2 +- internal/controller/http/supervisor.go | 21 +++++ internal/controller/http/works.go | 28 +++++- internal/dto/supervisors.go | 4 - internal/dto/waypoints.go | 13 +++ internal/dto/works_common.go | 14 +++ internal/entity/waypoint.go | 4 +- internal/entity/work.go | 4 +- internal/service/interfaces.go | 8 +- internal/service/profile.go | 8 +- internal/service/repo_pg/supervisor.go | 32 +++++++ internal/service/repo_pg/waypoint.go | 36 +++++++ internal/service/repo_pg/work.go | 53 +++++------ internal/service/work.go | 93 +++++++++++++++++-- .../20221003080212_create_waypoints.down.sql | 1 + .../20221003080212_create_waypoints.up.sql | 15 +++ swagger/docs.go | 71 +++++++++----- swagger/swagger.json | 71 +++++++++----- swagger/swagger.yaml | 48 ++++++---- 21 files changed, 414 insertions(+), 118 deletions(-) create mode 100644 internal/dto/waypoints.go create mode 100644 internal/service/repo_pg/waypoint.go create mode 100644 migrations/20221003080212_create_waypoints.down.sql create mode 100644 migrations/20221003080212_create_waypoints.up.sql diff --git a/internal/app/app.go b/internal/app/app.go index 9d227a2..01efae6 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -24,6 +24,7 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, relationRepo := repo_pg.NewRelation(pg, l) //profileRepo := repo_pg.NewProfile(pg, l) workRepo := repo_pg.NewWork(pg, l) + waypointRepo := repo_pg.NewWaypointRepo(pg, l) feedbackRepo := repo_pg.NewFeedback(pg, l) userRepo := repo_pg.NewUser(pg, l) studentRepo := repo_pg.NewStudent(pg, l) @@ -32,7 +33,7 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, authService := service.NewAuth(userRepo, l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) profileService := service.NewProfile(studentRepo, supervisorRepo, l) //bidService := service.NewBid(relationRepo, l) - workService := service.NewWork(workRepo, relationRepo, studentRepo, l) + workService := service.NewWork(workRepo, relationRepo, studentRepo, supervisorRepo, waypointRepo, l) relationService := service.NewRelation(relationRepo, l) feedbackService := service.NewFeedback(feedbackRepo, l) diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index 8765e27..bf29980 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -19,9 +19,10 @@ type ( Get(RelationID int) (*dto.RelationResp, error) } WorkService interface { + //GetPlenty() (*dto.WorkPlenty, error) + Get(workID int) (*dto.WorkFullResp, error) GetStudentWorks(studentID int) (*dto.StudentViewWorkPlenty, error) GetSupervisorWorks(supervisorID int) (*dto.SupervisorViewWorkPlenty, error) - GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error) } FeedbackService interface { Add(data *dto.FeedbackReq) (int, error) diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index fa81fc8..03d25bc 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -156,7 +156,7 @@ func NewStudentRoutes( //student.GET("/:student_id/relations", ctrl.get) //student.PUT("/bid", ctrl.applyBid) //student.POST("/ssr", ctrl.createSSR) - //student.GET("/work/supervisor_id", ctrl.getSupervisors) + //student.GET("/work/supervisor_id", ctrl.getPlenty) //student.GET("/feedback/:supervisor_id", ctrl.getFeedback) //student.PUT("/feedback", ctrl.provideFeedback) } diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index 85f84d6..2e7be93 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -113,6 +113,26 @@ func (ctrl *supervisor) getWorks(ctx echo.Context) error { // // return ctx.JSON(http.StatusOK, resp) // } + +//// ShowAccount godoc +//// @Summary Get supervisors of the work +//// @Tags supervisors +//// @Param work_id path int true "Work ID" +//// @Produce json +//// @Success 200 {object} dto.WorkSupervisorPlenty +//// @Router /api/v1/supervisors [get] +//// @Security OAuth2Password +//func (ctrl *supervisor) getSupervisors(ctx echo.Context) error { +// workID, _ := strconv.Atoi(ctx.QueryParam("work_id")) +// +// respDTO, err := ctrl.workService.GetWorkSupervisors(workID) +// if err != nil { +// return echo.ErrNotFound +// } +// +// return ctx.JSON(http.StatusOK, respDTO) +//} + func NewSupervisorRoutes( router *echo.Group, l logger.Interface, @@ -128,6 +148,7 @@ func NewSupervisorRoutes( { g.GET("/:supervisor_id/profile", ctrl.getProfile) g.GET("/:supervisor_id/works", ctrl.getWorks) + //g.GET("/", ctrl.getSupervisors) //g.GET("/bid", ctrl.getBids) //g.POST("/bid/resolve", ctrl.resolveBid) //g.GET("/work", ctrl.getWorks) diff --git a/internal/controller/http/works.go b/internal/controller/http/works.go index fa2d5f4..95f8d87 100644 --- a/internal/controller/http/works.go +++ b/internal/controller/http/works.go @@ -14,18 +14,35 @@ type works struct { workService WorkService } +//// ShowAccount godoc +//// @Summary Get supervisors of the work +//// @Tags works +//// @Param work_id path int true "Work ID" +//// @Produce json +//// @Success 200 {object} dto.WorkPlenty +//// @Router /api/v1/works/ [get] +//// @Security OAuth2Password +//func (ctrl *works) getPlenty(ctx echo.Context) error { +// respDTO, err := ctrl.workService.GetPlenty() +// if err != nil { +// return echo.ErrNotFound +// } +// +// return ctx.JSON(http.StatusOK, respDTO) +//} + // ShowAccount godoc // @Summary Get supervisors of the work // @Tags works // @Param work_id path int true "Work ID" // @Produce json -// @Success 200 {object} dto.WorkSupervisorPlenty -// @Router /api/v1/works/{work_id}/supervisors [get] +// @Success 200 {object} dto.WorkFullResp +// @Router /api/v1/works/{work_id} [get] // @Security OAuth2Password -func (ctrl *works) getSupervisors(ctx echo.Context) error { +func (ctrl *works) get(ctx echo.Context) error { workID, _ := strconv.Atoi(ctx.Param("work_id")) - respDTO, err := ctrl.workService.GetWorkSupervisors(workID) + respDTO, err := ctrl.workService.Get(workID) if err != nil { return echo.ErrNotFound } @@ -47,7 +64,8 @@ func NewWorksRoutes( works := router.Group("/works", middlewares.MakeAuthMiddleware(config)) { - works.GET("/:work_id/supervisors", ctrl.getSupervisors) + //works.GET("/", ctrl.getPlenty) + works.GET("/:work_id", ctrl.get) } } diff --git a/internal/dto/supervisors.go b/internal/dto/supervisors.go index 94556e0..b1b7c1a 100644 --- a/internal/dto/supervisors.go +++ b/internal/dto/supervisors.go @@ -24,7 +24,3 @@ type WorkSupervisorShort struct { IsHead bool `json:"head"` IsFull bool `json:"full"` } - -type WorkSupervisorPlenty struct { - Supervisors []*WorkSupervisorShort `json:"supervisors"` -} diff --git a/internal/dto/waypoints.go b/internal/dto/waypoints.go new file mode 100644 index 0000000..3eb1de4 --- /dev/null +++ b/internal/dto/waypoints.go @@ -0,0 +1,13 @@ +package dto + +import "ssr/pkg/misc" + +type WaypointResp struct { + Title string `json:"title"` + Description string `json:"description"` + Deadline misc.Date `json:"deadline" swaggertype:"string"` +} + +type WaypointPlenty struct { + Waypoints []*WaypointResp `json:"waypoints"` +} diff --git a/internal/dto/works_common.go b/internal/dto/works_common.go index 1434ab5..4b9f077 100644 --- a/internal/dto/works_common.go +++ b/internal/dto/works_common.go @@ -8,8 +8,22 @@ type WorkResp struct { Kind WorkKindResp `json:"kind"` } +type WorkFullResp struct { + WorkID int `json:"id"` + Description string `json:"description"` + Semester int8 `json:"semester"` + Subject SubjectResp `json:"subject"` + Kind WorkKindResp `json:"kind"` + Waypoints []*WaypointResp `json:"waypoints"` + Supervisors []*WorkSupervisorShort `json:"supervisors"` +} + type WorkShortResp struct { WorkID int `json:"id"` Subject SubjectResp `json:"subject"` Kind WorkKindResp `json:"kind"` } + +type WorkPlenty struct { + Works []*WorkShortResp `json:"works"` +} diff --git a/internal/entity/waypoint.go b/internal/entity/waypoint.go index adaa0d8..851d3e2 100644 --- a/internal/entity/waypoint.go +++ b/internal/entity/waypoint.go @@ -5,7 +5,9 @@ import ( ) type Waypoint struct { - WorkID int + WaypointID int `db:"waypoint_id"` + WorkID int `db:"work_id"` Deadline time.Time + Title string Description string } diff --git a/internal/entity/work.go b/internal/entity/work.go index 9a4da7d..57e5d57 100644 --- a/internal/entity/work.go +++ b/internal/entity/work.go @@ -13,13 +13,13 @@ type Work struct { Semester int8 } -type SvWork struct { +type SupervisorViewWork struct { Work IsHead bool `db:"is_head"` IsFull bool `db:"is_full"` } -type WorkSv struct { +type WorkSupervisor struct { Supervisor `db:"sv"` IsHead bool `db:"is_head"` IsFull bool `db:"is_full"` diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index c81afb2..5f5c0d0 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -14,6 +14,7 @@ type ( } SupervisorRepo interface { GetFullSupervisor(userID int) (*entity.Supervisor, error) + GetSupervisorsByWorkID(workID int) ([]*entity.WorkSupervisor, error) } ProfileRepo interface { GetStProfile(email string) (*entity.StProfile, error) @@ -28,12 +29,15 @@ type ( GetRelationStatus(studentID, workID int) (entity.StatusSSR, error) } WorkRepo interface { + Get(workID int) (*entity.Work, error) GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) - GetSupervisorWorks(supervisorID int) ([]*entity.SvWork, error) - GetWorkSupervisors(workID int) ([]*entity.WorkSv, error) + GetSupervisorWorks(supervisorID int) ([]*entity.SupervisorViewWork, error) } FeedbackRepo interface { Create(studentID, supervisorID, workID int, content string) (int, error) GetBySupervisorID(supervisorID int) ([]*entity.Feedback, error) } + WaypointRepo interface { + GetPlenty(workID int) ([]*entity.Waypoint, error) + } ) diff --git a/internal/service/profile.go b/internal/service/profile.go index 11bb01e..d891619 100644 --- a/internal/service/profile.go +++ b/internal/service/profile.go @@ -20,8 +20,8 @@ func NewProfile(stRepo StudentRepo, svRepo SupervisorRepo, l logger.Interface) * } } -func (uc *Profile) GetStudentProfile(userID int) (*dto.Student, error) { - dbData, err := uc.stRepo.GetStudent(userID) +func (service *Profile) GetStudentProfile(userID int) (*dto.Student, error) { + dbData, err := service.stRepo.GetStudent(userID) if err != nil { return nil, err } @@ -37,8 +37,8 @@ func (uc *Profile) GetStudentProfile(userID int) (*dto.Student, error) { }, nil } -func (uc *Profile) GetSupervisorProfile(userID int) (*dto.Supervisor, error) { - dbData, err := uc.svRepo.GetFullSupervisor(userID) +func (service *Profile) GetSupervisorProfile(userID int) (*dto.Supervisor, error) { + dbData, err := service.svRepo.GetFullSupervisor(userID) if err != nil { return nil, err } diff --git a/internal/service/repo_pg/supervisor.go b/internal/service/repo_pg/supervisor.go index aaafc76..e1112d6 100644 --- a/internal/service/repo_pg/supervisor.go +++ b/internal/service/repo_pg/supervisor.go @@ -61,3 +61,35 @@ func (repo *Supervisor) GetFullSupervisor(userID int) (*entity.Supervisor, error return &supervisorFull, nil } + +func (repo *Supervisor) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSupervisor, error) { + const query = ` + select + sv.about as "sv.about", + sv.birthdate as "sv.birthdate", + sv.department_id as "sv.department_id", + + u.user_id as "sv.user.user_id", + u.email as "sv.user.email", + u.first_name as "sv.user.first_name", + u.last_name as "sv.user.last_name", + u.photo_url as "sv.user.photo_url", + sw.is_full as is_full, + sw.is_head as is_head + from supervisors sv + join supervisor_work sw on sv.user_id = sw.supervisor_id + join users u using (user_id) + where sw.work_id = $1; + ` + + var supervisors []*entity.WorkSupervisor + + err := repo.Conn.Select(&supervisors, query, workID) + if err != nil { + err := fmt.Errorf("Work->GetSupervisorsByWorkID->repo.Conn.Select: %w", err) + repo.l.Error(err) + return nil, err + } + + return supervisors, nil +} diff --git a/internal/service/repo_pg/waypoint.go b/internal/service/repo_pg/waypoint.go new file mode 100644 index 0000000..365c479 --- /dev/null +++ b/internal/service/repo_pg/waypoint.go @@ -0,0 +1,36 @@ +package repo_pg + +import ( + "fmt" + "ssr/internal/entity" + "ssr/pkg/logger" + "ssr/pkg/postgres" +) + +type Waypoint struct { + *BasePgRepo +} + +func NewWaypointRepo(pg *postgres.Postgres, l logger.Interface) *Waypoint { + return &Waypoint{ + BasePgRepo: NewPgRepo(pg, l), + } +} + +func (repo *Waypoint) GetPlenty(workID int) ([]*entity.Waypoint, error) { + query := ` + select * from waypoints w + where w.work_id = $1; + ` + + var waypoints []*entity.Waypoint + + err := repo.Conn.Select(&waypoints, query, workID) + if err != nil { + err := fmt.Errorf("Waypoint->getPlenty->repo.Conn.Select: %w", err) + repo.l.Error(err) + return nil, err + } + + return waypoints, nil +} diff --git a/internal/service/repo_pg/work.go b/internal/service/repo_pg/work.go index 350bd04..2d194ee 100644 --- a/internal/service/repo_pg/work.go +++ b/internal/service/repo_pg/work.go @@ -17,7 +17,7 @@ func NewWork(pg *postgres.Postgres, l logger.Interface) *Work { } } -func (r *Work) GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) { +func (repo *Work) GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) { const query = ` select w.work_id, w.description, w.semester, wk.name as "work_kind.name", @@ -33,17 +33,17 @@ func (r *Work) GetStudentWorks(departmentID string, semester int) ([]*entity.Wor var works []*entity.Work - err := r.Conn.Select(&works, query, departmentID, semester) + err := repo.Conn.Select(&works, query, departmentID, semester) if err != nil { - err := fmt.Errorf("Work->GetStudentWorks->r.Conn.Select: %w", err) - r.l.Error(err) + err := fmt.Errorf("Work->GetStudentWorks->repo.Conn.Select: %w", err) + repo.l.Error(err) return nil, err } return works, nil } -func (r *Work) GetSupervisorWorks(supervisorID int) ([]*entity.SvWork, error) { +func (repo *Work) GetSupervisorWorks(supervisorID int) ([]*entity.SupervisorViewWork, error) { const query = ` select w.work_id, w.description, w.semester, wk.name as "work_kind.name", @@ -59,44 +59,41 @@ func (r *Work) GetSupervisorWorks(supervisorID int) ([]*entity.SvWork, error) { join work_kinds wk using (work_kind_id) where sw.supervisor_id = $1; ` - var works []*entity.SvWork + var works []*entity.SupervisorViewWork - err := r.Conn.Select(&works, query, supervisorID) + err := repo.Conn.Select(&works, query, supervisorID) if err != nil { - err := fmt.Errorf("Work->GetSupervisorWorks->r.Conn.Select: %w", err) - r.l.Error(err) + err := fmt.Errorf("Work->GetSupervisorWorks->repo.Conn.Select: %w", err) + repo.l.Error(err) return nil, err } return works, nil } -func (r *Work) GetWorkSupervisors(workID int) ([]*entity.WorkSv, error) { +func (repo *Work) Get(workID int) (*entity.Work, error) { const query = ` select - sv.about as "sv.about", - sv.birthdate as "sv.birthdate", - sv.department_id as "sv.department_id", - u.email as "sv.user.email", - u.first_name as "sv.user.first_name", - u.last_name as "sv.user.last_name", - u.photo_url as "sv.user.photo_url", - sw.is_full as is_full, - sw.is_head as is_head - from supervisors sv - join supervisor_work sw on sv.user_id = sw.supervisor_id - join users u using (user_id) - where sw.work_id = $1; + w.work_id, w.description, w.semester, + wk.work_kind_id as "work_kind.work_kind_id", + wk.name as "work_kind.name", + s.subject_id as "subject.subject_id", + s.name as "subject.name", + s.department_id as "subject.department_id" + from works w + join work_kinds wk using ("work_kind_id") + join subjects s using ("subject_id") + where work_id = $1 ` - var supervisors []*entity.WorkSv + work := entity.Work{} - err := r.Conn.Select(&supervisors, query, workID) + err := repo.Conn.Get(&work, query, workID) if err != nil { - err := fmt.Errorf("Work->GetWorkSupervisors->r.Conn.Select: %w", err) - r.l.Error(err) + err := fmt.Errorf("Work->Get->repo.Conn.Get(): %w", err) + repo.l.Error(err) return nil, err } - return supervisors, nil + return &work, nil } diff --git a/internal/service/work.go b/internal/service/work.go index 834cacd..5a3a181 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -4,6 +4,7 @@ import ( "ssr/internal/dto" "ssr/internal/entity" "ssr/pkg/logger" + "ssr/pkg/misc" "time" ) @@ -12,14 +13,25 @@ type Work struct { workRepo WorkRepo relationRepo RelationRepo stRepo StudentRepo + svRepo SupervisorRepo + waypointRepo WaypointRepo } -func NewWork(workRepo WorkRepo, ssrRepo RelationRepo, stRepo StudentRepo, l logger.Interface) *Work { +func NewWork( + workRepo WorkRepo, + ssrRepo RelationRepo, + stRepo StudentRepo, + svRepo SupervisorRepo, + waypointRepo WaypointRepo, + l logger.Interface, +) *Work { return &Work{ Base: NewBase(l), workRepo: workRepo, relationRepo: ssrRepo, stRepo: stRepo, + svRepo: svRepo, + waypointRepo: waypointRepo, } } @@ -111,17 +123,35 @@ func (service *Work) GetSupervisorWorks(supervisorID int) (*dto.SupervisorViewWo }, nil } -func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, error) { - supervisorsData, err := service.workRepo.GetWorkSupervisors(workID) +func (service *Work) Get(workID int) (*dto.WorkFullResp, error) { + workData, err := service.workRepo.Get(workID) if err != nil { return nil, err } - var resp []*dto.WorkSupervisorShort + waypointsData, err := service.waypointRepo.GetPlenty(workID) + if err != nil { + return nil, err + } + + var waypoints []*dto.WaypointResp + for _, waypointData := range waypointsData { + waypoints = append(waypoints, &dto.WaypointResp{ + Title: waypointData.Title, + Description: waypointData.Description, + Deadline: misc.Date{Time: waypointData.Deadline}, + }) + } + supervisorsData, err := service.svRepo.GetSupervisorsByWorkID(workID) + if err != nil { + return nil, err + } + var supervisors []*dto.WorkSupervisorShort for _, db := range supervisorsData { - resp = append(resp, &dto.WorkSupervisorShort{ + supervisors = append(supervisors, &dto.WorkSupervisorShort{ SupervisorShort: dto.SupervisorShort{ + UserID: db.Supervisor.User.UserID, FirstName: db.User.FirstName, LastName: db.User.LastName, }, @@ -130,7 +160,56 @@ func (service *Work) GetWorkSupervisors(workID int) (*dto.WorkSupervisorPlenty, }) } - return &dto.WorkSupervisorPlenty{ - Supervisors: resp, + return &dto.WorkFullResp{ + WorkID: workData.WorkID, + Description: workData.Description, + Semester: workData.Semester, + Subject: dto.SubjectResp{ + ID: workData.Subject.SubjectID, + Name: workData.Subject.Name, + Department: workData.Subject.DepartmentID, + }, + Kind: dto.WorkKindResp{ + ID: workData.WorkKind.WorkKindID, + Name: workData.WorkKind.Name, + }, + Waypoints: waypoints, + Supervisors: supervisors, }, nil } + +// +//func (service *Work) GetPlenty(workID int) (*dto.WorkFullResp, error) { +// workData, err := service.workRepo.Get(workID) +// if err != nil { +// return nil, err +// } +// +// waypointsData, err := service.waypointRepo.GetPlenty(workID) +// +// var waypoints []*dto.WaypointResp +// +// for _, waypointData := range waypointsData { +// waypoints = append(waypoints, &dto.WaypointResp{ +// Title: waypointData.Title, +// Description: waypointData.Description, +// Deadline: misc.Date{Time: waypointData.Deadline}, +// }) +// } +// +// return &dto.WorkFullResp{ +// WorkID: workData.WorkID, +// Description: workData.Description, +// Semester: workData.Semester, +// Subject: dto.SubjectResp{ +// ID: workData.Subject.SubjectID, +// Name: workData.Subject.Name, +// Department: workData.Subject.DepartmentID, +// }, +// Kind: dto.WorkKindResp{ +// ID: workData.WorkKind.WorkKindID, +// Name: workData.WorkKind.Name, +// }, +// Waypoints: waypoints, +// }, nil +//} diff --git a/migrations/20221003080212_create_waypoints.down.sql b/migrations/20221003080212_create_waypoints.down.sql new file mode 100644 index 0000000..82ded23 --- /dev/null +++ b/migrations/20221003080212_create_waypoints.down.sql @@ -0,0 +1 @@ +drop table "waypoints" cascade; \ No newline at end of file diff --git a/migrations/20221003080212_create_waypoints.up.sql b/migrations/20221003080212_create_waypoints.up.sql new file mode 100644 index 0000000..954e97a --- /dev/null +++ b/migrations/20221003080212_create_waypoints.up.sql @@ -0,0 +1,15 @@ +CREATE TABLE "waypoints" +( + "waypoint_id" bigint unique generated always as identity, + "work_id" bigint not null, + "deadline" date not null, + "title" text not null, + "description" text not null +); + + +ALTER TABLE "waypoints" + ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"); + +insert into waypoints(work_id, deadline, title, description) + values (1, '2022-11-01', 'Выбрать тему', 'Необходимо определиться с темой курсовой работы и предоставить ее руководителю.') diff --git a/swagger/docs.go b/swagger/docs.go index 6e0cd41..ae5ced9 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -312,7 +312,7 @@ const docTemplate = `{ } } }, - "/api/v1/works/{work_id}/supervisors": { + "/api/v1/works/{work_id}": { "get": { "security": [ { @@ -339,7 +339,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSupervisorPlenty" + "$ref": "#/definitions/dto.WorkFullResp" } } } @@ -429,15 +429,9 @@ const docTemplate = `{ "student": { "$ref": "#/definitions/dto.StudentShort" }, - "student_id": { - "type": "integer" - }, "supervisor": { "$ref": "#/definitions/dto.SupervisorShort" }, - "supervisor_id": { - "type": "integer" - }, "work": { "$ref": "#/definitions/dto.WorkShortResp" } @@ -511,10 +505,6 @@ const docTemplate = `{ "dto.StudentViewWorkShortResp": { "type": "object", "properties": { - "is_started": { - "description": "TODO", - "type": "boolean" - }, "work": { "$ref": "#/definitions/dto.WorkShortResp" } @@ -602,6 +592,52 @@ const docTemplate = `{ } } }, + "dto.WaypointResp": { + "type": "object", + "properties": { + "deadline": { + "type": "string" + }, + "description": { + "type": "string" + }, + "title": { + "type": "string" + } + } + }, + "dto.WorkFullResp": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "kind": { + "$ref": "#/definitions/dto.WorkKindResp" + }, + "semester": { + "type": "integer" + }, + "subject": { + "$ref": "#/definitions/dto.SubjectResp" + }, + "supervisors": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.WorkSupervisorShort" + } + }, + "waypoints": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.WaypointResp" + } + } + } + }, "dto.WorkKindResp": { "type": "object", "properties": { @@ -647,17 +683,6 @@ const docTemplate = `{ } } }, - "dto.WorkSupervisorPlenty": { - "type": "object", - "properties": { - "supervisors": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.WorkSupervisorShort" - } - } - } - }, "dto.WorkSupervisorShort": { "type": "object", "properties": { diff --git a/swagger/swagger.json b/swagger/swagger.json index 621a378..fe2bb23 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -308,7 +308,7 @@ } } }, - "/api/v1/works/{work_id}/supervisors": { + "/api/v1/works/{work_id}": { "get": { "security": [ { @@ -335,7 +335,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/dto.WorkSupervisorPlenty" + "$ref": "#/definitions/dto.WorkFullResp" } } } @@ -425,15 +425,9 @@ "student": { "$ref": "#/definitions/dto.StudentShort" }, - "student_id": { - "type": "integer" - }, "supervisor": { "$ref": "#/definitions/dto.SupervisorShort" }, - "supervisor_id": { - "type": "integer" - }, "work": { "$ref": "#/definitions/dto.WorkShortResp" } @@ -507,10 +501,6 @@ "dto.StudentViewWorkShortResp": { "type": "object", "properties": { - "is_started": { - "description": "TODO", - "type": "boolean" - }, "work": { "$ref": "#/definitions/dto.WorkShortResp" } @@ -598,6 +588,52 @@ } } }, + "dto.WaypointResp": { + "type": "object", + "properties": { + "deadline": { + "type": "string" + }, + "description": { + "type": "string" + }, + "title": { + "type": "string" + } + } + }, + "dto.WorkFullResp": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "kind": { + "$ref": "#/definitions/dto.WorkKindResp" + }, + "semester": { + "type": "integer" + }, + "subject": { + "$ref": "#/definitions/dto.SubjectResp" + }, + "supervisors": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.WorkSupervisorShort" + } + }, + "waypoints": { + "type": "array", + "items": { + "$ref": "#/definitions/dto.WaypointResp" + } + } + } + }, "dto.WorkKindResp": { "type": "object", "properties": { @@ -643,17 +679,6 @@ } } }, - "dto.WorkSupervisorPlenty": { - "type": "object", - "properties": { - "supervisors": { - "type": "array", - "items": { - "$ref": "#/definitions/dto.WorkSupervisorShort" - } - } - } - }, "dto.WorkSupervisorShort": { "type": "object", "properties": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index e3a9389..b2bbd54 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -53,12 +53,8 @@ definitions: type: string student: $ref: '#/definitions/dto.StudentShort' - student_id: - type: integer supervisor: $ref: '#/definitions/dto.SupervisorShort' - supervisor_id: - type: integer work: $ref: '#/definitions/dto.WorkShortResp' type: object @@ -106,9 +102,6 @@ definitions: type: object dto.StudentViewWorkShortResp: properties: - is_started: - description: TODO - type: boolean work: $ref: '#/definitions/dto.WorkShortResp' type: object @@ -165,6 +158,36 @@ definitions: work: $ref: '#/definitions/dto.WorkShortResp' type: object + dto.WaypointResp: + properties: + deadline: + type: string + description: + type: string + title: + type: string + type: object + dto.WorkFullResp: + properties: + description: + type: string + id: + type: integer + kind: + $ref: '#/definitions/dto.WorkKindResp' + semester: + type: integer + subject: + $ref: '#/definitions/dto.SubjectResp' + supervisors: + items: + $ref: '#/definitions/dto.WorkSupervisorShort' + type: array + waypoints: + items: + $ref: '#/definitions/dto.WaypointResp' + type: array + type: object dto.WorkKindResp: properties: id: @@ -194,13 +217,6 @@ definitions: subject: $ref: '#/definitions/dto.SubjectResp' type: object - dto.WorkSupervisorPlenty: - properties: - supervisors: - items: - $ref: '#/definitions/dto.WorkSupervisorShort' - type: array - type: object dto.WorkSupervisorShort: properties: first_name: @@ -404,7 +420,7 @@ paths: summary: Get supervisor's works tags: - supervisor - /api/v1/works/{work_id}/supervisors: + /api/v1/works/{work_id}: get: parameters: - description: Work ID @@ -418,7 +434,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/dto.WorkSupervisorPlenty' + $ref: '#/definitions/dto.WorkFullResp' security: - OAuth2Password: [] summary: Get supervisors of the work From d460948592bf3875eec04e04bfa1c18ea4f770ba Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Mon, 3 Oct 2022 12:53:16 +0300 Subject: [PATCH 11/12] upgrade: refactored --- internal/service/interfaces.go | 2 +- internal/service/profile.go | 2 +- internal/service/repo_pg/supervisor.go | 16 ++++++++-------- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index 5f5c0d0..2a31222 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -13,7 +13,7 @@ type ( GetStudentShort(userID int) (*entity.StudentShort, error) } SupervisorRepo interface { - GetFullSupervisor(userID int) (*entity.Supervisor, error) + GetSupervisor(userID int) (*entity.Supervisor, error) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSupervisor, error) } ProfileRepo interface { diff --git a/internal/service/profile.go b/internal/service/profile.go index d891619..66e4399 100644 --- a/internal/service/profile.go +++ b/internal/service/profile.go @@ -38,7 +38,7 @@ func (service *Profile) GetStudentProfile(userID int) (*dto.Student, error) { } func (service *Profile) GetSupervisorProfile(userID int) (*dto.Supervisor, error) { - dbData, err := service.svRepo.GetFullSupervisor(userID) + dbData, err := service.svRepo.GetSupervisor(userID) if err != nil { return nil, err } diff --git a/internal/service/repo_pg/supervisor.go b/internal/service/repo_pg/supervisor.go index e1112d6..2077ee2 100644 --- a/internal/service/repo_pg/supervisor.go +++ b/internal/service/repo_pg/supervisor.go @@ -17,24 +17,24 @@ func NewSupervisor(pg *postgres.Postgres, l logger.Interface) *Supervisor { } } -func (repo *Supervisor) GetSupervisor(userID int) (*entity.SupervisorShort, error) { +func (repo *Supervisor) GetSupervisorShort(userID int) (*entity.SupervisorShort, error) { const query = ` select * from supervisors where user_id = $1 ` - supervisor := entity.SupervisorShort{} + supervisorShort := entity.SupervisorShort{} - err := repo.Conn.Get(&supervisor, query, userID) + err := repo.Conn.Get(&supervisorShort, query, userID) if err != nil { err := fmt.Errorf("SupervisorShort->Get->repo.Conn.Get(): %w", err) repo.l.Error(err) return nil, err } - return &supervisor, nil + return &supervisorShort, nil } -func (repo *Supervisor) GetFullSupervisor(userID int) (*entity.Supervisor, error) { +func (repo *Supervisor) GetSupervisor(userID int) (*entity.Supervisor, error) { const query = ` select s.about, @@ -50,16 +50,16 @@ func (repo *Supervisor) GetFullSupervisor(userID int) (*entity.Supervisor, error where user_id = $1 ` - supervisorFull := entity.Supervisor{} + supervisor := entity.Supervisor{} - err := repo.Conn.Get(&supervisorFull, query, userID) + err := repo.Conn.Get(&supervisor, query, userID) if err != nil { err := fmt.Errorf("SupervisorShort->GetFull->repo.Conn.Get(): %w", err) repo.l.Error(err) return nil, err } - return &supervisorFull, nil + return &supervisor, nil } func (repo *Supervisor) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSupervisor, error) { From 49b3a87cbbf2a22aae6b8c2bc7afcde51f336e03 Mon Sep 17 00:00:00 2001 From: ivaaahn Date: Tue, 4 Oct 2022 23:11:15 +0300 Subject: [PATCH 12/12] upgrade: refactored --- internal/app/app.go | 5 -- internal/controller/http/interfaces.go | 5 -- internal/controller/http/router.go | 3 +- internal/controller/http/student.go | 84 ------------------ internal/controller/http/supervisor.go | 85 +------------------ internal/controller/http/works.go | 18 ---- internal/dto/feedback.go | 26 ------ internal/entity/feedback.go | 15 ---- internal/entity/user.go | 6 +- internal/service/auth.go | 4 +- internal/service/bid.go | 75 ---------------- internal/service/feedback.go | 45 ---------- internal/service/interfaces.go | 8 -- internal/service/relation.go | 47 ++-------- internal/service/repo_pg/feedback.go | 63 -------------- internal/service/repo_pg/profile.go | 58 ------------- internal/service/repo_pg/relation.go | 24 +++--- internal/service/repo_pg/student.go | 12 +-- internal/service/repo_pg/supervisor.go | 10 +-- internal/service/repo_pg/user.go | 2 +- internal/service/work.go | 38 +-------- migrations/20220508102907_create_users.up.sql | 8 +- .../20220509115124_create_students.up.sql | 2 +- .../20220509192451_create_supervisors.up.sql | 2 +- .../20220509195738_create_sv_work.up.sql | 1 + .../20220606071757_create_feedbacks.down.sql | 1 - .../20220606071757_create_feedbacks.up.sql | 22 ----- .../20221003080212_create_waypoints.up.sql | 2 +- 28 files changed, 47 insertions(+), 624 deletions(-) delete mode 100644 internal/dto/feedback.go delete mode 100644 internal/entity/feedback.go delete mode 100644 internal/service/bid.go delete mode 100644 internal/service/feedback.go delete mode 100644 internal/service/repo_pg/feedback.go delete mode 100644 internal/service/repo_pg/profile.go delete mode 100644 migrations/20220606071757_create_feedbacks.down.sql delete mode 100644 migrations/20220606071757_create_feedbacks.up.sql diff --git a/internal/app/app.go b/internal/app/app.go index 01efae6..7af04f9 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -22,20 +22,16 @@ func setupMiddlewares(server *echo.Echo) { func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, cfg *config.Config) { relationRepo := repo_pg.NewRelation(pg, l) - //profileRepo := repo_pg.NewProfile(pg, l) workRepo := repo_pg.NewWork(pg, l) waypointRepo := repo_pg.NewWaypointRepo(pg, l) - feedbackRepo := repo_pg.NewFeedback(pg, l) userRepo := repo_pg.NewUser(pg, l) studentRepo := repo_pg.NewStudent(pg, l) supervisorRepo := repo_pg.NewSupervisor(pg, l) authService := service.NewAuth(userRepo, l, cfg.Auth.TokenExp, []byte(cfg.Auth.SigningKey)) profileService := service.NewProfile(studentRepo, supervisorRepo, l) - //bidService := service.NewBid(relationRepo, l) workService := service.NewWork(workRepo, relationRepo, studentRepo, supervisorRepo, waypointRepo, l) relationService := service.NewRelation(relationRepo, l) - feedbackService := service.NewFeedback(feedbackRepo, l) ctrl.NewRouter( server, @@ -45,7 +41,6 @@ func makeInjections(server *echo.Echo, pg *postgres.Postgres, l *logger.Logger, profileService, workService, relationService, - feedbackService, ) } diff --git a/internal/controller/http/interfaces.go b/internal/controller/http/interfaces.go index bf29980..03bc4f4 100644 --- a/internal/controller/http/interfaces.go +++ b/internal/controller/http/interfaces.go @@ -19,13 +19,8 @@ type ( Get(RelationID int) (*dto.RelationResp, error) } WorkService interface { - //GetPlenty() (*dto.WorkPlenty, error) Get(workID int) (*dto.WorkFullResp, error) GetStudentWorks(studentID int) (*dto.StudentViewWorkPlenty, error) GetSupervisorWorks(supervisorID int) (*dto.SupervisorViewWorkPlenty, error) } - FeedbackService interface { - Add(data *dto.FeedbackReq) (int, error) - GetOnSupervisor(supervisorID int) (*dto.FeedbackPlenty, error) - } ) diff --git a/internal/controller/http/router.go b/internal/controller/http/router.go index bc86443..cbe18d4 100644 --- a/internal/controller/http/router.go +++ b/internal/controller/http/router.go @@ -16,14 +16,13 @@ func NewRouter( profiles ProfileService, works WorkService, relations RelationsService, - feedback FeedbackService, ) { g := server.Group("/api/v1") g.GET("/swagger/*", echoSwagger.WrapHandler) { NewAuthRoutes(g, l, auth) - NewStudentRoutes(g, l, config, profiles, works, relations, feedback) + NewStudentRoutes(g, l, config, profiles, works, relations) NewSupervisorRoutes(g, l, config, profiles, works) NewWorksRoutes(g, l, config, works) NewRelationRoutes(g, l, config, relations) diff --git a/internal/controller/http/student.go b/internal/controller/http/student.go index 03d25bc..f5003a0 100644 --- a/internal/controller/http/student.go +++ b/internal/controller/http/student.go @@ -14,7 +14,6 @@ type student struct { profileService ProfileService workService WorkService relationsService RelationsService - feedbackService FeedbackService } // ShowAccount godoc @@ -56,81 +55,6 @@ func (ctrl *student) getWorks(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -//// ShowAccount godoc -//// @Summary Start SSR -//// @Tags student -//// @Accept json -//// @Param ApplyBid body dto.CreateSSR true "ssr info" -//// @Produce json -//// @Success 200 {object} dto.StViewRelation -//// @Router /api/student/ssr [post] -//// @Security Auth -//func (ctrl *student) createSSR(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// reqDTO := &dto.CreateSSR{} -// if err := ctx.Bind(reqDTO); err != nil { -// return echo.ErrBadRequest -// } -// -// respDTO, err := ctrl.relationService.Accept(reqDTO) -// if err != nil { -// return echo.ErrInternalServerError -// } -// -// return ctx.JSON(http.StatusCreated, respDTO) -//} - -//// ShowAccount godoc -//// @Summary Provide a feedback -//// @Tags student -//// @Accept json -//// @Param Feedback body dto.FeedbackReq true "feedback info" -//// @Produce json -//// @Success 201 {object} dto.FeedbackAddResp -//// @Failure 500 -//// @Router /api/student/feedback [put] -//// @Security Authorization -//func (ctrl *student) provideFeedback(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// reqDTO := &dto.FeedbackReq{} -// if err := ctx.Bind(reqDTO); err != nil { -// return echo.ErrBadRequest -// } -// -// id, err := ctrl.feedbackService.Add(reqDTO) -// if err != nil { -// return echo.NewHTTPError(http.StatusConflict) -// } -// -// return ctx.JSON(http.StatusCreated, dto.FeedbackAddResp{FeedbackID: id}) -//} - -//// ShowAccount godoc -//// @Summary Get feedbacks on the supervisor. -//// @Tags student -//// @Param supervisor_id path integer true "Supervisor ID" -//// @Produce json -//// @Success 200 {object} dto.FeedbackPlenty -//// @Router /api/student/feedback [get] -//// @Security Auth -//func (ctrl *student) getFeedback(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// supervisorID, _ := strconv.Atoi(ctx.Param("supervisor_id")) -// -// respDTO, err := ctrl.feedbackService.GetOnSupervisor(supervisorID) -// if err != nil { -// return echo.ErrInternalServerError -// } -// -// return ctx.JSON(http.StatusOK, respDTO) -//} - func NewStudentRoutes( router *echo.Group, l logger.Interface, @@ -138,14 +62,12 @@ func NewStudentRoutes( profileService ProfileService, worksService WorkService, relationService RelationsService, - feedbackService FeedbackService, ) { ctrl := &student{ l, profileService, worksService, relationService, - feedbackService, } student := router.Group("/students", middlewares.MakeAuthMiddleware(config), middlewares.CheckRole) @@ -153,12 +75,6 @@ func NewStudentRoutes( { student.GET("/:student_id/profile", ctrl.getProfile) student.GET("/:student_id/works", ctrl.getWorks) - //student.GET("/:student_id/relations", ctrl.get) - //student.PUT("/bid", ctrl.applyBid) - //student.POST("/ssr", ctrl.createSSR) - //student.GET("/work/supervisor_id", ctrl.getPlenty) - //student.GET("/feedback/:supervisor_id", ctrl.getFeedback) - //student.PUT("/feedback", ctrl.provideFeedback) } } diff --git a/internal/controller/http/supervisor.go b/internal/controller/http/supervisor.go index 2e7be93..26273f7 100644 --- a/internal/controller/http/supervisor.go +++ b/internal/controller/http/supervisor.go @@ -12,8 +12,7 @@ import ( type supervisor struct { l logger.Interface profileService ProfileService - //relationsService SvBidService - workService WorkService + workService WorkService } // ShowAccount godoc @@ -56,89 +55,11 @@ func (ctrl *supervisor) getWorks(ctx echo.Context) error { return ctx.JSON(http.StatusOK, respDTO) } -// // ShowAccount godoc -// // @Summary GetUserByEmail supervisor's bids -// // @Tags supervisor -// // @Param supervisor_id query int true "Supervisor ID" -// // @Produce json -// // @Success 200 {object} dto.SvBids -// // @Router /api/supervisor/bid [get] -// // @Security Auth -// -// func (ctrl *supervisor) getBids(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// supervisorID, _ := strconv.Atoi(ctx.QueryParam("supervisor_id")) -// -// respDTO, err := ctrl.relationsService.GetSupervisorRelations(supervisorID) -// if err != nil { -// ctrl.l.Error(err) -// return echo.NewHTTPError(http.StatusInternalServerError, "TODO") -// } -// -// return ctx.JSON(http.StatusOK, respDTO) -// } -// -// // ShowAccount godoc -// // @Summary Accept or Decline student's bid -// // @Tags supervisor -// // @Param ResolveBid body dto.ResolveBid true "bid info" -// // @Produce json -// // @Success 200 {object} dto.ResolveBidResp -// // @Router /api/supervisor/bid/resolve [post] -// // @Security Auth -// -// func (ctrl *supervisor) resolveBid(ctx echo.Context) error { -// email, _ := misc.ExtractCtx(ctx) -// ctrl.l.Debug(fmt.Sprintf("Email: %s", email)) -// -// reqDTO := &dto.ResolveBid{} -// if err := ctx.Bind(reqDTO); err != nil { -// return echo.ErrBadRequest -// } -// -// if err := ctrl.relationsService.Resolve(reqDTO); err != nil { -// return echo.NewHTTPError(http.StatusInternalServerError) -// } -// -// newStatus := "" -// if reqDTO.Accept { -// newStatus = "accepted" -// } else { -// newStatus = "rejected" -// } -// -// resp := dto.ResolveBidResp{NewStatus: newStatus} -// -// return ctx.JSON(http.StatusOK, resp) -// } - -//// ShowAccount godoc -//// @Summary Get supervisors of the work -//// @Tags supervisors -//// @Param work_id path int true "Work ID" -//// @Produce json -//// @Success 200 {object} dto.WorkSupervisorPlenty -//// @Router /api/v1/supervisors [get] -//// @Security OAuth2Password -//func (ctrl *supervisor) getSupervisors(ctx echo.Context) error { -// workID, _ := strconv.Atoi(ctx.QueryParam("work_id")) -// -// respDTO, err := ctrl.workService.GetWorkSupervisors(workID) -// if err != nil { -// return echo.ErrNotFound -// } -// -// return ctx.JSON(http.StatusOK, respDTO) -//} - func NewSupervisorRoutes( router *echo.Group, l logger.Interface, config *config.Config, profileService ProfileService, - // relationsService SvBidService, workService WorkService, ) { ctrl := &supervisor{l, profileService, workService} @@ -148,10 +69,6 @@ func NewSupervisorRoutes( { g.GET("/:supervisor_id/profile", ctrl.getProfile) g.GET("/:supervisor_id/works", ctrl.getWorks) - //g.GET("/", ctrl.getSupervisors) - //g.GET("/bid", ctrl.getBids) - //g.POST("/bid/resolve", ctrl.resolveBid) - //g.GET("/work", ctrl.getWorks) } } diff --git a/internal/controller/http/works.go b/internal/controller/http/works.go index 95f8d87..ac42a3d 100644 --- a/internal/controller/http/works.go +++ b/internal/controller/http/works.go @@ -14,23 +14,6 @@ type works struct { workService WorkService } -//// ShowAccount godoc -//// @Summary Get supervisors of the work -//// @Tags works -//// @Param work_id path int true "Work ID" -//// @Produce json -//// @Success 200 {object} dto.WorkPlenty -//// @Router /api/v1/works/ [get] -//// @Security OAuth2Password -//func (ctrl *works) getPlenty(ctx echo.Context) error { -// respDTO, err := ctrl.workService.GetPlenty() -// if err != nil { -// return echo.ErrNotFound -// } -// -// return ctx.JSON(http.StatusOK, respDTO) -//} - // ShowAccount godoc // @Summary Get supervisors of the work // @Tags works @@ -64,7 +47,6 @@ func NewWorksRoutes( works := router.Group("/works", middlewares.MakeAuthMiddleware(config)) { - //works.GET("/", ctrl.getPlenty) works.GET("/:work_id", ctrl.get) } diff --git a/internal/dto/feedback.go b/internal/dto/feedback.go deleted file mode 100644 index f6e49f0..0000000 --- a/internal/dto/feedback.go +++ /dev/null @@ -1,26 +0,0 @@ -package dto - -type FeedbackReq struct { - StudentID int `json:"studentID"` - SupervisorID int `json:"supervisorID"` - WorkID int `json:"workID"` - Content string `json:"content"` -} - -type FeedbackResp struct { - StudentID int `json:"studentID"` - StudentFullName string `json:"student_full_name"` - SupervisorID int `json:"supervisorID"` - WorkID int `json:"workID"` - WorkKind string `json:"work_kind"` - WorkSubject string `json:"work_subject"` - Content string `json:"content"` -} - -type FeedbackAddResp struct { - FeedbackID int `json:"feedback_id"` -} - -type FeedbackPlenty struct { - Feedbacks []*FeedbackResp `json:"feedbacks"` -} diff --git a/internal/entity/feedback.go b/internal/entity/feedback.go deleted file mode 100644 index 34ee542..0000000 --- a/internal/entity/feedback.go +++ /dev/null @@ -1,15 +0,0 @@ -package entity - -import "time" - -type Feedback struct { - FeedbackID int `db:"feedback_id"` - WorkID int `db:"work_id"` - WorkKind string `db:"work_kind"` - WorkSubject string `db:"work_subject"` - StudentID int `db:"student_id"` - StudentFullName string `db:"student_full_name"` - SupervisorID int `db:"supervisor_id"` - CreatedAt time.Time `db:"created_at"` - Content string `db:"content"` -} diff --git a/internal/entity/user.go b/internal/entity/user.go index 7ca3c6e..a8d54d1 100644 --- a/internal/entity/user.go +++ b/internal/entity/user.go @@ -8,7 +8,7 @@ const ( ) type UserFull struct { - UserID int `db:"user_id"` + ID int `db:"id"` Email string `db:"email"` FirstName string `db:"first_name"` LastName string `db:"last_name"` @@ -18,7 +18,7 @@ type UserFull struct { } type User struct { - UserID int `db:"user_id"` + ID int `db:"id"` Email string `db:"email"` FirstName string `db:"first_name"` LastName string `db:"last_name"` @@ -26,7 +26,7 @@ type User struct { } type UserShort struct { - UserID int `db:"user_id"` + ID int `db:"id"` FirstName string `db:"first_name"` LastName string `db:"last_name"` } diff --git a/internal/service/auth.go b/internal/service/auth.go index 8b36f37..f809b87 100644 --- a/internal/service/auth.go +++ b/internal/service/auth.go @@ -36,7 +36,7 @@ func (service *Auth) Login(email, password string) (*dto.LoginResponse, error) { return nil, err } - tokenClaims := misc.NewAppJWTClaims(service.tokenExp, dbData.UserID, string(dbData.Role)) + tokenClaims := misc.NewAppJWTClaims(service.tokenExp, dbData.ID, string(dbData.Role)) token := jwt.NewWithClaims(jwt.SigningMethodHS256, tokenClaims) tokenStr, err := token.SignedString(service.signingKey) @@ -48,7 +48,7 @@ func (service *Auth) Login(email, password string) (*dto.LoginResponse, error) { return &dto.LoginResponse{ Token: tokenStr, TokenType: "Bearer", - UserID: dbData.UserID, + UserID: dbData.ID, Role: string(dbData.Role), }, nil } diff --git a/internal/service/bid.go b/internal/service/bid.go deleted file mode 100644 index b4414f8..0000000 --- a/internal/service/bid.go +++ /dev/null @@ -1,75 +0,0 @@ -package service - -//type Bid struct { -// *Base -// repo RelationRepo -//} -// -//func NewBid(r RelationRepo, l logger.Interface) *Bid { -// return &Bid{ -// Base: NewBase(l), -// repo: r, -// } -//} -// -//func (service *Bid) GetSupervisorBids(supervisorID int) (*dto.SvBids, error) { -// dbData, err := service.repo.GetSupervisorRelations(supervisorID) -// if err != nil { -// return nil, err -// } -// -// var resp []*dto.SvBid -// -// for _, db := range dbData { -// resp = append(resp, &dto.SvBid{ -// BidID: db.RelationID, -// Status: db.Status, -// CreatedAt: db.CreatedAt, -// Student: dto.Student{ -// Email: db.Email, -// FirstName: db.FirstName, -// LastName: db.LastName, -// Year: db.Year, -// PhotoUrl: db.PhotoUrl, -// Department: db.StProfile.DepartmentID, -// }, -// Work: dto.WorkResp{ -// Description: db.Work.Description, -// Semester: db.Work.Semester, -// Kind: dto.WorkKindResp{ -// ID: db.WorkKind.WorkKindID, -// Name: db.WorkKind.Name, -// }, -// Subject: dto.SubjectResp{ -// ID: db.SubjectID, -// Name: db.Subject.Name, -// Department: db.Subject.DepartmentID, -// }, -// }, -// }) -// } -// -// return &dto.SvBids{Bids: resp}, nil -//} -// -////func (service *Bid) Apply(data *dto.RelationCreateReq) (*dto.RelationCreateResp, error) { -//// bidID, err := service.repo.Create(data.StudentID, data.SupervisorID, data.WorkID) -//// if err != nil { -//// return nil, err -//// } -//// -//// return &dto.RelationCreateResp{BidID: bidID}, nil -////} -//// -////func (service *Bid) Resolve(data *dto.ResolveBid) error { -//// var status entity.StatusSSR -//// -//// if data.Accept { -//// status = "accepted" -//// } else { -//// status = "rejected" -//// } -//// -//// _, err := service.repo.Update(data.BidID, status) -//// return err -////} diff --git a/internal/service/feedback.go b/internal/service/feedback.go deleted file mode 100644 index 1356435..0000000 --- a/internal/service/feedback.go +++ /dev/null @@ -1,45 +0,0 @@ -package service - -import ( - "ssr/internal/dto" - "ssr/pkg/logger" -) - -type Feedback struct { - *Base - repo FeedbackRepo -} - -func NewFeedback(r FeedbackRepo, l logger.Interface) *Feedback { - return &Feedback{ - Base: NewBase(l), - repo: r, - } -} - -func (uc *Feedback) Add(data *dto.FeedbackReq) (int, error) { - return uc.repo.Create(data.StudentID, data.SupervisorID, data.WorkID, data.Content) -} - -func (uc *Feedback) GetOnSupervisor(supervisorID int) (*dto.FeedbackPlenty, error) { - dbData, err := uc.repo.GetBySupervisorID(supervisorID) - if err != nil { - return nil, err - } - - var resp []*dto.FeedbackResp - - for _, db := range dbData { - resp = append(resp, &dto.FeedbackResp{ - StudentID: db.StudentID, - StudentFullName: db.StudentFullName, - SupervisorID: db.SupervisorID, - WorkID: db.WorkID, - WorkKind: db.WorkKind, - WorkSubject: db.WorkSubject, - Content: db.Content, - }) - } - - return &dto.FeedbackPlenty{Feedbacks: resp}, nil -} diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index 2a31222..cf1a424 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -16,10 +16,6 @@ type ( GetSupervisor(userID int) (*entity.Supervisor, error) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSupervisor, error) } - ProfileRepo interface { - GetStProfile(email string) (*entity.StProfile, error) - GetSvProfile(email string) (*entity.SvProfile, error) - } RelationRepo interface { Create(studentID, supervisorID, workID int) (int, error) GetRelationsByStudentID(studentID int) ([]*entity.RelationShort, error) @@ -33,10 +29,6 @@ type ( GetStudentWorks(departmentID string, semester int) ([]*entity.Work, error) GetSupervisorWorks(supervisorID int) ([]*entity.SupervisorViewWork, error) } - FeedbackRepo interface { - Create(studentID, supervisorID, workID int, content string) (int, error) - GetBySupervisorID(supervisorID int) ([]*entity.Feedback, error) - } WaypointRepo interface { GetPlenty(workID int) ([]*entity.Waypoint, error) } diff --git a/internal/service/relation.go b/internal/service/relation.go index 42cb59b..5fac7b8 100644 --- a/internal/service/relation.go +++ b/internal/service/relation.go @@ -40,12 +40,12 @@ func (service *Relation) GetPlenty(studentID, supervisorID int) (*dto.RelationPl RelationID: db.RelationID, Status: db.Status, Supervisor: dto.SupervisorShort{ - UserID: db.SupervisorShort.User.UserID, + UserID: db.SupervisorShort.User.ID, FirstName: db.SupervisorShort.User.FirstName, LastName: db.SupervisorShort.User.LastName, }, Student: dto.StudentShort{ - UserID: db.StudentShort.User.UserID, + UserID: db.StudentShort.User.ID, FirstName: db.StudentShort.User.FirstName, LastName: db.StudentShort.User.LastName, }, @@ -77,7 +77,7 @@ func (service *Relation) Get(id int) (*dto.RelationResp, error) { RelationID: rel.RelationID, Status: rel.Status, Supervisor: dto.Supervisor{ - UserID: rel.Supervisor.User.UserID, + UserID: rel.Supervisor.User.ID, Email: rel.Supervisor.User.Email, FirstName: rel.Supervisor.User.FirstName, LastName: rel.Supervisor.User.LastName, @@ -101,7 +101,7 @@ func (service *Relation) Get(id int) (*dto.RelationResp, error) { Semester: rel.Work.Semester, }, Student: dto.Student{ - UserID: rel.Student.User.UserID, + UserID: rel.Student.User.ID, Email: rel.Student.User.Email, FirstName: rel.Student.User.FirstName, LastName: rel.Student.User.LastName, @@ -147,7 +147,7 @@ func (service *Relation) Update(data *dto.RelationUpdateReq) (*dto.RelationResp, }, }, Student: dto.Student{ - UserID: relation.Student.User.UserID, + UserID: relation.Student.User.ID, Email: relation.Student.User.Email, FirstName: relation.Student.User.FirstName, LastName: relation.Student.User.LastName, @@ -159,40 +159,3 @@ func (service *Relation) Update(data *dto.RelationUpdateReq) (*dto.RelationResp, Status: relation.Status, }, nil } - -//func (service *Relation) Accept(data *dto.CreateSSR) (*dto.StViewRelation, error) { -// ssrID, err := service.repo.Update(data.BidID, "wip") -// if err != nil { -// return nil, err -// } -// -// ssr, err := service.repo.Get(data.StudentID, ssrID) -// if err != nil { -// return nil, err -// } -// -// return &dto.StViewRelation{ -// RelID: ssr.RelationID, -// Status: ssr.Status, -// CreatedAt: ssr.CreatedAt, -// Supervisor: dto.Supervisor{ -// Email: ssr.Supervisor.Email, -// FirstName: ssr.Supervisor.FirstName, -// LastName: ssr.Supervisor.LastName, -// About: ssr.Supervisor.About, -// Birthdate: misc.Date{Time: ssr.Birthdate}, -// PhotoUrl: ssr.PhotoUrl, -// Department: ssr.DepartmentID, -// }, -// Work: dto.WorkResp{ -// WorkID: ssr.WorkID, -// Description: ssr.Work.Description, -// Semester: ssr.Work.Semester, -// Subject: dto.SubjectResp{ -// ID: ssr.ID, -// Name: ssr.Subject.Name, -// Department: ssr.DepartmentID, -// }, -// }, -// }, nil -//} diff --git a/internal/service/repo_pg/feedback.go b/internal/service/repo_pg/feedback.go deleted file mode 100644 index e6c4156..0000000 --- a/internal/service/repo_pg/feedback.go +++ /dev/null @@ -1,63 +0,0 @@ -package repo_pg - -import ( - "fmt" - "ssr/internal/entity" - "ssr/pkg/logger" - "ssr/pkg/postgres" -) - -type Feedback struct { - *BasePgRepo -} - -func NewFeedback(pg *postgres.Postgres, l logger.Interface) *Feedback { - return &Feedback{ - BasePgRepo: NewPgRepo(pg, l), - } -} - -func (f *Feedback) Create(studentID, supervisorID, workID int, content string) (int, error) { - query := ` - insert into feedbacks (student_id, supervisor_id, work_id, content) - values ($1, $2, $3, $4) - returning feedback_id; - ` - - var feedbackID int - err := f.Conn.QueryRowx(query, studentID, supervisorID, workID, content).Scan(&feedbackID) - if err != nil { - err := fmt.Errorf("repo_pg.Feedback->Accept->r.Conn.QueryRowx: %w", err) - f.l.Error(err) - return 0, err - } - - return feedbackID, nil -} - -func (f *Feedback) GetBySupervisorID(supervisorID int) ([]*entity.Feedback, error) { - query := ` - select - f.*, - concat (u.first_name, ' ', u.last_name) AS student_full_name, - wk.name as work_kind, - subj.name as work_subject - from feedbacks f - join students s using (student_id) - join users u using (user_id) - join works w using (work_id) - join work_kinds wk using (work_kind_id) - join subjects subj using (subject_id) - where f.supervisor_id = $1 - ` - - var feedbacks []*entity.Feedback - - if err := f.Conn.Select(&feedbacks, query, supervisorID); err != nil { - err := fmt.Errorf("repo_pg.Feedback->GetBySupervisorID->r.Conn.Select: %w", err) - f.l.Error(err) - return nil, err - } - - return feedbacks, nil -} diff --git a/internal/service/repo_pg/profile.go b/internal/service/repo_pg/profile.go deleted file mode 100644 index 2de7cec..0000000 --- a/internal/service/repo_pg/profile.go +++ /dev/null @@ -1,58 +0,0 @@ -package repo_pg - -import ( - "fmt" - "ssr/internal/entity" - "ssr/pkg/logger" - "ssr/pkg/postgres" -) - -type Profile struct { - *BasePgRepo -} - -func NewProfile(pg *postgres.Postgres, l logger.Interface) *Profile { - return &Profile{ - BasePgRepo: NewPgRepo(pg, l), - } -} - -func (repo *Profile) GetStProfile(email string) (*entity.StProfile, error) { - const query = ` - select * - from users u - join students s using (user_id) - where email = $1 - ` - - student := entity.StProfile{} - - err := repo.Conn.Get(&student, query, email) - if err != nil { - err := fmt.Errorf("Profile->GetStProfile->repo.Conn.Get(): %w", err) - repo.l.Error(err) - return nil, err - } - - return &student, nil -} - -func (repo *Profile) GetSvProfile(email string) (*entity.SvProfile, error) { - const query = ` - select * - from users u - join supervisors s using (user_id) - where email = $1 - ` - - supervisor := entity.SvProfile{} - - err := repo.Conn.Get(&supervisor, query, email) - if err != nil { - err := fmt.Errorf("Profile->GetSvProfile->repo.Conn.Get(): %w", err) - repo.l.Error(err) - return nil, err - } - - return &supervisor, nil -} diff --git a/internal/service/repo_pg/relation.go b/internal/service/repo_pg/relation.go index 0a11be0..87f5934 100644 --- a/internal/service/repo_pg/relation.go +++ b/internal/service/repo_pg/relation.go @@ -28,7 +28,7 @@ func (repo *Relation) Get(id int) (*entity.Relation, error) { sv.birthdate as "sv.birthdate", sv.about as "sv.about", - svu.user_id as "sv.user.user_id", + svu.id as "sv.user.id", svu.email as "sv.user.email", svu.last_name as "sv.user.last_name", svu.first_name as "sv.user.first_name", @@ -36,7 +36,7 @@ func (repo *Relation) Get(id int) (*entity.Relation, error) { st.year as "st.year", st.department_id as "st.department_id", - stu.user_id as "st.user.user_id", + stu.id as "st.user.id", stu.email as "st.user.email", stu.last_name as "st.user.last_name", stu.first_name as "st.user.first_name", @@ -53,8 +53,8 @@ func (repo *Relation) Get(id int) (*entity.Relation, error) { from ssr join supervisors sv on ssr.supervisor_id = sv.user_id join students st on ssr.student_id = st.user_id - join users stu on st.user_id = stu.user_id - join users svu on sv.user_id = svu.user_id + join users stu on st.user_id = stu.id + join users svu on sv.user_id = svu.id join works w using (work_id) join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) @@ -80,13 +80,13 @@ func (repo *Relation) GetRelationsBySupervisorID(supervisorID int) ([]*entity.Re ssr.status, sv.department_id as "sv.department_id", - svu.user_id as "sv.user.user_id", + svu.id as "sv.user.id", svu.last_name as "sv.user.last_name", svu.first_name as "sv.user.first_name", st.year as "st.year", st.department_id as "st.department_id", - stu.user_id as "st.user.user_id", + stu.id as "st.user.id", stu.last_name as "st.user.last_name", stu.first_name as "st.user.first_name", @@ -102,8 +102,8 @@ func (repo *Relation) GetRelationsBySupervisorID(supervisorID int) ([]*entity.Re from ssr join supervisors sv on ssr.supervisor_id = sv.user_id join students st on ssr.student_id = st.user_id - join users stu on st.user_id = stu.user_id - join users svu on sv.user_id = svu.user_id + join users stu on st.user_id = stu.id + join users svu on sv.user_id = svu.id join works w using (work_id) join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) @@ -129,13 +129,13 @@ func (repo *Relation) GetRelationsByStudentID(studentID int) ([]*entity.Relation ssr.status, sv.department_id as "sv.department_id", - svu.user_id as "sv.user.user_id", + svu.id as "sv.user.id", svu.last_name as "sv.user.last_name", svu.first_name as "sv.user.first_name", st.year as "st.year", st.department_id as "st.department_id", - stu.user_id as "st.user.user_id", + stu.id as "st.user.id", stu.last_name as "st.user.last_name", stu.first_name as "st.user.first_name", @@ -151,8 +151,8 @@ func (repo *Relation) GetRelationsByStudentID(studentID int) ([]*entity.Relation from ssr join supervisors sv on ssr.supervisor_id = sv.user_id join students st on ssr.student_id = st.user_id - join users stu on st.user_id = stu.user_id - join users svu on sv.user_id = svu.user_id + join users stu on st.user_id = stu.id + join users svu on sv.user_id = svu.id join works w using (work_id) join work_kinds wk using (work_kind_id) join subjects subj using (subject_id) diff --git a/internal/service/repo_pg/student.go b/internal/service/repo_pg/student.go index 8adae87..5d4f8c8 100644 --- a/internal/service/repo_pg/student.go +++ b/internal/service/repo_pg/student.go @@ -24,10 +24,10 @@ func (repo *Student) GetStudentShort(userID int) (*entity.StudentShort, error) { s.department_id, u.last_name as "user.last_name", u.first_name as "user.first_name", - u.user_id as "user.user_id" + u.id as "user.id" from students s - join users u on s.user_id = u.user_id - where u.user_id = $1 + join users u on s.user_id = u.id + where u.id = $1 ` student := entity.StudentShort{} @@ -52,10 +52,10 @@ func (repo *Student) GetStudent(userID int) (*entity.Student, error) { u.first_name as "user.first_name", u.last_name as "user.last_name", u.photo_url as "user.photo_url", - u.user_id as "user.user_id" + u.id as "user.id" from users u - join students s using (user_id) - where user_id = $1 + join students s on s.user_id = u.id + where u.id = $1 ` studentFull := entity.Student{} diff --git a/internal/service/repo_pg/supervisor.go b/internal/service/repo_pg/supervisor.go index 2077ee2..ee0803d 100644 --- a/internal/service/repo_pg/supervisor.go +++ b/internal/service/repo_pg/supervisor.go @@ -44,10 +44,10 @@ func (repo *Supervisor) GetSupervisor(userID int) (*entity.Supervisor, error) { u.first_name as "user.first_name", u.last_name as "user.last_name", u.photo_url as "user.photo_url", - u.user_id as "user.user_id" + u.id as "user.id" from users u - join supervisors s using (user_id) - where user_id = $1 + join supervisors s on s.user_id = u.id + where u.id = $1 ` supervisor := entity.Supervisor{} @@ -69,7 +69,7 @@ func (repo *Supervisor) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSuperv sv.birthdate as "sv.birthdate", sv.department_id as "sv.department_id", - u.user_id as "sv.user.user_id", + u.id as "sv.user.id", u.email as "sv.user.email", u.first_name as "sv.user.first_name", u.last_name as "sv.user.last_name", @@ -78,7 +78,7 @@ func (repo *Supervisor) GetSupervisorsByWorkID(workID int) ([]*entity.WorkSuperv sw.is_head as is_head from supervisors sv join supervisor_work sw on sv.user_id = sw.supervisor_id - join users u using (user_id) + join users u on sv.user_id = u.id where sw.work_id = $1; ` diff --git a/internal/service/repo_pg/user.go b/internal/service/repo_pg/user.go index c066c42..b9641b5 100644 --- a/internal/service/repo_pg/user.go +++ b/internal/service/repo_pg/user.go @@ -52,7 +52,7 @@ func (r *User) GetUserByEmail(email string) (*entity.UserFull, error) { func (r *User) GetUserByID(userID int) (*entity.UserFull, error) { auth := entity.UserFull{} - err := r.Conn.Get(&auth, "select * from user where user_id = $1", userID) + err := r.Conn.Get(&auth, "select * from user where id = $1", userID) if err != nil { err := fmt.Errorf("UserFull->r.Conn.Get(): %w", err) r.l.Error(err) diff --git a/internal/service/work.go b/internal/service/work.go index 5a3a181..b4cbca2 100644 --- a/internal/service/work.go +++ b/internal/service/work.go @@ -151,7 +151,7 @@ func (service *Work) Get(workID int) (*dto.WorkFullResp, error) { for _, db := range supervisorsData { supervisors = append(supervisors, &dto.WorkSupervisorShort{ SupervisorShort: dto.SupervisorShort{ - UserID: db.Supervisor.User.UserID, + UserID: db.Supervisor.User.ID, FirstName: db.User.FirstName, LastName: db.User.LastName, }, @@ -177,39 +177,3 @@ func (service *Work) Get(workID int) (*dto.WorkFullResp, error) { Supervisors: supervisors, }, nil } - -// -//func (service *Work) GetPlenty(workID int) (*dto.WorkFullResp, error) { -// workData, err := service.workRepo.Get(workID) -// if err != nil { -// return nil, err -// } -// -// waypointsData, err := service.waypointRepo.GetPlenty(workID) -// -// var waypoints []*dto.WaypointResp -// -// for _, waypointData := range waypointsData { -// waypoints = append(waypoints, &dto.WaypointResp{ -// Title: waypointData.Title, -// Description: waypointData.Description, -// Deadline: misc.Date{Time: waypointData.Deadline}, -// }) -// } -// -// return &dto.WorkFullResp{ -// WorkID: workData.WorkID, -// Description: workData.Description, -// Semester: workData.Semester, -// Subject: dto.SubjectResp{ -// ID: workData.Subject.SubjectID, -// Name: workData.Subject.Name, -// Department: workData.Subject.DepartmentID, -// }, -// Kind: dto.WorkKindResp{ -// ID: workData.WorkKind.WorkKindID, -// Name: workData.WorkKind.Name, -// }, -// Waypoints: waypoints, -// }, nil -//} diff --git a/migrations/20220508102907_create_users.up.sql b/migrations/20220508102907_create_users.up.sql index f533eca..c3589ab 100644 --- a/migrations/20220508102907_create_users.up.sql +++ b/migrations/20220508102907_create_users.up.sql @@ -1,16 +1,20 @@ CREATE TYPE "user_role" AS ENUM ( 'st', - 'sv' + 'sv', + 'su' ); CREATE TABLE "users" ( - "user_id" bigint generated always as identity unique, + "id" bigint generated always as identity unique, "email" varchar unique not null, + "is_active" bool not null default true, "first_name" varchar not null, "last_name" varchar not null, "photo_url" varchar not null, "role" user_role not null, + "created_at" timestamp not null default now(), + "last_login" timestamp default now(), "password" varchar not null ); diff --git a/migrations/20220509115124_create_students.up.sql b/migrations/20220509115124_create_students.up.sql index 438a2d8..374dabc 100644 --- a/migrations/20220509115124_create_students.up.sql +++ b/migrations/20220509115124_create_students.up.sql @@ -7,7 +7,7 @@ CREATE TABLE "students" ); ALTER TABLE "students" - ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"), + ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id"), ADD FOREIGN KEY ("department_id") REFERENCES "departments" ("department_id"); diff --git a/migrations/20220509192451_create_supervisors.up.sql b/migrations/20220509192451_create_supervisors.up.sql index 63d299b..ad44da7 100644 --- a/migrations/20220509192451_create_supervisors.up.sql +++ b/migrations/20220509192451_create_supervisors.up.sql @@ -7,7 +7,7 @@ CREATE TABLE "supervisors" ); ALTER TABLE "supervisors" - ADD FOREIGN KEY ("user_id") REFERENCES "users" ("user_id"), + ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id"), ADD FOREIGN KEY ("department_id") REFERENCES "departments" ("department_id"); diff --git a/migrations/20220509195738_create_sv_work.up.sql b/migrations/20220509195738_create_sv_work.up.sql index b70735b..5647f45 100644 --- a/migrations/20220509195738_create_sv_work.up.sql +++ b/migrations/20220509195738_create_sv_work.up.sql @@ -1,5 +1,6 @@ CREATE TABLE "supervisor_work" ( + "id" bigint generated always as identity unique, "work_id" bigint not null, "supervisor_id" bigint not null, "is_head" bool, diff --git a/migrations/20220606071757_create_feedbacks.down.sql b/migrations/20220606071757_create_feedbacks.down.sql deleted file mode 100644 index 37e8098..0000000 --- a/migrations/20220606071757_create_feedbacks.down.sql +++ /dev/null @@ -1 +0,0 @@ -drop table "feedbacks" cascade; \ No newline at end of file diff --git a/migrations/20220606071757_create_feedbacks.up.sql b/migrations/20220606071757_create_feedbacks.up.sql deleted file mode 100644 index 6ebdbef..0000000 --- a/migrations/20220606071757_create_feedbacks.up.sql +++ /dev/null @@ -1,22 +0,0 @@ -CREATE TABLE "feedbacks" -( - "feedback_id" bigint unique generated always as identity, - "work_id" bigint not null, - "created_at" timestamp default now(), - "supervisor_id" bigint not null, - "student_id" bigint not null, - "content" text not null -); - - -ALTER TABLE "feedbacks" - ADD FOREIGN KEY ("work_id") REFERENCES "works" ("work_id"), - ADD FOREIGN KEY ("supervisor_id") REFERENCES "supervisors" ("user_id"), - ADD FOREIGN KEY ("student_id") REFERENCES "students" ("user_id"), - ADD CONSTRAINT feedbacks_unique_members_constraint UNIQUE (work_id, student_id); - -CREATE INDEX ON "feedbacks" (supervisor_id); -CREATE INDEX ON "feedbacks" (student_id, work_id); -CREATE INDEX ON "feedbacks" (supervisor_id, work_id); - - diff --git a/migrations/20221003080212_create_waypoints.up.sql b/migrations/20221003080212_create_waypoints.up.sql index 954e97a..b33a28c 100644 --- a/migrations/20221003080212_create_waypoints.up.sql +++ b/migrations/20221003080212_create_waypoints.up.sql @@ -4,7 +4,7 @@ CREATE TABLE "waypoints" "work_id" bigint not null, "deadline" date not null, "title" text not null, - "description" text not null + "description" text not null );