From a4439df858dcca801e3ab03c9b28d9ceb8d6cfc3 Mon Sep 17 00:00:00 2001 From: Shailendra Kanherkar Date: Wed, 21 Aug 2024 12:28:37 +0530 Subject: [PATCH 01/22] updated mina script --- deploy.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deploy.rb b/deploy.rb index c0caab7..3cb15fe 100644 --- a/deploy.rb +++ b/deploy.rb @@ -22,7 +22,7 @@ task :production do set :deploy_to, '/www/peerly-backend' set :domain, ENV['PEERLY_PRODUCTIONS_IP'] - set :branch, 'Deployment' + set :branch, 'main' end task :setup do From 2308abb7cd4e6eae2b0718c03cf060ec582906b3 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Wed, 21 Aug 2024 17:24:41 +0530 Subject: [PATCH 02/22] [Deployment] IST time check --- internal/app/cronjob/updateDailyData.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/app/cronjob/updateDailyData.go b/internal/app/cronjob/updateDailyData.go index 6dd7424..81810d5 100644 --- a/internal/app/cronjob/updateDailyData.go +++ b/internal/app/cronjob/updateDailyData.go @@ -12,8 +12,8 @@ const DAILY_JOB = "DAILY_JOB" const SAY_HELLO_DAILY_CRON_JOB_INTERVAL_DAYS = 1 var SayHelloDailyJobTiming = JobTime{ - hours: 0, - minutes: 0, + hours: 17, + minutes: 28, seconds: 0, } From 7ca7f1360fd07099925b93bb13bca2503f31c084 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Wed, 21 Aug 2024 17:31:22 +0530 Subject: [PATCH 03/22] [Deployment] IST time check --- internal/app/cronjob/updateDailyData.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/internal/app/cronjob/updateDailyData.go b/internal/app/cronjob/updateDailyData.go index 81810d5..0e4b225 100644 --- a/internal/app/cronjob/updateDailyData.go +++ b/internal/app/cronjob/updateDailyData.go @@ -13,7 +13,7 @@ const SAY_HELLO_DAILY_CRON_JOB_INTERVAL_DAYS = 1 var SayHelloDailyJobTiming = JobTime{ hours: 17, - minutes: 28, + minutes: 34, seconds: 0, } @@ -59,9 +59,12 @@ func (cron *DailyJob) Schedule() { 0, // Nanosecond: 0 location, // Timezone: Asia/Kolkata ) + + logger.Info("IST time check: ",jobTimeInKolkata) + // Convert to UTC jobTimeInUTC := jobTimeInKolkata.UTC() - + logger.Info("UTC time check: ",jobTimeInUTC) cron.job, err = cron.scheduler.NewJob( gocron.DailyJob( SAY_HELLO_DAILY_CRON_JOB_INTERVAL_DAYS, From 3932a247e1cdf4709d60024bf7ff03e11bed5389 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Wed, 21 Aug 2024 17:34:25 +0530 Subject: [PATCH 04/22] [Deployment] ist check --- internal/app/cronjob/updateDailyData.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/app/cronjob/updateDailyData.go b/internal/app/cronjob/updateDailyData.go index 0e4b225..be1b4fd 100644 --- a/internal/app/cronjob/updateDailyData.go +++ b/internal/app/cronjob/updateDailyData.go @@ -13,7 +13,7 @@ const SAY_HELLO_DAILY_CRON_JOB_INTERVAL_DAYS = 1 var SayHelloDailyJobTiming = JobTime{ hours: 17, - minutes: 34, + minutes: 37, seconds: 0, } @@ -53,9 +53,9 @@ func (cron *DailyJob) Schedule() { currentTimeInKolkata.Year(), // Year: current year currentTimeInKolkata.Month(), // Month: current month currentTimeInKolkata.Day(), // Day: today's date - int(MonthlyJobTiming.hours), // Hour: from MonthlyJobTiming - int(MonthlyJobTiming.minutes), // Minute: from MonthlyJobTiming - int(MonthlyJobTiming.seconds), // Second: from MonthlyJobTiming + int(SayHelloDailyJobTiming.hours), // Hour: from MonthlyJobTiming + int(SayHelloDailyJobTiming.minutes), // Minute: from MonthlyJobTiming + int(SayHelloDailyJobTiming.seconds), // Second: from MonthlyJobTiming 0, // Nanosecond: 0 location, // Timezone: Asia/Kolkata ) From a0082ddeef99112e8ae86502464d1464d109386d Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Wed, 21 Aug 2024 18:51:27 +0530 Subject: [PATCH 05/22] [Deployment] ist check --- internal/app/cronjob/updateDailyData.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/app/cronjob/updateDailyData.go b/internal/app/cronjob/updateDailyData.go index be1b4fd..0b9ee37 100644 --- a/internal/app/cronjob/updateDailyData.go +++ b/internal/app/cronjob/updateDailyData.go @@ -12,8 +12,8 @@ const DAILY_JOB = "DAILY_JOB" const SAY_HELLO_DAILY_CRON_JOB_INTERVAL_DAYS = 1 var SayHelloDailyJobTiming = JobTime{ - hours: 17, - minutes: 37, + hours: 18, + minutes: 55, seconds: 0, } From b5db7d047aa861f43d47292e8a796a9ad624da93 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Wed, 21 Aug 2024 19:00:33 +0530 Subject: [PATCH 06/22] [Deployment] reset monthly an daily update data timing --- internal/app/cronjob/monthlyUpdateData.go | 4 ++-- internal/app/cronjob/updateDailyData.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/app/cronjob/monthlyUpdateData.go b/internal/app/cronjob/monthlyUpdateData.go index c164743..43c70d5 100644 --- a/internal/app/cronjob/monthlyUpdateData.go +++ b/internal/app/cronjob/monthlyUpdateData.go @@ -14,8 +14,8 @@ const MONTHLY_JOB = "MONTHLY_JOB" const MONTHLY_CRON_JOB_INTERVAL_MONTHS = 1 var MonthlyJobTiming = JobTime{ - hours: 0, - minutes: 0, + hours: 23, + minutes: 59, seconds: 0, } diff --git a/internal/app/cronjob/updateDailyData.go b/internal/app/cronjob/updateDailyData.go index 0b9ee37..43902d8 100644 --- a/internal/app/cronjob/updateDailyData.go +++ b/internal/app/cronjob/updateDailyData.go @@ -12,8 +12,8 @@ const DAILY_JOB = "DAILY_JOB" const SAY_HELLO_DAILY_CRON_JOB_INTERVAL_DAYS = 1 var SayHelloDailyJobTiming = JobTime{ - hours: 18, - minutes: 55, + hours: 0, + minutes: 0, seconds: 0, } From d8d45599f23119cf93d4527d68cec91f54dc13b2 Mon Sep 17 00:00:00 2001 From: Sharyu Marwadi Date: Thu, 22 Aug 2024 11:16:27 +0530 Subject: [PATCH 07/22] [Deployment] migration updation --- internal/repository/migrations/1723875193_moderation.up.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/repository/migrations/1723875193_moderation.up.sql b/internal/repository/migrations/1723875193_moderation.up.sql index fd4c3a0..5570861 100644 --- a/internal/repository/migrations/1723875193_moderation.up.sql +++ b/internal/repository/migrations/1723875193_moderation.up.sql @@ -1,4 +1,4 @@ -IF NOT EXISTS create type status as enum('reported','resolved','deleted'); +create type status as enum('reported','resolved','deleted'); alter table resolutions add status status From 6b3228df3cb4e1430fa00dce10b7a6294267e3f3 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Fri, 23 Aug 2024 14:43:32 +0530 Subject: [PATCH 08/22] [feature/UpdateLogs] added debug logs --- .env.example | 1 + assets/silverBadge.png | Bin 9765 -> 10366 bytes cmd/main.go | 10 +- go.mod | 1 + go.sum | 2 + internal/api/appreciation.go | 30 ++++-- internal/api/log.go | 43 ++++++++ internal/api/organizationconfig.go | 9 +- internal/api/ping.go | 5 +- internal/api/reward.go | 11 ++- internal/api/router.go | 6 ++ internal/api/user.go | 3 + internal/app/appreciation/service.go | 48 +++++---- internal/pkg/apperrors/errors.go | 6 +- internal/pkg/config/config.go | 4 + internal/pkg/constants/system.go | 23 +++-- internal/pkg/dto/log.go | 6 ++ internal/pkg/logger/log.go | 92 ++++++++++++++++-- internal/pkg/middleware/jwtMiddleware.go | 12 +++ .../repository/postgresdb/appreciation.go | 52 +++++----- logs/2024-08-23_12-51-17_peerly_backend.log | 2 + 21 files changed, 282 insertions(+), 84 deletions(-) create mode 100644 internal/api/log.go create mode 100644 internal/pkg/dto/log.go create mode 100644 logs/2024-08-23_12-51-17_peerly_backend.log diff --git a/.env.example b/.env.example index 5101925..9851533 100644 --- a/.env.example +++ b/.env.example @@ -29,3 +29,4 @@ INTRANET_BASE_URL = https://pg-stage-intranet.joshsoftware.com SENDGRID_API_KEY=sendgrid_api_key SENDER_EMAIL=sendgrid_email +DEVELOPER_KEY = developer_key \ No newline at end of file diff --git a/assets/silverBadge.png b/assets/silverBadge.png index 6dacd2c121c7173085a539d9b47fd7ca2c4fc15a..af83817152b14e2062939fcf0d49d92c666ec94d 100644 GIT binary patch literal 10366 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 delta 9763 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 { + log.Error(req.Context(),"Invalid reward point") dto.ErrorRepsonse(rw,apperrors.InvalidRewardPoint) return } reward.AppreciationId = int64(apprId) resp, err := rewardSvc.GiveReward(req.Context(),reward) if err != nil { + log.Error(req.Context(),"resp err: ",err) dto.ErrorRepsonse(rw, err) return } + + log.Debug(req.Context(),"giveRewardHandler: resp: ",resp) + dto.SuccessRepsonse(rw, http.StatusCreated, "Reward given successfully", resp) }) } diff --git a/internal/api/router.go b/internal/api/router.go index 64c44ab..155516b 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -22,7 +22,13 @@ func NewRouter(deps app.Dependencies) *mux.Router { router := mux.NewRouter() peerlySubrouter := router.PathPrefix("/peerly").Subrouter() + // Add the RequestIDMiddleware to the subrouter + peerlySubrouter.Use(middleware.RequestIDMiddleware) + peerlySubrouter.HandleFunc("/ping", pingHandler).Methods(http.MethodGet) + + peerlySubrouter.HandleFunc("/set_logger_level", loggerHandler).Methods(http.MethodPost) + // Version 1 API management v1 := fmt.Sprintf("application/vnd.%s.v1", config.AppName()) diff --git a/internal/api/user.go b/internal/api/user.go index 34db4e5..a64d4a6 100644 --- a/internal/api/user.go +++ b/internal/api/user.go @@ -13,6 +13,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + log "github.com/joshsoftware/peerly-backend/internal/pkg/logger" logger "github.com/sirupsen/logrus" ) @@ -224,11 +225,13 @@ func listUsersHandler(userSvc user.Service) http.HandlerFunc { func getActiveUserListHandler(userSvc user.Service) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { + log.Debug(req.Context(),"getActiveUserListHandler: req: ",req) resp, err := userSvc.GetActiveUserList(req.Context()) if err != nil { dto.ErrorRepsonse(rw, err) return } + log.Debug(req.Context(),"getActiveUserListHandler: resp: ",resp) dto.SuccessRepsonse(rw, http.StatusOK, "Active Users list", resp) } } diff --git a/internal/app/appreciation/service.go b/internal/app/appreciation/service.go index b0bfdf7..864a323 100644 --- a/internal/app/appreciation/service.go +++ b/internal/app/appreciation/service.go @@ -10,9 +10,12 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + log "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" + + // logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) type service struct { @@ -43,6 +46,7 @@ func NewService(appreciationRepo repository.AppreciationStorer, coreValuesRepo r func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto.Appreciation) (dto.Appreciation, error) { + log.Debug(ctx,"svc: CreateAppreciation: appreciation: ",appreciation) //add quarter appreciation.Quarter = utils.GetQuarter() @@ -50,14 +54,16 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto data := ctx.Value(constants.UserId) sender, ok := data.(int64) if !ok { - logger.Error("err in parsing userid from token") + logger.Error(ctx,"err in parsing userid from token") return dto.Appreciation{}, apperrors.InternalServer } + log.Debug(ctx,"sender: ",sender) //check is receiver present in database chk, err := apprSvc.appreciationRepo.IsUserPresent(ctx, nil, appreciation.Receiver) + log.Debug(ctx,"chk: ",chk," err: ",err) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx,"err: %v", err) return dto.Appreciation{}, err } if !chk { @@ -92,7 +98,7 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto //check is corevalue present in database _, err = apprSvc.corevaluesRespo.GetCoreValue(ctx, int64(appreciation.CoreValueID)) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx,"err: %v", err) return dto.Appreciation{}, err } @@ -103,14 +109,14 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto appr, err := apprSvc.appreciationRepo.CreateAppreciation(ctx, tx, appreciation) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx,"err: %v", err) return dto.Appreciation{}, err } res := mapAppreciationDBToDTO(appr) apprInfo, err := apprSvc.appreciationRepo.GetAppreciationById(ctx, tx, int32(res.ID)) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx,"err: %v", err) return res, nil } @@ -122,13 +128,13 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto } senderInfo,err := apprSvc.userRepo.GetUserById(ctx,reqGetUserById) if err != nil{ - logger.Info("error in getting create appreciation sender info") + logger.Info(ctx,"error in getting create appreciation sender info") } reqGetUserById.UserId = appreciation.Receiver receiverInfo,err := apprSvc.userRepo.GetUserById(ctx,reqGetUserById) if err != nil{ - logger.Info("error in getting create appreciation sender info") + logger.Info(ctx,"error in getting create appreciation sender info") } err = sendAppreciationEmail(apprInfo,senderInfo.Email,receiverInfo.Email) apprSvc.sendAppreciationNotificationToReceiver(ctx, apprInfo) @@ -140,7 +146,7 @@ func (apprSvc *service) GetAppreciationById(ctx context.Context, appreciationId resAppr, err := apprSvc.appreciationRepo.GetAppreciationById(ctx, nil, appreciationId) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx,"err: %v", err) return dto.AppreciationResponse{}, err } @@ -151,7 +157,7 @@ func (apprSvc *service) ListAppreciations(ctx context.Context, filter dto.Apprec infos, pagination, err := apprSvc.appreciationRepo.ListAppreciations(ctx, nil, filter) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx,"err: %v", err) return dto.ListAppreciationsResponse{}, err } @@ -196,13 +202,13 @@ func (apprSvc *service) UpdateAppreciation(ctx context.Context) (bool, error) { _, err = apprSvc.appreciationRepo.UpdateAppreciationTotalRewardsOfYesterday(ctx, tx) if err != nil { - logger.Error("err: ", err.Error()) + logger.Error(ctx,"err: ", err.Error()) return false, err } userBadgeDetails, err := apprSvc.appreciationRepo.UpdateUserBadgesBasedOnTotalRewards(ctx, tx) if err != nil { - logger.Error("err: ", err.Error()) + logger.Error(ctx,"err: ", err.Error()) return false, err } @@ -226,17 +232,17 @@ func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail CoreValueName: emailData.CoreValueName, } - logger.Info("appreciation sender email: -----------> ",senderEmail) - logger.Info("appreciation receiver email: -----------> ",receiverEmail) + logger.Info(context.Background(),"appreciation sender email: -----------> ",senderEmail) + logger.Info(context.Background(),"appreciation receiver email: -----------> ",receiverEmail) mailReq := email.NewMail([]string{receiverEmail}, []string{senderEmail}, []string{}, fmt.Sprintf("%s %s appreciated %s %s",emailData.SenderFirstName,emailData.SenderLastName,emailData.ReceiverFirstName,emailData.ReceiverLastName)) err := mailReq.ParseTemplate("./internal/app/email/templates/createAppreciation.html", templateData) if err != nil { - logger.Errorf("err in creating html file : %v", err) + logger.Errorf(context.Background(),"err in creating html file : %v", err) return err } err = mailReq.Send(plainTextContent) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(context.Background(),"err: %v", err) return err } return nil @@ -246,7 +252,7 @@ func (apprSvc *service) sendAppreciationNotificationToReceiver(ctx context.Conte notificationTokens, err := apprSvc.userRepo.ListDeviceTokensByUserID(ctx, appr.ReceiverID) if err != nil { - logger.Errorf("err in getting device tokens: %v", err) + logger.Errorf(ctx,"err in getting device tokens: %v", err) return } @@ -272,7 +278,7 @@ func (apprSvc *service) sendAppreciationNotificationToAll(ctx context.Context, a func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repository.UserBadgeDetails) { - logger.Info("user Badge Details:---------------->\n ", userBadgeDetails) + logger.Info(context.Background(),"user Badge Details:---------------->\n ", userBadgeDetails) for _, userBadgeDetail := range userBadgeDetails { // Determine the BadgeImageUrl based on the BadgeName @@ -300,16 +306,16 @@ func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repositor BadgeImageName: badgeImageUrl, AppreciationPoints: userBadgeDetail.BadgePoints, } - logger.Info("badge data: ", templateData) + logger.Info(context.Background(),"badge data: ", templateData) mailReq := email.NewMail([]string{userBadgeDetail.Email}, []string{}, []string{}, "Received an badge") err := mailReq.ParseTemplate("./internal/app/email/templates/badge.html", templateData) if err != nil { - logger.Errorf("err in creating html file : %v", err) + logger.Errorf(context.Background(),"err in creating html file : %v", err) return } err = mailReq.Send("badge allocation") if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(context.Background(),"err: %v", err) return } } diff --git a/internal/pkg/apperrors/errors.go b/internal/pkg/apperrors/errors.go index 3468839..04d9030 100644 --- a/internal/pkg/apperrors/errors.go +++ b/internal/pkg/apperrors/errors.go @@ -73,6 +73,8 @@ const ( InvalidPage = CustomError("Invalid page value") NegativeGradePoints = CustomError("Grade points cannot be negative") NegativeBadgePoints = CustomError("Badge reward points cannot be negative") + UnauthorizedDeveloper = CustomError("Unauthorised developer") + InvalidLoggerLevel = CustomError("Invalid Logger Level") ) // ErrKeyNotSet - Returns error object specific to the key value passed in @@ -87,11 +89,11 @@ func GetHTTPStatusCode(err error) int { return http.StatusInternalServerError case OrganizationConfigNotFound, OrganizationNotFound, InvalidOrgId, GradeNotFound, AppreciationNotFound, PageParamNotFound, InvalidCoreValueData, InvalidIntranetData: return http.StatusNotFound - case BadRequest, InvalidId, JSONParsingErrorReq, TextFieldBlank, InvalidParentValue, DescFieldBlank, UniqueCoreValue, SelfAppreciationError, CannotReportOwnAppreciation, RepeatedReport, InvalidCoreValueID, InvalidReceiverID, InvalidRewardMultiplier, InvalidRewardQuotaRenewalFrequency, InvalidTimezone, InvalidRewardPoint, InvalidEmail, InvalidPassword, DescriptionLengthExceed, InvalidPageSize, InvalidPage, NegativeGradePoints, NegativeBadgePoints: + case InvalidLoggerLevel,BadRequest, InvalidId, JSONParsingErrorReq, TextFieldBlank, InvalidParentValue, DescFieldBlank, UniqueCoreValue, SelfAppreciationError, CannotReportOwnAppreciation, RepeatedReport, InvalidCoreValueID, InvalidReceiverID, InvalidRewardMultiplier, InvalidRewardQuotaRenewalFrequency, InvalidTimezone, InvalidRewardPoint, InvalidEmail, InvalidPassword, DescriptionLengthExceed, InvalidPageSize, InvalidPage, NegativeGradePoints, NegativeBadgePoints: return http.StatusBadRequest case InvalidContactEmail, InvalidDomainName, UserAlreadyPresent, RewardAlreadyPresent, RepeatedUser: return http.StatusConflict - case InvalidAuthToken, RoleUnathorized, IntranetValidationFailed: + case InvalidAuthToken, RoleUnathorized, IntranetValidationFailed, UnauthorizedDeveloper: return http.StatusUnauthorized case RewardQuotaIsNotSufficient: return http.StatusUnprocessableEntity diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index de00f59..f97966f 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -103,3 +103,7 @@ func PeerlyBaseUrl() string { func IntranetBaseUrl() string { return (ReadEnvString(constants.IntranetBaseUrl)) } + +func DeveloperKey() string { + return (ReadEnvString(constants.DeveloperKey)) +} diff --git a/internal/pkg/constants/system.go b/internal/pkg/constants/system.go index bac0232..9a005ae 100644 --- a/internal/pkg/constants/system.go +++ b/internal/pkg/constants/system.go @@ -2,6 +2,7 @@ package constants type UserIdCtxKey string type RoleCtxKey string +type RequestIDCtxKey string // System Constants used to setup environment and basic functionality const ( @@ -17,20 +18,22 @@ const ( IntranetBaseUrl = "INTRANET_BASE_URL" POST = "POST" GET = "GET" + DeveloperKey = "DEVELOPER_KEY" ) // User required constants const ( - AuthorizationHeader = "Authorization" - ClientCode = "Client-Code" - UserRole = "user" - AdminRole = "admin" - UserId UserIdCtxKey = "userId" - Role RoleCtxKey = "role" - IntranetAuth = "Intranet-Auth" - PeerlyValidationPath = "/api/peerly/v1/sessions/login" - GetIntranetUserDataPath = "/api/peerly/v1/users/" - ListIntranetUsersPath = "/api/peerly/v1/users?page=%d&per_page=%d" + RequestID RequestIDCtxKey = "RequestID" + AuthorizationHeader = "Authorization" + ClientCode = "Client-Code" + UserRole = "user" + AdminRole = "admin" + UserId UserIdCtxKey = "userId" + Role RoleCtxKey = "role" + IntranetAuth = "Intranet-Auth" + PeerlyValidationPath = "/api/peerly/v1/sessions/login" + GetIntranetUserDataPath = "/api/peerly/v1/users/" + ListIntranetUsersPath = "/api/peerly/v1/users?page=%d&per_page=%d" ) // Pagination Metadata constants diff --git a/internal/pkg/dto/log.go b/internal/pkg/dto/log.go new file mode 100644 index 0000000..cec38c3 --- /dev/null +++ b/internal/pkg/dto/log.go @@ -0,0 +1,6 @@ +package dto + +type ChangeLogLevelRequest struct { + LogLevel string `json:"loglevel"` + DeveloperKey string `json:"developer_key"` +} \ No newline at end of file diff --git a/internal/pkg/logger/log.go b/internal/pkg/logger/log.go index ea9b121..49a7a95 100644 --- a/internal/pkg/logger/log.go +++ b/internal/pkg/logger/log.go @@ -1,25 +1,99 @@ package log import ( + "context" + "fmt" + "io" + "os" + "time" + + "github.com/joshsoftware/peerly-backend/internal/pkg/constants" l "github.com/sirupsen/logrus" + "gopkg.in/natefinch/lumberjack.v2" ) +var Logger *l.Logger + +var lumberjackLogger = &lumberjack.Logger{ + MaxSize: 100, // megabytes + MaxBackups: 3, // number of log files + MaxAge: 365, // days + Compress: true, +} + // Error - prints out an error -func Error(appError error, msg string, triggeringError error) { - l.WithFields(l.Fields{"appError": appError, "message": msg}).Error(triggeringError) +func Error(ctx context.Context, args ...interface{}) { + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "" + } + Logger.Error(requestID, args) } -// Warn - for warnings -func Warn(appError error, msg string, triggeringError error) { - l.WithFields(l.Fields{"appError": appError, "message": msg}).Warn(triggeringError) +// Errorf - prints out an error with formatted output +func Errorf(ctx context.Context, format string, args ...interface{}) { + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "" + } + Logger.Errorf("req_id: [%s] "+format, append([]interface{}{requestID}, args...)...) +} + +// Warn - prints out a warning +func Warn(ctx context.Context, args ...interface{}) { + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "" + } + Logger.Warn("req_id: ", requestID, args) } // Fatal - will print out the error info and exit the program -func Fatal(appError error, msg string, triggeringError error) { - l.WithFields(l.Fields{"appError": appError, "message": msg}).Fatal(triggeringError) +func Fatal(ctx context.Context, args ...interface{}) { + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "" + } + Logger.Fatal("req_id: ", requestID, args) } // Info - prints out basic information -func Info(msg string) { - l.WithFields(l.Fields{"info": msg}).Info(msg) +func Info(ctx context.Context, args ...interface{}) { + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "" + } + Logger.Info("req_id: ", requestID, args) +} + +// Info - prints out basic information +func Debug(ctx context.Context, args ...interface{}) { + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "" + } + Logger.Debug("req_id: ", requestID, args) +} + +func SetupLogger() (*l.Logger, error) { + + lumberjackLogger.Filename = fmt.Sprintf("./logs/%s_peerly_backend.log", time.Now().Format("2006-01-02_15-04-05")) + file, err := os.Create(lumberjackLogger.Filename) + if err != nil { + return nil, fmt.Errorf("failed to create log file: %w", err) + } + file.Close() + + // Initialize Logrus logger + logger := l.New() + logger.SetOutput(io.MultiWriter(os.Stdout, lumberjackLogger)) + logger.SetFormatter(&l.TextFormatter{ + FullTimestamp: true, + }) + + // Set the logging level + logger.SetLevel(l.InfoLevel) + + Logger = logger + return logger, nil } diff --git a/internal/pkg/middleware/jwtMiddleware.go b/internal/pkg/middleware/jwtMiddleware.go index ecd541d..9c6bc8e 100644 --- a/internal/pkg/middleware/jwtMiddleware.go +++ b/internal/pkg/middleware/jwtMiddleware.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/dgrijalva/jwt-go" + "github.com/google/uuid" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/config" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" @@ -60,9 +61,20 @@ func JwtAuthMiddleware(next http.Handler, roles []string) http.Handler { fmt.Println("setting id: ", Id) ctx := context.WithValue(req.Context(), constants.UserId, Id) ctx = context.WithValue(ctx, constants.Role, Role) + req = req.WithContext(ctx) next.ServeHTTP(rw, req) }) } + +// RequestIDMiddleware generates a request ID and adds it to the request context. +func RequestIDMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reqestId := uuid.NewString() + ctx := context.WithValue(r.Context(), constants.RequestID, reqestId) + r = r.WithContext(ctx) + next.ServeHTTP(w, r) + }) +} diff --git a/internal/repository/postgresdb/appreciation.go b/internal/repository/postgresdb/appreciation.go index 14fb5cb..5f73ff8 100644 --- a/internal/repository/postgresdb/appreciation.go +++ b/internal/repository/postgresdb/appreciation.go @@ -13,7 +13,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) var AppreciationColumns = []string{"id", "core_value_id", "description", "quarter", "sender", "receiver"} @@ -46,14 +46,14 @@ func (appr *appreciationsStore) CreateAppreciation(ctx context.Context, tx repos Suffix("RETURNING id,core_value_id, description,total_reward_points,quarter,sender,receiver,created_at,updated_at"). ToSql() if err != nil { - logger.Errorf("error in generating squirrel query, err: %v", err) + logger.Errorf(ctx,"error in generating squirrel query, err: %v", err) return repository.Appreciation{}, apperrors.InternalServerError } var resAppr repository.Appreciation err = queryExecutor.QueryRowx(insertQuery, args...).StructScan(&resAppr) if err != nil { - logger.Errorf("Error executing create appreciation insert query: %v", err) + logger.Errorf(ctx,"Error executing create appreciation insert query: %v", err) return repository.Appreciation{}, apperrors.InternalServer } @@ -68,7 +68,7 @@ func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repo data := ctx.Value(constants.UserId) userID, ok := data.(int64) if !ok { - logger.Error("err in parsing userID from token") + logger.Error(ctx,"err in parsing userID from token") return repository.AppreciationResponse{}, apperrors.InternalServer } @@ -112,7 +112,7 @@ func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repo ToSql() if err != nil { - logger.Errorf("error in generating squirrel query, err: %v", err) + logger.Errorf(ctx,"error in generating squirrel query, err: %v", err) return repository.AppreciationResponse{}, apperrors.InternalServer } @@ -122,10 +122,10 @@ func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repo err = queryExecutor.QueryRowx(query, args...).StructScan(&resAppr) if err != nil { if err == sql.ErrNoRows { - logger.Warn(fmt.Sprintf("no appreciation found with id: %d", apprId)) + logger.Warn(ctx,fmt.Sprintf("no appreciation found with id: %d", apprId)) return repository.AppreciationResponse{}, apperrors.AppreciationNotFound } - logger.Errorf("failed to execute query: %v", err) + logger.Errorf(ctx,"failed to execute query: %v", err) return repository.AppreciationResponse{}, apperrors.InternalServer } return resAppr, nil @@ -138,7 +138,7 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi data := ctx.Value(constants.UserId) userID, ok := data.(int64) if !ok { - logger.Error("err in parsing userID from token") + logger.Error(ctx,"err in parsing userID from token") return []repository.AppreciationResponse{}, repository.Pagination{}, apperrors.InternalServerError } @@ -168,14 +168,14 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi countSql, countArgs, err := queryBuilder.ToSql() if err != nil { - logger.Error("failed to build count query: ", err.Error()) + logger.Error(ctx,"failed to build count query: ", err.Error()) return []repository.AppreciationResponse{}, repository.Pagination{}, apperrors.InternalServerError } var totalRecords int32 err = queryExecutor.QueryRowx(countSql, countArgs...).Scan(&totalRecords) if err != nil { - logger.Error("failed to execute count query: ", err.Error()) + logger.Error(ctx,"failed to execute count query: ", err.Error()) return []repository.AppreciationResponse{}, repository.Pagination{}, apperrors.InternalServerError } @@ -227,27 +227,27 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi queryBuilder = queryBuilder.Limit(uint64(filter.Limit)).Offset(uint64(offset)) sql, args, err := queryBuilder.ToSql() if err != nil { - logger.Error("failed to build query: ", err.Error()) + logger.Error(ctx,"failed to build query: ", err.Error()) return nil, repository.Pagination{}, apperrors.InternalServerError } queryExecutor = appr.InitiateQueryExecutor(tx) res := make([]repository.AppreciationResponse, 0) - logger.Info("sp : filter: ", filter) - logger.Info("sp : sql: ", sql) - logger.Info("sp : args: ", args) + logger.Info(ctx,"filter: ", filter) + logger.Info(ctx,"sql: ", sql) + logger.Info(ctx,"args: ", args) err = sqlx.Select(queryExecutor, &res, sql, args...) if err != nil { - logger.Error("failed to execute query appreciation: ", err.Error()) - logger.Error("err res data: ", res) + logger.Error(ctx,"failed to execute query appreciation: ", err.Error()) + logger.Error(ctx,"err res data: ", res) return nil, repository.Pagination{}, apperrors.InternalServerError } id := ctx.Value(constants.UserId) fmt.Println("id -> ", id) userId, ok := ctx.Value(constants.UserId).(int64) if !ok { - logger.Error("unable to convert context user id to int64") + logger.Error(ctx,"unable to convert context user id to int64") return nil, repository.Pagination{}, apperrors.InternalServerError } @@ -256,12 +256,12 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi queryBuilder = repository.Sq.Select("reported_by").From("resolutions").Where(squirrel.Eq{"appreciation_id": appreciation.ID}) query, args, err := queryBuilder.ToSql() if err != nil { - logger.Errorf("error in generating squirrel query, err: %s", err.Error()) + logger.Errorf(ctx,"error in generating squirrel query, err: %s", err.Error()) return nil, repository.Pagination{}, apperrors.InternalServerError } err = appr.DB.SelectContext(ctx, &userIds, query, args...) if err != nil { - logger.Errorf("error in reported flag query, err: %s", err.Error()) + logger.Errorf(ctx,"error in reported flag query, err: %s", err.Error()) return nil, repository.Pagination{}, apperrors.InternalServerError } res[idx].ReportedFlag = slices.Contains(userIds, userId) @@ -280,7 +280,7 @@ func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repos ToSql() if err != nil { - logger.Error("Error building SQL: ", err.Error()) + logger.Error(ctx,"Error building SQL: ", err.Error()) return apperrors.InternalServer } @@ -288,18 +288,18 @@ func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repos result, err := queryExecutor.Exec(query, args...) if err != nil { - logger.Error("Error executing SQL: ", err.Error()) + logger.Error(ctx,"Error executing SQL: ", err.Error()) return apperrors.InternalServer } rowsAffected, err := result.RowsAffected() if err != nil { - logger.Error("Error getting rows affected: ", err.Error()) + logger.Error(ctx,"Error getting rows affected: ", err.Error()) return apperrors.InternalServer } if rowsAffected == 0 { - logger.Warn("No rows affected") + logger.Warn(ctx,"No rows affected") return apperrors.AppreciationNotFound } @@ -315,7 +315,7 @@ func (appr *appreciationsStore) IsUserPresent(ctx context.Context, tx repository ToSql() if err != nil { - logger.Error("err ", err.Error()) + logger.Error(ctx,"err ", err.Error()) return false, apperrors.InternalServer } @@ -325,7 +325,7 @@ func (appr *appreciationsStore) IsUserPresent(ctx context.Context, tx repository // Execute the query err = queryExecutor.QueryRowx(query, args...).Scan(&count) if err != nil { - logger.Error("failed to execute query: ", err.Error()) + logger.Error(ctx,"failed to execute query: ", err.Error()) return false, apperrors.InternalServer } @@ -360,7 +360,7 @@ WHERE app.id = agg.appreciation_id; // Execute the query using the query executor _, err := queryExecutor.Exec(query) if err != nil { - logger.Error("Error executing SQL query:", err.Error()) + logger.Error(ctx,"Error executing SQL query:", err.Error()) return false, apperrors.InternalServer } diff --git a/logs/2024-08-23_12-51-17_peerly_backend.log b/logs/2024-08-23_12-51-17_peerly_backend.log new file mode 100644 index 0000000..4159b51 --- /dev/null +++ b/logs/2024-08-23_12-51-17_peerly_backend.log @@ -0,0 +1,2 @@ +time="2024-08-23T12:51:17+05:30" level=info msg="Starting Peerly Application..." +time="2024-08-23T12:51:23+05:30" level=info msg="2024-08-23T12:51:23+05:30 | 401 | \t 112.994µs | localhost:33001 | POST /peerly/set_logger_level" From 4fba193b252878ab05ec067741e1a5622ad7bbde Mon Sep 17 00:00:00 2001 From: Sharyu Marwadi Date: Fri, 23 Aug 2024 15:50:31 +0530 Subject: [PATCH 09/22] [feature/UpdateLogs] logs updated --- internal/api/badges.go | 4 +- internal/api/coreValues.go | 6 +- internal/api/grades.go | 4 +- internal/api/reportAppreciation.go | 14 +- internal/api/user.go | 32 ++--- internal/app/badges/service.go | 9 +- internal/app/coreValues/service.go | 17 +-- internal/app/grades/service.go | 8 +- internal/app/reportAppreciations/service.go | 29 +++-- .../app/reportAppreciations/service_test.go | 6 +- internal/app/users/service.go | 84 ++++++------ internal/app/users/service_test.go | 20 ++- .../repository/mocks/AppreciationStorer.go | 122 ++++++++---------- .../mocks/ReportAppreciationStorer.go | 36 ++++++ internal/repository/mocks/UserStorer.go | 1 + internal/repository/postgresdb/coreValues.go | 6 +- .../postgresdb/reportAppreciation.go | 14 +- internal/repository/postgresdb/user.go | 36 +++--- 18 files changed, 240 insertions(+), 208 deletions(-) diff --git a/internal/api/badges.go b/internal/api/badges.go index f344029..e6473e1 100644 --- a/internal/api/badges.go +++ b/internal/api/badges.go @@ -8,7 +8,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/badges" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) func listBadgesHandler(badgeSvc badges.Service) http.HandlerFunc { @@ -30,7 +30,7 @@ func editBadgesHandler(badgeSvc badges.Service) http.HandlerFunc { var reqData dto.UpdateBadgeReq err := json.NewDecoder(req.Body).Decode(&reqData) if err != nil { - logger.Errorf("error while decoding request data, err: %s", err.Error()) + logger.Errorf(req.Context(), "error while decoding request data, err: %s", err.Error()) err = apperrors.JSONParsingErrorReq dto.ErrorRepsonse(rw, err) return diff --git a/internal/api/coreValues.go b/internal/api/coreValues.go index 4574e27..add8482 100644 --- a/internal/api/coreValues.go +++ b/internal/api/coreValues.go @@ -8,7 +8,7 @@ import ( corevalues "github.com/joshsoftware/peerly-backend/internal/app/coreValues" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) func listCoreValuesHandler(coreValueSvc corevalues.Service) http.HandlerFunc { @@ -46,7 +46,7 @@ func createCoreValueHandler(coreValueSvc corevalues.Service) http.HandlerFunc { var coreValue dto.CreateCoreValueReq err := json.NewDecoder(req.Body).Decode(&coreValue) if err != nil { - logger.Errorf("error while decoding request data, err: %s", err.Error()) + logger.Errorf(req.Context(), "error while decoding request data, err: %s", err.Error()) err = apperrors.JSONParsingErrorReq dto.ErrorRepsonse(rw, err) return @@ -72,7 +72,7 @@ func updateCoreValueHandler(coreValueSvc corevalues.Service) http.HandlerFunc { var updateReq dto.UpdateQueryRequest err := json.NewDecoder(req.Body).Decode(&updateReq) if err != nil { - logger.Errorf("error while decoding request data, err: %s", err.Error()) + logger.Errorf(req.Context(), "error while decoding request data, err: %s", err.Error()) err = apperrors.JSONParsingErrorReq dto.ErrorRepsonse(rw, err) return diff --git a/internal/api/grades.go b/internal/api/grades.go index de77801..739369c 100644 --- a/internal/api/grades.go +++ b/internal/api/grades.go @@ -8,7 +8,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/grades" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) func listGradesHandler(gradeSvc grades.Service) http.HandlerFunc { @@ -30,7 +30,7 @@ func editGradesHandler(gradeSvc grades.Service) http.HandlerFunc { var reqData dto.UpdateGradeReq err := json.NewDecoder(req.Body).Decode(&reqData) if err != nil { - logger.Errorf("error while decoding request data, err: %s", err.Error()) + logger.Errorf(ctx, "error while decoding request data, err: %s", err.Error()) err = apperrors.JSONParsingErrorReq dto.ErrorRepsonse(rw, err) return diff --git a/internal/api/reportAppreciation.go b/internal/api/reportAppreciation.go index 2ec1601..e05cf23 100644 --- a/internal/api/reportAppreciation.go +++ b/internal/api/reportAppreciation.go @@ -9,7 +9,7 @@ import ( reportappreciations "github.com/joshsoftware/peerly-backend/internal/app/reportAppreciations" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) func reportAppreciationHandler(reportAppreciationSvc reportappreciations.Service) http.HandlerFunc { @@ -23,7 +23,7 @@ func reportAppreciationHandler(reportAppreciationSvc reportappreciations.Service appreciationId, err := strconv.ParseInt(vars["id"], 10, 64) if err != nil { - logger.WithField("err", err.Error()).Error("Error while parsing appreciation id from url") + logger.Errorf(req.Context(), "error while parsing appreciation id from url, err: %v", err) err = apperrors.InternalServerError return @@ -31,7 +31,7 @@ func reportAppreciationHandler(reportAppreciationSvc reportappreciations.Service var reqData dto.ReportAppreciationReq err = json.NewDecoder(req.Body).Decode(&reqData) if err != nil { - logger.WithField("err", err.Error()).Error("Error while decoding request data") + logger.Errorf(req.Context(), "err while decoding request data, err: %v", err) dto.ErrorRepsonse(rw, err) return } @@ -68,14 +68,14 @@ func moderateAppreciation(reportAppreciationSvc reportappreciations.Service) htt } resolutionId, err := strconv.ParseInt(vars["id"], 10, 64) if err != nil { - logger.Errorf("error while parsing id, err: %s", err.Error()) + logger.Errorf(req.Context(), "error while parsing id, err: %s", err.Error()) err = apperrors.InternalServerError return } var reqData dto.ModerationReq err = json.NewDecoder(req.Body).Decode(&reqData) if err != nil { - logger.Errorf("error while decoding request data, err:%s", err.Error()) + logger.Errorf(req.Context(), "error while decoding request data, err:%s", err.Error()) dto.ErrorRepsonse(rw, err) return } @@ -99,14 +99,14 @@ func resolveAppreciation(reportAppreciationSvc reportappreciations.Service) http } resolutionId, err := strconv.ParseInt(vars["id"], 10, 64) if err != nil { - logger.Errorf("error while parsing id, err: %s", err.Error()) + logger.Errorf(req.Context(), "error while parsing id, err: %s", err.Error()) err = apperrors.InternalServerError return } var reqData dto.ModerationReq err = json.NewDecoder(req.Body).Decode(&reqData) if err != nil { - logger.Errorf("error while decoding request data, err:%s", err.Error()) + logger.Errorf(req.Context(), "error while decoding request data, err:%s", err.Error()) dto.ErrorRepsonse(rw, err) return } diff --git a/internal/api/user.go b/internal/api/user.go index a64d4a6..e6ef06d 100644 --- a/internal/api/user.go +++ b/internal/api/user.go @@ -14,7 +14,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" log "github.com/joshsoftware/peerly-backend/internal/pkg/logger" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) func loginUser(userSvc user.Service) http.HandlerFunc { @@ -70,7 +70,7 @@ func loginAdmin(userSvc user.Service) http.HandlerFunc { var reqData dto.AdminLoginReq err := json.NewDecoder(req.Body).Decode(&reqData) if err != nil { - logger.Errorf("error while decoding request data. err: %s", err.Error()) + logger.Errorf(req.Context(), "error while decoding request data. err: %v", err) err = apperrors.JSONParsingErrorReq dto.ErrorRepsonse(rw, err) return @@ -94,9 +94,11 @@ func listIntranetUsersHandler(userSvc user.Service) http.HandlerFunc { return } + ctx := req.Context() + page := req.URL.Query().Get("page") if page == "" { - logger.Error("page query parameter is required") + logger.Error(ctx, "page query parameter is required") err := apperrors.PageParamNotFound dto.ErrorRepsonse(rw, err) return @@ -104,14 +106,12 @@ func listIntranetUsersHandler(userSvc user.Service) http.HandlerFunc { pageInt, err := strconv.ParseInt(page, 10, 64) if err != nil { - logger.Errorf("error page string to int64 conversion. err:%s ", err.Error()) + logger.Errorf(ctx, "error page string to int64 conversion. err:%s ", err.Error()) err = apperrors.InternalServerError dto.ErrorRepsonse(rw, err) return } - ctx := req.Context() - validateResp, err := userSvc.ValidatePeerly(ctx, authToken) if err != nil { dto.ErrorRepsonse(rw, err) @@ -135,10 +135,13 @@ func listIntranetUsersHandler(userSvc user.Service) http.HandlerFunc { func registerUser(userSvc user.Service) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { + + ctx := req.Context() + var user dto.IntranetUserData err := json.NewDecoder(req.Body).Decode(&user) if err != nil { - logger.Errorf("error while decoding request data. err: %s", err.Error()) + logger.Errorf(ctx, "error while decoding request data. err: %s", err.Error()) err = apperrors.JSONParsingErrorReq dto.ErrorRepsonse(rw, err) return @@ -150,8 +153,6 @@ func registerUser(userSvc user.Service) http.HandlerFunc { return } - ctx := req.Context() - resp, err := userSvc.RegisterUser(ctx, user) if err != nil { dto.ErrorRepsonse(rw, err) @@ -170,9 +171,11 @@ func listUsersHandler(userSvc user.Service) http.HandlerFunc { dto.ErrorRepsonse(rw, err) return } + + ctx := req.Context() pageInt, err := strconv.ParseInt(page, 10, 64) if err != nil { - logger.Errorf("error in page string to int64 conversion, err:%s", err.Error()) + logger.Errorf(ctx, "error in page string to int64 conversion, err:%s", err.Error()) err = apperrors.InternalServerError dto.ErrorRepsonse(rw, err) } @@ -189,7 +192,7 @@ func listUsersHandler(userSvc user.Service) http.HandlerFunc { } else { perPageInt, err = strconv.ParseInt(perPage, 10, 64) if err != nil { - logger.Errorf("error in page size string to int64 conversion, err:%s", err.Error()) + logger.Errorf(ctx, "error in page size string to int64 conversion, err:%s", err.Error()) err = apperrors.InternalServerError dto.ErrorRepsonse(rw, err) } @@ -225,13 +228,13 @@ func listUsersHandler(userSvc user.Service) http.HandlerFunc { func getActiveUserListHandler(userSvc user.Service) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { - log.Debug(req.Context(),"getActiveUserListHandler: req: ",req) + log.Debug(req.Context(), "getActiveUserListHandler: req: ", req) resp, err := userSvc.GetActiveUserList(req.Context()) if err != nil { dto.ErrorRepsonse(rw, err) return } - log.Debug(req.Context(),"getActiveUserListHandler: resp: ",resp) + log.Debug(req.Context(), "getActiveUserListHandler: resp: ", resp) dto.SuccessRepsonse(rw, http.StatusOK, "Active Users list", resp) } } @@ -265,7 +268,7 @@ func adminNotificationHandler(userSvc user.Service) http.HandlerFunc { var notificationReq dto.AdminNotificationReq err := json.NewDecoder(req.Body).Decode(¬ificationReq) if err != nil { - logger.Errorf("error while decoding request data. err: %s", err.Error()) + logger.Errorf(req.Context(), "error while decoding request data. err: %s", err.Error()) err = apperrors.JSONParsingErrorReq dto.ErrorRepsonse(rw, err) return @@ -308,7 +311,6 @@ func appreciationReportHandler(userSvc user.Service, appreciationSvc appreciatio } } - func reportedAppreciationReportHandler(userSvc user.Service, reportAppreciationSvc reportappreciations.Service) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { diff --git a/internal/app/badges/service.go b/internal/app/badges/service.go index 7e86a1d..9936ad7 100644 --- a/internal/app/badges/service.go +++ b/internal/app/badges/service.go @@ -5,9 +5,9 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" ) type service struct { @@ -29,8 +29,9 @@ func (bs *service) ListBadges(ctx context.Context) (resp []dto.Badge, err error) dbResp, err := bs.badgesRepo.ListBadges(ctx) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError + return } for _, item := range dbResp { @@ -50,14 +51,14 @@ func (gs *service) EditBadge(ctx context.Context, id string, rewardPoints int64) var reqData dto.UpdateBadgeReq reqData.Id = badgeId if rewardPoints < 0 { - logger.Errorf("badge reward points cannot be negative, reward points: %d", rewardPoints) + logger.Errorf(ctx, "badge reward points cannot be negative, reward points: %d", rewardPoints) err = apperrors.NegativeBadgePoints return } reqData.RewardPoints = rewardPoints err = gs.badgesRepo.EditBadge(ctx, reqData) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } diff --git a/internal/app/coreValues/service.go b/internal/app/coreValues/service.go index 6f2f2aa..ae4b0cc 100644 --- a/internal/app/coreValues/service.go +++ b/internal/app/coreValues/service.go @@ -5,9 +5,9 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" ) type service struct { @@ -31,8 +31,9 @@ func (cs *service) ListCoreValues(ctx context.Context) (resp []dto.CoreValue, er dbResp, err := cs.coreValuesRepo.ListCoreValues(ctx) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError + return } for _, value := range dbResp { @@ -65,7 +66,7 @@ func (cs *service) CreateCoreValue(ctx context.Context, coreValue dto.CreateCore isUnique, err := cs.coreValuesRepo.CheckUniqueCoreVal(ctx, coreValue.Name) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -81,7 +82,7 @@ func (cs *service) CreateCoreValue(ctx context.Context, coreValue dto.CreateCore dbResp, err := cs.coreValuesRepo.CreateCoreValue(ctx, coreValue) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -115,7 +116,7 @@ func (cs *service) UpdateCoreValue(ctx context.Context, coreValueID string, reqD isUnique, err := cs.coreValuesRepo.CheckUniqueCoreVal(ctx, reqData.Name) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -128,7 +129,7 @@ func (cs *service) UpdateCoreValue(ctx context.Context, coreValueID string, reqD dbResp, err := cs.coreValuesRepo.UpdateCoreValue(ctx, reqData) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return @@ -142,12 +143,12 @@ func (cs *service) UpdateCoreValue(ctx context.Context, coreValueID string, reqD func (cs *service) validateParentCoreValue(ctx context.Context, coreValueID int64) (ok bool) { coreValue, err := cs.coreValuesRepo.GetCoreValue(ctx, coreValueID) if err != nil { - logger.Errorf("parent core value id not present, err: %s", err.Error()) + logger.Errorf(ctx, "parent core value id not present, err: %s", err.Error()) return } if coreValue.ParentCoreValueID.Valid { - logger.Error("Invalid parent core value id") + logger.Error(ctx, "Invalid parent core value id") return } diff --git a/internal/app/grades/service.go b/internal/app/grades/service.go index 35bb575..146c7db 100644 --- a/internal/app/grades/service.go +++ b/internal/app/grades/service.go @@ -5,9 +5,9 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" ) type service struct { @@ -29,7 +29,7 @@ func (gs *service) ListGrades(ctx context.Context) (resp []dto.Grade, err error) dbResp, err := gs.gradesRepo.ListGrades(ctx) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError } @@ -50,14 +50,14 @@ func (gs *service) EditGrade(ctx context.Context, id string, points int64) (err var reqData dto.UpdateGradeReq reqData.Id = gradeId if points < 0 { - logger.Errorf("grade points cannot be negative, grade points: %d", points) + logger.Errorf(ctx, "grade points cannot be negative, grade points: %d", points) err = apperrors.NegativeGradePoints return } reqData.Points = points err = gs.gradesRepo.EditGrade(ctx, reqData) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } diff --git a/internal/app/reportAppreciations/service.go b/internal/app/reportAppreciations/service.go index c17b696..2ecfdf7 100644 --- a/internal/app/reportAppreciations/service.go +++ b/internal/app/reportAppreciations/service.go @@ -9,8 +9,8 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" ) type service struct { @@ -40,7 +40,7 @@ func (rs *service) ReportAppreciation(ctx context.Context, reqData dto.ReportApp fmt.Printf("reporterId: %T", reporterId) data, ok := reporterId.(int64) if !ok { - logger.Error("Error in typecasting reporter id") + logger.Error(ctx, "Error in typecasting reporter id") err = apperrors.InternalServerError return } @@ -117,7 +117,7 @@ func (rs *service) ListReportedAppreciations(ctx context.Context) (dto.ListRepor appreciations, err := rs.reportAppreciationRepo.ListReportedAppreciations(ctx) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return resp, err } @@ -181,7 +181,7 @@ func (rs *service) DeleteAppreciation(ctx context.Context, reqData dto.Moderatio fmt.Printf("moderatorId: %T", moderatorId) data, ok := moderatorId.(int64) if !ok { - logger.Error("Error in typecasting moderator id") + logger.Error(ctx, "Error in typecasting moderator id") err = apperrors.InternalServerError return } @@ -195,7 +195,7 @@ func (rs *service) DeleteAppreciation(ctx context.Context, reqData dto.Moderatio reqData.AppreciationId = appreciation.Appreciation_id err = rs.reportAppreciationRepo.DeleteAppreciation(ctx, reqData) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -300,12 +300,13 @@ func sendReportEmail(senderEmail string, senderFirstName string, senderLastName AppreciationReceiverName: fmt.Sprint(apprReceiverFirstName, " ", apprReceiverLastName), } - logger.Info("report sender email: ---------> ", senderEmail) + ctx := context.Background() + logger.Info(ctx, "report sender email: ---------> ", senderEmail) mailReq := email.NewMail([]string{senderEmail}, []string{"samnitpatil@gmail.com"}, []string{"samirpatil9882@gmail.com"}, "Appreciaion Reported") mailReq.ParseTemplate("./internal/app/email/templates/reportAppreciation.html", templateData) err := mailReq.Send(plainTextContent) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx, "err: %v", err) return err } return nil @@ -316,7 +317,7 @@ func (rs *service) ResolveAppreciation(ctx context.Context, reqData dto.Moderati fmt.Printf("moderatorId: %T", moderatorId) data, ok := moderatorId.(int64) if !ok { - logger.Error("Error in typecasting moderator id") + logger.Error(ctx, "Error in typecasting moderator id") err = apperrors.InternalServerError return } @@ -329,7 +330,7 @@ func (rs *service) ResolveAppreciation(ctx context.Context, reqData dto.Moderati reqData.AppreciationId = appreciation.Appreciation_id err = rs.reportAppreciationRepo.ResolveAppreciation(ctx, reqData) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -381,12 +382,13 @@ func sendDeleteEmail(senderEmail string, templateData dto.DeleteAppreciationMail // Plain text content plainTextContent := "Samnit " + "123456" - logger.Info("report sender email: ---------> ", senderEmail) + ctx := context.Background() + logger.Info(ctx, "report sender email: ---------> ", senderEmail) mailReq := email.NewMail([]string{senderEmail}, []string{"sharyu.marwadi@joshsoftware.com"}, []string{}, "Appreciaion Deleted") mailReq.ParseTemplate("./internal/app/email/templates/deleteAppreciation.html", templateData) err := mailReq.Send(plainTextContent) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx, "err: %v", err) return err } return nil @@ -396,12 +398,13 @@ func sendResolveEmail(senderEmail string, templateData dto.ResolveAppreciationMa // Plain text content plainTextContent := "Samnit " + "123456" - logger.Info("report sender email: ---------> ", senderEmail) + ctx := context.Background() + logger.Info(ctx, "report sender email: ---------> ", senderEmail) mailReq := email.NewMail([]string{senderEmail}, []string{"sharyu.marwadi@joshsoftware.com"}, []string{}, "Appreciaion Resolved") mailReq.ParseTemplate("./internal/app/email/templates/resolveAppreciation.html", templateData) err := mailReq.Send(plainTextContent) if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx, "err: %v", err) return err } return nil diff --git a/internal/app/reportAppreciations/service_test.go b/internal/app/reportAppreciations/service_test.go index dc8c324..8df71d4 100644 --- a/internal/app/reportAppreciations/service_test.go +++ b/internal/app/reportAppreciations/service_test.go @@ -15,7 +15,8 @@ import ( func TestReportAppreciation(t *testing.T) { reportAppreciationRepo := mocks.NewReportAppreciationStorer(t) userRepo := mocks.NewUserStorer(t) - service := NewService(reportAppreciationRepo, userRepo) + appreciationRepo := mocks.NewAppreciationStorer(t) + service := NewService(reportAppreciationRepo, userRepo, appreciationRepo) tests := []struct { name string @@ -140,7 +141,8 @@ func TestReportAppreciation(t *testing.T) { func TestListReportedAppreciations(t *testing.T) { reportAppreciationRepo := mocks.NewReportAppreciationStorer(t) userRepo := mocks.NewUserStorer(t) - service := NewService(reportAppreciationRepo, userRepo) + appreciationRepo := mocks.NewAppreciationStorer(t) + service := NewService(reportAppreciationRepo, userRepo, appreciationRepo) tests := []struct { name string diff --git a/internal/app/users/service.go b/internal/app/users/service.go index 0c72366..d692ed4 100644 --- a/internal/app/users/service.go +++ b/internal/app/users/service.go @@ -17,8 +17,8 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/config" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" "github.com/xuri/excelize/v2" "golang.org/x/crypto/bcrypt" ) @@ -55,7 +55,7 @@ func (us *service) ValidatePeerly(ctx context.Context, authToken string) (data d client := &http.Client{} validationReq, err := http.NewRequest(http.MethodPost, config.IntranetBaseUrl()+constants.PeerlyValidationPath, nil) if err != nil { - logger.Errorf("error in creating new validation request err: %s", err.Error()) + logger.Errorf(ctx, "error in creating new validation request err: %s", err.Error()) err = apperrors.InternalServerError return } @@ -63,25 +63,25 @@ func (us *service) ValidatePeerly(ctx context.Context, authToken string) (data d validationReq.Header.Add(constants.ClientCode, config.IntranetClientCode()) resp, err := client.Do(validationReq) if err != nil { - logger.Errorf("error in intranet validation api. status returned: %d, err: %s", resp.StatusCode, err.Error()) + logger.Errorf(ctx, "error in intranet validation api. status returned: %d, err: %s", resp.StatusCode, err.Error()) err = apperrors.InternalServerError return } if resp.StatusCode != http.StatusOK { - logger.Errorf("error returned, status returned: %d", resp.StatusCode) + logger.Errorf(ctx, "error returned, status returned: %d", resp.StatusCode) err = apperrors.IntranetValidationFailed return } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { - logger.Errorf("error in readall parsing. err: %s", err.Error()) + logger.Errorf(ctx, "error in readall parsing. err: %s", err.Error()) err = apperrors.JSONParsingErrorResp return } err = json.Unmarshal(body, &data) if err != nil { - logger.Errorf("error in unmarshal parsing. err: %s", err.Error()) + logger.Errorf(ctx, "error in unmarshal parsing. err: %s", err.Error()) err = apperrors.JSONParsingErrorResp return } @@ -95,7 +95,7 @@ func (us *service) GetIntranetUserData(ctx context.Context, req dto.GetIntranetU url := fmt.Sprintf("%s%s%d", config.IntranetBaseUrl(), constants.GetIntranetUserDataPath, req.UserId) intranetReq, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { - logger.Errorf("error in creating new get user request. err: %s", err.Error()) + logger.Errorf(ctx, "error in creating new get user request. err: %s", err.Error()) err = apperrors.InternalServerError return } @@ -103,14 +103,14 @@ func (us *service) GetIntranetUserData(ctx context.Context, req dto.GetIntranetU intranetReq.Header.Add(constants.AuthorizationHeader, req.Token) resp, err := client.Do(intranetReq) if err != nil { - logger.Errorf("error in intranet get user api. status returned: %d, err: %s ", resp.StatusCode, err.Error()) - logger.Errorf("error response: %v", resp) + logger.Errorf(ctx, "error in intranet get user api. status returned: %d, err: %s ", resp.StatusCode, err.Error()) + logger.Errorf(ctx, "error response: %v", resp) err = apperrors.InternalServerError return } if resp.StatusCode != http.StatusOK { - logger.Errorf("error in intranet get user api. status returned: %d ", resp.StatusCode) - logger.Errorf("error response: %v", resp) + logger.Errorf(ctx, "error in intranet get user api. status returned: %d ", resp.StatusCode) + logger.Errorf(ctx, "error response: %v", resp) err = apperrors.InternalServerError return } @@ -118,7 +118,7 @@ func (us *service) GetIntranetUserData(ctx context.Context, req dto.GetIntranetU body, err := io.ReadAll(resp.Body) if err != nil { - logger.Errorf("error in io.readall. err: %s", err.Error()) + logger.Errorf(ctx, "error in io.readall. err: %s", err.Error()) err = apperrors.JSONParsingErrorResp return } @@ -127,7 +127,7 @@ func (us *service) GetIntranetUserData(ctx context.Context, req dto.GetIntranetU err = json.Unmarshal(body, &respData) if err != nil { - logger.Errorf("error in unmarshalling data. err: %s", err.Error()) + logger.Errorf(ctx, "error in unmarshalling data. err: %s", err.Error()) err = apperrors.JSONParsingErrorResp return } @@ -153,7 +153,7 @@ func (us *service) LoginUser(ctx context.Context, u dto.IntranetUserData) (dto.L //sync user data syncNeeded, dataToBeUpdated, err := us.syncData(ctx, u, user) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return resp, err } @@ -161,7 +161,7 @@ func (us *service) LoginUser(ctx context.Context, u dto.IntranetUserData) (dto.L err = us.userRepo.SyncData(ctx, dataToBeUpdated) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return resp, err } @@ -193,7 +193,7 @@ func (us *service) LoginUser(ctx context.Context, u dto.IntranetUserData) (dto.L tokenString, err := token.SignedString(jwtKey) if err != nil { - logger.Errorf("error generating authtoken. err: %s", err.Error()) + logger.Errorf(ctx, "error generating authtoken. err: %s", err.Error()) err = apperrors.InternalServerError return resp, err } @@ -203,7 +203,7 @@ func (us *service) LoginUser(ctx context.Context, u dto.IntranetUserData) (dto.L err = us.userRepo.AddDeviceToken(ctx, user.Id, u.NotificationToken) if err != nil { - logger.Errorf("err in adding device token: %v", err) + logger.Errorf(ctx, "err in adding device token: %v", err) } return resp, nil @@ -227,7 +227,7 @@ func (us *service) RegisterUser(ctx context.Context, u dto.IntranetUserData) (us //reward_multiplier from organization config reward_multiplier, err := us.userRepo.GetRewardMultiplier(ctx) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -236,7 +236,7 @@ func (us *service) RegisterUser(ctx context.Context, u dto.IntranetUserData) (us //get role by name roleId, err := us.userRepo.GetRoleByName(ctx, constants.UserRole) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -250,7 +250,7 @@ func (us *service) RegisterUser(ctx context.Context, u dto.IntranetUserData) (us //register user dbResp, err := us.userRepo.CreateNewUser(ctx, svcData) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -265,7 +265,7 @@ func (us *service) ListIntranetUsers(ctx context.Context, reqData dto.GetUserLis url := config.IntranetBaseUrl() + fmt.Sprintf(constants.ListIntranetUsersPath, reqData.Page, constants.DefaultPageSize) intranetReq, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { - logger.Errorf("error in creating new intranet user list request. err: %s", err.Error()) + logger.Errorf(ctx, "error in creating new intranet user list request. err: %s", err.Error()) err = apperrors.InternalServerError return } @@ -273,12 +273,12 @@ func (us *service) ListIntranetUsers(ctx context.Context, reqData dto.GetUserLis intranetReq.Header.Add(constants.AuthorizationHeader, reqData.AuthToken) resp, err := client.Do(intranetReq) if err != nil { - logger.Errorf("error in intranet get user api. status returned: %d, err: %s ", resp.StatusCode, err.Error()) + logger.Errorf(ctx, "error in intranet get user api. status returned: %d, err: %s ", resp.StatusCode, err.Error()) err = apperrors.InternalServerError return } if resp.StatusCode != http.StatusOK { - logger.Errorf("erro in intranet user list request. status returned: %d", resp.StatusCode) + logger.Errorf(ctx, "erro in intranet user list request. status returned: %d", resp.StatusCode) err = apperrors.InternalServerError return } @@ -288,13 +288,13 @@ func (us *service) ListIntranetUsers(ctx context.Context, reqData dto.GetUserLis body, err := io.ReadAll(resp.Body) if err != nil { - logger.Errorf("error in io.readall, err: %s", err.Error()) + logger.Errorf(ctx, "error in io.readall, err: %s", err.Error()) err = apperrors.JSONParsingErrorResp } err = json.Unmarshal(body, &respData) if err != nil { - logger.Errorf("error in unmarshalling data, err: %s", err.Error()) + logger.Errorf(ctx, "error in unmarshalling data, err: %s", err.Error()) err = apperrors.JSONParsingErrorResp return } @@ -316,7 +316,7 @@ func (us *service) ListUsers(ctx context.Context, reqData dto.ListUsersReq) (res dbResp, totalCount, err := us.userRepo.ListUsers(ctx, reqData) if err != nil { - logger.Errorf(err.Error()) + logger.Errorf(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -357,14 +357,14 @@ func (us *service) AdminLogin(ctx context.Context, loginReq dto.AdminLoginReq) ( } if dbUser.RoleID != 2 { - logger.Errorf("unathorized access") + logger.Errorf(ctx, "unathorized access") err = apperrors.RoleUnathorized return } err = bcrypt.CompareHashAndPassword([]byte(dbUser.Password.String), []byte(loginReq.Password)) if err != nil { - logger.Errorf("invalid password, err: %s", err.Error()) + logger.Errorf(ctx, "invalid password, err: %s", err.Error()) err = apperrors.InvalidPassword return } @@ -387,7 +387,7 @@ func (us *service) AdminLogin(ctx context.Context, loginReq dto.AdminLoginReq) ( tokenString, err := token.SignedString(jwtKey) if err != nil { - logger.Errorf("error generating authtoken. err: %s", err.Error()) + logger.Errorf(ctx, "error generating authtoken. err: %s", err.Error()) err = apperrors.InternalServerError return resp, err } @@ -440,7 +440,7 @@ func (us *service) GetUserById(ctx context.Context) (user dto.GetUserByIdResp, e fmt.Printf("userId: %T", id) userId, ok := id.(int64) if !ok { - logger.Error("Error in typecasting user id") + logger.Error(ctx, "Error in typecasting user id") err = apperrors.InternalServerError return } @@ -459,7 +459,7 @@ func (us *service) GetUserById(ctx context.Context) (user dto.GetUserByIdResp, e grade, err := us.userRepo.GetGradeById(ctx, user.GradeId) if err != nil { - logger.Errorf(err.Error()) + logger.Errorf(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -517,7 +517,7 @@ func (us *service) GetTop10Users(ctx context.Context) (users []dto.Top10User, er quaterTimeStamp := GetQuarterStartUnixTime() dbUsers, err := us.userRepo.GetTop10Users(ctx, quaterTimeStamp) if err != nil { - logger.Error(err.Error()) + logger.Error(ctx, err.Error()) err = apperrors.InternalServerError return } @@ -558,7 +558,7 @@ func (us *service) sendRewardQuotaRefillEmailToAll(ctx context.Context) { } dbUsers, _, err := us.userRepo.ListUsers(ctx, reqData) if err != nil { - logger.Errorf("error in getting users for email") + logger.Errorf(ctx, "error in getting users for email") return } @@ -567,10 +567,10 @@ func (us *service) sendRewardQuotaRefillEmailToAll(ctx context.Context) { usersEmails = append(usersEmails, user.Email) } - logger.Info("user emails : ") + logger.Info(ctx, "user emails : ") for _, userEmail := range usersEmails { - logger.Infoln("email: ", userEmail) + logger.Info(ctx, "email: ", userEmail) } templateData := struct { @@ -582,12 +582,12 @@ func (us *service) sendRewardQuotaRefillEmailToAll(ctx context.Context) { mailReq := email.NewMail([]string{"samnitpatil9882@gmail.com"}, []string{"samnitpatil@gmail.com"}, []string{"samirpatil9882@gmail.com"}, "Reward Quota Refilled") err = mailReq.ParseTemplate("./internal/app/email/templates/rewardQuotaReset.html", templateData) if err != nil { - logger.Errorf("err in creating html file : %v", err) + logger.Errorf(ctx, "err in creating html file : %v", err) return } err = mailReq.Send("reward quota renewal") if err != nil { - logger.Errorf("err: %v", err) + logger.Errorf(ctx, "err: %v", err) return } } @@ -603,7 +603,7 @@ func (us *service) NotificationByAdmin(ctx context.Context, notificationReq dto. notificationTokens, err := us.userRepo.ListDeviceTokensByUserID(ctx, notificationReq.Id) if err != nil { - logger.Errorf("err in getting device tokens: %v", err) + logger.Errorf(ctx, "err in getting device tokens: %v", err) err = apperrors.InternalServerError return } @@ -635,7 +635,7 @@ func (us *service) AllAppreciationReport(ctx context.Context, appreciations []dt sheetName := "Appreciations" index, err := f.NewSheet(sheetName) if err != nil { - logger.Errorf("err in generating newsheet, err: %v", err) + logger.Errorf(ctx, "err in generating newsheet, err: %v", err) return } @@ -668,7 +668,7 @@ func (us *service) AllAppreciationReport(ctx context.Context, appreciations []dt // Save the Excel file temporarily tempFileName = "report.xlsx" if err = f.SaveAs(tempFileName); err != nil { - logger.Errorf("Failed to save file: %v", err) + logger.Errorf(ctx, "Failed to save file: %v", err) return } @@ -684,7 +684,7 @@ func (us *service) ReportedAppreciationReport(ctx context.Context, appreciations sheetName := "ReportedAppreciations" index, err := f.NewSheet(sheetName) if err != nil { - logger.Errorf("err in generating newsheet, err: %v", err) + logger.Errorf(ctx, "err in generating newsheet, err: %v", err) return } @@ -723,7 +723,7 @@ func (us *service) ReportedAppreciationReport(ctx context.Context, appreciations // Save the Excel file temporarily tempFileName = "reportedAppreciations.xlsx" if err = f.SaveAs(tempFileName); err != nil { - logger.Errorf("Failed to save file: %v", err) + logger.Errorf(ctx, "Failed to save file: %v", err) return } diff --git a/internal/app/users/service_test.go b/internal/app/users/service_test.go index 29b2227..007ded4 100644 --- a/internal/app/users/service_test.go +++ b/internal/app/users/service_test.go @@ -503,20 +503,16 @@ func TestGetActiveUserList(t *testing.T) { }, expectedResp: []dto.ActiveUser{ { - ID: 55, - FirstName: "Deepak", - LastName: "Kumar", - ProfileImageURL: "", - BadgeName: "", - AppreciationPoints: 0, + ID: 55, + FirstName: "Deepak", + LastName: "Kumar", + ProfileImageURL: "", }, { - ID: 58, - FirstName: "Dominic", - LastName: "Lopes", - ProfileImageURL: "", - BadgeName: "Gold", - AppreciationPoints: 5000, + ID: 58, + FirstName: "Dominic", + LastName: "Lopes", + ProfileImageURL: "", }, }, expectedError: nil, diff --git a/internal/repository/mocks/AppreciationStorer.go b/internal/repository/mocks/AppreciationStorer.go index 675a209..4c35c92 100644 --- a/internal/repository/mocks/AppreciationStorer.go +++ b/internal/repository/mocks/AppreciationStorer.go @@ -1,17 +1,12 @@ -// Code generated by mockery v2.43.2. DO NOT EDIT. +// Code generated by mockery v1.0.0. DO NOT EDIT. package mocks -import ( - context "context" - - dto "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - mock "github.com/stretchr/testify/mock" - - repository "github.com/joshsoftware/peerly-backend/internal/repository" - - sqlx "github.com/jmoiron/sqlx" -) +import context "context" +import dto "github.com/joshsoftware/peerly-backend/internal/pkg/dto" +import mock "github.com/stretchr/testify/mock" +import repository "github.com/joshsoftware/peerly-backend/internal/repository" +import sqlx "github.com/jmoiron/sqlx" // AppreciationStorer is an autogenerated mock type for the AppreciationStorer type type AppreciationStorer struct { @@ -22,15 +17,7 @@ type AppreciationStorer struct { func (_m *AppreciationStorer) BeginTx(ctx context.Context) (repository.Transaction, error) { ret := _m.Called(ctx) - if len(ret) == 0 { - panic("no return value specified for BeginTx") - } - var r0 repository.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (repository.Transaction, error)); ok { - return rf(ctx) - } if rf, ok := ret.Get(0).(func(context.Context) repository.Transaction); ok { r0 = rf(ctx) } else { @@ -39,6 +26,7 @@ func (_m *AppreciationStorer) BeginTx(ctx context.Context) (repository.Transacti } } + var r1 error if rf, ok := ret.Get(1).(func(context.Context) error); ok { r1 = rf(ctx) } else { @@ -52,21 +40,14 @@ func (_m *AppreciationStorer) BeginTx(ctx context.Context) (repository.Transacti func (_m *AppreciationStorer) CreateAppreciation(ctx context.Context, tx repository.Transaction, appreciation dto.Appreciation) (repository.Appreciation, error) { ret := _m.Called(ctx, tx, appreciation) - if len(ret) == 0 { - panic("no return value specified for CreateAppreciation") - } - var r0 repository.Appreciation - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.Appreciation) (repository.Appreciation, error)); ok { - return rf(ctx, tx, appreciation) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.Appreciation) repository.Appreciation); ok { r0 = rf(ctx, tx, appreciation) } else { r0 = ret.Get(0).(repository.Appreciation) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, dto.Appreciation) error); ok { r1 = rf(ctx, tx, appreciation) } else { @@ -80,10 +61,6 @@ func (_m *AppreciationStorer) CreateAppreciation(ctx context.Context, tx reposit func (_m *AppreciationStorer) DeleteAppreciation(ctx context.Context, tx repository.Transaction, apprId int32) error { ret := _m.Called(ctx, tx, apprId) - if len(ret) == 0 { - panic("no return value specified for DeleteAppreciation") - } - var r0 error if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int32) error); ok { r0 = rf(ctx, tx, apprId) @@ -98,21 +75,14 @@ func (_m *AppreciationStorer) DeleteAppreciation(ctx context.Context, tx reposit func (_m *AppreciationStorer) GetAppreciationById(ctx context.Context, tx repository.Transaction, appreciationId int32) (repository.AppreciationResponse, error) { ret := _m.Called(ctx, tx, appreciationId) - if len(ret) == 0 { - panic("no return value specified for GetAppreciationById") - } - var r0 repository.AppreciationResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int32) (repository.AppreciationResponse, error)); ok { - return rf(ctx, tx, appreciationId) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int32) repository.AppreciationResponse); ok { r0 = rf(ctx, tx, appreciationId) } else { r0 = ret.Get(0).(repository.AppreciationResponse) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, int32) error); ok { r1 = rf(ctx, tx, appreciationId) } else { @@ -126,10 +96,6 @@ func (_m *AppreciationStorer) GetAppreciationById(ctx context.Context, tx reposi func (_m *AppreciationStorer) HandleTransaction(ctx context.Context, tx repository.Transaction, isSuccess bool) error { ret := _m.Called(ctx, tx, isSuccess) - if len(ret) == 0 { - panic("no return value specified for HandleTransaction") - } - var r0 error if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, bool) error); ok { r0 = rf(ctx, tx, isSuccess) @@ -144,10 +110,6 @@ func (_m *AppreciationStorer) HandleTransaction(ctx context.Context, tx reposito func (_m *AppreciationStorer) InitiateQueryExecutor(tx repository.Transaction) sqlx.Ext { ret := _m.Called(tx) - if len(ret) == 0 { - panic("no return value specified for InitiateQueryExecutor") - } - var r0 sqlx.Ext if rf, ok := ret.Get(0).(func(repository.Transaction) sqlx.Ext); ok { r0 = rf(tx) @@ -164,21 +126,14 @@ func (_m *AppreciationStorer) InitiateQueryExecutor(tx repository.Transaction) s func (_m *AppreciationStorer) IsUserPresent(ctx context.Context, tx repository.Transaction, userID int64) (bool, error) { ret := _m.Called(ctx, tx, userID) - if len(ret) == 0 { - panic("no return value specified for IsUserPresent") - } - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int64) (bool, error)); ok { - return rf(ctx, tx, userID) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int64) bool); ok { r0 = rf(ctx, tx, userID) } else { r0 = ret.Get(0).(bool) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, int64) error); ok { r1 = rf(ctx, tx, userID) } else { @@ -192,16 +147,7 @@ func (_m *AppreciationStorer) IsUserPresent(ctx context.Context, tx repository.T func (_m *AppreciationStorer) ListAppreciations(ctx context.Context, tx repository.Transaction, filter dto.AppreciationFilter) ([]repository.AppreciationResponse, repository.Pagination, error) { ret := _m.Called(ctx, tx, filter) - if len(ret) == 0 { - panic("no return value specified for ListAppreciations") - } - var r0 []repository.AppreciationResponse - var r1 repository.Pagination - var r2 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.AppreciationFilter) ([]repository.AppreciationResponse, repository.Pagination, error)); ok { - return rf(ctx, tx, filter) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.AppreciationFilter) []repository.AppreciationResponse); ok { r0 = rf(ctx, tx, filter) } else { @@ -210,12 +156,14 @@ func (_m *AppreciationStorer) ListAppreciations(ctx context.Context, tx reposito } } + var r1 repository.Pagination if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, dto.AppreciationFilter) repository.Pagination); ok { r1 = rf(ctx, tx, filter) } else { r1 = ret.Get(1).(repository.Pagination) } + var r2 error if rf, ok := ret.Get(2).(func(context.Context, repository.Transaction, dto.AppreciationFilter) error); ok { r2 = rf(ctx, tx, filter) } else { @@ -225,8 +173,50 @@ func (_m *AppreciationStorer) ListAppreciations(ctx context.Context, tx reposito return r0, r1, r2 } -// NewAppreciationStorer creates a new instance of AppreciationStorer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. +// UpdateAppreciationTotalRewardsOfYesterday provides a mock function with given fields: ctx, tx +func (_m *AppreciationStorer) UpdateAppreciationTotalRewardsOfYesterday(ctx context.Context, tx repository.Transaction) (bool, error) { + ret := _m.Called(ctx, tx) + + var r0 bool + if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction) bool); ok { + r0 = rf(ctx, tx) + } else { + r0 = ret.Get(0).(bool) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction) error); ok { + r1 = rf(ctx, tx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// UpdateUserBadgesBasedOnTotalRewards provides a mock function with given fields: ctx, tx +func (_m *AppreciationStorer) UpdateUserBadgesBasedOnTotalRewards(ctx context.Context, tx repository.Transaction) ([]repository.UserBadgeDetails, error) { + ret := _m.Called(ctx, tx) + + var r0 []repository.UserBadgeDetails + if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction) []repository.UserBadgeDetails); ok { + r0 = rf(ctx, tx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]repository.UserBadgeDetails) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction) error); ok { + r1 = rf(ctx, tx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + func NewAppreciationStorer(t interface { mock.TestingT Cleanup(func()) diff --git a/internal/repository/mocks/ReportAppreciationStorer.go b/internal/repository/mocks/ReportAppreciationStorer.go index e2e5eb5..010cac4 100644 --- a/internal/repository/mocks/ReportAppreciationStorer.go +++ b/internal/repository/mocks/ReportAppreciationStorer.go @@ -96,6 +96,27 @@ func (_m *ReportAppreciationStorer) DeleteAppreciation(ctx context.Context, mode return r0 } +// GetResolution provides a mock function with given fields: ctx, id +func (_m *ReportAppreciationStorer) GetResolution(ctx context.Context, id int64) (repository.ListReportedAppreciations, error) { + ret := _m.Called(ctx, id) + + var r0 repository.ListReportedAppreciations + if rf, ok := ret.Get(0).(func(context.Context, int64) repository.ListReportedAppreciations); ok { + r0 = rf(ctx, id) + } else { + r0 = ret.Get(0).(repository.ListReportedAppreciations) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, int64) error); ok { + r1 = rf(ctx, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetSenderAndReceiver provides a mock function with given fields: ctx, reqData func (_m *ReportAppreciationStorer) GetSenderAndReceiver(ctx context.Context, reqData dto.ReportAppreciationReq) (dto.GetSenderAndReceiverResp, error) { ret := _m.Called(ctx, reqData) @@ -161,6 +182,21 @@ func (_m *ReportAppreciationStorer) ReportAppreciation(ctx context.Context, repo return r0, r1 } +// ResolveAppreciation provides a mock function with given fields: ctx, moderationReq +func (_m *ReportAppreciationStorer) ResolveAppreciation(ctx context.Context, moderationReq dto.ModerationReq) error { + ret := _m.Called(ctx, moderationReq) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, dto.ModerationReq) error); ok { + r0 = rf(ctx, moderationReq) + } else { + r0 = ret.Error(0) + } + + return r0 +} + + func NewReportAppreciationStorer(t interface { mock.TestingT Cleanup(func()) diff --git a/internal/repository/mocks/UserStorer.go b/internal/repository/mocks/UserStorer.go index 29df5de..33cb751 100644 --- a/internal/repository/mocks/UserStorer.go +++ b/internal/repository/mocks/UserStorer.go @@ -386,3 +386,4 @@ func NewUserStorer(t interface { return mock } + diff --git a/internal/repository/postgresdb/coreValues.go b/internal/repository/postgresdb/coreValues.go index 444e7e3..4371105 100644 --- a/internal/repository/postgresdb/coreValues.go +++ b/internal/repository/postgresdb/coreValues.go @@ -9,8 +9,8 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" ) var CoreValueColumns = []string{"id", "name", "description", "parent_core_value_id"} @@ -56,7 +56,7 @@ func (cs *coreValueStore) GetCoreValue(ctx context.Context, coreValueID int64) ( getCoreValueQuery, args, err := queryBuilder.ToSql() if err != nil { - logger.Errorf("error in generating squirrel query, err: %s", err.Error()) + logger.Errorf(ctx, "error in generating squirrel query, err: %s", err.Error()) err = apperrors.InternalServerError return } @@ -68,7 +68,7 @@ func (cs *coreValueStore) GetCoreValue(ctx context.Context, coreValueID int64) ( args..., ) if err != nil { - logger.Errorf("error while getting core value, corevalue_id: %d, err: %s", coreValueID, err.Error()) + logger.Errorf(ctx, "error while getting core value, corevalue_id: %d, err: %s", coreValueID, err.Error()) err = apperrors.InvalidCoreValueData return } diff --git a/internal/repository/postgresdb/reportAppreciation.go b/internal/repository/postgresdb/reportAppreciation.go index 2bb7811..a72a5b1 100644 --- a/internal/repository/postgresdb/reportAppreciation.go +++ b/internal/repository/postgresdb/reportAppreciation.go @@ -8,8 +8,8 @@ import ( "github.com/jmoiron/sqlx" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" ) type reportAppreciationStore struct { @@ -39,7 +39,7 @@ func (rs *reportAppreciationStore) CheckAppreciation(ctx context.Context, reqDat reqData.AppreciationId, ) if err != nil { - logger.WithField("err", err.Error()).Error("Error in retriving appreciation count") + logger.Errorf(ctx, "error in retriving appreciation, err: %v") return } if count == 0 { @@ -60,7 +60,7 @@ func (rs *reportAppreciationStore) CheckDuplicateReport(ctx context.Context, req reqData.ReportedBy, ) if err != nil { - logger.WithField("err", err.Error()).Error("Error in looking for duplicate report") + logger.Errorf(ctx, "error in looking for duplicate report, err: %v", err) return } if count > 0 { @@ -79,7 +79,7 @@ func (rs *reportAppreciationStore) GetSenderAndReceiver(ctx context.Context, req reqData.AppreciationId, ) if err != nil { - logger.WithField("err", err.Error()).Error("Error in fetching appreciation sender and receiver") + logger.Errorf(ctx, "error in fetching appreciation sender and receiver, err: %v", err) return } return @@ -96,7 +96,7 @@ func (rs *reportAppreciationStore) ReportAppreciation(ctx context.Context, repor reportReq.ReportedBy, ) if err != nil { - logger.WithField("err", err.Error()).Error("Error in creating report") + logger.Error(ctx, "error in creating report, err:%v", err) return } return @@ -190,11 +190,11 @@ func (rs *reportAppreciationStore) GetResolution(ctx context.Context, id int64) ) if err != nil { if err == sql.ErrNoRows { - logger.Errorf("no such resolution exists") + logger.Errorf(ctx, "no such resolution exists") err = apperrors.InvalidId return } - logger.Errorf("error in retriving reported appriciation, err:%w", err) + logger.Errorf(ctx, "error in retriving reported appriciation, err:%w", err) err = apperrors.InternalServerError return } diff --git a/internal/repository/postgresdb/user.go b/internal/repository/postgresdb/user.go index 1153f48..4177d19 100644 --- a/internal/repository/postgresdb/user.go +++ b/internal/repository/postgresdb/user.go @@ -10,8 +10,8 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" ) var ( @@ -50,7 +50,7 @@ func (us *userStore) GetUserByEmail(ctx context.Context, email string) (user rep queryBuilder := repository.Sq.Select(userColumns...).From(us.UsersTable).Where(squirrel.Like{"email": email}) getUserByEmailQuery, args, err := queryBuilder.ToSql() if err != nil { - logger.Errorf("error in generating query, err: %s", err.Error()) + logger.Errorf(ctx, "error in generating query, err: %s", err.Error()) err = apperrors.InternalServerError return } @@ -67,7 +67,7 @@ func (us *userStore) GetUserByEmail(ctx context.Context, email string) (user rep return } else { // Possible that there's no rows in the result set - logger.Errorf("error selecting user from database by email, err: %s", err.Error()) + logger.Errorf(ctx, "error selecting user from database by email, err: %s", err.Error()) err = apperrors.InternalServerError return } @@ -126,7 +126,7 @@ func (us *userStore) GetGradeByName(ctx context.Context, name string) (grade rep queryBuilder := repository.Sq.Select(gradeColumns...).From(us.GradesTable).Where(squirrel.Like{"name": name}) getGradeId, args, err := queryBuilder.ToSql() if err != nil { - logger.Errorf("error in generating query, err: %s", err) + logger.Errorf(ctx, "error in generating query, err: %s", err) err = apperrors.InternalServerError return } @@ -137,7 +137,7 @@ func (us *userStore) GetGradeByName(ctx context.Context, name string) (grade rep err = apperrors.GradeNotFound return } - logger.Errorf("error in retriving grade id, grade: %s, err: %s", name, err.Error()) + logger.Errorf(ctx, "error in retriving grade id, grade: %s, err: %s", name, err.Error()) err = apperrors.InternalServerError return } @@ -251,7 +251,7 @@ func (us *userStore) ListUsers(ctx context.Context, reqData dto.ListUsersReq) (r err = us.DB.Select(&resp, listUsersQuery, args...) if err != nil { if err == sql.ErrNoRows { - logger.Errorf("no fields returned, err:%s", err.Error()) + logger.Errorf(ctx, "no fields returned, err:%s", err.Error()) err = nil return } @@ -325,11 +325,11 @@ LEFT JOIN WHERE ub.id = (SELECT MAX(id) FROM user_badges WHERE user_id = ub.user_id)) AS b ON u.id = b.user_id LIMIT 10; ` - logger.Info("afterTime: ", afterTime) + logger.Info(ctx, "afterTime: ", afterTime) rows, err := queryExecutor.Query(query, afterTime, afterTime, afterTime) if err != nil { - logger.Error("err: userStore ", err.Error()) + logger.Error(ctx, "err: userStore ", err.Error()) return []repository.ActiveUser{}, err } defer rows.Close() @@ -344,14 +344,14 @@ LIMIT 10; &user.BadgeName, &user.AppreciationPoints, ); err != nil { - logger.Error("err: userStore ", err.Error()) + logger.Error(ctx, "err: userStore ", err.Error()) return nil, err } activeUsers = append(activeUsers, user) } if err = rows.Err(); err != nil { - logger.Error("err: userStore ", err.Error()) + logger.Error(ctx, "err: userStore ", err.Error()) return []repository.ActiveUser{}, err } @@ -370,7 +370,7 @@ func (us *userStore) UpdateRewardQuota(ctx context.Context, tx repository.Transa _, err = queryExecutor.Exec(query) if err != nil { - logger.Error("err: userStore ", err.Error()) + logger.Error(ctx, "err: userStore ", err.Error()) return err } return @@ -402,11 +402,11 @@ func (us *userStore) GetUserById(ctx context.Context, reqData dto.GetUserByIdReq err = us.DB.Select(&userList, getUserById, reqData.QuaterTimeStamp, reqData.UserId) if err != nil { if err == sql.ErrNoRows { - logger.WithField("err", err.Error()).Error("No fields returned") + logger.Errorf(ctx, "no fields returned, err:%v", err) err = apperrors.InvalidId return } - logger.WithField("err", err.Error()).Error("Error in fetching users from database") + logger.Errorf(ctx, "error in fetching users from database, err: %v", err) err = apperrors.InternalServerError return } @@ -480,11 +480,11 @@ func (us *userStore) GetAdmin(ctx context.Context, email string) (user repositor ) if err != nil { if err == sql.ErrNoRows { - logger.Errorf("invalid user email, err:%s", err.Error()) + logger.Errorf(ctx, "invalid user email, err:%s", err.Error()) err = apperrors.InvalidEmail return } - logger.Errorf("error in get admin query, err: %s", err.Error()) + logger.Errorf(ctx, "error in get admin query, err: %s", err.Error()) err = apperrors.InternalServerError return } @@ -502,7 +502,7 @@ func (us *userStore) AddDeviceToken(ctx context.Context, userID int64, notificat Suffix("RETURNING id,user_id,notification_token"). ToSql() if err != nil { - logger.Errorf("error in generating squirrel query, err: %v", err) + logger.Errorf(ctx, "error in generating squirrel query, err: %v", err) return apperrors.InternalServerError } @@ -517,10 +517,10 @@ func (us *userStore) AddDeviceToken(ctx context.Context, userID int64, notificat err = us.DB.QueryRowx(insertQuery, args...).StructScan(&device) if err != nil { if err == sql.ErrNoRows { - logger.Error("device not found") + logger.Error(ctx, "device not found") return apperrors.InternalServerError } - logger.Errorf("failed to execute query: %v", err) + logger.Errorf(ctx, "failed to execute query: %v", err) return apperrors.InternalServerError } return nil From 069f6c84609ab820a3faa23d939b5dab3988d133 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Mon, 26 Aug 2024 10:33:02 +0530 Subject: [PATCH 10/22] [feature/UpdateLogs] logs added --- internal/api/appreciation.go | 1 - internal/api/organizationconfig.go | 30 ++-- internal/app/appreciation/mocks/Service.go | 45 ++++-- internal/app/appreciation/service.go | 22 +-- internal/app/appreciation/service_test.go | 11 +- internal/app/cronjob/cronJob.go | 6 +- internal/app/cronjob/monthlyUpdateData.go | 9 +- internal/app/cronjob/updateDailyData.go | 6 +- internal/app/email/service.go | 26 ++-- internal/app/notification/service.go | 23 +-- internal/app/organizationConfig/service.go | 24 +++- internal/app/reward/service.go | 23 +-- internal/app/reward/service_test.go | 14 +- internal/pkg/logger/log.go | 11 +- .../repository/postgresdb/appreciation.go | 48 ++++++- .../postgresdb/organizationConfig.go | 28 ++-- internal/repository/postgresdb/rewards.go | 39 ++--- logs/2024-08-23_18-52-42_peerly_backend.log | 134 ++++++++++++++++++ 18 files changed, 379 insertions(+), 121 deletions(-) create mode 100644 logs/2024-08-23_18-52-42_peerly_backend.log diff --git a/internal/api/appreciation.go b/internal/api/appreciation.go index 53d005d..95bf25d 100644 --- a/internal/api/appreciation.go +++ b/internal/api/appreciation.go @@ -11,7 +11,6 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/dto" log "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" - // logger "github.com/sirupsen/logrus" ) func createAppreciationHandler(appreciationSvc appreciation.Service) http.HandlerFunc { diff --git a/internal/api/organizationconfig.go b/internal/api/organizationconfig.go index 0c4eec4..73568a4 100644 --- a/internal/api/organizationconfig.go +++ b/internal/api/organizationconfig.go @@ -7,9 +7,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/organizationConfig" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - log "github.com/joshsoftware/peerly-backend/internal/pkg/logger" - - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) @@ -17,14 +15,14 @@ import ( func getOrganizationConfigHandler(orgSvc organizationConfig.Service) http.HandlerFunc { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - log.Debug(req.Context(),"getOrganizationConfigHandler: req: ",req) + logger.Debug(req.Context(),"getOrganizationConfigHandler: req: ",req) orgConfig, err := orgSvc.GetOrganizationConfig(req.Context()) if err != nil { - logger.Errorf("Error while fetching organization: %v",err) + logger.Errorf(req.Context(),"Error while fetching organization: %v",err) dto.ErrorRepsonse(rw, err) return } - log.Debug(req.Context(),"getOrganizationConfigHandler: resp: ",orgConfig) + logger.Debug(req.Context(),"getOrganizationConfigHandler: resp: ",orgConfig) dto.SuccessRepsonse(rw, http.StatusOK, "organization config fetched successfully",orgConfig) }) } @@ -33,29 +31,29 @@ func getOrganizationConfigHandler(orgSvc organizationConfig.Service) http.Handle func createOrganizationConfigHandler(orgSvc organizationConfig.Service) http.HandlerFunc { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - log.Debug(req.Context(),"createOrganizationConfigHandler: req: ",req) + logger.Debug(req.Context(),"createOrganizationConfigHandler: req: ",req) var orgConfig dto.OrganizationConfig err := json.NewDecoder(req.Body).Decode(&orgConfig) if err != nil { - logger.Errorf("Error while decoding organization config data: %v",err) + logger.Errorf(req.Context(),"Error while decoding organization config data: %v",err) dto.ErrorRepsonse(rw, apperrors.JSONParsingErrorReq) return } err = orgConfig.OrgValidate() if err != nil { - logger.Errorf("Error in validating request : %v",err) + logger.Errorf(req.Context(),"Error in validating request : %v",err) dto.ErrorRepsonse(rw, err) return } createdOrganizationConfig, err := orgSvc.CreateOrganizationConfig(req.Context(), orgConfig) if err != nil { - logger.Errorf("Error in creating organization config: %v",err) + logger.Errorf(req.Context(),"Error in creating organization config: %v",err) dto.ErrorRepsonse(rw, err) return } - log.Debug(req.Context(),"createOrganizationConfigHandler: resp: ",createdOrganizationConfig) + logger.Debug(req.Context(),"createOrganizationConfigHandler: resp: ",createdOrganizationConfig) dto.SuccessRepsonse(rw, http.StatusCreated, "Organization Config Created Successfully" ,createdOrganizationConfig) }) } @@ -66,28 +64,28 @@ func updateOrganizationConfigHandler(orgSvc organizationConfig.Service) http.Han var organizationConfig dto.OrganizationConfig err := json.NewDecoder(req.Body).Decode(&organizationConfig) if err != nil { - logger.Errorf("Error while decoding organization data: %v",err) + logger.Errorf(req.Context(),"Error while decoding organization data: %v",err) dto.ErrorRepsonse(rw, apperrors.JSONParsingErrorReq) return } - log.Debug(req.Context(),"updateOrganizationConfigHandler: request: ",req) + logger.Debug(req.Context(),"updateOrganizationConfigHandler: request: ",req) organizationConfig.ID = 1 err = organizationConfig.OrgUpdateValidate() if err != nil { - logger.Errorf("Error in validating request : %v",err) + logger.Errorf(req.Context(),"Error in validating request : %v",err) dto.ErrorRepsonse(rw, err) return } updatedOrganization, err := orgSvc.UpdateOrganizationConfig(req.Context(), organizationConfig) if err != nil { - logger.Errorf("Error while updating organization: %v",err) + logger.Errorf(req.Context(),"Error while updating organization: %v",err) dto.ErrorRepsonse(rw, err) return } - log.Debug(req.Context(),"updateOrganizationConfigHandler: resp: ",updatedOrganization) + logger.Debug(req.Context(),"updateOrganizationConfigHandler: resp: ",updatedOrganization) dto.SuccessRepsonse(rw, http.StatusOK, "Organization Config Updated Successfully" ,updatedOrganization) }) diff --git a/internal/app/appreciation/mocks/Service.go b/internal/app/appreciation/mocks/Service.go index b7daca4..1478f8d 100644 --- a/internal/app/appreciation/mocks/Service.go +++ b/internal/app/appreciation/mocks/Service.go @@ -7,6 +7,8 @@ import ( dto "github.com/joshsoftware/peerly-backend/internal/pkg/dto" mock "github.com/stretchr/testify/mock" + + repository "github.com/joshsoftware/peerly-backend/internal/repository" ) // Service is an autogenerated mock type for the Service type @@ -116,22 +118,47 @@ func (_m *Service) ListAppreciations(ctx context.Context, filter dto.Appreciatio return r0, r1 } -// sendAppreciationEmail provides a mock function with given fields: to, sub, maildata -func (_m *Service) sendAppreciationEmail(to string, sub string, maildata string) error { - ret := _m.Called(to, sub, maildata) +// UpdateAppreciation provides a mock function with given fields: ctx +func (_m *Service) UpdateAppreciation(ctx context.Context) (bool, error) { + ret := _m.Called(ctx) if len(ret) == 0 { - panic("no return value specified for sendAppreciationEmail") + panic("no return value specified for UpdateAppreciation") } - var r0 error - if rf, ok := ret.Get(0).(func(string, string, string) error); ok { - r0 = rf(to, sub, maildata) + var r0 bool + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (bool, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) bool); ok { + r0 = rf(ctx) } else { - r0 = ret.Error(0) + r0 = ret.Get(0).(bool) } - return r0 + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// sendAppreciationNotificationToAll provides a mock function with given fields: ctx, appr +func (_m *Service) sendAppreciationNotificationToAll(ctx context.Context, appr repository.AppreciationResponse) { + _m.Called(ctx, appr) +} + +// sendAppreciationNotificationToReceiver provides a mock function with given fields: ctx, appr +func (_m *Service) sendAppreciationNotificationToReceiver(ctx context.Context, appr repository.AppreciationResponse) { + _m.Called(ctx, appr) +} + +// sendEmailForBadgeAllocation provides a mock function with given fields: userBadgeDetails +func (_m *Service) sendEmailForBadgeAllocation(userBadgeDetails []repository.UserBadgeDetails) { + _m.Called(userBadgeDetails) } // NewService creates a new instance of Service. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. diff --git a/internal/app/appreciation/service.go b/internal/app/appreciation/service.go index 864a323..de043aa 100644 --- a/internal/app/appreciation/service.go +++ b/internal/app/appreciation/service.go @@ -10,11 +10,9 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - log "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" "github.com/joshsoftware/peerly-backend/internal/repository" - // logger "github.com/sirupsen/logrus" logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) @@ -46,7 +44,7 @@ func NewService(appreciationRepo repository.AppreciationStorer, coreValuesRepo r func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto.Appreciation) (dto.Appreciation, error) { - log.Debug(ctx,"svc: CreateAppreciation: appreciation: ",appreciation) + logger.Debug(ctx,"svc: CreateAppreciation: appreciation: ",appreciation) //add quarter appreciation.Quarter = utils.GetQuarter() @@ -58,10 +56,10 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto return dto.Appreciation{}, apperrors.InternalServer } - log.Debug(ctx,"sender: ",sender) + logger.Debug(ctx,"sender: ",sender) //check is receiver present in database chk, err := apprSvc.appreciationRepo.IsUserPresent(ctx, nil, appreciation.Receiver) - log.Debug(ctx,"chk: ",chk," err: ",err) + logger.Debug(ctx,"chk: ",chk," err: ",err) if err != nil { logger.Errorf(ctx,"err: %v", err) return dto.Appreciation{}, err @@ -144,18 +142,21 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto func (apprSvc *service) GetAppreciationById(ctx context.Context, appreciationId int32) (dto.AppreciationResponse, error) { + logger.Debug(ctx,"appreciationId: ",appreciationId) resAppr, err := apprSvc.appreciationRepo.GetAppreciationById(ctx, nil, appreciationId) + logger.Debug(ctx,"apprSvc: resAppr: ",resAppr," err: ",err) if err != nil { logger.Errorf(ctx,"err: %v", err) return dto.AppreciationResponse{}, err } - return mapRepoGetAppreciationInfoToDTOGetAppreciationInfo(resAppr), nil } func (apprSvc *service) ListAppreciations(ctx context.Context, filter dto.AppreciationFilter) (dto.ListAppreciationsResponse, error) { + logger.Debug(ctx," filter: ",filter) infos, pagination, err := apprSvc.appreciationRepo.ListAppreciations(ctx, nil, filter) + logger.Debug(ctx," infos: ",infos," pagination: ",pagination," err: ",err) if err != nil { logger.Errorf(ctx,"err: %v", err) return dto.ListAppreciationsResponse{}, err @@ -166,10 +167,12 @@ func (apprSvc *service) ListAppreciations(ctx context.Context, filter dto.Apprec responses = append(responses, mapRepoGetAppreciationInfoToDTOGetAppreciationInfo(info)) } paginationResp := dtoPagination(pagination) + logger.Debug(ctx," apprSvc: ",responses," paginationResp: ",paginationResp) return dto.ListAppreciationsResponse{Appreciations: responses, MetaData: paginationResp}, nil } func (apprSvc *service) DeleteAppreciation(ctx context.Context, apprId int32) error { + logger.Debug(ctx,"apprSvc: apprId: ",apprId) return apprSvc.appreciationRepo.DeleteAppreciation(ctx, nil, apprId) } @@ -211,7 +214,7 @@ func (apprSvc *service) UpdateAppreciation(ctx context.Context) (bool, error) { logger.Error(ctx,"err: ", err.Error()) return false, err } - + logger.Debug(ctx,"apprSvc: UpdateAppreciation: ",userBadgeDetails) apprSvc.sendEmailForBadgeAllocation(userBadgeDetails) return true, nil } @@ -250,12 +253,14 @@ func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail func (apprSvc *service) sendAppreciationNotificationToReceiver(ctx context.Context, appr repository.AppreciationResponse) { + logger.Debug(ctx,"apprSvc: apprResponse: ",appr) notificationTokens, err := apprSvc.userRepo.ListDeviceTokensByUserID(ctx, appr.ReceiverID) if err != nil { logger.Errorf(ctx,"err in getting device tokens: %v", err) return } + logger.Debug(ctx,"apprSvc: notificationTokens: ",notificationTokens) msg := notification.Message{ Title: "Received Appreciation", Body: fmt.Sprintf("You've been appreciated by %s %s! Well done and keep up the JOSH!", appr.SenderFirstName, appr.SenderLastName), @@ -269,6 +274,7 @@ func (apprSvc *service) sendAppreciationNotificationToReceiver(ctx context.Conte func (apprSvc *service) sendAppreciationNotificationToAll(ctx context.Context, appr repository.AppreciationResponse) { + logger.Debug(ctx," apprSvc: appr: ",appr) msg := notification.Message{ Title: "Appreciation", Body: fmt.Sprintf(" %s %s appreciated %s %s", appr.SenderFirstName, appr.SenderLastName, appr.ReceiverFirstName, appr.ReceiverLastName), @@ -278,7 +284,7 @@ func (apprSvc *service) sendAppreciationNotificationToAll(ctx context.Context, a func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repository.UserBadgeDetails) { - logger.Info(context.Background(),"user Badge Details:---------------->\n ", userBadgeDetails) + logger.Debug(context.Background(),"user Badge Details:---------------->\n ", userBadgeDetails) for _, userBadgeDetail := range userBadgeDetails { // Determine the BadgeImageUrl based on the BadgeName diff --git a/internal/app/appreciation/service_test.go b/internal/app/appreciation/service_test.go index 5a3a28a..df892d4 100644 --- a/internal/app/appreciation/service_test.go +++ b/internal/app/appreciation/service_test.go @@ -18,7 +18,8 @@ import ( func TestCreateAppreciation(t *testing.T) { appreciationRepo := mocks.NewAppreciationStorer(t) corevalueRepo := mocks.NewCoreValueStorer(t) - service := NewService(appreciationRepo, corevalueRepo) + userRepo := mocks.NewUserStorer(t) + service := NewService(appreciationRepo, corevalueRepo,userRepo) tests := []struct { name string @@ -110,7 +111,9 @@ func TestCreateAppreciation(t *testing.T) { func TestGetAppreciationById(t *testing.T) { appreciationRepo := mocks.NewAppreciationStorer(t) - service := NewService(appreciationRepo, nil) + coreValueRepo := mocks.NewCoreValueStorer(t) + userRepo := mocks.NewUserStorer(t) + service := NewService(appreciationRepo, coreValueRepo,userRepo) tests := []struct { name string @@ -210,7 +213,9 @@ func TestGetAppreciationById(t *testing.T) { func TestValidateAppreciation(t *testing.T) { appreciationRepo := mocks.NewAppreciationStorer(t) - service := NewService(appreciationRepo, nil) + coreValueRepo := mocks.NewCoreValueStorer(t) + userRepo := mocks.NewUserStorer(t) + service := NewService(appreciationRepo, coreValueRepo,userRepo) tests := []struct { name string diff --git a/internal/app/cronjob/cronJob.go b/internal/app/cronjob/cronJob.go index 139dd43..f142145 100644 --- a/internal/app/cronjob/cronJob.go +++ b/internal/app/cronjob/cronJob.go @@ -5,7 +5,7 @@ import ( "time" "github.com/go-co-op/gocron/v2" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) type Job interface { // Schedules the cron job @@ -29,9 +29,9 @@ func (cron *CronJob) Execute(task func(context.Context)) { ctx := context.Background() startTime := time.Now() - logger.Info("cron job Started at %s", startTime.Format("2006-01-02 15:04:05")) + logger.Infof(ctx,"cron job Started at %s", startTime.Format("2006-01-02 15:04:05")) defer func() { - logger.Info("cron job done %s, took: %v", cron.name, time.Since(startTime)) + logger.Infof(ctx,"cron job done %s, took: %v", cron.name, time.Since(startTime)) }() // Channel to check if signal task is completed diff --git a/internal/app/cronjob/monthlyUpdateData.go b/internal/app/cronjob/monthlyUpdateData.go index 78a7736..0ea1a98 100644 --- a/internal/app/cronjob/monthlyUpdateData.go +++ b/internal/app/cronjob/monthlyUpdateData.go @@ -7,7 +7,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/notification" user "github.com/joshsoftware/peerly-backend/internal/app/users" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) const MONTHLY_JOB = "MONTHLY_JOB" @@ -50,15 +50,16 @@ func (cron *MonthlyJob) Schedule() { ) cron.scheduler.Start() if err != nil { - logger.Warn(context.TODO(), "error occurred while scheduling %s, message %+v", cron.name, err.Error()) + logger.Infof(context.TODO(), "error occurred while scheduling %s, message %+v", cron.name, err.Error()) } } func (cron *MonthlyJob) Task(ctx context.Context) { logger.Info(ctx, "in monthly job task") for i := 0; i < 3; i++ { - logger.Info("cron job attempt:", i+1) + logger.Info(ctx,"cron job attempt:", i+1) err := cron.userService.UpdateRewardQuota(ctx) + logger.Error(ctx,"err: ",err) if err == nil { sendRewardQuotaRefilledNotificationToAll() break @@ -72,6 +73,8 @@ func sendRewardQuotaRefilledNotificationToAll() { Title: "Reward Quota is Refilled", Body: "Your reward quota is reset! You now recognize your colleagues.", } + + logger.Debug(context.Background(),"msg:",msg) msg.SendNotificationToTopic("peerly") } diff --git a/internal/app/cronjob/updateDailyData.go b/internal/app/cronjob/updateDailyData.go index 8599d0a..31b6ed6 100644 --- a/internal/app/cronjob/updateDailyData.go +++ b/internal/app/cronjob/updateDailyData.go @@ -5,7 +5,7 @@ import ( "github.com/go-co-op/gocron/v2" apprSvc "github.com/joshsoftware/peerly-backend/internal/app/appreciation" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) @@ -62,8 +62,10 @@ func (cron *DailyJob) Schedule() { func (cron *DailyJob) Task(ctx context.Context) { logger.Info(ctx, "in daily job task") for i:=0;i<3;i++{ - logger.Info("cron job attempt:",i+1) + logger.Info(ctx,"cron job attempt:",i+1) isSuccess,err := cron.appreciationService.UpdateAppreciation(ctx) + + logger.Info(ctx," isSuccess: ",isSuccess," err: ",err) if err==nil && isSuccess{ break } diff --git a/internal/app/email/service.go b/internal/app/email/service.go index e468d99..dc0af8c 100644 --- a/internal/app/email/service.go +++ b/internal/app/email/service.go @@ -2,13 +2,14 @@ package email import ( "bytes" + "context" "fmt" "html/template" "github.com/joshsoftware/peerly-backend/internal/pkg/config" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" - logger "github.com/sirupsen/logrus" ) // MailService represents the interface for our mail service. @@ -29,18 +30,19 @@ type Mail struct { func (ms *Mail) Send(plainTextContent string) error { + logger.Info(context.Background()," Mail: ",ms) senderEmail := config.ReadEnvString("SENDER_EMAIL") if senderEmail == "" { - logger.Error("SENDER_EMAIL environment variable is not set") + logger.Error(context.Background(),"SENDER_EMAIL environment variable is not set") return fmt.Errorf("sender email not configured") } sendGridAPIKey := config.ReadEnvString("SENDGRID_API_KEY") if sendGridAPIKey == "" { - logger.Error("SENDGRID_API_KEY environment variable is not set") + logger.Error(context.Background(),"SENDGRID_API_KEY environment variable is not set") return fmt.Errorf("sendgrid API key not configured") } - logger.Info("from_------------->, ",senderEmail) + logger.Info(context.Background(),"from_------------->, ",senderEmail) fromEmail := mail.NewEmail("Peerly", senderEmail) content := mail.NewContent("text/html", ms.body) @@ -74,14 +76,14 @@ func (ms *Mail) Send(plainTextContent string) error { response, err := client.Send(m) if err != nil { - logger.Error("unable to send mail", "error", err) + logger.Error(context.Background(),"unable to send mail", "error", err) return err } - logger.Info("Email request sent successfully!") - logger.Infof("Response status code: %v", response.StatusCode) - logger.Infof("Response body: %v", response.Body) - logger.Infof("Response headers: %v", response.Headers) + logger.Info(context.Background(),"Email response: ") + logger.Infof(context.Background(),"Response status code: %v", response.StatusCode) + logger.Infof(context.Background(),"Response body: %v", response.Body) + logger.Infof(context.Background(),"Response headers: %v", response.Headers) return nil } func (r *Mail) ParseTemplate(templateFileName string, data interface{}) error { @@ -94,9 +96,9 @@ func (r *Mail) ParseTemplate(templateFileName string, data interface{}) error { return err } r.body = buf.String() - logger.Info("--------------------->") - logger.Info(r.body) - logger.Info("--------------------->") + logger.Info(context.Background(),"--------------------->") + logger.Info(context.Background(),r.body) + logger.Info(context.Background(),"--------------------->") return nil } diff --git a/internal/app/notification/service.go b/internal/app/notification/service.go index 8d75634..7487e8d 100644 --- a/internal/app/notification/service.go +++ b/internal/app/notification/service.go @@ -6,7 +6,7 @@ import ( firebase "firebase.google.com/go" "firebase.google.com/go/messaging" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "google.golang.org/api/option" ) @@ -31,7 +31,7 @@ func (notificationSvc *Message) SendNotificationToNotificationToken(notification opt := option.WithCredentialsFile(serviceAccountKey) app, err := firebase.NewApp(context.Background(), nil, opt) if err != nil { - logger.Errorf("Error initializing app: %v", err) + logger.Errorf(context.Background(),"Error initializing app: %v", err) err = apperrors.InternalServerError return } @@ -39,10 +39,12 @@ func (notificationSvc *Message) SendNotificationToNotificationToken(notification // Obtain a messaging client from the Firebase app client, err := app.Messaging(context.Background()) if err != nil { - logger.Errorf("Error getting Messaging client: %v", err) + logger.Errorf(context.Background(),"Error getting Messaging client: %v", err) err = apperrors.InternalServerError return } + + logger.Debug(context.Background()," notificationSvc: ",notificationSvc) // Create a message to send message := &messaging.Message{ Notification: &messaging.Notification{ @@ -54,12 +56,14 @@ func (notificationSvc *Message) SendNotificationToNotificationToken(notification // Send the message response, err := client.Send(context.Background(), message) + logger.Debug(context.Background()," response: ",response) + logger.Debug(context.Background()," err: ",err) if err != nil { - logger.Errorf("Error sending message: %v", err) + logger.Errorf(context.Background(),"Error sending message: %v", err) err = apperrors.InternalServerError return } - logger.Infof("Successfully sent message: %v", response) + logger.Infof(context.Background(),"Successfully sent message: %v", response) return } @@ -72,7 +76,7 @@ func (notificationSvc *Message) SendNotificationToTopic(topic string) (err error opt := option.WithCredentialsFile(serviceAccountKey) app, err := firebase.NewApp(context.Background(), nil, opt) if err != nil { - logger.Errorf("error initializing app: %v", err) + logger.Errorf(context.Background(),"error initializing app: %v", err) err = apperrors.InternalServerError return } @@ -80,11 +84,12 @@ func (notificationSvc *Message) SendNotificationToTopic(topic string) (err error // Obtain a messaging client from the Firebase app client, err := app.Messaging(context.Background()) if err != nil { - logger.Errorf("error getting Messaging client: %v", err) + logger.Errorf(context.Background(),"error getting Messaging client: %v", err) err = apperrors.InternalServerError return } + logger.Debug(context.Background()," notificationSvc: ",notificationSvc) // Create a message to send message := &messaging.Message{ Notification: &messaging.Notification{ @@ -97,12 +102,12 @@ func (notificationSvc *Message) SendNotificationToTopic(topic string) (err error // Send the message response, err := client.Send(context.Background(), message) if err != nil { - logger.Errorf("error sending message: %v", err) + logger.Errorf(context.Background(),"error sending message: %v", err) err = apperrors.InternalServerError return } - logger.Infof("Successfully sent message: %v", response) + logger.Infof(context.Background(),"Successfully sent message: %v", response) return } diff --git a/internal/app/organizationConfig/service.go b/internal/app/organizationConfig/service.go index 3afdbe3..b346531 100644 --- a/internal/app/organizationConfig/service.go +++ b/internal/app/organizationConfig/service.go @@ -7,7 +7,8 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/dto" "github.com/joshsoftware/peerly-backend/internal/repository" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" + ) type service struct { @@ -29,9 +30,11 @@ func NewService(organizationConfigRepo repository.OrganizationConfigStorer) Serv func (orgSvc *service) GetOrganizationConfig(ctx context.Context) (dto.OrganizationConfig, error) { + logger.Debug(ctx," orgSvc: GetOrganizationConfig") organization, err := orgSvc.OrganizationConfigRepo.GetOrganizationConfig(ctx,nil) + logger.Debug(context.Background()," orgSvc: GetOrganizationConfig: organization: ",organization," err: ",err) if err != nil { - logger.Errorf("err: %v",err) + logger.Errorf(context.Background(),"err: %v",err) return dto.OrganizationConfig{}, err } org := organizationConfigToDTO(organization) @@ -42,15 +45,17 @@ func (orgSvc *service) GetOrganizationConfig(ctx context.Context) (dto.Organizat func (orgSvc *service) CreateOrganizationConfig(ctx context.Context, organizationConfig dto.OrganizationConfig) (dto.OrganizationConfig, error) { + logger.Debug(ctx," orgSvc: CreateOrganizationConfig: organizationConfig: ",organizationConfig) data := ctx.Value(constants.UserId) userID, ok := data.(int64) if !ok { - logger.Error("err in parsing userid from token") + logger.Error(context.Background(),"err in parsing userid from token") return dto.OrganizationConfig{},apperrors.InternalServer } organizationConfig.CreatedBy = userID organizationConfig.UpdatedBy = userID + logger.Debug(ctx," organizationConfig: ",organizationConfig) _ ,err := orgSvc.OrganizationConfigRepo.GetOrganizationConfig(ctx,nil); if err != apperrors.OrganizationConfigNotFound { return dto.OrganizationConfig{},apperrors.OrganizationConfigAlreadyPresent @@ -58,35 +63,40 @@ func (orgSvc *service) CreateOrganizationConfig(ctx context.Context, organizatio createdOrganizationConfig, err := orgSvc.OrganizationConfigRepo.CreateOrganizationConfig(ctx,nil, organizationConfig) if err != nil { - logger.Errorf("err: %v",err) + logger.Errorf(context.Background(),"err: %v",err) return dto.OrganizationConfig{}, err } + logger.Debug(ctx," createdOrganizationConfig: ",createdOrganizationConfig) org := organizationConfigToDTO(createdOrganizationConfig) return org, nil } func (orgSvc *service) UpdateOrganizationConfig(ctx context.Context, organizationConfig dto.OrganizationConfig) (dto.OrganizationConfig, error) { + logger.Debug(ctx," orgSvc: UpdateOrganizationConfig: organizationConfig: ",organizationConfig) data := ctx.Value(constants.UserId) userID, ok := data.(int64) if !ok { - logger.Error("err in parsing userid from token") + logger.Error(ctx,"err in parsing userid from token") return dto.OrganizationConfig{},apperrors.InternalServer } organizationConfig.UpdatedBy = userID _ ,err := orgSvc.OrganizationConfigRepo.GetOrganizationConfig(ctx,nil); if err != nil { - logger.Errorf("err: %v",err) + logger.Errorf(ctx,"err: %v",err) return dto.OrganizationConfig{},err } + logger.Debug(ctx," orgSvc: UpdateOrganizationConfig: organizationConfig: ",organizationConfig) updatedOrganization, err := orgSvc.OrganizationConfigRepo.UpdateOrganizationConfig(ctx,nil, organizationConfig) if err != nil { - logger.Errorf("err: %v",err) + logger.Errorf(ctx,"err: %v",err) return dto.OrganizationConfig{}, err } + org := organizationConfigToDTO(updatedOrganization) + logger.Debug(ctx," org: ",org) return org, nil } diff --git a/internal/app/reward/service.go b/internal/app/reward/service.go index 9d76c34..83748ff 100644 --- a/internal/app/reward/service.go +++ b/internal/app/reward/service.go @@ -9,7 +9,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) type service struct { @@ -32,16 +32,18 @@ func NewService(rewardRepo repository.RewardStorer, appreciationRepo repository. func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (dto.Reward, error) { + logger.Debug(ctx," rwrdSvc: GiveReward: ",rewardReq) //add sender data := ctx.Value(constants.UserId) sender, ok := data.(int64) if !ok { - logger.Error("err in parsing userid from token") + logger.Error(ctx,"err in parsing userid from token") return dto.Reward{}, apperrors.InternalServer } rewardReq.SenderId = sender appr, err := rwrdSvc.appreciationRepo.GetAppreciationById(ctx, nil, int32(rewardReq.AppreciationId)) + logger.Debug(ctx," appr: ",appr) if err != nil { return dto.Reward{}, err } @@ -55,6 +57,7 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d } userChk, err := rwrdSvc.rewardRepo.UserHasRewardQuota(ctx, nil, rewardReq.SenderId, rewardReq.Point) + logger.Debug(ctx," userChk: ",userChk," err: ",err) if err != nil { return dto.Reward{}, err } @@ -64,6 +67,7 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d } rwrdChk, err := rwrdSvc.rewardRepo.IsUserRewardForAppreciationPresent(ctx, nil, rewardReq.AppreciationId, rewardReq.SenderId) + logger.Debug(ctx," rwrdChk: ",rwrdChk," err: ",err) if err != nil { return dto.Reward{}, err } @@ -125,22 +129,21 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d } userInfo ,err := rwrdSvc.userRepo.GetUserById(ctx,req) if err != nil { - logger.Errorf("err in getting user data: %v",err) + logger.Errorf(ctx,"err in getting user data: %v",err) } rwrdSvc.sendRewardNotificationToSender(ctx,userInfo) rwrdSvc.sendRewardNotificationToReceiver(ctx,appr.ReceiverID) return reward, nil } -func GetQuarterStartUnixTime() { - panic("unimplemented") -} func (rwrdSvc *service) sendRewardNotificationToSender(ctx context.Context, user dto.GetUserByIdResp) { + logger.Debug(ctx," rwrdSvc: sendRewardNotificationToSender: user: ",user) notificationTokens, err := rwrdSvc.userRepo.ListDeviceTokensByUserID(ctx, user.UserId) + logger.Debug(ctx," notificationTokens: ",notificationTokens) if err != nil { - logger.Errorf("err in getting device tokens: %v", err) + logger.Errorf(ctx,"err in gettinsendRewardNotificationToSenderg device tokens: %v", err) return } @@ -149,6 +152,7 @@ func (rwrdSvc *service) sendRewardNotificationToSender(ctx context.Context, user Body: "You have successfully given a reward! ", } + logger.Debug(ctx," msg: ",msg) for _, notificationToken := range notificationTokens { msg.SendNotificationToNotificationToken(notificationToken) } @@ -157,9 +161,11 @@ func (rwrdSvc *service) sendRewardNotificationToSender(ctx context.Context, user func (rwrdSvc *service) sendRewardNotificationToReceiver(ctx context.Context, userID int64) { + logger.Debug(ctx," rwrdSvc: sendRewardNotificationToReceiver") notificationTokens, err := rwrdSvc.userRepo.ListDeviceTokensByUserID(ctx, userID) + logger.Debug(ctx," notificationTokens: ",notificationTokens) if err != nil { - logger.Errorf("err in getting device tokens: %v", err) + logger.Errorf(ctx," err in getting device tokens: %v", err) return } @@ -168,6 +174,7 @@ func (rwrdSvc *service) sendRewardNotificationToReceiver(ctx context.Context, us Body: "You've been awarded a reward! Well done and keep up the JOSH!", } + logger.Debug(ctx," rwrdSvc: msg: ",msg) for _, notificationToken := range notificationTokens { msg.SendNotificationToNotificationToken(notificationToken) } diff --git a/internal/app/reward/service_test.go b/internal/app/reward/service_test.go index b6ec824..5540cb8 100644 --- a/internal/app/reward/service_test.go +++ b/internal/app/reward/service_test.go @@ -34,7 +34,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(false, nil) rwrdMock.On("BeginTx", mock.Anything).Return(nil, nil) @@ -66,7 +66,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 1, ReceiverId: 2}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 1, ReceiverID: 2}, nil) }, isErrorExpected: true, expectedResult: dto.Reward{}, @@ -80,7 +80,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 1}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 1}, nil) }, isErrorExpected: true, expectedResult: dto.Reward{}, @@ -94,7 +94,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(false, nil) }, isErrorExpected: true, @@ -109,7 +109,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(true, nil) }, @@ -125,7 +125,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(false, nil) rwrdMock.On("BeginTx", mock.Anything).Return(nil, apperrors.InternalServer) @@ -142,7 +142,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(false, nil) rwrdMock.On("BeginTx", mock.Anything).Return(nil, nil) diff --git a/internal/pkg/logger/log.go b/internal/pkg/logger/log.go index 49a7a95..69a55a8 100644 --- a/internal/pkg/logger/log.go +++ b/internal/pkg/logger/log.go @@ -66,7 +66,16 @@ func Info(ctx context.Context, args ...interface{}) { Logger.Info("req_id: ", requestID, args) } -// Info - prints out basic information +// Infof - prints out basic information +func Infof(ctx context.Context, format string, args ...interface{}) { + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "" + } + Logger.Infof("req_id: [%s] "+format, append([]interface{}{requestID}, args...)...) +} + +// Debug - prints out debug information func Debug(ctx context.Context, args ...interface{}) { requestID, ok := ctx.Value(constants.RequestID).(string) if !ok { diff --git a/internal/repository/postgresdb/appreciation.go b/internal/repository/postgresdb/appreciation.go index 5f73ff8..a4121c6 100644 --- a/internal/repository/postgresdb/appreciation.go +++ b/internal/repository/postgresdb/appreciation.go @@ -38,6 +38,7 @@ func NewAppreciationRepo(db *sqlx.DB) repository.AppreciationStorer { func (appr *appreciationsStore) CreateAppreciation(ctx context.Context, tx repository.Transaction, appreciation dto.Appreciation) (repository.Appreciation, error) { + logger.Debug(ctx," appr: CreateAppreciation: appreciation: ",appreciation) queryExecutor := appr.InitiateQueryExecutor(tx) insertQuery, args, err := repository.Sq. @@ -50,6 +51,8 @@ func (appr *appreciationsStore) CreateAppreciation(ctx context.Context, tx repos return repository.Appreciation{}, apperrors.InternalServerError } + logger.Debug(ctx," insertQuery: ",insertQuery) + logger.Debug(ctx," args: ",args) var resAppr repository.Appreciation err = queryExecutor.QueryRowx(insertQuery, args...).StructScan(&resAppr) if err != nil { @@ -62,6 +65,7 @@ func (appr *appreciationsStore) CreateAppreciation(ctx context.Context, tx repos func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repository.Transaction, apprId int32) (repository.AppreciationResponse, error) { + logger.Debug(ctx," appr: GetAppreciationById: apprId: ",apprId) queryExecutor := appr.InitiateQueryExecutor(tx) // Get logged-in user ID @@ -116,6 +120,8 @@ func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repo return repository.AppreciationResponse{}, apperrors.InternalServer } + logger.Debug(ctx," appr: query: ",query) + logger.Debug(ctx," appr: args: ",args) var resAppr repository.AppreciationResponse // Execute the query @@ -128,10 +134,12 @@ func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repo logger.Errorf(ctx,"failed to execute query: %v", err) return repository.AppreciationResponse{}, apperrors.InternalServer } + logger.Debug(ctx," resAppr: ",resAppr) return resAppr, nil } func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx repository.Transaction, filter dto.AppreciationFilter) ([]repository.AppreciationResponse, repository.Pagination, error) { + logger.Debug(ctx," appr: ListAppreciations: filter: ",filter) queryExecutor := appr.InitiateQueryExecutor(tx) // Get logged-in user ID @@ -172,6 +180,9 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi return []repository.AppreciationResponse{}, repository.Pagination{}, apperrors.InternalServerError } + logger.Debug(ctx,"countSql: ",countSql) + logger.Debug(ctx,"countArgs: ",countArgs) + var totalRecords int32 err = queryExecutor.QueryRowx(countSql, countArgs...).Scan(&totalRecords) if err != nil { @@ -180,6 +191,7 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi } pagination := getPaginationMetaData(filter.Page, filter.Limit, totalRecords) + logger.Debug(ctx," pagination: ",pagination) queryBuilder = queryBuilder.RemoveColumns() queryBuilder = queryBuilder.Columns( "a.id", @@ -222,7 +234,7 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi } offset := (filter.Page - 1) * filter.Limit - + logger.Debug(ctx," offset: ",offset) // Add pagination queryBuilder = queryBuilder.Limit(uint64(filter.Limit)).Offset(uint64(offset)) sql, args, err := queryBuilder.ToSql() @@ -231,6 +243,8 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi return nil, repository.Pagination{}, apperrors.InternalServerError } + logger.Debug(ctx," sqlQuery: ",sql) + logger.Debug(ctx," args: ",args) queryExecutor = appr.InitiateQueryExecutor(tx) res := make([]repository.AppreciationResponse, 0) @@ -244,13 +258,14 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi return nil, repository.Pagination{}, apperrors.InternalServerError } id := ctx.Value(constants.UserId) - fmt.Println("id -> ", id) + logger.Debug(ctx," id -> ", id) userId, ok := ctx.Value(constants.UserId).(int64) if !ok { logger.Error(ctx,"unable to convert context user id to int64") return nil, repository.Pagination{}, apperrors.InternalServerError } + logger.Debug(ctx," userId: ",userId) for idx, appreciation := range res { var userIds []int64 queryBuilder = repository.Sq.Select("reported_by").From("resolutions").Where(squirrel.Eq{"appreciation_id": appreciation.ID}) @@ -259,6 +274,9 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi logger.Errorf(ctx,"error in generating squirrel query, err: %s", err.Error()) return nil, repository.Pagination{}, apperrors.InternalServerError } + + logger.Debug(ctx," query: ",query) + logger.Debug(ctx," args: ",args) err = appr.DB.SelectContext(ctx, &userIds, query, args...) if err != nil { logger.Errorf(ctx,"error in reported flag query, err: %s", err.Error()) @@ -267,10 +285,14 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi res[idx].ReportedFlag = slices.Contains(userIds, userId) } + logger.Debug(ctx," res: ",res) + logger.Debug(ctx," pagination: ",pagination) return res, pagination, nil } func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repository.Transaction, apprId int32) error { + logger.Debug(ctx," appr: ",appr) + logger.Debug(ctx," apprId: ",apprId) query, args, err := repository.Sq.Update(appr.AppreciationsTable). Set("is_valid", false). Where(squirrel.And{ @@ -279,6 +301,8 @@ func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repos }). ToSql() + logger.Debug(ctx," query: ",query) + logger.Debug(ctx," args: ",args) if err != nil { logger.Error(ctx,"Error building SQL: ", err.Error()) return apperrors.InternalServer @@ -308,12 +332,14 @@ func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repos func (appr *appreciationsStore) IsUserPresent(ctx context.Context, tx repository.Transaction, userID int64) (bool, error) { + logger.Debug(ctx," appr: IsUserPresent: userID: ",userID) // Build the SQL query query, args, err := repository.Sq.Select("COUNT(*)"). From(appr.UsersTable). Where(squirrel.Eq{"id": userID}). ToSql() + logger.Debug(ctx," query: ",query) if err != nil { logger.Error(ctx,"err ", err.Error()) return false, apperrors.InternalServer @@ -329,13 +355,14 @@ func (appr *appreciationsStore) IsUserPresent(ctx context.Context, tx repository return false, apperrors.InternalServer } + logger.Debug(ctx," count: ",count) // Check if user is present return count > 0, nil } func (appr *appreciationsStore) UpdateAppreciationTotalRewardsOfYesterday(ctx context.Context, tx repository.Transaction) (bool, error) { - fmt.Println("UpdateAppreciationTotalRewardsOfYesterday") - + logger.Debug(ctx,"appr: UpdateAppreciationTotalRewardsOfYesterday") + logger.Info(ctx,"appr: UpdateAppreciationTotalRewardsOfYesterday") // Initialize query executor queryExecutor := appr.InitiateQueryExecutor(tx) @@ -357,20 +384,29 @@ FROM ( WHERE app.id = agg.appreciation_id; ` + logger.Debug(ctx," query: ",query) // Execute the query using the query executor - _, err := queryExecutor.Exec(query) + res, err := queryExecutor.Exec(query) if err != nil { logger.Error(ctx,"Error executing SQL query:", err.Error()) return false, apperrors.InternalServer } + rowsAffected,err := res.RowsAffected() + if err != nil{ + logger.Error(ctx," err: ",err) + return false,nil + } + logger.Info(ctx," rowsAffected: ",rowsAffected) return true, nil } func (appr *appreciationsStore) UpdateUserBadgesBasedOnTotalRewards(ctx context.Context, tx repository.Transaction) ([]repository.UserBadgeDetails, error) { + logger.Info(ctx," appr: UpdateUserBadgesBasedOnTotalRewards") queryExecutor := appr.InitiateQueryExecutor(tx) afterTime := GetQuarterStartUnixTime() + logger.Info(ctx," aftertime: ",afterTime) query := ` -- Calculate total reward points for each receiver WITH receiver_points AS ( @@ -452,6 +488,7 @@ JOIN badges b ON ib.badge_id = b.id; ` + logger.Debug(ctx," query: ",query) rows, err := queryExecutor.Query(query, afterTime, afterTime) if err != nil { return []repository.UserBadgeDetails{}, err @@ -467,6 +504,7 @@ JOIN userBadgeDetails = append(userBadgeDetails, detail) } + logger.Debug(ctx," userBadgeDetails: ",userBadgeDetails) if err = rows.Err(); err != nil { return []repository.UserBadgeDetails{}, err } diff --git a/internal/repository/postgresdb/organizationConfig.go b/internal/repository/postgresdb/organizationConfig.go index 839acc0..bb59725 100644 --- a/internal/repository/postgresdb/organizationConfig.go +++ b/internal/repository/postgresdb/organizationConfig.go @@ -9,10 +9,10 @@ import ( sq "github.com/Masterminds/squirrel" "github.com/jmoiron/sqlx" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" + "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/joshsoftware/peerly-backend/internal/repository" - "github.com/joshsoftware/peerly-backend/internal/pkg/constants" - logger "github.com/sirupsen/logrus" ) type OrganizationConfigStore struct { @@ -29,6 +29,8 @@ func NewOrganizationConfigRepo(db *sqlx.DB) repository.OrganizationConfigStorer func (org *OrganizationConfigStore) CreateOrganizationConfig(ctx context.Context,tx repository.Transaction, orgConfigInfo dto.OrganizationConfig) (createdOrganization repository.OrganizationConfig, err error) { + logger.Info(ctx," org: CreateOrganizationConfig") + logger.Debug(ctx," orgConfigInfo: ",orgConfigInfo) queryExecutor := org.InitiateQueryExecutor(tx) insertQuery, args, err := repository.Sq. @@ -42,21 +44,25 @@ func (org *OrganizationConfigStore) CreateOrganizationConfig(ctx context.Context Suffix("RETURNING id, reward_multiplier ,reward_quota_renewal_frequency, timezone, created_by, updated_by, created_at, updated_at"). ToSql() if err != nil { - logger.Errorf("err in creating query: %v",err) + logger.Errorf(ctx,"err in creating query: %v",err) return repository.OrganizationConfig{}, apperrors.InternalServer } err = queryExecutor.QueryRowx(insertQuery, args...).StructScan(&createdOrganization) if err != nil { if err == sql.ErrNoRows { - logger.Errorf("err in creating orgconfig : %v ", err) + logger.Errorf(ctx,"err in creating orgconfig : %v ", err) return repository.OrganizationConfig{}, apperrors.InternalServer } } + + logger.Debug(ctx," query: ",insertQuery) + logger.Debug(ctx," args: ",args) return } func (org *OrganizationConfigStore) UpdateOrganizationConfig(ctx context.Context, tx repository.Transaction, reqOrganization dto.OrganizationConfig) (updatedOrganization repository.OrganizationConfig, err error) { + logger.Info(ctx," org: UpdateOrganizationConfig: ") queryExecutor := org.InitiateQueryExecutor(tx) updateBuilder := repository.Sq.Update(org.OrganizationConfigTable). @@ -79,14 +85,16 @@ func (org *OrganizationConfigStore) UpdateOrganizationConfig(ctx context.Context query, args, err := updateBuilder.ToSql() if err != nil { - logger.Errorf("Error building update query: %v",err) + logger.Errorf(ctx,"Error building update query: %v",err) return repository.OrganizationConfig{}, err } + logger.Debug(ctx," query: ",query) + logger.Debug(ctx," args: ",args) err = queryExecutor.QueryRowx(query, args...).StructScan(&updatedOrganization) if err != nil { if err == sql.ErrNoRows { - logger.Errorf("err in updating orgconfig : %v ", err) + logger.Errorf(ctx,"err in updating orgconfig : %v ", err) return repository.OrganizationConfig{}, apperrors.InternalServer } } @@ -95,6 +103,7 @@ func (org *OrganizationConfigStore) UpdateOrganizationConfig(ctx context.Context // GetOrganization - returns an organization from the database if it exists based on its ID primary key func (org *OrganizationConfigStore) GetOrganizationConfig(ctx context.Context, tx repository.Transaction) (updatedOrgConfig repository.OrganizationConfig, err error) { + logger.Debug(ctx," org: GetOrganizationConfig") queryExecutor := org.InitiateQueryExecutor(tx) queryBuilder := repository.Sq. @@ -104,20 +113,21 @@ func (org *OrganizationConfigStore) GetOrganizationConfig(ctx context.Context, t query, args, err := queryBuilder.ToSql() if err != nil { - logger.Errorf("Error building select query: %v",err) + logger.Errorf(ctx,"Error building select query: %v",err) return repository.OrganizationConfig{}, err } err = queryExecutor.QueryRowx( query, args...).StructScan(&updatedOrgConfig) if err != nil { if errors.Is(err, sql.ErrNoRows) { - logger.Errorf("Organization not found: %v",err) + logger.Errorf(ctx,"Organization not found: %v",err) return repository.OrganizationConfig{}, apperrors.OrganizationConfigNotFound } - logger.Errorf("Error fetching organization: %v",err) + logger.Errorf(ctx,"Error fetching organization: %v",err) return repository.OrganizationConfig{}, err } + logger.Debug(ctx," updateOrgConfig: ",updatedOrgConfig) return updatedOrgConfig, nil } diff --git a/internal/repository/postgresdb/rewards.go b/internal/repository/postgresdb/rewards.go index fdde384..0e3466a 100644 --- a/internal/repository/postgresdb/rewards.go +++ b/internal/repository/postgresdb/rewards.go @@ -2,7 +2,6 @@ package repository import ( "context" - "fmt" "github.com/Masterminds/squirrel" "github.com/jmoiron/sqlx" @@ -10,7 +9,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" "github.com/joshsoftware/peerly-backend/internal/repository" - logger "github.com/sirupsen/logrus" + logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" ) type rewardStore struct { @@ -25,6 +24,7 @@ func NewRewardRepo(db *sqlx.DB) repository.RewardStorer { func (rwrd *rewardStore) GiveReward(ctx context.Context, tx repository.Transaction, reward dto.Reward) (repository.Reward, error) { + logger.Debug(ctx," rwrd: GiveReward") queryExecutor := rwrd.InitiateQueryExecutor(tx) insertQuery, args, err := repository.Sq. Insert("rewards"). @@ -34,26 +34,28 @@ func (rwrd *rewardStore) GiveReward(ctx context.Context, tx repository.Transacti ToSql() if err != nil { - logger.Error("err: ", "error in creating query", err.Error()) + logger.Error(ctx,"err: ", "error in creating query", err.Error()) return repository.Reward{}, apperrors.InternalServer } + logger.Debug(ctx," insertQuery: ",insertQuery) + logger.Debug(ctx," args: ",args) var rewardInfo repository.Reward err = queryExecutor.QueryRowx(insertQuery, args...).Scan(&rewardInfo.Id, &rewardInfo.AppreciationId, &rewardInfo.Point, &rewardInfo.SenderId, &rewardInfo.CreatedAt) if err != nil { - logger.Error("Error executing create reward insert query: ", err) + logger.Error(ctx,"Error executing create reward insert query: ", err) return repository.Reward{}, apperrors.InternalServer } + logger.Debug(ctx," rewardInfo: ",rewardInfo) return rewardInfo, nil } func (rwrd *rewardStore) IsUserRewardForAppreciationPresent(ctx context.Context, tx repository.Transaction, apprId int64, senderId int64) (bool, error) { // Initialize the Squirrel query builder - - fmt.Println("appr id: ", apprId) - fmt.Println("sender: ", senderId) + logger.Info(ctx," appr id: ", apprId) + logger.Info(ctx," sender: ", senderId) // Build the SQL query query, args, err := repository.Sq.Select("COUNT(*)"). From("rewards"). @@ -63,11 +65,11 @@ func (rwrd *rewardStore) IsUserRewardForAppreciationPresent(ctx context.Context, }). ToSql() if err != nil { - logger.Error("err ", err.Error()) + logger.Error(ctx,"err ", err.Error()) return false, apperrors.InternalServer } - fmt.Println("query: ", query) + logger.Debug(ctx," query: ", query) queryExecutor := rwrd.InitiateQueryExecutor(tx) @@ -75,10 +77,10 @@ func (rwrd *rewardStore) IsUserRewardForAppreciationPresent(ctx context.Context, // Execute the query err = queryExecutor.QueryRowx(query, args...).Scan(&count) if err != nil { - logger.Error("failed to execute query: ", err.Error()) + logger.Error(ctx,"failed to execute query: ", err.Error()) return false, apperrors.InternalServer } - fmt.Println("count: ", count) + logger.Info(ctx," count: ", count) // Check if user and appreciation id is present return count > 0, nil } @@ -93,21 +95,21 @@ func (rwrd *rewardStore) DeduceRewardQuotaOfUser(ctx context.Context, tx reposit ToSql() if err != nil { - logger.Error("err: building SQL Query ", err.Error()) + logger.Error(ctx,"err: building SQL Query ", err.Error()) return false, err } // Execute the query within the transaction context result, err := queryExecutor.Exec(updateQuery, args...) if err != nil { - logger.Error("err: error executing SQL query:", err.Error()) + logger.Error(ctx,"err: error executing SQL query:", err.Error()) return false, err } // Check how many rows were affected rowsAffected, err := result.RowsAffected() if err != nil { - logger.Error("err: error getting rows affected:", err) + logger.Error(ctx,"err: error getting rows affected:", err) return false, err } @@ -119,6 +121,7 @@ func (rwrd *rewardStore) UserHasRewardQuota(ctx context.Context, tx repository.T // Initialize the Squirrel query builder // psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) + logger.Info(ctx," rwrd: UserHasRewardQuota",userID," ",points) // Build the SQL query query := ` SELECT COUNT(*) @@ -131,8 +134,8 @@ func (rwrd *rewardStore) UserHasRewardQuota(ctx context.Context, tx repository.T // Arguments for the query args := []interface{}{userID, points} - fmt.Println("id: ", userID, "points: ", points) - fmt.Println("query: ", query) + logger.Info(ctx,"id: ", userID, "points: ", points) + logger.Info(ctx,"query: ", query) queryExecutor := rwrd.InitiateQueryExecutor(tx) @@ -140,10 +143,10 @@ func (rwrd *rewardStore) UserHasRewardQuota(ctx context.Context, tx repository.T // Execute the query err := queryExecutor.QueryRowx(query, args...).Scan(&count) if err != nil { - logger.Error("failed to execute query: ", err.Error()) + logger.Error(ctx,"failed to execute query: ", err.Error()) return false, apperrors.InternalServer } - fmt.Println("count: ", count) + logger.Info(ctx," count: ", count) // Check if user is present return count > 0, nil } diff --git a/logs/2024-08-23_18-52-42_peerly_backend.log b/logs/2024-08-23_18-52-42_peerly_backend.log new file mode 100644 index 0000000..07a60e1 --- /dev/null +++ b/logs/2024-08-23_18-52-42_peerly_backend.log @@ -0,0 +1,134 @@ +time="2024-08-23T18:52:42+05:30" level=info msg="Starting Peerly Application..." +time="2024-08-23T18:53:19+05:30" level=info msg="2024-08-23T18:53:19+05:30 | 401 | \t 79.746µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T18:53:22+05:30" level=info msg="req_id: 96e87117-d1a8-4ca3-b73a-76f1d5c510a3[ping]" +time="2024-08-23T18:53:22+05:30" level=info msg="2024-08-23T18:53:22+05:30 | 200 | \t 127.759µs | localhost:33001 | GET /peerly/ping" +time="2024-08-23T18:53:40+05:30" level=info msg="req_id: 0d13dc29-93e2-4f2b-9489-3f695da0ec5f[loggerHandler]" +time="2024-08-23T18:53:40+05:30" level=info msg="2024-08-23T18:53:40+05:30 | 200 | \t 108.894µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T18:53:48+05:30" level=debug msg="debug ping" +time="2024-08-23T18:53:48+05:30" level=info msg="req_id: 624be32c-cef9-47fa-87f8-42cfcbc77979[ping]" +time="2024-08-23T18:53:48+05:30" level=info msg="2024-08-23T18:53:48+05:30 | 200 | \t 82.07µs | localhost:33001 | GET /peerly/ping" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[listAppreciationsHandler]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[listAppreciationsHandler: request: 0xc0003a8a20]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[filter: {false DESC 1 10}]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ filter: {false DESC 1 10}]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ appr: ListAppreciations: filter: {false DESC 1 10}]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[countArgs: [true]]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ pagination: {10 1 1 2}]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ offset: 0]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ args: [true]]" +time="2024-08-23T18:53:59+05:30" level=info msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[filter: {false DESC 1 10}]" +time="2024-08-23T18:53:59+05:30" level=info msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T18:53:59+05:30" level=info msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[args: [true]]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ id -> 212]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ userId: 212]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ args: [2]]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ args: [1]]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ pagination: {10 1 1 2}]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" +time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" +time="2024-08-23T18:53:59+05:30" level=info msg="2024-08-23T18:53:59+05:30 | 200 | \t 30.51005ms | localhost:33001 | GET /peerly/appreciations" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[listAppreciationsHandler]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[listAppreciationsHandler: request: 0xc000418ea0]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[filter: {false DESC 1 10}]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ filter: {false DESC 1 10}]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ appr: ListAppreciations: filter: {false DESC 1 10}]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[countArgs: [true]]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ pagination: {10 1 1 2}]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ offset: 0]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ args: [true]]" +time="2024-08-23T18:54:50+05:30" level=info msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[filter: {false DESC 1 10}]" +time="2024-08-23T18:54:50+05:30" level=info msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T18:54:50+05:30" level=info msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[args: [true]]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ id -> 212]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ userId: 212]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ args: [2]]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ args: [1]]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ pagination: {10 1 1 2}]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" +time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" +time="2024-08-23T18:54:50+05:30" level=info msg="2024-08-23T18:54:50+05:30 | 200 | \t 2.20324ms | localhost:33001 | GET /peerly/appreciations" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[listAppreciationsHandler]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: + + +[listAppreciationsHandler: request: 0xc000710d80]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[filter: {false DESC 1 10}]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ filter: {false DESC 1 10}]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ appr: ListAppreciations: filter: {false DESC 1 10}]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[countArgs: [true]]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ pagination: {10 1 1 2}]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ offset: 0]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ args: [true]]" +time="2024-08-23T18:55:17+05:30" level=info msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[filter: {false DESC 1 10}]" +time="2024-08-23T18:55:17+05:30" level=info msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T18:55:17+05:30" level=info msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[args: [true]]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ id -> 212]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ userId: 212]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ args: [2]]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ args: [1]]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ pagination: {10 1 1 2}]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" +time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" +time="2024-08-23T18:55:17+05:30" level=info msg="2024-08-23T18:55:17+05:30 | 200 | \t 3.137759ms | localhost:33001 | GET /peerly/appreciations" +time="2024-08-23T19:06:59+05:30" level=debug msg="req_id: cd0ea421-078e-4647-8f61-813c79b9687b[loggerHandler: req: 0xc0002fe900]" +time="2024-08-23T19:06:59+05:30" level=info msg="req_id: cd0ea421-078e-4647-8f61-813c79b9687b[loggerHandler]" +time="2024-08-23T19:06:59+05:30" level=info msg="2024-08-23T19:06:59+05:30 | 200 | \t 232.983µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T19:07:05+05:30" level=info msg="req_id: b21cdecf-28d4-4d01-9093-e5570ba27cf1[loggerHandler]" +time="2024-08-23T19:07:05+05:30" level=info msg="2024-08-23T19:07:05+05:30 | 200 | \t 109.087µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T19:07:14+05:30" level=info msg="req_id: d9b3c156-34c4-42ff-bf62-a18e35874cc7[loggerHandler]" +time="2024-08-23T19:07:14+05:30" level=info msg="2024-08-23T19:07:14+05:30 | 200 | \t 185.868µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T19:07:20+05:30" level=debug msg="req_id: 743084e6-954d-4cb9-b54e-e76512860323[loggerHandler: req: 0xc0002ff200]" +time="2024-08-23T19:07:20+05:30" level=info msg="req_id: 743084e6-954d-4cb9-b54e-e76512860323[loggerHandler]" +time="2024-08-23T19:07:20+05:30" level=info msg="2024-08-23T19:07:20+05:30 | 200 | \t 160.004µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T19:23:52+05:30" level=info msg="req_id: 68e986fa-4ab1-4464-ba1d-1936596a6e86[filter: {false DESC 1 10}]" +time="2024-08-23T19:23:52+05:30" level=info msg="req_id: 68e986fa-4ab1-4464-ba1d-1936596a6e86[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T19:23:52+05:30" level=info msg="req_id: 68e986fa-4ab1-4464-ba1d-1936596a6e86[args: [true]]" +time="2024-08-23T19:23:52+05:30" level=info msg="2024-08-23T19:23:52+05:30 | 200 | \t 3.323247ms | localhost:33001 | GET /peerly/appreciations" +time="2024-08-23T19:24:20+05:30" level=info msg="req_id: 2f951672-89b2-4dea-b759-0d294ea4e341[loggerHandler]" +time="2024-08-23T19:24:20+05:30" level=info msg="2024-08-23T19:24:20+05:30 | 200 | \t 172.893µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T19:24:27+05:30" level=info msg="req_id: 4a5b199b-6fd9-441e-89ca-d007c48a73cf[loggerHandler]" +time="2024-08-23T19:24:27+05:30" level=info msg="2024-08-23T19:24:27+05:30 | 200 | \t 175.533µs | localhost:33001 | POST /peerly/set_logger_level" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[listAppreciationsHandler]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[listAppreciationsHandler: request: 0xc0002fefc0]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[filter: {false DESC 1 10}]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ filter: {false DESC 1 10}]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ appr: ListAppreciations: filter: {false DESC 1 10}]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[countArgs: [true]]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ pagination: {10 1 1 2}]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ offset: 0]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ args: [true]]" +time="2024-08-23T19:24:33+05:30" level=info msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[filter: {false DESC 1 10}]" +time="2024-08-23T19:24:33+05:30" level=info msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" +time="2024-08-23T19:24:33+05:30" level=info msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[args: [true]]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ id -> 212]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ userId: 212]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ args: [2]]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ args: [1]]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ pagination: {10 1 1 2}]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" +time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" +time="2024-08-23T19:24:33+05:30" level=info msg="2024-08-23T19:24:33+05:30 | 200 | \t 4.73416ms | localhost:33001 | GET /peerly/appreciations" From a61d8efd34377ce3c78496752e4f2adc42fda0fa Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Mon, 26 Aug 2024 12:42:31 +0530 Subject: [PATCH 11/22] [ feature/UpdateLogs] main.go updated --- cmd/main.go | 16 ++- logs/2024-08-23_12-51-17_peerly_backend.log | 2 - logs/2024-08-23_18-52-42_peerly_backend.log | 134 -------------------- 3 files changed, 10 insertions(+), 142 deletions(-) delete mode 100644 logs/2024-08-23_12-51-17_peerly_backend.log delete mode 100644 logs/2024-08-23_18-52-42_peerly_backend.log diff --git a/cmd/main.go b/cmd/main.go index d86ec81..0f40b92 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -95,13 +95,17 @@ func startApp() (err error) { // Context for main function ctx := context.Background() - logger,err := log.SetupLogger() - logger.Info("Starting Peerly Application...") - defer logger.Info("Shutting Down Peerly Application...") + lg,err := log.SetupLogger() + if err != nil{ + logger.Error("logger setup failed ",err.Error()) + return + } + log.Info(ctx,"Starting Peerly Application...") + defer log.Info(ctx,"Shutting Down Peerly Application...") //initialize database dbInstance, err := repository.InitializeDatabase() if err != nil { - logger.WithField("err", err.Error()).Error("Database init failed") + log.Error(ctx,"Database init failed") return } @@ -119,7 +123,7 @@ func startApp() (err error) { // Initializing Cron Job scheduler, err := gocron.NewScheduler() if err != nil { - logger.Error(ctx, "scheduler creation failed with error: %s", err.Error()) + log.Error(ctx, "scheduler creation failed with error: %s", err.Error()) return } @@ -130,7 +134,7 @@ func startApp() (err error) { // Negroni logger setup negroniLogger := negroni.NewLogger() - negroniLogger.ALogger = logger + negroniLogger.ALogger = lg // Initialize web server server := negroni.New(negroniLogger) diff --git a/logs/2024-08-23_12-51-17_peerly_backend.log b/logs/2024-08-23_12-51-17_peerly_backend.log deleted file mode 100644 index 4159b51..0000000 --- a/logs/2024-08-23_12-51-17_peerly_backend.log +++ /dev/null @@ -1,2 +0,0 @@ -time="2024-08-23T12:51:17+05:30" level=info msg="Starting Peerly Application..." -time="2024-08-23T12:51:23+05:30" level=info msg="2024-08-23T12:51:23+05:30 | 401 | \t 112.994µs | localhost:33001 | POST /peerly/set_logger_level" diff --git a/logs/2024-08-23_18-52-42_peerly_backend.log b/logs/2024-08-23_18-52-42_peerly_backend.log deleted file mode 100644 index 07a60e1..0000000 --- a/logs/2024-08-23_18-52-42_peerly_backend.log +++ /dev/null @@ -1,134 +0,0 @@ -time="2024-08-23T18:52:42+05:30" level=info msg="Starting Peerly Application..." -time="2024-08-23T18:53:19+05:30" level=info msg="2024-08-23T18:53:19+05:30 | 401 | \t 79.746µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T18:53:22+05:30" level=info msg="req_id: 96e87117-d1a8-4ca3-b73a-76f1d5c510a3[ping]" -time="2024-08-23T18:53:22+05:30" level=info msg="2024-08-23T18:53:22+05:30 | 200 | \t 127.759µs | localhost:33001 | GET /peerly/ping" -time="2024-08-23T18:53:40+05:30" level=info msg="req_id: 0d13dc29-93e2-4f2b-9489-3f695da0ec5f[loggerHandler]" -time="2024-08-23T18:53:40+05:30" level=info msg="2024-08-23T18:53:40+05:30 | 200 | \t 108.894µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T18:53:48+05:30" level=debug msg="debug ping" -time="2024-08-23T18:53:48+05:30" level=info msg="req_id: 624be32c-cef9-47fa-87f8-42cfcbc77979[ping]" -time="2024-08-23T18:53:48+05:30" level=info msg="2024-08-23T18:53:48+05:30 | 200 | \t 82.07µs | localhost:33001 | GET /peerly/ping" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[listAppreciationsHandler]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[listAppreciationsHandler: request: 0xc0003a8a20]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[filter: {false DESC 1 10}]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ filter: {false DESC 1 10}]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ appr: ListAppreciations: filter: {false DESC 1 10}]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[countArgs: [true]]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ pagination: {10 1 1 2}]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ offset: 0]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ args: [true]]" -time="2024-08-23T18:53:59+05:30" level=info msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[filter: {false DESC 1 10}]" -time="2024-08-23T18:53:59+05:30" level=info msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T18:53:59+05:30" level=info msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[args: [true]]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ id -> 212]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ userId: 212]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ args: [2]]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ args: [1]]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ pagination: {10 1 1 2}]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" -time="2024-08-23T18:53:59+05:30" level=debug msg="req_id: 993bf3fc-7d18-4c21-8f32-355d41a10c99[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" -time="2024-08-23T18:53:59+05:30" level=info msg="2024-08-23T18:53:59+05:30 | 200 | \t 30.51005ms | localhost:33001 | GET /peerly/appreciations" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[listAppreciationsHandler]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[listAppreciationsHandler: request: 0xc000418ea0]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[filter: {false DESC 1 10}]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ filter: {false DESC 1 10}]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ appr: ListAppreciations: filter: {false DESC 1 10}]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[countArgs: [true]]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ pagination: {10 1 1 2}]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ offset: 0]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ args: [true]]" -time="2024-08-23T18:54:50+05:30" level=info msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[filter: {false DESC 1 10}]" -time="2024-08-23T18:54:50+05:30" level=info msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T18:54:50+05:30" level=info msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[args: [true]]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ id -> 212]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ userId: 212]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ args: [2]]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ args: [1]]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ pagination: {10 1 1 2}]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" -time="2024-08-23T18:54:50+05:30" level=debug msg="req_id: d958d92c-9683-4a3a-ad05-5758c77175f8[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" -time="2024-08-23T18:54:50+05:30" level=info msg="2024-08-23T18:54:50+05:30 | 200 | \t 2.20324ms | localhost:33001 | GET /peerly/appreciations" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[listAppreciationsHandler]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: - - -[listAppreciationsHandler: request: 0xc000710d80]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[filter: {false DESC 1 10}]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ filter: {false DESC 1 10}]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ appr: ListAppreciations: filter: {false DESC 1 10}]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[countArgs: [true]]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ pagination: {10 1 1 2}]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ offset: 0]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ args: [true]]" -time="2024-08-23T18:55:17+05:30" level=info msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[filter: {false DESC 1 10}]" -time="2024-08-23T18:55:17+05:30" level=info msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T18:55:17+05:30" level=info msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[args: [true]]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ id -> 212]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ userId: 212]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ args: [2]]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ args: [1]]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ pagination: {10 1 1 2}]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" -time="2024-08-23T18:55:17+05:30" level=debug msg="req_id: ba37597e-2d40-4cc4-8791-e9a36fd3d778[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" -time="2024-08-23T18:55:17+05:30" level=info msg="2024-08-23T18:55:17+05:30 | 200 | \t 3.137759ms | localhost:33001 | GET /peerly/appreciations" -time="2024-08-23T19:06:59+05:30" level=debug msg="req_id: cd0ea421-078e-4647-8f61-813c79b9687b[loggerHandler: req: 0xc0002fe900]" -time="2024-08-23T19:06:59+05:30" level=info msg="req_id: cd0ea421-078e-4647-8f61-813c79b9687b[loggerHandler]" -time="2024-08-23T19:06:59+05:30" level=info msg="2024-08-23T19:06:59+05:30 | 200 | \t 232.983µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T19:07:05+05:30" level=info msg="req_id: b21cdecf-28d4-4d01-9093-e5570ba27cf1[loggerHandler]" -time="2024-08-23T19:07:05+05:30" level=info msg="2024-08-23T19:07:05+05:30 | 200 | \t 109.087µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T19:07:14+05:30" level=info msg="req_id: d9b3c156-34c4-42ff-bf62-a18e35874cc7[loggerHandler]" -time="2024-08-23T19:07:14+05:30" level=info msg="2024-08-23T19:07:14+05:30 | 200 | \t 185.868µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T19:07:20+05:30" level=debug msg="req_id: 743084e6-954d-4cb9-b54e-e76512860323[loggerHandler: req: 0xc0002ff200]" -time="2024-08-23T19:07:20+05:30" level=info msg="req_id: 743084e6-954d-4cb9-b54e-e76512860323[loggerHandler]" -time="2024-08-23T19:07:20+05:30" level=info msg="2024-08-23T19:07:20+05:30 | 200 | \t 160.004µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T19:23:52+05:30" level=info msg="req_id: 68e986fa-4ab1-4464-ba1d-1936596a6e86[filter: {false DESC 1 10}]" -time="2024-08-23T19:23:52+05:30" level=info msg="req_id: 68e986fa-4ab1-4464-ba1d-1936596a6e86[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T19:23:52+05:30" level=info msg="req_id: 68e986fa-4ab1-4464-ba1d-1936596a6e86[args: [true]]" -time="2024-08-23T19:23:52+05:30" level=info msg="2024-08-23T19:23:52+05:30 | 200 | \t 3.323247ms | localhost:33001 | GET /peerly/appreciations" -time="2024-08-23T19:24:20+05:30" level=info msg="req_id: 2f951672-89b2-4dea-b759-0d294ea4e341[loggerHandler]" -time="2024-08-23T19:24:20+05:30" level=info msg="2024-08-23T19:24:20+05:30 | 200 | \t 172.893µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T19:24:27+05:30" level=info msg="req_id: 4a5b199b-6fd9-441e-89ca-d007c48a73cf[loggerHandler]" -time="2024-08-23T19:24:27+05:30" level=info msg="2024-08-23T19:24:27+05:30 | 200 | \t 175.533µs | localhost:33001 | POST /peerly/set_logger_level" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[listAppreciationsHandler]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[listAppreciationsHandler: request: 0xc0002fefc0]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[filter: {false DESC 1 10}]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ filter: {false DESC 1 10}]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ appr: ListAppreciations: filter: {false DESC 1 10}]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[countSql: SELECT COUNT(*) FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id WHERE a.is_valid = $1]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[countArgs: [true]]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ pagination: {10 1 1 2}]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ offset: 0]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ sqlQuery: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ args: [true]]" -time="2024-08-23T19:24:33+05:30" level=info msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[filter: {false DESC 1 10}]" -time="2024-08-23T19:24:33+05:30" level=info msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[sql: SELECT a.id, cv.name AS core_value_name, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point, cv.description AS core_value_description, a.description, a.is_valid, a.total_reward_points, a.quarter, u_sender.id AS sender_id, u_sender.first_name AS sender_first_name, u_sender.last_name AS sender_last_name, u_sender.profile_image_url AS sender_image_url, u_sender.designation AS sender_designation, u_receiver.id AS receiver_id, u_receiver.first_name AS receiver_first_name, u_receiver.last_name AS receiver_last_name, u_receiver.profile_image_url AS receiver_image_url, u_receiver.designation AS receiver_designation, a.created_at, a.updated_at, COUNT(r.id) AS total_rewards, COALESCE((\n\t\t\t\tSELECT SUM(r2.point) \n\t\t\t\tFROM rewards r2 \n\t\t\t\tWHERE r2.appreciation_id = a.id AND r2.sender = 212\n\t\t\t), 0) AS given_reward_point FROM appreciations a LEFT JOIN users u_sender ON a.sender = u_sender.id LEFT JOIN users u_receiver ON a.receiver = u_receiver.id LEFT JOIN core_values cv ON a.core_value_id = cv.id LEFT JOIN rewards r ON a.id = r.appreciation_id WHERE a.is_valid = $1 GROUP BY a.id, cv.name, cv.description, u_sender.id, u_receiver.id ORDER BY a.created_at DESC LIMIT 10 OFFSET 0]" -time="2024-08-23T19:24:33+05:30" level=info msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[args: [true]]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ id -> 212]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ userId: 212]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ args: [2]]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ query: SELECT reported_by FROM resolutions WHERE appreciation_id = $1]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ args: [1]]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ res: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}]]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ pagination: {10 1 1 2}]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ infos: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 0 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 0 false 0 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. true 300 2 212 Sharyu Marwadi { true} Software Engineer 187 Samnit Patil { true} Software Engineer 1 false 0 1724262140433 1724321985724}] pagination: {10 1 1 2} err: ]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[ apprSvc: [{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] paginationResp: {1 1 10 2}]" -time="2024-08-23T19:24:33+05:30" level=debug msg="req_id: 5c1ff079-b78c-4de5-b17c-108d55671404[listAppreciationsHandler: response: {[{2 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 0 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 0 0 false 1724329694764 1724329694764} {1 Integrity & Ethics We uphold integrity in every action, ensuring our decisions align with the highest moral standards. Lorem Ipsum\u00a0 not only. 300 2 212 Sharyu Marwadi Software Engineer 187 Samnit Patil Software Engineer 1 0 false 1724262140433 1724321985724}] {1 1 10 2}}]" -time="2024-08-23T19:24:33+05:30" level=info msg="2024-08-23T19:24:33+05:30 | 200 | \t 4.73416ms | localhost:33001 | GET /peerly/appreciations" From 8aaf7ef10348915d4f95c56e2d33f034a0f4b3c4 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Mon, 26 Aug 2024 12:52:58 +0530 Subject: [PATCH 12/22] [feature/UpdateLogs] logs folder added --- logs/2024-08-26_12-52-33_peerly_backend.log | 1 + 1 file changed, 1 insertion(+) create mode 100644 logs/2024-08-26_12-52-33_peerly_backend.log diff --git a/logs/2024-08-26_12-52-33_peerly_backend.log b/logs/2024-08-26_12-52-33_peerly_backend.log new file mode 100644 index 0000000..45441b7 --- /dev/null +++ b/logs/2024-08-26_12-52-33_peerly_backend.log @@ -0,0 +1 @@ +time="2024-08-26T12:52:33+05:30" level=info msg="req_id: [Starting Peerly Application...]" From a03cd5241dde03d980405b2a38bf117ed20a039c Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Mon, 26 Aug 2024 13:14:31 +0530 Subject: [PATCH 13/22] [feature/UpdateLogs] defer function changed --- cmd/main.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 0f40b92..e504ba7 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -98,7 +98,7 @@ func startApp() (err error) { lg,err := log.SetupLogger() if err != nil{ logger.Error("logger setup failed ",err.Error()) - return + return err } log.Info(ctx,"Starting Peerly Application...") defer log.Info(ctx,"Shutting Down Peerly Application...") @@ -106,7 +106,7 @@ func startApp() (err error) { dbInstance, err := repository.InitializeDatabase() if err != nil { log.Error(ctx,"Database init failed") - return + return err } //cors @@ -124,11 +124,15 @@ func startApp() (err error) { scheduler, err := gocron.NewScheduler() if err != nil { log.Error(ctx, "scheduler creation failed with error: %s", err.Error()) - return + return err } cronjob.InitializeJobs(services.AppreciationService, services.UserService, scheduler) - defer scheduler.Shutdown() + defer func() { + if err := scheduler.Shutdown(); err != nil { + log.Error(ctx, "Scheduler shutdown failed: %s", err.Error()) + } + }() //initialize router router := api.NewRouter(services) From 208ccf7f1d12b37af22a12f797554d9ff5fea1a4 Mon Sep 17 00:00:00 2001 From: Sharyu Marwadi Date: Tue, 27 Aug 2024 12:07:39 +0530 Subject: [PATCH 14/22] [fix/AdminPermissions] permissions given to admin --- internal/api/router.go | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/internal/api/router.go b/internal/api/router.go index 64c44ab..3e3bce8 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -27,13 +27,13 @@ func NewRouter(deps app.Dependencies) *mux.Router { v1 := fmt.Sprintf("application/vnd.%s.v1", config.AppName()) //corevalues - peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(getCoreValueHandler(deps.CoreValueService), []string{constants.UserRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(getCoreValueHandler(deps.CoreValueService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) peerlySubrouter.Handle("/core_values", middleware.JwtAuthMiddleware(listCoreValuesHandler(deps.CoreValueService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/core_values", middleware.JwtAuthMiddleware(createCoreValueHandler(deps.CoreValueService), []string{constants.UserRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/core_values", middleware.JwtAuthMiddleware(createCoreValueHandler(deps.CoreValueService), []string{constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(updateCoreValueHandler(deps.CoreValueService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(updateCoreValueHandler(deps.CoreValueService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) //users @@ -47,44 +47,44 @@ func NewRouter(deps app.Dependencies) *mux.Router { peerlySubrouter.Handle("/users", middleware.JwtAuthMiddleware(listUsersHandler(deps.UserService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/user_profile", middleware.JwtAuthMiddleware(getUserByIdHandler(deps.UserService), []string{constants.UserRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/user_profile", middleware.JwtAuthMiddleware(getUserByIdHandler(deps.UserService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) peerlySubrouter.Handle("/users/active", getActiveUserListHandler(deps.UserService)).Methods(http.MethodGet) - peerlySubrouter.Handle("/users/top10", middleware.JwtAuthMiddleware(getTop10UserHandler(deps.UserService), []string{constants.UserRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/users/top10", middleware.JwtAuthMiddleware(getTop10UserHandler(deps.UserService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/admin/notification", middleware.JwtAuthMiddleware(adminNotificationHandler(deps.UserService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/admin/notification", middleware.JwtAuthMiddleware(adminNotificationHandler(deps.UserService), []string{constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/admin/appreciation_report", middleware.JwtAuthMiddleware(appreciationReportHandler(deps.UserService, deps.AppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet) + peerlySubrouter.Handle("/admin/appreciation_report", middleware.JwtAuthMiddleware(appreciationReportHandler(deps.UserService, deps.AppreciationService), []string{constants.AdminRole})).Methods(http.MethodGet) - peerlySubrouter.Handle("/admin/reported_appreciation_report", middleware.JwtAuthMiddleware(reportedAppreciationReportHandler(deps.UserService, deps.ReportAppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet) + peerlySubrouter.Handle("/admin/reported_appreciation_report", middleware.JwtAuthMiddleware(reportedAppreciationReportHandler(deps.UserService, deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodGet) //appreciations - peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(getAppreciationByIDHandler(deps.AppreciationService), []string{constants.UserRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(getAppreciationByIDHandler(deps.AppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) peerlySubrouter.Handle("/appreciations", middleware.JwtAuthMiddleware(listAppreciationsHandler(deps.AppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(deleteAppreciationHandler(deps.AppreciationService), []string{constants.UserRole})).Methods(http.MethodDelete).Headers(versionHeader, v1) + peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(deleteAppreciationHandler(deps.AppreciationService), []string{constants.AdminRole})).Methods(http.MethodDelete).Headers(versionHeader, v1) - peerlySubrouter.Handle("/appreciations", middleware.JwtAuthMiddleware(createAppreciationHandler(deps.AppreciationService), []string{constants.UserRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/appreciations", middleware.JwtAuthMiddleware(createAppreciationHandler(deps.AppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) //report appreciation - peerlySubrouter.Handle("/report_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(reportAppreciationHandler(deps.ReportAppreciationService), []string{constants.UserRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/report_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(reportAppreciationHandler(deps.ReportAppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/report_appreciations", middleware.JwtAuthMiddleware(listReportedAppreciations(deps.ReportAppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/report_appreciations", middleware.JwtAuthMiddleware(listReportedAppreciations(deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/moderate_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(moderateAppreciation(deps.ReportAppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/moderate_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(moderateAppreciation(deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) - peerlySubrouter.Handle("/resolve_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(resolveAppreciation(deps.ReportAppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/resolve_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(resolveAppreciation(deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) //grades peerlySubrouter.Handle("/grades", middleware.JwtAuthMiddleware(listGradesHandler(deps.GradeService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/grades/{id:[0-9]+}", middleware.JwtAuthMiddleware(editGradesHandler(deps.GradeService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPatch).Headers(versionHeader, v1) + peerlySubrouter.Handle("/grades/{id:[0-9]+}", middleware.JwtAuthMiddleware(editGradesHandler(deps.GradeService), []string{constants.AdminRole})).Methods(http.MethodPatch).Headers(versionHeader, v1) // reward appreciation - peerlySubrouter.Handle("/reward/{id:[0-9]+}", middleware.JwtAuthMiddleware(giveRewardHandler(deps.RewardService), []string{constants.UserRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/reward/{id:[0-9]+}", middleware.JwtAuthMiddleware(giveRewardHandler(deps.RewardService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) // organization config peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(getOrganizationConfigHandler(deps.OrganizationConfigService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) @@ -92,15 +92,13 @@ func NewRouter(deps app.Dependencies) *mux.Router { //organization config data inserted by seed file // peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(createOrganizationConfigHandler(deps.OrganizationConfigService),[]string{constants.UserRole})).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(updateOrganizationConfigHandler(deps.OrganizationConfigService), []string{constants.UserRole})).Methods(http.MethodPut).Headers(versionHeader, v1) - - peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(updateOrganizationConfigHandler(deps.OrganizationConfigService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(updateOrganizationConfigHandler(deps.OrganizationConfigService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) //badges peerlySubrouter.Handle("/badges", middleware.JwtAuthMiddleware(listBadgesHandler(deps.BadgeService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/badges/{id:[0-9]+}", middleware.JwtAuthMiddleware(editBadgesHandler(deps.BadgeService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPatch).Headers(versionHeader, v1) + peerlySubrouter.Handle("/badges/{id:[0-9]+}", middleware.JwtAuthMiddleware(editBadgesHandler(deps.BadgeService), []string{constants.AdminRole})).Methods(http.MethodPatch).Headers(versionHeader, v1) // No version requirement for /ping peerlySubrouter.HandleFunc("/ping", pingHandler).Methods(http.MethodGet) From 368973f5dc393b3cdb38cdf4c7b8d2a67c0060bb Mon Sep 17 00:00:00 2001 From: Sharyu Marwadi Date: Tue, 27 Aug 2024 13:17:24 +0530 Subject: [PATCH 15/22] [fix/AdminPermissions] iota logic added --- internal/app/users/service.go | 4 ++-- internal/pkg/constants/system.go | 5 +++++ internal/pkg/dto/users.go | 10 +++++----- internal/pkg/middleware/jwtMiddleware.go | 5 ++--- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/internal/app/users/service.go b/internal/app/users/service.go index 0c72366..254afcf 100644 --- a/internal/app/users/service.go +++ b/internal/app/users/service.go @@ -181,7 +181,7 @@ func (us *service) LoginUser(ctx context.Context, u dto.IntranetUserData) (dto.L claims := &dto.Claims{ Id: user.Id, - Role: constants.UserRole, + Role: constants.User, StandardClaims: jwt.StandardClaims{ ExpiresAt: expirationTime.Unix(), }, @@ -375,7 +375,7 @@ func (us *service) AdminLogin(ctx context.Context, loginReq dto.AdminLoginReq) ( claims := &dto.Claims{ Id: user.Id, - Role: constants.AdminRole, + Role: constants.Admin, StandardClaims: jwt.StandardClaims{ ExpiresAt: expirationTime.Unix(), }, diff --git a/internal/pkg/constants/system.go b/internal/pkg/constants/system.go index bac0232..7f1673b 100644 --- a/internal/pkg/constants/system.go +++ b/internal/pkg/constants/system.go @@ -19,6 +19,11 @@ const ( GET = "GET" ) +const ( + Admin int = iota + User +) + // User required constants const ( AuthorizationHeader = "Authorization" diff --git a/internal/pkg/dto/users.go b/internal/pkg/dto/users.go index b7ec808..cec99dd 100644 --- a/internal/pkg/dto/users.go +++ b/internal/pkg/dto/users.go @@ -64,7 +64,7 @@ type GetIntranetUserDataReq struct { type Claims struct { Id int64 - Role string + Role int jwt.StandardClaims } @@ -109,10 +109,10 @@ type ListUsersReq struct { } type ActiveUser struct { - ID int `json:"id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - ProfileImageURL string `json:"profile_image_url"` + ID int `json:"id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + ProfileImageURL string `json:"profile_image_url"` // BadgeName string `json:"badge_name"` // AppreciationPoints int `json:"appreciation_points"` } diff --git a/internal/pkg/middleware/jwtMiddleware.go b/internal/pkg/middleware/jwtMiddleware.go index ecd541d..5858aa2 100644 --- a/internal/pkg/middleware/jwtMiddleware.go +++ b/internal/pkg/middleware/jwtMiddleware.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "net/http" - "slices" "strings" "github.com/dgrijalva/jwt-go" @@ -15,7 +14,7 @@ import ( logger "github.com/sirupsen/logrus" ) -func JwtAuthMiddleware(next http.Handler, roles []string) http.Handler { +func JwtAuthMiddleware(next http.Handler, role int) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { jwtKey := config.JWTKey() authToken := req.Header.Get(constants.AuthorizationHeader) @@ -50,7 +49,7 @@ func JwtAuthMiddleware(next http.Handler, roles []string) http.Handler { Id := claims.Id Role := claims.Role - if !slices.Contains(roles, Role) { + if Role > role { err := apperrors.RoleUnathorized dto.ErrorRepsonse(rw, err) return From 327598aa0cc347b61222f52ce486360a3c6b6737 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Wed, 28 Aug 2024 13:20:15 +0530 Subject: [PATCH 16/22] [feature/addEmailAndNotification] image url changed as per env --- internal/app/appreciation/service.go | 13 +++++--- internal/app/email/templates/badge.html | 2 +- .../email/templates/deleteAppreciation.html | 2 +- .../email/templates/receiverAppreciation.html | 2 +- .../email/templates/reportAppreciation.html | 2 +- .../email/templates/senderAppreciation.html | 2 +- internal/app/reportAppreciations/service.go | 31 ++++++++++--------- internal/pkg/constants/system.go | 18 +++++++++++ internal/pkg/dto/reportAppreciations.go | 13 ++++---- 9 files changed, 56 insertions(+), 29 deletions(-) diff --git a/internal/app/appreciation/service.go b/internal/app/appreciation/service.go index 15988ee..170b4b2 100644 --- a/internal/app/appreciation/service.go +++ b/internal/app/appreciation/service.go @@ -8,6 +8,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/notification" user "github.com/joshsoftware/peerly-backend/internal/app/users" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" + "github.com/joshsoftware/peerly-backend/internal/pkg/config" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" @@ -227,12 +228,16 @@ func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail Description string CoreValueName string CoreValueBackgroundColor string + ReceiverIconImageURL string + SenderIconImageURL string }{ SenderName: fmt.Sprint(emailData.SenderFirstName, " ", emailData.SenderLastName), ReceiverName: fmt.Sprint(emailData.ReceiverFirstName, " ", emailData.ReceiverLastName), Description: emailData.Description, CoreValueName: emailData.CoreValueName, CoreValueBackgroundColor: utils.GetCoreValueBackgroundColor(emailData.CoreValueName), + ReceiverIconImageURL: fmt.Sprint(config.PeerlyBaseUrl()+constants.ClosedEnvelopeIconImagePath), + SenderIconImageURL: fmt.Sprint(config.PeerlyBaseUrl()+constants.OpenEnvelopeIconImagePath), } logger.Info(context.Background(),"appreciation sender email: -----------> ",senderEmail) @@ -302,13 +307,13 @@ func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repositor var badgeImageUrl string switch userBadgeDetail.BadgeName.String { case "Bronze": - badgeImageUrl = "bronzeBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.BronzeBadgeIconImagePath) case "Silver": - badgeImageUrl = "silverBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.SilverBadgeIconImagePath) case "Gold": - badgeImageUrl = "goldBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.GoldBadgeIconImagePath) case "Platinum": - badgeImageUrl = "platinumBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.PlatinumIconImagePath) } // repository.UserBadgeDetails diff --git a/internal/app/email/templates/badge.html b/internal/app/email/templates/badge.html index 9d50d96..b894a29 100644 --- a/internal/app/email/templates/badge.html +++ b/internal/app/email/templates/badge.html @@ -16,7 +16,7 @@

Peerly

- Badge Image + Badge Image

Hi {{.EmployeeName}}

Congratulations!
You have achieved the {{.BadgeName}} badge for
accumulating {{.AppreciationPoints}} points.

diff --git a/internal/app/email/templates/deleteAppreciation.html b/internal/app/email/templates/deleteAppreciation.html index 2730ba4..67cf6aa 100644 --- a/internal/app/email/templates/deleteAppreciation.html +++ b/internal/app/email/templates/deleteAppreciation.html @@ -25,7 +25,7 @@ style="background-color: #F5F8FF; padding: 40px 20px; text-align: center; color: #000000;">

Peerly

- appreciation

diff --git a/internal/app/email/templates/receiverAppreciation.html b/internal/app/email/templates/receiverAppreciation.html index 515f2b2..1c134b6 100644 --- a/internal/app/email/templates/receiverAppreciation.html +++ b/internal/app/email/templates/receiverAppreciation.html @@ -16,7 +16,7 @@

Peerly

- appreciation + appreciation

Bravo!
You have received a deserved
word of appreciation.
Keep inspiring those around you!

{{.SenderName}} appreciated you
Core Value
diff --git a/internal/app/email/templates/reportAppreciation.html b/internal/app/email/templates/reportAppreciation.html index 1cb16c2..975acec 100644 --- a/internal/app/email/templates/reportAppreciation.html +++ b/internal/app/email/templates/reportAppreciation.html @@ -16,7 +16,7 @@

Peerly

- Feedback Icon + Feedback Icon

Your feedback is important for us,thank you
for reporting.
Our team will look into this and necessary
action will be taken soon.

Hi {{.SenderName}} diff --git a/internal/app/email/templates/senderAppreciation.html b/internal/app/email/templates/senderAppreciation.html index 2170f0c..335f723 100644 --- a/internal/app/email/templates/senderAppreciation.html +++ b/internal/app/email/templates/senderAppreciation.html @@ -16,7 +16,7 @@

Peerly

- Thank You + Thank You

Hi {{.SenderName}}

You've successfully sent appreciation to {{.ReceiverName}}.

Core Value
diff --git a/internal/app/reportAppreciations/service.go b/internal/app/reportAppreciations/service.go index e5c9543..00d11f2 100644 --- a/internal/app/reportAppreciations/service.go +++ b/internal/app/reportAppreciations/service.go @@ -7,6 +7,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/email" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" + "github.com/joshsoftware/peerly-backend/internal/pkg/config" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" @@ -231,12 +232,13 @@ func (rs *service) DeleteAppreciation(ctx context.Context, reqData dto.Moderatio } templateData := dto.DeleteAppreciationMail{ - ModeratorComment: reqData.ModeratorComment, - AppreciationBy: sender.FirstName + " " + sender.LastName, - AppreciationTo: receiver.FirstName + " " + receiver.LastName, - ReportingComment: appreciation.ReportingComment, - AppreciationDesc: appreciation.AppreciationDesc, - Date: appreciation.CreatedAt, + ModeratorComment: reqData.ModeratorComment, + AppreciationBy: sender.FirstName + " " + sender.LastName, + AppreciationTo: receiver.FirstName + " " + receiver.LastName, + ReportingComment: appreciation.ReportingComment, + AppreciationDesc: appreciation.AppreciationDesc, + Date: appreciation.CreatedAt, + ReportIconImageURL: fmt.Sprint(config.PeerlyBaseUrl() + constants.CheckIconImagePath), } fmt.Println("Reporter mail: ", reporter.Email) @@ -294,14 +296,16 @@ func sendReportEmail(senderEmail string, senderFirstName string, senderLastName ReportingComment string AppreciationSenderName string AppreciationReceiverName string + ReportIconImageURL string }{ SenderName: fmt.Sprint(senderFirstName, " ", senderLastName), ReportingComment: reportingComment, AppreciationSenderName: fmt.Sprint(apprSenderFirstName, " ", apprSenderLastName), AppreciationReceiverName: fmt.Sprint(apprReceiverFirstName, " ", apprReceiverLastName), + ReportIconImageURL: fmt.Sprint(config.PeerlyBaseUrl() + constants.CheckIconImagePath), } - logger.Info(ctx,"report sender email: ---------> ",senderEmail) + logger.Info(ctx, "report sender email: ---------> ", senderEmail) mailReq := email.NewMail([]string{senderEmail}, []string{"dl_peerly.support@joshsoftware.com"}, []string{}, "🙏 Thanks for Your Feedback! We’re On It! 🔧") mailReq.ParseTemplate("./internal/app/email/templates/reportAppreciation.html", templateData) err := mailReq.Send() @@ -312,7 +316,6 @@ func sendReportEmail(senderEmail string, senderFirstName string, senderLastName return nil } - func (rs *service) ResolveAppreciation(ctx context.Context, reqData dto.ModerationReq) (err error) { moderatorId := ctx.Value(constants.UserId) fmt.Printf("moderatorId: %T", moderatorId) @@ -383,16 +386,16 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str ctx := context.Background() ctx = context.WithValue(ctx, constants.RequestID, "deleteEmail") - logger.Info(ctx,"reporter email: ---------> ", reporterEmail) + logger.Info(ctx, "reporter email: ---------> ", reporterEmail) mailReq := email.NewMail([]string{reporterEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/deleteAppreciation.html", templateData) err := mailReq.Send() if err != nil { - logger.Errorf(context.Background(),"err: %v", err) + logger.Errorf(context.Background(), "err: %v", err) return err } - logger.Info(ctx,"sender email: ---------> ", reporterEmail) + logger.Info(ctx, "sender email: ---------> ", reporterEmail) mailReq = email.NewMail([]string{senderEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/senderDeleteEmail.html", templateData) err = mailReq.Send() @@ -401,12 +404,12 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str return err } - logger.Info(ctx,"receiver email: ---------> ", reporterEmail) + logger.Info(ctx, "receiver email: ---------> ", reporterEmail) mailReq = email.NewMail([]string{receiverEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/receiverDeleteEmail.html", templateData) err = mailReq.Send() if err != nil { - logger.Errorf(ctx,"err: %v", err) + logger.Errorf(ctx, "err: %v", err) return err } @@ -415,7 +418,7 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str func sendResolveEmail(senderEmail string, templateData dto.ResolveAppreciationMail) error { - logger.Info(context.Background(),"report sender email: ---------> ", senderEmail) + logger.Info(context.Background(), "report sender email: ---------> ", senderEmail) mailReq := email.NewMail([]string{senderEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/resolveAppreciation.html", templateData) err := mailReq.Send() diff --git a/internal/pkg/constants/system.go b/internal/pkg/constants/system.go index 9a005ae..cb85826 100644 --- a/internal/pkg/constants/system.go +++ b/internal/pkg/constants/system.go @@ -1,5 +1,11 @@ package constants +import ( + "fmt" + + "github.com/joshsoftware/peerly-backend/internal/pkg/config" +) + type UserIdCtxKey string type RoleCtxKey string type RequestIDCtxKey string @@ -56,3 +62,15 @@ const ( ) const DefaultOrgID = 1 + +// EmailTemplate Icon url +const ( + BronzeBadgeIconImagePath = "/peerly/assets/bronzeBadge.png" + SilverBadgeIconImagePath = "/peerly/assets/silverBadge.png" + GoldBadgeIconImagePath = "/peerly/assets/goldBadge.png" + PlatinumIconImagePath = "/peerly/assets/platinumBadge.png" + CheckIconImagePath = "/peerly/assets/checkIcon.png" + ClosedEnvelopeIconImagePath = "/peerly/assets/closedEnvelopeIcon.png" + OpenEnvelopeIconImagePath = "/peerly/assets/openEnvelopeIcon.png" + RewardQuotaRenewalIconImagePath = "/peerly/assets/rewardQuotaRenewal.png" +) diff --git a/internal/pkg/dto/reportAppreciations.go b/internal/pkg/dto/reportAppreciations.go index 58899d0..2c1dfdd 100644 --- a/internal/pkg/dto/reportAppreciations.go +++ b/internal/pkg/dto/reportAppreciations.go @@ -68,12 +68,13 @@ type ModerationReq struct { } type DeleteAppreciationMail struct { - ModeratorComment string - AppreciationBy string - AppreciationTo string - ReportingComment string - AppreciationDesc string - Date int64 + ModeratorComment string + AppreciationBy string + AppreciationTo string + ReportingComment string + AppreciationDesc string + Date int64 + ReportIconImageURL string } type ResolveAppreciationMail struct { From d128713d9240686e947b1f5516356ad782812673 Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Wed, 28 Aug 2024 13:26:04 +0530 Subject: [PATCH 17/22] [feature/addEmailAndNotification] import cycle removed --- .gitignore | 3 +- internal/app/appreciation/service.go | 13 +++++--- internal/app/email/templates/badge.html | 2 +- .../email/templates/deleteAppreciation.html | 2 +- .../email/templates/receiverAppreciation.html | 2 +- .../email/templates/reportAppreciation.html | 2 +- .../email/templates/senderAppreciation.html | 2 +- internal/app/reportAppreciations/service.go | 31 ++++++++++--------- internal/pkg/constants/system.go | 13 ++++++++ internal/pkg/dto/reportAppreciations.go | 13 ++++---- 10 files changed, 53 insertions(+), 30 deletions(-) diff --git a/.gitignore b/.gitignore index e95eeb1..0c8b6cf 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,5 @@ go.work.sum .env .vscode -serviceAccountKey.json \ No newline at end of file +serviceAccountKey.json +/logs/* \ No newline at end of file diff --git a/internal/app/appreciation/service.go b/internal/app/appreciation/service.go index 15988ee..170b4b2 100644 --- a/internal/app/appreciation/service.go +++ b/internal/app/appreciation/service.go @@ -8,6 +8,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/notification" user "github.com/joshsoftware/peerly-backend/internal/app/users" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" + "github.com/joshsoftware/peerly-backend/internal/pkg/config" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" "github.com/joshsoftware/peerly-backend/internal/pkg/utils" @@ -227,12 +228,16 @@ func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail Description string CoreValueName string CoreValueBackgroundColor string + ReceiverIconImageURL string + SenderIconImageURL string }{ SenderName: fmt.Sprint(emailData.SenderFirstName, " ", emailData.SenderLastName), ReceiverName: fmt.Sprint(emailData.ReceiverFirstName, " ", emailData.ReceiverLastName), Description: emailData.Description, CoreValueName: emailData.CoreValueName, CoreValueBackgroundColor: utils.GetCoreValueBackgroundColor(emailData.CoreValueName), + ReceiverIconImageURL: fmt.Sprint(config.PeerlyBaseUrl()+constants.ClosedEnvelopeIconImagePath), + SenderIconImageURL: fmt.Sprint(config.PeerlyBaseUrl()+constants.OpenEnvelopeIconImagePath), } logger.Info(context.Background(),"appreciation sender email: -----------> ",senderEmail) @@ -302,13 +307,13 @@ func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repositor var badgeImageUrl string switch userBadgeDetail.BadgeName.String { case "Bronze": - badgeImageUrl = "bronzeBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.BronzeBadgeIconImagePath) case "Silver": - badgeImageUrl = "silverBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.SilverBadgeIconImagePath) case "Gold": - badgeImageUrl = "goldBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.GoldBadgeIconImagePath) case "Platinum": - badgeImageUrl = "platinumBadge" + badgeImageUrl = fmt.Sprint(config.PeerlyBaseUrl()+constants.PlatinumIconImagePath) } // repository.UserBadgeDetails diff --git a/internal/app/email/templates/badge.html b/internal/app/email/templates/badge.html index 9d50d96..b894a29 100644 --- a/internal/app/email/templates/badge.html +++ b/internal/app/email/templates/badge.html @@ -16,7 +16,7 @@

Peerly

- Badge Image + Badge Image

Hi {{.EmployeeName}}

Congratulations!
You have achieved the {{.BadgeName}} badge for
accumulating {{.AppreciationPoints}} points.

diff --git a/internal/app/email/templates/deleteAppreciation.html b/internal/app/email/templates/deleteAppreciation.html index 2730ba4..67cf6aa 100644 --- a/internal/app/email/templates/deleteAppreciation.html +++ b/internal/app/email/templates/deleteAppreciation.html @@ -25,7 +25,7 @@ style="background-color: #F5F8FF; padding: 40px 20px; text-align: center; color: #000000;">

Peerly

- appreciation

diff --git a/internal/app/email/templates/receiverAppreciation.html b/internal/app/email/templates/receiverAppreciation.html index 515f2b2..1c134b6 100644 --- a/internal/app/email/templates/receiverAppreciation.html +++ b/internal/app/email/templates/receiverAppreciation.html @@ -16,7 +16,7 @@

Peerly

- appreciation + appreciation

Bravo!
You have received a deserved
word of appreciation.
Keep inspiring those around you!

{{.SenderName}} appreciated you
Core Value
diff --git a/internal/app/email/templates/reportAppreciation.html b/internal/app/email/templates/reportAppreciation.html index 1cb16c2..975acec 100644 --- a/internal/app/email/templates/reportAppreciation.html +++ b/internal/app/email/templates/reportAppreciation.html @@ -16,7 +16,7 @@

Peerly

- Feedback Icon + Feedback Icon

Your feedback is important for us,thank you
for reporting.
Our team will look into this and necessary
action will be taken soon.

Hi {{.SenderName}} diff --git a/internal/app/email/templates/senderAppreciation.html b/internal/app/email/templates/senderAppreciation.html index 2170f0c..335f723 100644 --- a/internal/app/email/templates/senderAppreciation.html +++ b/internal/app/email/templates/senderAppreciation.html @@ -16,7 +16,7 @@

Peerly

- Thank You + Thank You

Hi {{.SenderName}}

You've successfully sent appreciation to {{.ReceiverName}}.

Core Value
diff --git a/internal/app/reportAppreciations/service.go b/internal/app/reportAppreciations/service.go index e5c9543..00d11f2 100644 --- a/internal/app/reportAppreciations/service.go +++ b/internal/app/reportAppreciations/service.go @@ -7,6 +7,7 @@ import ( "github.com/joshsoftware/peerly-backend/internal/app/email" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" + "github.com/joshsoftware/peerly-backend/internal/pkg/config" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" @@ -231,12 +232,13 @@ func (rs *service) DeleteAppreciation(ctx context.Context, reqData dto.Moderatio } templateData := dto.DeleteAppreciationMail{ - ModeratorComment: reqData.ModeratorComment, - AppreciationBy: sender.FirstName + " " + sender.LastName, - AppreciationTo: receiver.FirstName + " " + receiver.LastName, - ReportingComment: appreciation.ReportingComment, - AppreciationDesc: appreciation.AppreciationDesc, - Date: appreciation.CreatedAt, + ModeratorComment: reqData.ModeratorComment, + AppreciationBy: sender.FirstName + " " + sender.LastName, + AppreciationTo: receiver.FirstName + " " + receiver.LastName, + ReportingComment: appreciation.ReportingComment, + AppreciationDesc: appreciation.AppreciationDesc, + Date: appreciation.CreatedAt, + ReportIconImageURL: fmt.Sprint(config.PeerlyBaseUrl() + constants.CheckIconImagePath), } fmt.Println("Reporter mail: ", reporter.Email) @@ -294,14 +296,16 @@ func sendReportEmail(senderEmail string, senderFirstName string, senderLastName ReportingComment string AppreciationSenderName string AppreciationReceiverName string + ReportIconImageURL string }{ SenderName: fmt.Sprint(senderFirstName, " ", senderLastName), ReportingComment: reportingComment, AppreciationSenderName: fmt.Sprint(apprSenderFirstName, " ", apprSenderLastName), AppreciationReceiverName: fmt.Sprint(apprReceiverFirstName, " ", apprReceiverLastName), + ReportIconImageURL: fmt.Sprint(config.PeerlyBaseUrl() + constants.CheckIconImagePath), } - logger.Info(ctx,"report sender email: ---------> ",senderEmail) + logger.Info(ctx, "report sender email: ---------> ", senderEmail) mailReq := email.NewMail([]string{senderEmail}, []string{"dl_peerly.support@joshsoftware.com"}, []string{}, "🙏 Thanks for Your Feedback! We’re On It! 🔧") mailReq.ParseTemplate("./internal/app/email/templates/reportAppreciation.html", templateData) err := mailReq.Send() @@ -312,7 +316,6 @@ func sendReportEmail(senderEmail string, senderFirstName string, senderLastName return nil } - func (rs *service) ResolveAppreciation(ctx context.Context, reqData dto.ModerationReq) (err error) { moderatorId := ctx.Value(constants.UserId) fmt.Printf("moderatorId: %T", moderatorId) @@ -383,16 +386,16 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str ctx := context.Background() ctx = context.WithValue(ctx, constants.RequestID, "deleteEmail") - logger.Info(ctx,"reporter email: ---------> ", reporterEmail) + logger.Info(ctx, "reporter email: ---------> ", reporterEmail) mailReq := email.NewMail([]string{reporterEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/deleteAppreciation.html", templateData) err := mailReq.Send() if err != nil { - logger.Errorf(context.Background(),"err: %v", err) + logger.Errorf(context.Background(), "err: %v", err) return err } - logger.Info(ctx,"sender email: ---------> ", reporterEmail) + logger.Info(ctx, "sender email: ---------> ", reporterEmail) mailReq = email.NewMail([]string{senderEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/senderDeleteEmail.html", templateData) err = mailReq.Send() @@ -401,12 +404,12 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str return err } - logger.Info(ctx,"receiver email: ---------> ", reporterEmail) + logger.Info(ctx, "receiver email: ---------> ", reporterEmail) mailReq = email.NewMail([]string{receiverEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/receiverDeleteEmail.html", templateData) err = mailReq.Send() if err != nil { - logger.Errorf(ctx,"err: %v", err) + logger.Errorf(ctx, "err: %v", err) return err } @@ -415,7 +418,7 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str func sendResolveEmail(senderEmail string, templateData dto.ResolveAppreciationMail) error { - logger.Info(context.Background(),"report sender email: ---------> ", senderEmail) + logger.Info(context.Background(), "report sender email: ---------> ", senderEmail) mailReq := email.NewMail([]string{senderEmail}, []string{}, []string{}, "Results of reported appreciation") mailReq.ParseTemplate("./internal/app/email/templates/resolveAppreciation.html", templateData) err := mailReq.Send() diff --git a/internal/pkg/constants/system.go b/internal/pkg/constants/system.go index 9a005ae..a8c61f7 100644 --- a/internal/pkg/constants/system.go +++ b/internal/pkg/constants/system.go @@ -1,5 +1,6 @@ package constants + type UserIdCtxKey string type RoleCtxKey string type RequestIDCtxKey string @@ -56,3 +57,15 @@ const ( ) const DefaultOrgID = 1 + +// EmailTemplate Icon url +const ( + BronzeBadgeIconImagePath = "/peerly/assets/bronzeBadge.png" + SilverBadgeIconImagePath = "/peerly/assets/silverBadge.png" + GoldBadgeIconImagePath = "/peerly/assets/goldBadge.png" + PlatinumIconImagePath = "/peerly/assets/platinumBadge.png" + CheckIconImagePath = "/peerly/assets/checkIcon.png" + ClosedEnvelopeIconImagePath = "/peerly/assets/closedEnvelopeIcon.png" + OpenEnvelopeIconImagePath = "/peerly/assets/openEnvelopeIcon.png" + RewardQuotaRenewalIconImagePath = "/peerly/assets/rewardQuotaRenewal.png" +) diff --git a/internal/pkg/dto/reportAppreciations.go b/internal/pkg/dto/reportAppreciations.go index 58899d0..2c1dfdd 100644 --- a/internal/pkg/dto/reportAppreciations.go +++ b/internal/pkg/dto/reportAppreciations.go @@ -68,12 +68,13 @@ type ModerationReq struct { } type DeleteAppreciationMail struct { - ModeratorComment string - AppreciationBy string - AppreciationTo string - ReportingComment string - AppreciationDesc string - Date int64 + ModeratorComment string + AppreciationBy string + AppreciationTo string + ReportingComment string + AppreciationDesc string + Date int64 + ReportIconImageURL string } type ResolveAppreciationMail struct { From dd2acfc3837a175619b0d39c956d4828bc99818c Mon Sep 17 00:00:00 2001 From: Sharyu Marwadi Date: Thu, 29 Aug 2024 13:05:02 +0530 Subject: [PATCH 18/22] [fix/AdminPermissions] route permissions updated --- internal/api/router.go | 52 +++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/internal/api/router.go b/internal/api/router.go index 3e3bce8..243fd2b 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -27,13 +27,13 @@ func NewRouter(deps app.Dependencies) *mux.Router { v1 := fmt.Sprintf("application/vnd.%s.v1", config.AppName()) //corevalues - peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(getCoreValueHandler(deps.CoreValueService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(getCoreValueHandler(deps.CoreValueService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/core_values", middleware.JwtAuthMiddleware(listCoreValuesHandler(deps.CoreValueService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/core_values", middleware.JwtAuthMiddleware(listCoreValuesHandler(deps.CoreValueService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/core_values", middleware.JwtAuthMiddleware(createCoreValueHandler(deps.CoreValueService), []string{constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/core_values", middleware.JwtAuthMiddleware(createCoreValueHandler(deps.CoreValueService), constants.Admin)).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(updateCoreValueHandler(deps.CoreValueService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/core_values/{id:[0-9]+}", middleware.JwtAuthMiddleware(updateCoreValueHandler(deps.CoreValueService), constants.Admin)).Methods(http.MethodPut).Headers(versionHeader, v1) //users @@ -45,60 +45,60 @@ func NewRouter(deps app.Dependencies) *mux.Router { peerlySubrouter.Handle("/intranet/users", listIntranetUsersHandler(deps.UserService)).Methods(http.MethodGet) - peerlySubrouter.Handle("/users", middleware.JwtAuthMiddleware(listUsersHandler(deps.UserService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/users", middleware.JwtAuthMiddleware(listUsersHandler(deps.UserService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/user_profile", middleware.JwtAuthMiddleware(getUserByIdHandler(deps.UserService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/user_profile", middleware.JwtAuthMiddleware(getUserByIdHandler(deps.UserService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/users/active", getActiveUserListHandler(deps.UserService)).Methods(http.MethodGet) + peerlySubrouter.Handle("/users/active", middleware.JwtAuthMiddleware(getActiveUserListHandler(deps.UserService), constants.User)).Methods(http.MethodGet) - peerlySubrouter.Handle("/users/top10", middleware.JwtAuthMiddleware(getTop10UserHandler(deps.UserService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/users/top10", middleware.JwtAuthMiddleware(getTop10UserHandler(deps.UserService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/admin/notification", middleware.JwtAuthMiddleware(adminNotificationHandler(deps.UserService), []string{constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/admin/notification", middleware.JwtAuthMiddleware(adminNotificationHandler(deps.UserService), constants.Admin)).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/admin/appreciation_report", middleware.JwtAuthMiddleware(appreciationReportHandler(deps.UserService, deps.AppreciationService), []string{constants.AdminRole})).Methods(http.MethodGet) + peerlySubrouter.Handle("/admin/appreciation_report", middleware.JwtAuthMiddleware(appreciationReportHandler(deps.UserService, deps.AppreciationService), constants.Admin)).Methods(http.MethodGet) - peerlySubrouter.Handle("/admin/reported_appreciation_report", middleware.JwtAuthMiddleware(reportedAppreciationReportHandler(deps.UserService, deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodGet) + peerlySubrouter.Handle("/admin/reported_appreciation_report", middleware.JwtAuthMiddleware(reportedAppreciationReportHandler(deps.UserService, deps.ReportAppreciationService), constants.Admin)).Methods(http.MethodGet) //appreciations - peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(getAppreciationByIDHandler(deps.AppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(getAppreciationByIDHandler(deps.AppreciationService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/appreciations", middleware.JwtAuthMiddleware(listAppreciationsHandler(deps.AppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/appreciations", middleware.JwtAuthMiddleware(listAppreciationsHandler(deps.AppreciationService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(deleteAppreciationHandler(deps.AppreciationService), []string{constants.AdminRole})).Methods(http.MethodDelete).Headers(versionHeader, v1) + peerlySubrouter.Handle("/appreciations/{id:[0-9]+}", middleware.JwtAuthMiddleware(deleteAppreciationHandler(deps.AppreciationService), constants.Admin)).Methods(http.MethodDelete).Headers(versionHeader, v1) - peerlySubrouter.Handle("/appreciations", middleware.JwtAuthMiddleware(createAppreciationHandler(deps.AppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/appreciations", middleware.JwtAuthMiddleware(createAppreciationHandler(deps.AppreciationService), constants.User)).Methods(http.MethodPost).Headers(versionHeader, v1) //report appreciation - peerlySubrouter.Handle("/report_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(reportAppreciationHandler(deps.ReportAppreciationService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/report_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(reportAppreciationHandler(deps.ReportAppreciationService), constants.User)).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/report_appreciations", middleware.JwtAuthMiddleware(listReportedAppreciations(deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/report_appreciations", middleware.JwtAuthMiddleware(listReportedAppreciations(deps.ReportAppreciationService), constants.Admin)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/moderate_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(moderateAppreciation(deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/moderate_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(moderateAppreciation(deps.ReportAppreciationService), constants.Admin)).Methods(http.MethodPut).Headers(versionHeader, v1) - peerlySubrouter.Handle("/resolve_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(resolveAppreciation(deps.ReportAppreciationService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/resolve_appreciation/{id:[0-9]+}", middleware.JwtAuthMiddleware(resolveAppreciation(deps.ReportAppreciationService), constants.Admin)).Methods(http.MethodPut).Headers(versionHeader, v1) //grades - peerlySubrouter.Handle("/grades", middleware.JwtAuthMiddleware(listGradesHandler(deps.GradeService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/grades", middleware.JwtAuthMiddleware(listGradesHandler(deps.GradeService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/grades/{id:[0-9]+}", middleware.JwtAuthMiddleware(editGradesHandler(deps.GradeService), []string{constants.AdminRole})).Methods(http.MethodPatch).Headers(versionHeader, v1) + peerlySubrouter.Handle("/grades/{id:[0-9]+}", middleware.JwtAuthMiddleware(editGradesHandler(deps.GradeService), constants.Admin)).Methods(http.MethodPatch).Headers(versionHeader, v1) // reward appreciation - peerlySubrouter.Handle("/reward/{id:[0-9]+}", middleware.JwtAuthMiddleware(giveRewardHandler(deps.RewardService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodPost).Headers(versionHeader, v1) + peerlySubrouter.Handle("/reward/{id:[0-9]+}", middleware.JwtAuthMiddleware(giveRewardHandler(deps.RewardService), constants.User)).Methods(http.MethodPost).Headers(versionHeader, v1) // organization config - peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(getOrganizationConfigHandler(deps.OrganizationConfigService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(getOrganizationConfigHandler(deps.OrganizationConfigService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) //organization config data inserted by seed file // peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(createOrganizationConfigHandler(deps.OrganizationConfigService),[]string{constants.UserRole})).Methods(http.MethodPost).Headers(versionHeader, v1) - peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(updateOrganizationConfigHandler(deps.OrganizationConfigService), []string{constants.AdminRole})).Methods(http.MethodPut).Headers(versionHeader, v1) + peerlySubrouter.Handle("/organizationconfig", middleware.JwtAuthMiddleware(updateOrganizationConfigHandler(deps.OrganizationConfigService), constants.Admin)).Methods(http.MethodPut).Headers(versionHeader, v1) //badges - peerlySubrouter.Handle("/badges", middleware.JwtAuthMiddleware(listBadgesHandler(deps.BadgeService), []string{constants.UserRole, constants.AdminRole})).Methods(http.MethodGet).Headers(versionHeader, v1) + peerlySubrouter.Handle("/badges", middleware.JwtAuthMiddleware(listBadgesHandler(deps.BadgeService), constants.User)).Methods(http.MethodGet).Headers(versionHeader, v1) - peerlySubrouter.Handle("/badges/{id:[0-9]+}", middleware.JwtAuthMiddleware(editBadgesHandler(deps.BadgeService), []string{constants.AdminRole})).Methods(http.MethodPatch).Headers(versionHeader, v1) + peerlySubrouter.Handle("/badges/{id:[0-9]+}", middleware.JwtAuthMiddleware(editBadgesHandler(deps.BadgeService), constants.Admin)).Methods(http.MethodPatch).Headers(versionHeader, v1) // No version requirement for /ping peerlySubrouter.HandleFunc("/ping", pingHandler).Methods(http.MethodGet) From 42560aab00fd6413829b0fb497ea64c23b454fd2 Mon Sep 17 00:00:00 2001 From: Sharyu Marwadi Date: Thu, 29 Aug 2024 15:33:22 +0530 Subject: [PATCH 19/22] [fix/AdminPermissions] go vet errors removed --- internal/app/appreciation/mocks/Service.go | 83 ++++++------ internal/app/appreciation/service.go | 25 ++-- internal/app/appreciation/service_test.go | 21 +-- internal/app/cronjob/cronJob.go | 5 +- .../app/reportAppreciations/service_test.go | 6 +- internal/app/reward/service_test.go | 19 ++- internal/app/users/mocks/Service.go | 81 ++++++++++++ internal/app/users/service.go | 6 +- internal/app/users/service_test.go | 20 ++- .../repository/mocks/AppreciationStorer.go | 122 ++++++++---------- .../mocks/ReportAppreciationStorer.go | 35 +++++ .../postgresdb/reportAppreciation.go | 2 +- 12 files changed, 260 insertions(+), 165 deletions(-) diff --git a/internal/app/appreciation/mocks/Service.go b/internal/app/appreciation/mocks/Service.go index b7daca4..1c8a8c2 100644 --- a/internal/app/appreciation/mocks/Service.go +++ b/internal/app/appreciation/mocks/Service.go @@ -1,13 +1,11 @@ -// Code generated by mockery v2.43.2. DO NOT EDIT. +// Code generated by mockery v1.0.0. DO NOT EDIT. package mocks -import ( - context "context" - - dto "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - mock "github.com/stretchr/testify/mock" -) +import context "context" +import dto "github.com/joshsoftware/peerly-backend/internal/pkg/dto" +import mock "github.com/stretchr/testify/mock" +import repository "github.com/joshsoftware/peerly-backend/internal/repository" // Service is an autogenerated mock type for the Service type type Service struct { @@ -18,21 +16,14 @@ type Service struct { func (_m *Service) CreateAppreciation(ctx context.Context, _a1 dto.Appreciation) (dto.Appreciation, error) { ret := _m.Called(ctx, _a1) - if len(ret) == 0 { - panic("no return value specified for CreateAppreciation") - } - var r0 dto.Appreciation - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, dto.Appreciation) (dto.Appreciation, error)); ok { - return rf(ctx, _a1) - } if rf, ok := ret.Get(0).(func(context.Context, dto.Appreciation) dto.Appreciation); ok { r0 = rf(ctx, _a1) } else { r0 = ret.Get(0).(dto.Appreciation) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, dto.Appreciation) error); ok { r1 = rf(ctx, _a1) } else { @@ -46,10 +37,6 @@ func (_m *Service) CreateAppreciation(ctx context.Context, _a1 dto.Appreciation) func (_m *Service) DeleteAppreciation(ctx context.Context, apprId int32) error { ret := _m.Called(ctx, apprId) - if len(ret) == 0 { - panic("no return value specified for DeleteAppreciation") - } - var r0 error if rf, ok := ret.Get(0).(func(context.Context, int32) error); ok { r0 = rf(ctx, apprId) @@ -64,21 +51,14 @@ func (_m *Service) DeleteAppreciation(ctx context.Context, apprId int32) error { func (_m *Service) GetAppreciationById(ctx context.Context, appreciationId int32) (dto.AppreciationResponse, error) { ret := _m.Called(ctx, appreciationId) - if len(ret) == 0 { - panic("no return value specified for GetAppreciationById") - } - var r0 dto.AppreciationResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, int32) (dto.AppreciationResponse, error)); ok { - return rf(ctx, appreciationId) - } if rf, ok := ret.Get(0).(func(context.Context, int32) dto.AppreciationResponse); ok { r0 = rf(ctx, appreciationId) } else { r0 = ret.Get(0).(dto.AppreciationResponse) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, int32) error); ok { r1 = rf(ctx, appreciationId) } else { @@ -92,21 +72,14 @@ func (_m *Service) GetAppreciationById(ctx context.Context, appreciationId int32 func (_m *Service) ListAppreciations(ctx context.Context, filter dto.AppreciationFilter) (dto.ListAppreciationsResponse, error) { ret := _m.Called(ctx, filter) - if len(ret) == 0 { - panic("no return value specified for ListAppreciations") - } - var r0 dto.ListAppreciationsResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, dto.AppreciationFilter) (dto.ListAppreciationsResponse, error)); ok { - return rf(ctx, filter) - } if rf, ok := ret.Get(0).(func(context.Context, dto.AppreciationFilter) dto.ListAppreciationsResponse); ok { r0 = rf(ctx, filter) } else { r0 = ret.Get(0).(dto.ListAppreciationsResponse) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, dto.AppreciationFilter) error); ok { r1 = rf(ctx, filter) } else { @@ -116,26 +89,42 @@ func (_m *Service) ListAppreciations(ctx context.Context, filter dto.Appreciatio return r0, r1 } -// sendAppreciationEmail provides a mock function with given fields: to, sub, maildata -func (_m *Service) sendAppreciationEmail(to string, sub string, maildata string) error { - ret := _m.Called(to, sub, maildata) +// UpdateAppreciation provides a mock function with given fields: ctx +func (_m *Service) UpdateAppreciation(ctx context.Context) (bool, error) { + ret := _m.Called(ctx) - if len(ret) == 0 { - panic("no return value specified for sendAppreciationEmail") + var r0 bool + if rf, ok := ret.Get(0).(func(context.Context) bool); ok { + r0 = rf(ctx) + } else { + r0 = ret.Get(0).(bool) } - var r0 error - if rf, ok := ret.Get(0).(func(string, string, string) error); ok { - r0 = rf(to, sub, maildata) + var r1 error + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) } else { - r0 = ret.Error(0) + r1 = ret.Error(1) } - return r0 + return r0, r1 +} + +// sendAppreciationNotificationToAll provides a mock function with given fields: ctx, appr +func (_m *Service) sendAppreciationNotificationToAll(ctx context.Context, appr repository.AppreciationResponse) { + _m.Called(ctx, appr) +} + +// sendAppreciationNotificationToReceiver provides a mock function with given fields: ctx, appr +func (_m *Service) sendAppreciationNotificationToReceiver(ctx context.Context, appr repository.AppreciationResponse) { + _m.Called(ctx, appr) +} + +// sendEmailForBadgeAllocation provides a mock function with given fields: userBadgeDetails +func (_m *Service) sendEmailForBadgeAllocation(userBadgeDetails []repository.UserBadgeDetails) { + _m.Called(userBadgeDetails) } -// NewService creates a new instance of Service. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. func NewService(t interface { mock.TestingT Cleanup(func()) diff --git a/internal/app/appreciation/service.go b/internal/app/appreciation/service.go index b0bfdf7..098a63e 100644 --- a/internal/app/appreciation/service.go +++ b/internal/app/appreciation/service.go @@ -28,9 +28,6 @@ type Service interface { ListAppreciations(ctx context.Context, filter dto.AppreciationFilter) (dto.ListAppreciationsResponse, error) DeleteAppreciation(ctx context.Context, apprId int32) error UpdateAppreciation(ctx context.Context) (bool, error) - sendAppreciationNotificationToReceiver(ctx context.Context, appr repository.AppreciationResponse) - sendAppreciationNotificationToAll(ctx context.Context, appr repository.AppreciationResponse) - sendEmailForBadgeAllocation(userBadgeDetails []repository.UserBadgeDetails) } func NewService(appreciationRepo repository.AppreciationStorer, coreValuesRepo repository.CoreValueStorer, userRepo repository.UserStorer) Service { @@ -120,17 +117,17 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto UserId: sender, QuaterTimeStamp: quaterTimeStamp, } - senderInfo,err := apprSvc.userRepo.GetUserById(ctx,reqGetUserById) - if err != nil{ + senderInfo, err := apprSvc.userRepo.GetUserById(ctx, reqGetUserById) + if err != nil { logger.Info("error in getting create appreciation sender info") } reqGetUserById.UserId = appreciation.Receiver - receiverInfo,err := apprSvc.userRepo.GetUserById(ctx,reqGetUserById) - if err != nil{ + receiverInfo, err := apprSvc.userRepo.GetUserById(ctx, reqGetUserById) + if err != nil { logger.Info("error in getting create appreciation sender info") } - err = sendAppreciationEmail(apprInfo,senderInfo.Email,receiverInfo.Email) + err = sendAppreciationEmail(apprInfo, senderInfo.Email, receiverInfo.Email) apprSvc.sendAppreciationNotificationToReceiver(ctx, apprInfo) apprSvc.sendAppreciationNotificationToAll(ctx, apprInfo) return res, nil @@ -210,25 +207,25 @@ func (apprSvc *service) UpdateAppreciation(ctx context.Context) (bool, error) { return true, nil } -func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail string,receiverEmail string) error { +func sendAppreciationEmail(emailData repository.AppreciationResponse, senderEmail string, receiverEmail string) error { // Plain text content plainTextContent := "Samnit " + "123456" templateData := struct { SenderName string - ReceiverName string + ReceiverName string Description string CoreValueName string }{ SenderName: fmt.Sprint(emailData.SenderFirstName, " ", emailData.SenderLastName), - ReceiverName: fmt.Sprint(emailData.ReceiverFirstName, " ", emailData.ReceiverLastName), + ReceiverName: fmt.Sprint(emailData.ReceiverFirstName, " ", emailData.ReceiverLastName), Description: emailData.Description, CoreValueName: emailData.CoreValueName, } - logger.Info("appreciation sender email: -----------> ",senderEmail) - logger.Info("appreciation receiver email: -----------> ",receiverEmail) - mailReq := email.NewMail([]string{receiverEmail}, []string{senderEmail}, []string{}, fmt.Sprintf("%s %s appreciated %s %s",emailData.SenderFirstName,emailData.SenderLastName,emailData.ReceiverFirstName,emailData.ReceiverLastName)) + logger.Info("appreciation sender email: -----------> ", senderEmail) + logger.Info("appreciation receiver email: -----------> ", receiverEmail) + mailReq := email.NewMail([]string{receiverEmail}, []string{senderEmail}, []string{}, fmt.Sprintf("%s %s appreciated %s %s", emailData.SenderFirstName, emailData.SenderLastName, emailData.ReceiverFirstName, emailData.ReceiverLastName)) err := mailReq.ParseTemplate("./internal/app/email/templates/createAppreciation.html", templateData) if err != nil { logger.Errorf("err in creating html file : %v", err) diff --git a/internal/app/appreciation/service_test.go b/internal/app/appreciation/service_test.go index 5a3a28a..bbd0526 100644 --- a/internal/app/appreciation/service_test.go +++ b/internal/app/appreciation/service_test.go @@ -18,7 +18,8 @@ import ( func TestCreateAppreciation(t *testing.T) { appreciationRepo := mocks.NewAppreciationStorer(t) corevalueRepo := mocks.NewCoreValueStorer(t) - service := NewService(appreciationRepo, corevalueRepo) + userRepo := mocks.NewUserStorer(t) + service := NewService(appreciationRepo, corevalueRepo, userRepo) tests := []struct { name string @@ -41,11 +42,11 @@ func TestCreateAppreciation(t *testing.T) { apprMock.On("IsUserPresent", mock.Anything, nil, int64(2)).Return(true, nil).Once() apprMock.On("BeginTx", mock.Anything).Return(tx, nil).Once() coreValueRepo.On("GetCoreValue", mock.Anything, int64(1)).Return(repository.CoreValue{ - ID: 1, - Name:"Trust", - Description:"We foster trust by being transparent,reliable, and accountable in all our actions", - ParentCoreValueID:sql.NullInt64{Int64:int64(0),Valid: true}, - }, nil).Once() + ID: 1, + Name: "Trust", + Description: "We foster trust by being transparent,reliable, and accountable in all our actions", + ParentCoreValueID: sql.NullInt64{Int64: int64(0), Valid: true}, + }, nil).Once() apprMock.On("CreateAppreciation", mock.Anything, tx, mock.Anything).Return(repository.Appreciation{ID: 1}, nil).Once() apprMock.On("HandleTransaction", mock.Anything, tx, true).Return(nil).Once() }, @@ -110,7 +111,9 @@ func TestCreateAppreciation(t *testing.T) { func TestGetAppreciationById(t *testing.T) { appreciationRepo := mocks.NewAppreciationStorer(t) - service := NewService(appreciationRepo, nil) + coreVaueRepo := mocks.NewCoreValueStorer(t) + userRepo := mocks.NewUserStorer(t) + service := NewService(appreciationRepo, coreVaueRepo, userRepo) tests := []struct { name string @@ -210,7 +213,9 @@ func TestGetAppreciationById(t *testing.T) { func TestValidateAppreciation(t *testing.T) { appreciationRepo := mocks.NewAppreciationStorer(t) - service := NewService(appreciationRepo, nil) + coreVaueRepo := mocks.NewCoreValueStorer(t) + userRepo := mocks.NewUserStorer(t) + service := NewService(appreciationRepo, coreVaueRepo, userRepo) tests := []struct { name string diff --git a/internal/app/cronjob/cronJob.go b/internal/app/cronjob/cronJob.go index 139dd43..5f1cbf4 100644 --- a/internal/app/cronjob/cronJob.go +++ b/internal/app/cronjob/cronJob.go @@ -7,6 +7,7 @@ import ( "github.com/go-co-op/gocron/v2" logger "github.com/sirupsen/logrus" ) + type Job interface { // Schedules the cron job Schedule() @@ -29,9 +30,9 @@ func (cron *CronJob) Execute(task func(context.Context)) { ctx := context.Background() startTime := time.Now() - logger.Info("cron job Started at %s", startTime.Format("2006-01-02 15:04:05")) + logger.Infof("cron job Started at %s", startTime.Format("2006-01-02 15:04:05")) defer func() { - logger.Info("cron job done %s, took: %v", cron.name, time.Since(startTime)) + logger.Infof("cron job done %s, took: %v", cron.name, time.Since(startTime)) }() // Channel to check if signal task is completed diff --git a/internal/app/reportAppreciations/service_test.go b/internal/app/reportAppreciations/service_test.go index dc8c324..8df71d4 100644 --- a/internal/app/reportAppreciations/service_test.go +++ b/internal/app/reportAppreciations/service_test.go @@ -15,7 +15,8 @@ import ( func TestReportAppreciation(t *testing.T) { reportAppreciationRepo := mocks.NewReportAppreciationStorer(t) userRepo := mocks.NewUserStorer(t) - service := NewService(reportAppreciationRepo, userRepo) + appreciationRepo := mocks.NewAppreciationStorer(t) + service := NewService(reportAppreciationRepo, userRepo, appreciationRepo) tests := []struct { name string @@ -140,7 +141,8 @@ func TestReportAppreciation(t *testing.T) { func TestListReportedAppreciations(t *testing.T) { reportAppreciationRepo := mocks.NewReportAppreciationStorer(t) userRepo := mocks.NewUserStorer(t) - service := NewService(reportAppreciationRepo, userRepo) + appreciationRepo := mocks.NewAppreciationStorer(t) + service := NewService(reportAppreciationRepo, userRepo, appreciationRepo) tests := []struct { name string diff --git a/internal/app/reward/service_test.go b/internal/app/reward/service_test.go index b6ec824..95cf11a 100644 --- a/internal/app/reward/service_test.go +++ b/internal/app/reward/service_test.go @@ -15,7 +15,6 @@ import ( "github.com/stretchr/testify/mock" ) - func TestGiveReward(t *testing.T) { tests := []struct { name string @@ -34,7 +33,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(false, nil) rwrdMock.On("BeginTx", mock.Anything).Return(nil, nil) @@ -66,7 +65,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 1, ReceiverId: 2}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) }, isErrorExpected: true, expectedResult: dto.Reward{}, @@ -80,7 +79,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 1}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) }, isErrorExpected: true, expectedResult: dto.Reward{}, @@ -94,7 +93,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(false, nil) }, isErrorExpected: true, @@ -109,7 +108,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(true, nil) }, @@ -125,7 +124,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(false, nil) rwrdMock.On("BeginTx", mock.Anything).Return(nil, apperrors.InternalServer) @@ -142,7 +141,7 @@ func TestGiveReward(t *testing.T) { Point: 10, }, setup: func(rwrdMock *mocks.RewardStorer, apprMock *mocks.AppreciationStorer) { - apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationInfo{SenderId: 2, ReceiverId: 3}, nil) + apprMock.On("GetAppreciationById", mock.Anything, nil, 1).Return(repository.AppreciationResponse{SenderID: 2, ReceiverID: 3}, nil) rwrdMock.On("UserHasRewardQuota", mock.Anything, nil, int64(1), int64(10)).Return(true, nil) rwrdMock.On("IsUserRewardForAppreciationPresent", mock.Anything, nil, int64(1), int64(1)).Return(false, nil) rwrdMock.On("BeginTx", mock.Anything).Return(nil, nil) @@ -166,8 +165,8 @@ func TestGiveReward(t *testing.T) { } service := &service{ - rewardRepo: rwrdMock, - appreciationRepo: apprMock, + rewardRepo: rwrdMock, + appreciationRepo: apprMock, } result, err := service.GiveReward(test.ctx, test.rewardReq) diff --git a/internal/app/users/mocks/Service.go b/internal/app/users/mocks/Service.go index 4c360d1..801452c 100644 --- a/internal/app/users/mocks/Service.go +++ b/internal/app/users/mocks/Service.go @@ -11,6 +11,48 @@ type Service struct { mock.Mock } +// AdminLogin provides a mock function with given fields: ctx, loginReq +func (_m *Service) AdminLogin(ctx context.Context, loginReq dto.AdminLoginReq) (dto.LoginUserResp, error) { + ret := _m.Called(ctx, loginReq) + + var r0 dto.LoginUserResp + if rf, ok := ret.Get(0).(func(context.Context, dto.AdminLoginReq) dto.LoginUserResp); ok { + r0 = rf(ctx, loginReq) + } else { + r0 = ret.Get(0).(dto.LoginUserResp) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, dto.AdminLoginReq) error); ok { + r1 = rf(ctx, loginReq) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// AllAppreciationReport provides a mock function with given fields: ctx, appreciations +func (_m *Service) AllAppreciationReport(ctx context.Context, appreciations []dto.AppreciationResponse) (string, error) { + ret := _m.Called(ctx, appreciations) + + var r0 string + if rf, ok := ret.Get(0).(func(context.Context, []dto.AppreciationResponse) string); ok { + r0 = rf(ctx, appreciations) + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, []dto.AppreciationResponse) error); ok { + r1 = rf(ctx, appreciations) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetActiveUserList provides a mock function with given fields: ctx func (_m *Service) GetActiveUserList(ctx context.Context) ([]dto.ActiveUser, error) { ret := _m.Called(ctx) @@ -164,6 +206,20 @@ func (_m *Service) LoginUser(ctx context.Context, u dto.IntranetUserData) (dto.L return r0, r1 } +// NotificationByAdmin provides a mock function with given fields: ctx, notificationReq +func (_m *Service) NotificationByAdmin(ctx context.Context, notificationReq dto.AdminNotificationReq) error { + ret := _m.Called(ctx, notificationReq) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, dto.AdminNotificationReq) error); ok { + r0 = rf(ctx, notificationReq) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // RegisterUser provides a mock function with given fields: ctx, u func (_m *Service) RegisterUser(ctx context.Context, u dto.IntranetUserData) (dto.User, error) { ret := _m.Called(ctx, u) @@ -185,6 +241,27 @@ func (_m *Service) RegisterUser(ctx context.Context, u dto.IntranetUserData) (dt return r0, r1 } +// ReportedAppreciationReport provides a mock function with given fields: ctx, appreciations +func (_m *Service) ReportedAppreciationReport(ctx context.Context, appreciations []dto.ReportedAppreciation) (string, error) { + ret := _m.Called(ctx, appreciations) + + var r0 string + if rf, ok := ret.Get(0).(func(context.Context, []dto.ReportedAppreciation) string); ok { + r0 = rf(ctx, appreciations) + } else { + r0 = ret.Get(0).(string) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, []dto.ReportedAppreciation) error); ok { + r1 = rf(ctx, appreciations) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // UpdateRewardQuota provides a mock function with given fields: ctx func (_m *Service) UpdateRewardQuota(ctx context.Context) error { ret := _m.Called(ctx) @@ -220,6 +297,10 @@ func (_m *Service) ValidatePeerly(ctx context.Context, authToken string) (dto.Va return r0, r1 } +// sendRewardQuotaRefillEmailToAll provides a mock function with given fields: ctx +func (_m *Service) sendRewardQuotaRefillEmailToAll(ctx context.Context) { + _m.Called(ctx) +} func NewService(t interface { mock.TestingT diff --git a/internal/app/users/service.go b/internal/app/users/service.go index 254afcf..ecdc723 100644 --- a/internal/app/users/service.go +++ b/internal/app/users/service.go @@ -39,7 +39,6 @@ type Service interface { GetActiveUserList(ctx context.Context) ([]dto.ActiveUser, error) GetTop10Users(ctx context.Context) (users []dto.Top10User, err error) AdminLogin(ctx context.Context, loginReq dto.AdminLoginReq) (resp dto.LoginUserResp, err error) - sendRewardQuotaRefillEmailToAll(ctx context.Context) NotificationByAdmin(ctx context.Context, notificationReq dto.AdminNotificationReq) (err error) AllAppreciationReport(ctx context.Context, appreciations []dto.AppreciationResponse) (tempFileName string, err error) ReportedAppreciationReport(ctx context.Context, appreciations []dto.ReportedAppreciation) (tempFileName string, err error) @@ -642,7 +641,8 @@ func (us *service) AllAppreciationReport(ctx context.Context, appreciations []dt // Set header headers := []string{"Core value", "Core value description", "Appreciation description", "Sender first name", "Sender last name", "Sender designation", "Receiver first name", "Receiver last name", "Receiver designation", "Total rewards", "Total reward points"} for colIndex, header := range headers { - cell := fmt.Sprintf("%s1", string('A'+colIndex)) + + cell := fmt.Sprintf("%c1", 'A'+colIndex) f.SetCellValue(sheetName, cell, header) } @@ -691,7 +691,7 @@ func (us *service) ReportedAppreciationReport(ctx context.Context, appreciations // Set header headers := []string{"Core value", "Core value description", "Appreciation description", "Sender first name", "Sender last name", "Sender designation", "Receiver first name", "Receiver last name", "Receiver designation", "Reporting Comment", "Reported by first name", "Reported by last name", "Reported at", "Moderator comment", "Moderator first name", "Moderator last name", "Status"} for colIndex, header := range headers { - cell := fmt.Sprintf("%s1", string('A'+colIndex)) + cell := fmt.Sprintf("%c1", 'A'+colIndex) f.SetCellValue(sheetName, cell, header) } diff --git a/internal/app/users/service_test.go b/internal/app/users/service_test.go index 29b2227..007ded4 100644 --- a/internal/app/users/service_test.go +++ b/internal/app/users/service_test.go @@ -503,20 +503,16 @@ func TestGetActiveUserList(t *testing.T) { }, expectedResp: []dto.ActiveUser{ { - ID: 55, - FirstName: "Deepak", - LastName: "Kumar", - ProfileImageURL: "", - BadgeName: "", - AppreciationPoints: 0, + ID: 55, + FirstName: "Deepak", + LastName: "Kumar", + ProfileImageURL: "", }, { - ID: 58, - FirstName: "Dominic", - LastName: "Lopes", - ProfileImageURL: "", - BadgeName: "Gold", - AppreciationPoints: 5000, + ID: 58, + FirstName: "Dominic", + LastName: "Lopes", + ProfileImageURL: "", }, }, expectedError: nil, diff --git a/internal/repository/mocks/AppreciationStorer.go b/internal/repository/mocks/AppreciationStorer.go index 675a209..4c35c92 100644 --- a/internal/repository/mocks/AppreciationStorer.go +++ b/internal/repository/mocks/AppreciationStorer.go @@ -1,17 +1,12 @@ -// Code generated by mockery v2.43.2. DO NOT EDIT. +// Code generated by mockery v1.0.0. DO NOT EDIT. package mocks -import ( - context "context" - - dto "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - mock "github.com/stretchr/testify/mock" - - repository "github.com/joshsoftware/peerly-backend/internal/repository" - - sqlx "github.com/jmoiron/sqlx" -) +import context "context" +import dto "github.com/joshsoftware/peerly-backend/internal/pkg/dto" +import mock "github.com/stretchr/testify/mock" +import repository "github.com/joshsoftware/peerly-backend/internal/repository" +import sqlx "github.com/jmoiron/sqlx" // AppreciationStorer is an autogenerated mock type for the AppreciationStorer type type AppreciationStorer struct { @@ -22,15 +17,7 @@ type AppreciationStorer struct { func (_m *AppreciationStorer) BeginTx(ctx context.Context) (repository.Transaction, error) { ret := _m.Called(ctx) - if len(ret) == 0 { - panic("no return value specified for BeginTx") - } - var r0 repository.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (repository.Transaction, error)); ok { - return rf(ctx) - } if rf, ok := ret.Get(0).(func(context.Context) repository.Transaction); ok { r0 = rf(ctx) } else { @@ -39,6 +26,7 @@ func (_m *AppreciationStorer) BeginTx(ctx context.Context) (repository.Transacti } } + var r1 error if rf, ok := ret.Get(1).(func(context.Context) error); ok { r1 = rf(ctx) } else { @@ -52,21 +40,14 @@ func (_m *AppreciationStorer) BeginTx(ctx context.Context) (repository.Transacti func (_m *AppreciationStorer) CreateAppreciation(ctx context.Context, tx repository.Transaction, appreciation dto.Appreciation) (repository.Appreciation, error) { ret := _m.Called(ctx, tx, appreciation) - if len(ret) == 0 { - panic("no return value specified for CreateAppreciation") - } - var r0 repository.Appreciation - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.Appreciation) (repository.Appreciation, error)); ok { - return rf(ctx, tx, appreciation) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.Appreciation) repository.Appreciation); ok { r0 = rf(ctx, tx, appreciation) } else { r0 = ret.Get(0).(repository.Appreciation) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, dto.Appreciation) error); ok { r1 = rf(ctx, tx, appreciation) } else { @@ -80,10 +61,6 @@ func (_m *AppreciationStorer) CreateAppreciation(ctx context.Context, tx reposit func (_m *AppreciationStorer) DeleteAppreciation(ctx context.Context, tx repository.Transaction, apprId int32) error { ret := _m.Called(ctx, tx, apprId) - if len(ret) == 0 { - panic("no return value specified for DeleteAppreciation") - } - var r0 error if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int32) error); ok { r0 = rf(ctx, tx, apprId) @@ -98,21 +75,14 @@ func (_m *AppreciationStorer) DeleteAppreciation(ctx context.Context, tx reposit func (_m *AppreciationStorer) GetAppreciationById(ctx context.Context, tx repository.Transaction, appreciationId int32) (repository.AppreciationResponse, error) { ret := _m.Called(ctx, tx, appreciationId) - if len(ret) == 0 { - panic("no return value specified for GetAppreciationById") - } - var r0 repository.AppreciationResponse - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int32) (repository.AppreciationResponse, error)); ok { - return rf(ctx, tx, appreciationId) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int32) repository.AppreciationResponse); ok { r0 = rf(ctx, tx, appreciationId) } else { r0 = ret.Get(0).(repository.AppreciationResponse) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, int32) error); ok { r1 = rf(ctx, tx, appreciationId) } else { @@ -126,10 +96,6 @@ func (_m *AppreciationStorer) GetAppreciationById(ctx context.Context, tx reposi func (_m *AppreciationStorer) HandleTransaction(ctx context.Context, tx repository.Transaction, isSuccess bool) error { ret := _m.Called(ctx, tx, isSuccess) - if len(ret) == 0 { - panic("no return value specified for HandleTransaction") - } - var r0 error if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, bool) error); ok { r0 = rf(ctx, tx, isSuccess) @@ -144,10 +110,6 @@ func (_m *AppreciationStorer) HandleTransaction(ctx context.Context, tx reposito func (_m *AppreciationStorer) InitiateQueryExecutor(tx repository.Transaction) sqlx.Ext { ret := _m.Called(tx) - if len(ret) == 0 { - panic("no return value specified for InitiateQueryExecutor") - } - var r0 sqlx.Ext if rf, ok := ret.Get(0).(func(repository.Transaction) sqlx.Ext); ok { r0 = rf(tx) @@ -164,21 +126,14 @@ func (_m *AppreciationStorer) InitiateQueryExecutor(tx repository.Transaction) s func (_m *AppreciationStorer) IsUserPresent(ctx context.Context, tx repository.Transaction, userID int64) (bool, error) { ret := _m.Called(ctx, tx, userID) - if len(ret) == 0 { - panic("no return value specified for IsUserPresent") - } - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int64) (bool, error)); ok { - return rf(ctx, tx, userID) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, int64) bool); ok { r0 = rf(ctx, tx, userID) } else { r0 = ret.Get(0).(bool) } + var r1 error if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, int64) error); ok { r1 = rf(ctx, tx, userID) } else { @@ -192,16 +147,7 @@ func (_m *AppreciationStorer) IsUserPresent(ctx context.Context, tx repository.T func (_m *AppreciationStorer) ListAppreciations(ctx context.Context, tx repository.Transaction, filter dto.AppreciationFilter) ([]repository.AppreciationResponse, repository.Pagination, error) { ret := _m.Called(ctx, tx, filter) - if len(ret) == 0 { - panic("no return value specified for ListAppreciations") - } - var r0 []repository.AppreciationResponse - var r1 repository.Pagination - var r2 error - if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.AppreciationFilter) ([]repository.AppreciationResponse, repository.Pagination, error)); ok { - return rf(ctx, tx, filter) - } if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction, dto.AppreciationFilter) []repository.AppreciationResponse); ok { r0 = rf(ctx, tx, filter) } else { @@ -210,12 +156,14 @@ func (_m *AppreciationStorer) ListAppreciations(ctx context.Context, tx reposito } } + var r1 repository.Pagination if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction, dto.AppreciationFilter) repository.Pagination); ok { r1 = rf(ctx, tx, filter) } else { r1 = ret.Get(1).(repository.Pagination) } + var r2 error if rf, ok := ret.Get(2).(func(context.Context, repository.Transaction, dto.AppreciationFilter) error); ok { r2 = rf(ctx, tx, filter) } else { @@ -225,8 +173,50 @@ func (_m *AppreciationStorer) ListAppreciations(ctx context.Context, tx reposito return r0, r1, r2 } -// NewAppreciationStorer creates a new instance of AppreciationStorer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. +// UpdateAppreciationTotalRewardsOfYesterday provides a mock function with given fields: ctx, tx +func (_m *AppreciationStorer) UpdateAppreciationTotalRewardsOfYesterday(ctx context.Context, tx repository.Transaction) (bool, error) { + ret := _m.Called(ctx, tx) + + var r0 bool + if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction) bool); ok { + r0 = rf(ctx, tx) + } else { + r0 = ret.Get(0).(bool) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction) error); ok { + r1 = rf(ctx, tx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// UpdateUserBadgesBasedOnTotalRewards provides a mock function with given fields: ctx, tx +func (_m *AppreciationStorer) UpdateUserBadgesBasedOnTotalRewards(ctx context.Context, tx repository.Transaction) ([]repository.UserBadgeDetails, error) { + ret := _m.Called(ctx, tx) + + var r0 []repository.UserBadgeDetails + if rf, ok := ret.Get(0).(func(context.Context, repository.Transaction) []repository.UserBadgeDetails); ok { + r0 = rf(ctx, tx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]repository.UserBadgeDetails) + } + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, repository.Transaction) error); ok { + r1 = rf(ctx, tx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + func NewAppreciationStorer(t interface { mock.TestingT Cleanup(func()) diff --git a/internal/repository/mocks/ReportAppreciationStorer.go b/internal/repository/mocks/ReportAppreciationStorer.go index e2e5eb5..90d1a86 100644 --- a/internal/repository/mocks/ReportAppreciationStorer.go +++ b/internal/repository/mocks/ReportAppreciationStorer.go @@ -96,6 +96,27 @@ func (_m *ReportAppreciationStorer) DeleteAppreciation(ctx context.Context, mode return r0 } +// GetResolution provides a mock function with given fields: ctx, id +func (_m *ReportAppreciationStorer) GetResolution(ctx context.Context, id int64) (repository.ListReportedAppreciations, error) { + ret := _m.Called(ctx, id) + + var r0 repository.ListReportedAppreciations + if rf, ok := ret.Get(0).(func(context.Context, int64) repository.ListReportedAppreciations); ok { + r0 = rf(ctx, id) + } else { + r0 = ret.Get(0).(repository.ListReportedAppreciations) + } + + var r1 error + if rf, ok := ret.Get(1).(func(context.Context, int64) error); ok { + r1 = rf(ctx, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetSenderAndReceiver provides a mock function with given fields: ctx, reqData func (_m *ReportAppreciationStorer) GetSenderAndReceiver(ctx context.Context, reqData dto.ReportAppreciationReq) (dto.GetSenderAndReceiverResp, error) { ret := _m.Called(ctx, reqData) @@ -161,6 +182,20 @@ func (_m *ReportAppreciationStorer) ReportAppreciation(ctx context.Context, repo return r0, r1 } +// ResolveAppreciation provides a mock function with given fields: ctx, moderationReq +func (_m *ReportAppreciationStorer) ResolveAppreciation(ctx context.Context, moderationReq dto.ModerationReq) error { + ret := _m.Called(ctx, moderationReq) + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, dto.ModerationReq) error); ok { + r0 = rf(ctx, moderationReq) + } else { + r0 = ret.Error(0) + } + + return r0 +} + func NewReportAppreciationStorer(t interface { mock.TestingT Cleanup(func()) diff --git a/internal/repository/postgresdb/reportAppreciation.go b/internal/repository/postgresdb/reportAppreciation.go index 2bb7811..1b58f1f 100644 --- a/internal/repository/postgresdb/reportAppreciation.go +++ b/internal/repository/postgresdb/reportAppreciation.go @@ -194,7 +194,7 @@ func (rs *reportAppreciationStore) GetResolution(ctx context.Context, id int64) err = apperrors.InvalidId return } - logger.Errorf("error in retriving reported appriciation, err:%w", err) + logger.Errorf("error in retriving reported appriciation, err:%s", err.Error()) err = apperrors.InternalServerError return } From f4336d9a632fb2871a6ac640cca67bf777d74a0b Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Thu, 29 Aug 2024 15:34:40 +0530 Subject: [PATCH 20/22] [feature/addEmailAndNotification] email service validation and structure changed --- internal/app/appreciation/service.go | 38 +++++++--- internal/app/email/helper.go | 17 +++++ internal/app/email/service.go | 81 +++++++++++---------- internal/app/notification/service.go | 41 +---------- internal/app/reportAppreciations/service.go | 69 ++++++++++++++---- internal/pkg/apperrors/errors.go | 6 +- internal/pkg/constants/system.go | 6 ++ internal/pkg/logger/log.go | 4 +- 8 files changed, 156 insertions(+), 106 deletions(-) create mode 100644 internal/app/email/helper.go diff --git a/internal/app/appreciation/service.go b/internal/app/appreciation/service.go index 170b4b2..6db612e 100644 --- a/internal/app/appreciation/service.go +++ b/internal/app/appreciation/service.go @@ -240,21 +240,32 @@ func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail SenderIconImageURL: fmt.Sprint(config.PeerlyBaseUrl()+constants.OpenEnvelopeIconImagePath), } - logger.Info(context.Background(),"appreciation sender email: -----------> ",senderEmail) - logger.Info(context.Background(),"appreciation receiver email: -----------> ",receiverEmail) - mailReq := email.NewMail([]string{receiverEmail}, []string{}, []string{}, fmt.Sprintf("Kudos! You've Been Praised by %s %s! 🎉 ",emailData.SenderFirstName,emailData.SenderLastName)) - err := mailReq.ParseTemplate("./internal/app/email/templates/receiverAppreciation.html", templateData) + tos := []string{receiverEmail} + ccs := []string{} + bccs := []string{} + sub := fmt.Sprintf("Kudos! You've Been Praised by %s %s! 🎉 ",emailData.SenderFirstName,emailData.SenderLastName) + body,err := email.ParseTemplate("./internal/app/email/templates/receiverAppreciation.html", templateData) if err != nil { - logger.Errorf(context.Background(),"err in creating html file : %v", err) + logger.Errorf(context.Background(),"err in creating receiverAppreciation.html file : %v", err) return err } + mailReq := email.NewMail(tos, ccs, bccs, sub,body) err = mailReq.Send() if err != nil { logger.Errorf(context.Background(),"err: %v", err) return err } - mailReq = email.NewMail([]string{senderEmail}, []string{}, []string{}, fmt.Sprintf("Your appreciation to %s %s has been sent! 🙌",emailData.ReceiverFirstName,emailData.ReceiverLastName)) - err = mailReq.ParseTemplate("./internal/app/email/templates/senderAppreciation.html", templateData) + + tos = []string{senderEmail} + ccs = []string{} + bccs = []string{} + sub = fmt.Sprintf("Your appreciation to %s %s has been sent! 🙌",emailData.ReceiverFirstName,emailData.ReceiverLastName) + body,err = email.ParseTemplate("./internal/app/email/templates/senderAppreciation.html", templateData) + if err != nil { + logger.Errorf(context.Background(),"err in creating senderAppreciation.html file : %v", err) + return err + } + mailReq = email.NewMail(tos, ccs, bccs, sub,body) if err != nil { logger.Errorf(context.Background(),"err: %v",err) return err @@ -329,17 +340,22 @@ func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repositor AppreciationPoints: userBadgeDetail.BadgePoints, } logger.Info(context.Background(),"badge data: ", templateData) - mailReq := email.NewMail([]string{userBadgeDetail.Email}, []string{}, []string{}, fmt.Sprintf("You've Bagged the %s for Crushing %d Points! 🏆",userBadgeDetail.BadgeName.String, userBadgeDetail.BadgePoints)) - err := mailReq.ParseTemplate("./internal/app/email/templates/badge.html", templateData) + + tos := []string{userBadgeDetail.Email} + ccs := []string{} + bccs := []string{} + sub := fmt.Sprintf("You've Bagged the %s for Crushing %d Points! 🏆",userBadgeDetail.BadgeName.String, userBadgeDetail.BadgePoints) + body, err := email.ParseTemplate("./internal/app/email/templates/badge.html", templateData) if err != nil { - logger.Errorf(context.Background(),"err in creating html file : %v", err) + logger.Errorf(context.Background(),"err in creating badge.html file : %v", err) return } + + mailReq := email.NewMail(tos, ccs, bccs, sub,body) err = mailReq.Send() if err != nil { logger.Errorf(context.Background(),"err: %v", err) return } } - return } diff --git a/internal/app/email/helper.go b/internal/app/email/helper.go new file mode 100644 index 0000000..b38272e --- /dev/null +++ b/internal/app/email/helper.go @@ -0,0 +1,17 @@ +package email + +import ( + "bytes" + "html/template" +) +func ParseTemplate(templateFileName string, data interface{})(string, error) { + t, err := template.ParseFiles(templateFileName) + if err != nil { + return "",err + } + buf := new(bytes.Buffer) + if err = t.Execute(buf, data); err != nil { + return "",err + } + return buf.String(),nil +} \ No newline at end of file diff --git a/internal/app/email/service.go b/internal/app/email/service.go index 2586de9..151d09d 100644 --- a/internal/app/email/service.go +++ b/internal/app/email/service.go @@ -1,11 +1,10 @@ package email import ( - "bytes" "context" "fmt" - "html/template" + "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/config" logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "github.com/sendgrid/sendgrid-go" @@ -15,7 +14,6 @@ import ( // MailService represents the interface for our mail service. type MailService interface { Send() error - ParseTemplate(templateFileName string, data interface{}) error } // Mail represents a email request @@ -24,27 +22,26 @@ type Mail struct { to []string subject string body string - CC []string - BCC []string + cc []string + bcc []string } func (ms *Mail) Send() error { - logger.Info(context.Background()," Mail: ",ms) - senderEmail := config.ReadEnvString("SENDER_EMAIL") - if senderEmail == "" { - logger.Error(context.Background(),"SENDER_EMAIL environment variable is not set") - return fmt.Errorf("sender email not configured") - } + logger.Info(context.Background(), " Mail: ", ms) sendGridAPIKey := config.ReadEnvString("SENDGRID_API_KEY") if sendGridAPIKey == "" { - logger.Error(context.Background(),"SENDGRID_API_KEY environment variable is not set") + logger.Error(context.Background(), "SENDGRID_API_KEY environment variable is not set") return fmt.Errorf("sendgrid API key not configured") } - logger.Info(context.Background(),"from_------------->, ",senderEmail) - fromEmail := mail.NewEmail("Peerly", senderEmail) + err := ms.validateMail() + if err != nil { + logger.Errorf(context.Background(),"err: error in mail validation: %v",err) + return err + } + fromEmail := mail.NewEmail("Peerly", ms.from) content := mail.NewContent("text/html", ms.body) // create new *SGMailV3 @@ -54,21 +51,21 @@ func (ms *Mail) Send() error { personalization := mail.NewPersonalization() - for _,email := range ms.to{ + for _, email := range ms.to { toEmail := mail.NewEmail("to", email) personalization.AddTos(toEmail) } - for _,email := range ms.CC{ + for _, email := range ms.cc { ccEmail := mail.NewEmail("cc", email) personalization.AddCCs(ccEmail) } - for _,email := range ms.BCC{ + for _, email := range ms.bcc { bccEmail := mail.NewEmail("bcc", email) personalization.AddBCCs(bccEmail) } - + personalization.Subject = ms.subject m.AddPersonalizations(personalization) @@ -76,39 +73,43 @@ func (ms *Mail) Send() error { response, err := client.Send(m) if err != nil { - logger.Error(context.Background(),"unable to send mail", "error", err) + logger.Error(context.Background(), "unable to send mail", "error", err) return err } - logger.Info(context.Background(),"Email response: ") - logger.Infof(context.Background(),"Response status code: %v", response.StatusCode) - logger.Infof(context.Background(),"Response body: %v", response.Body) - logger.Infof(context.Background(),"Response headers: %v", response.Headers) + logger.Infof(context.Background(),"email sent successfully to %v ",ms.to) + logger.Debug(context.Background(), "Email response: %v ",response) return nil } -func (r *Mail) ParseTemplate(templateFileName string, data interface{}) error { - t, err := template.ParseFiles(templateFileName) - if err != nil { - return err - } - buf := new(bytes.Buffer) - if err = t.Execute(buf, data); err != nil { - return err - } - r.body = buf.String() - logger.Info(context.Background(),"--------------------->") - logger.Info(context.Background(),r.body) - logger.Info(context.Background(),"--------------------->") - return nil + +func (ms *Mail) validateMail() error { + if len(ms.to) == 0 { + return apperrors.InvalidTos + } + + if len(ms.from) == 0 { + return apperrors.InvalidFrom + } + + if len(ms.body) == 0 { + return apperrors.InvalidBody + } + + if len(ms.subject) == 0 { + return apperrors.InvalidSub + } + + return nil } // NewMail returns a new mail request. -func NewMail(to []string, cc []string, bcc []string, subject string) MailService { +func NewMail(to []string, cc []string, bcc []string, subject string, body string) MailService { return &Mail{ from: config.ReadEnvString("SENDER_EMAIL"), to: to, - CC: cc, - BCC: bcc, + cc: cc, + bcc: bcc, subject: subject, + body: body, } } diff --git a/internal/app/notification/service.go b/internal/app/notification/service.go index 7487e8d..da319cd 100644 --- a/internal/app/notification/service.go +++ b/internal/app/notification/service.go @@ -6,6 +6,7 @@ import ( firebase "firebase.google.com/go" "firebase.google.com/go/messaging" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" + "github.com/joshsoftware/peerly-backend/internal/pkg/constants" logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" "google.golang.org/api/option" ) @@ -13,7 +14,6 @@ import ( type NotificationService interface { SendNotificationToNotificationToken(notificationToken string) (err error) SendNotificationToTopic(topic string) (err error) - // SendNotificationToNotificationTokens(userId int64) } type Message struct { @@ -25,7 +25,7 @@ type Message struct { func (notificationSvc *Message) SendNotificationToNotificationToken(notificationToken string) (err error) { // Path to your service account key file - serviceAccountKey := "serviceAccountKey.json" + serviceAccountKey := constants.ServiceAccountKey // Initialize the Firebase app opt := option.WithCredentialsFile(serviceAccountKey) @@ -111,40 +111,3 @@ func (notificationSvc *Message) SendNotificationToTopic(topic string) (err error return } - -// func (notificationSvc *Message) SendNotificationToNotificationTokens(userId int64) { - -// // Path to your service account key file -// serviceAccountKey := "serviceAccountKey.json" - -// // Initialize the Firebase app -// opt := option.WithCredentialsFile(serviceAccountKey) -// app, err := firebase.NewApp(context.Background(), nil, opt) -// if err != nil { -// logger.Errorf("Error initializing app: %v", err) -// return -// } - -// // Obtain a messaging client from the Firebase app -// client, err := app.Messaging(context.Background()) -// if err != nil { -// logger.Errorf("Error getting Messaging client: %v", err) -// return -// } -// // Create a message to send -// message := &messaging.Message{ -// Notification: &messaging.Notification{ -// Title: notificationSvc.Title, -// Body: notificationSvc.Body, -// }, -// Token: notificationToken, -// } - -// // Send the message -// response, err := client.Send(context.Background(), message) -// if err != nil { -// logger.Errorf("Error sending message: %v", err) -// return -// } -// logger.Infof("Successfully sent message: %v", response) -// } diff --git a/internal/app/reportAppreciations/service.go b/internal/app/reportAppreciations/service.go index 00d11f2..e424dfc 100644 --- a/internal/app/reportAppreciations/service.go +++ b/internal/app/reportAppreciations/service.go @@ -305,10 +305,17 @@ func sendReportEmail(senderEmail string, senderFirstName string, senderLastName ReportIconImageURL: fmt.Sprint(config.PeerlyBaseUrl() + constants.CheckIconImagePath), } - logger.Info(ctx, "report sender email: ---------> ", senderEmail) - mailReq := email.NewMail([]string{senderEmail}, []string{"dl_peerly.support@joshsoftware.com"}, []string{}, "🙏 Thanks for Your Feedback! We’re On It! 🔧") - mailReq.ParseTemplate("./internal/app/email/templates/reportAppreciation.html", templateData) - err := mailReq.Send() + tos := []string{senderEmail} + ccs := []string{constants.HRDLGroup} + bccs := []string{} + sub := "🙏 Thanks for Your Feedback! We’re On It! 🔧" + body, err := email.ParseTemplate("./internal/app/email/templates/reportAppreciation.html", templateData) + if err != nil { + logger.Errorf(context.Background(),"err in creating reportAppreciation.html file : %v", err) + return err + } + mailReq := email.NewMail(tos,ccs ,bccs,sub,body ) + err = mailReq.Send() if err != nil { logger.Errorf(ctx, "err: %v", err) return err @@ -387,17 +394,34 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str ctx := context.Background() ctx = context.WithValue(ctx, constants.RequestID, "deleteEmail") logger.Info(ctx, "reporter email: ---------> ", reporterEmail) - mailReq := email.NewMail([]string{reporterEmail}, []string{}, []string{}, "Results of reported appreciation") - mailReq.ParseTemplate("./internal/app/email/templates/deleteAppreciation.html", templateData) - err := mailReq.Send() + tos := []string{reporterEmail} + ccs := []string{} + bccs := []string{} + sub := "Results of reported appreciation" + body, err := email.ParseTemplate("./internal/app/email/templates/deleteAppreciation.html", templateData) + if err != nil { + logger.Errorf(context.Background(),"err in creating deleteAppreciation.html file : %v", err) + return err + } + mailReq := email.NewMail(tos,ccs ,bccs,sub ,body ) + err = mailReq.Send() if err != nil { logger.Errorf(context.Background(), "err: %v", err) return err } logger.Info(ctx, "sender email: ---------> ", reporterEmail) - mailReq = email.NewMail([]string{senderEmail}, []string{}, []string{}, "Results of reported appreciation") - mailReq.ParseTemplate("./internal/app/email/templates/senderDeleteEmail.html", templateData) + + tos = []string{senderEmail} + ccs = []string{} + bccs = []string{} + sub = "Results of reported appreciation" + body,err = email.ParseTemplate("./internal/app/email/templates/senderDeleteEmail.html", templateData) + if err != nil { + logger.Errorf(context.Background(),"err in creating senderDeleteEmail.html file : %v", err) + return err + } + mailReq = email.NewMail(tos,ccs ,bccs,sub,body ) err = mailReq.Send() if err != nil { logger.Errorf(ctx, "err: %v", err) @@ -405,8 +429,17 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str } logger.Info(ctx, "receiver email: ---------> ", reporterEmail) - mailReq = email.NewMail([]string{receiverEmail}, []string{}, []string{}, "Results of reported appreciation") - mailReq.ParseTemplate("./internal/app/email/templates/receiverDeleteEmail.html", templateData) + + tos = []string{receiverEmail} + ccs = []string{} + bccs = []string{} + sub = "Results of reported appreciation" + body,err = email.ParseTemplate("./internal/app/email/templates/receiverDeleteEmail.html", templateData) + if err != nil { + logger.Errorf(context.Background(),"err in creating receiverDeleteEmail.html file : %v", err) + return err + } + mailReq = email.NewMail(tos,ccs,bccs, sub,body ) err = mailReq.Send() if err != nil { logger.Errorf(ctx, "err: %v", err) @@ -419,9 +452,17 @@ func sendDeleteEmail(reporterEmail string, senderEmail string, receiverEmail str func sendResolveEmail(senderEmail string, templateData dto.ResolveAppreciationMail) error { logger.Info(context.Background(), "report sender email: ---------> ", senderEmail) - mailReq := email.NewMail([]string{senderEmail}, []string{}, []string{}, "Results of reported appreciation") - mailReq.ParseTemplate("./internal/app/email/templates/resolveAppreciation.html", templateData) - err := mailReq.Send() + tos := []string{senderEmail} + ccs := []string{} + bccs := []string{} + sub := "Results of reported appreciation" + body ,err := email.ParseTemplate("./internal/app/email/templates/resolveAppreciation.html", templateData) + if err != nil { + logger.Errorf(context.Background(),"err in creating resolveAppreciation.html file : %v", err) + return err + } + mailReq := email.NewMail(tos, ccs, bccs, sub,body) + err = mailReq.Send() if err != nil { logger.Errorf(context.Background(), "err: %v", err) return err diff --git a/internal/pkg/apperrors/errors.go b/internal/pkg/apperrors/errors.go index 04d9030..f3c3280 100644 --- a/internal/pkg/apperrors/errors.go +++ b/internal/pkg/apperrors/errors.go @@ -75,6 +75,10 @@ const ( NegativeBadgePoints = CustomError("Badge reward points cannot be negative") UnauthorizedDeveloper = CustomError("Unauthorised developer") InvalidLoggerLevel = CustomError("Invalid Logger Level") + InvalidTos = CustomError("recipient email addresses are required") + InvalidFrom = CustomError("sender email address is required") + InvalidBody = CustomError("email body is required") + InvalidSub = CustomError("email subject is required") ) // ErrKeyNotSet - Returns error object specific to the key value passed in @@ -89,7 +93,7 @@ func GetHTTPStatusCode(err error) int { return http.StatusInternalServerError case OrganizationConfigNotFound, OrganizationNotFound, InvalidOrgId, GradeNotFound, AppreciationNotFound, PageParamNotFound, InvalidCoreValueData, InvalidIntranetData: return http.StatusNotFound - case InvalidLoggerLevel,BadRequest, InvalidId, JSONParsingErrorReq, TextFieldBlank, InvalidParentValue, DescFieldBlank, UniqueCoreValue, SelfAppreciationError, CannotReportOwnAppreciation, RepeatedReport, InvalidCoreValueID, InvalidReceiverID, InvalidRewardMultiplier, InvalidRewardQuotaRenewalFrequency, InvalidTimezone, InvalidRewardPoint, InvalidEmail, InvalidPassword, DescriptionLengthExceed, InvalidPageSize, InvalidPage, NegativeGradePoints, NegativeBadgePoints: + case InvalidLoggerLevel, BadRequest, InvalidId, JSONParsingErrorReq, TextFieldBlank, InvalidParentValue, DescFieldBlank, UniqueCoreValue, SelfAppreciationError, CannotReportOwnAppreciation, RepeatedReport, InvalidCoreValueID, InvalidReceiverID, InvalidRewardMultiplier, InvalidRewardQuotaRenewalFrequency, InvalidTimezone, InvalidRewardPoint, InvalidEmail, InvalidPassword, DescriptionLengthExceed, InvalidPageSize, InvalidPage, NegativeGradePoints, NegativeBadgePoints: return http.StatusBadRequest case InvalidContactEmail, InvalidDomainName, UserAlreadyPresent, RewardAlreadyPresent, RepeatedUser: return http.StatusConflict diff --git a/internal/pkg/constants/system.go b/internal/pkg/constants/system.go index a8c61f7..38efe89 100644 --- a/internal/pkg/constants/system.go +++ b/internal/pkg/constants/system.go @@ -69,3 +69,9 @@ const ( OpenEnvelopeIconImagePath = "/peerly/assets/openEnvelopeIcon.png" RewardQuotaRenewalIconImagePath = "/peerly/assets/rewardQuotaRenewal.png" ) + +//notificatio service account key file +const ServiceAccountKey = "serviceAccountKey.json" + +// Email Dl group of HRs +const HRDLGroup = "dl_peerly.support@joshsoftware.com" \ No newline at end of file diff --git a/internal/pkg/logger/log.go b/internal/pkg/logger/log.go index 69a55a8..83a7035 100644 --- a/internal/pkg/logger/log.go +++ b/internal/pkg/logger/log.go @@ -27,7 +27,9 @@ func Error(ctx context.Context, args ...interface{}) { if !ok { requestID = "" } - Logger.Error(requestID, args) + // Logger.Error(requestID, args) + logger := Logger.WithField("req_id", requestID) + logger.Log(l.ErrorLevel, args...) } // Errorf - prints out an error with formatted output From 182e74a0091c026bbc8323fcf9c8d8f89ea21d5a Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Fri, 30 Aug 2024 00:20:27 +0530 Subject: [PATCH 21/22] [feature/UpdateLogs] review comments resolved --- .gitignore | 3 +- internal/api/appreciation.go | 26 ++++---- internal/api/organizationconfig.go | 8 ++- internal/api/ping.go | 2 +- internal/api/reward.go | 4 +- internal/api/router.go | 2 +- internal/api/user.go | 9 ++- internal/app/appreciation/service.go | 58 ++++++++++------- internal/app/cronjob/monthlyUpdateData.go | 1 + internal/app/cronjob/updateDailyData.go | 4 +- internal/app/organizationConfig/service.go | 14 ++-- internal/app/reward/service.go | 24 +++++-- internal/app/users/service.go | 1 + internal/pkg/logger/log.go | 59 +++++++---------- internal/pkg/middleware/jwtMiddleware.go | 4 +- .../repository/postgresdb/appreciation.go | 65 ++++++++----------- .../postgresdb/organizationConfig.go | 20 +++--- internal/repository/postgresdb/rewards.go | 23 ++++--- 18 files changed, 168 insertions(+), 159 deletions(-) diff --git a/.gitignore b/.gitignore index e95eeb1..71e1e93 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,5 @@ go.work.sum .env .vscode -serviceAccountKey.json \ No newline at end of file +serviceAccountKey.json +logs/* \ No newline at end of file diff --git a/internal/api/appreciation.go b/internal/api/appreciation.go index 95bf25d..19a7bef 100644 --- a/internal/api/appreciation.go +++ b/internal/api/appreciation.go @@ -24,7 +24,7 @@ func createAppreciationHandler(appreciationSvc appreciation.Service) http.Handle return } - log.Debug(req.Context(),"createAppreciationHandler: request: ",req) + log.Info(req.Context(),"createAppreciationHandler: request: ",req) err = appreciation.ValidateCreateAppreciation() if err != nil { log.Errorf(req.Context(),"Error while validating request data : %v", err) @@ -34,35 +34,36 @@ func createAppreciationHandler(appreciationSvc appreciation.Service) http.Handle resp, err := appreciationSvc.CreateAppreciation(req.Context(), appreciation) if err != nil { - log.Errorf(req.Context(),"err : %v", err) + log.Errorf(req.Context(),"createAppreciationHandler: err : %v", err) dto.ErrorRepsonse(rw, err) return } log.Debug(req.Context(),"createAppreciationHandler: response: ",resp) + log.Info(req.Context(),"Appreciation created successfully") dto.SuccessRepsonse(rw, http.StatusCreated, "Appreciation created successfully", resp) }) } func getAppreciationByIDHandler(appreciationSvc appreciation.Service) http.HandlerFunc { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - vars := mux.Vars(req) apprID, err := strconv.Atoi(vars["id"]) if err != nil { + log.Errorf(req.Context(),"Error while decoding appreciation id : %v", err) dto.ErrorRepsonse(rw, err) return } - log.Debug(req.Context(),"getAppreciationByIDHandler: request: ",req) - + log.Info(req.Context(),"getAppreciationByIDHandler: request: ",req) resp, err := appreciationSvc.GetAppreciationById(req.Context(), int32(apprID)) if err != nil { - log.Errorf(req.Context(),"err : %v", err) + log.Errorf(req.Context(),"getAppreciationByIDHandler: err : %v", err) dto.ErrorRepsonse(rw, err) return } log.Debug(req.Context(),"getAppreciationByIDHandler: request: ",resp) + log.Info(req.Context(),"Appreciation data got successfully") dto.SuccessRepsonse(rw, http.StatusOK, "Appreciation data got successfully", resp) }) } @@ -70,8 +71,6 @@ func getAppreciationByIDHandler(appreciationSvc appreciation.Service) http.Handl // getAppreciationsHandler handles HTTP requests for appreciations func listAppreciationsHandler(appreciationSvc appreciation.Service) http.HandlerFunc { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - - log.Debug(req.Context(),"listAppreciationsHandler") var filter dto.AppreciationFilter filter.Name = req.URL.Query().Get("name") @@ -83,15 +82,15 @@ func listAppreciationsHandler(appreciationSvc appreciation.Service) http.Handler filter.Limit = limit filter.Page = page filter.Self = utils.GetSelfParam(req) - log.Debug(req.Context(),"listAppreciationsHandler: request: ",req) - log.Debug(req.Context(),"filter: ",filter) + log.Info(req.Context(),"listAppreciationsHandler: request: ",req) appreciations, err := appreciationSvc.ListAppreciations(req.Context(), filter) if err != nil { - log.Errorf(req.Context(),"err : %v", err) + log.Errorf(req.Context(),"listAppreciationsHandler: err : %v", err) dto.ErrorRepsonse(rw, err) return } log.Debug(req.Context(),"listAppreciationsHandler: response: ",appreciations) + log.Info(req.Context(),"Appreciations data got successfully") dto.SuccessRepsonse(rw, http.StatusOK, "Appreciations data got successfully ", appreciations) }) } @@ -106,14 +105,15 @@ func deleteAppreciationHandler(appreciationSvc appreciation.Service) http.Handle return } - log.Debug(req.Context(),"deleteAppreciationHandler: request: ",req) + log.Info(req.Context(),"deleteAppreciationHandler: request: ",req) err = appreciationSvc.DeleteAppreciation(req.Context(), int32(apprId)) if err != nil { - log.Errorf(req.Context(),"err : %v", err) + log.Errorf(req.Context(),"deleteAppreciationHandler: err : %v", err) dto.ErrorRepsonse(rw, err) return } log.Debug(req.Context(),"deleteAppreciationHandler: resp: ",err) + log.Info(req.Context(),"Appreciation invalidate successfully") dto.SuccessRepsonse(rw, http.StatusOK, "Appreciation invalidate successfully", nil) }) } diff --git a/internal/api/organizationconfig.go b/internal/api/organizationconfig.go index 73568a4..3c2e7f7 100644 --- a/internal/api/organizationconfig.go +++ b/internal/api/organizationconfig.go @@ -14,7 +14,6 @@ import ( func getOrganizationConfigHandler(orgSvc organizationConfig.Service) http.HandlerFunc { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - logger.Debug(req.Context(),"getOrganizationConfigHandler: req: ",req) orgConfig, err := orgSvc.GetOrganizationConfig(req.Context()) if err != nil { @@ -23,6 +22,7 @@ func getOrganizationConfigHandler(orgSvc organizationConfig.Service) http.Handle return } logger.Debug(req.Context(),"getOrganizationConfigHandler: resp: ",orgConfig) + logger.Info(req.Context(),"organization config fetched successfully") dto.SuccessRepsonse(rw, http.StatusOK, "organization config fetched successfully",orgConfig) }) } @@ -31,7 +31,7 @@ func getOrganizationConfigHandler(orgSvc organizationConfig.Service) http.Handle func createOrganizationConfigHandler(orgSvc organizationConfig.Service) http.HandlerFunc { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - logger.Debug(req.Context(),"createOrganizationConfigHandler: req: ",req) + logger.Debug(req.Context(),"createOrganizationConfigHandler: request: ",req) var orgConfig dto.OrganizationConfig err := json.NewDecoder(req.Body).Decode(&orgConfig) if err != nil { @@ -54,6 +54,7 @@ func createOrganizationConfigHandler(orgSvc organizationConfig.Service) http.Han return } logger.Debug(req.Context(),"createOrganizationConfigHandler: resp: ",createdOrganizationConfig) + logger.Info(req.Context(),"Organization Config Created Successfully") dto.SuccessRepsonse(rw, http.StatusCreated, "Organization Config Created Successfully" ,createdOrganizationConfig) }) } @@ -69,7 +70,7 @@ func updateOrganizationConfigHandler(orgSvc organizationConfig.Service) http.Han return } - logger.Debug(req.Context(),"updateOrganizationConfigHandler: request: ",req) + logger.Info(req.Context(),"updateOrganizationConfigHandler: request: ",req) organizationConfig.ID = 1 err = organizationConfig.OrgUpdateValidate() if err != nil { @@ -86,6 +87,7 @@ func updateOrganizationConfigHandler(orgSvc organizationConfig.Service) http.Han } logger.Debug(req.Context(),"updateOrganizationConfigHandler: resp: ",updatedOrganization) + logger.Info(req.Context(),"Organization Config Updated Successfully" ) dto.SuccessRepsonse(rw, http.StatusOK, "Organization Config Updated Successfully" ,updatedOrganization) }) diff --git a/internal/api/ping.go b/internal/api/ping.go index b4f3ee2..1f0f25c 100644 --- a/internal/api/ping.go +++ b/internal/api/ping.go @@ -8,7 +8,7 @@ import ( ) func pingHandler(rw http.ResponseWriter, req *http.Request) { - log.Logger.Debug("debug ping") + log.Debug(req.Context(),"debug ping") log.Info(req.Context(),"ping") dto.SuccessRepsonse(rw, http.StatusOK, "Success", "pong") } diff --git a/internal/api/reward.go b/internal/api/reward.go index 802d642..52073a8 100644 --- a/internal/api/reward.go +++ b/internal/api/reward.go @@ -22,7 +22,7 @@ func giveRewardHandler(rewardSvc reward.Service) http.HandlerFunc { return } - log.Debug(req.Context(),"giveRewardHandler: request: ",req) + log.Info(req.Context(),"giveRewardHandler: request: ",req) var reward dto.Reward err = json.NewDecoder(req.Body).Decode(&reward) @@ -47,7 +47,7 @@ func giveRewardHandler(rewardSvc reward.Service) http.HandlerFunc { } log.Debug(req.Context(),"giveRewardHandler: resp: ",resp) - + log.Info(req.Context(),"Reward given successfully") dto.SuccessRepsonse(rw, http.StatusCreated, "Reward given successfully", resp) }) } diff --git a/internal/api/router.go b/internal/api/router.go index 155516b..139f596 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -27,7 +27,7 @@ func NewRouter(deps app.Dependencies) *mux.Router { peerlySubrouter.HandleFunc("/ping", pingHandler).Methods(http.MethodGet) - peerlySubrouter.HandleFunc("/set_logger_level", loggerHandler).Methods(http.MethodPost) + peerlySubrouter.HandleFunc("/set_logger_level", loggerHandler).Methods(http.MethodPatch) // Version 1 API management v1 := fmt.Sprintf("application/vnd.%s.v1", config.AppName()) diff --git a/internal/api/user.go b/internal/api/user.go index e6ef06d..34fafa5 100644 --- a/internal/api/user.go +++ b/internal/api/user.go @@ -228,37 +228,42 @@ func listUsersHandler(userSvc user.Service) http.HandlerFunc { func getActiveUserListHandler(userSvc user.Service) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { - log.Debug(req.Context(), "getActiveUserListHandler: req: ", req) + log.Info(req.Context(), "getActiveUserListHandler: req: ", req) resp, err := userSvc.GetActiveUserList(req.Context()) if err != nil { dto.ErrorRepsonse(rw, err) return } log.Debug(req.Context(), "getActiveUserListHandler: resp: ", resp) + log.Info(req.Context(),"Active Users list") dto.SuccessRepsonse(rw, http.StatusOK, "Active Users list", resp) } } func getUserByIdHandler(userSvc user.Service) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { + log.Info(req.Context(),"getUserByIdHandler: request: ",req) resp, err := userSvc.GetUserById(req.Context()) if err != nil { + log.Errorf(req.Context(),"getUserByIdHandler: err: %v",err) dto.ErrorRepsonse(rw, err) return } + log.Info(req.Context(),) dto.SuccessRepsonse(rw, 200, "User fetched successfully", resp) - } } func getTop10UserHandler(userSvc user.Service) http.HandlerFunc { return func(rw http.ResponseWriter, req *http.Request) { + log.Info(req.Context(),"getTop10UserHandler: request: ",req) resp, err := userSvc.GetTop10Users(req.Context()) if err != nil { dto.ErrorRepsonse(rw, err) return } + log.Info(req.Context(),"Top 10 users fetched successfully") dto.SuccessRepsonse(rw, 200, "Top 10 users fetched successfully", resp) } } diff --git a/internal/app/appreciation/service.go b/internal/app/appreciation/service.go index de043aa..7b97a27 100644 --- a/internal/app/appreciation/service.go +++ b/internal/app/appreciation/service.go @@ -44,35 +44,36 @@ func NewService(appreciationRepo repository.AppreciationStorer, coreValuesRepo r func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto.Appreciation) (dto.Appreciation, error) { - logger.Debug(ctx,"svc: CreateAppreciation: appreciation: ",appreciation) //add quarter appreciation.Quarter = utils.GetQuarter() + logger.Debug(ctx,"service: CreateAppreciation: appreciation: ",appreciation) //add sender data := ctx.Value(constants.UserId) sender, ok := data.(int64) if !ok { - logger.Error(ctx,"err in parsing userid from token") + logger.Error(ctx,"service: err in parsing userid from token") return dto.Appreciation{}, apperrors.InternalServer } - logger.Debug(ctx,"sender: ",sender) //check is receiver present in database chk, err := apprSvc.appreciationRepo.IsUserPresent(ctx, nil, appreciation.Receiver) - logger.Debug(ctx,"chk: ",chk," err: ",err) if err != nil { logger.Errorf(ctx,"err: %v", err) return dto.Appreciation{}, err } if !chk { + logger.Errorf(ctx,"User not found (user_id): %v",appreciation.Receiver) return dto.Appreciation{}, apperrors.UserNotFound } appreciation.Sender = sender + logger.Debug(ctx,"service: appreciation: ",appreciation) //initializing database transaction tx, err := apprSvc.appreciationRepo.BeginTx(ctx) if err != nil { + logger.Errorf(ctx,"err: %v",err) return dto.Appreciation{}, err } @@ -80,7 +81,7 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto rvr := recover() defer func() { if rvr != nil { - logger.Info(ctx, "Transaction aborted because of panic: %v, Propagating panic further", rvr) + logger.Infof(ctx, "Transaction aborted because of panic: %v, Propagating panic further", rvr) panic(rvr) } }() @@ -88,7 +89,7 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto txErr := apprSvc.appreciationRepo.HandleTransaction(ctx, tx, err == nil && rvr == nil) if txErr != nil { err = txErr - logger.Info(ctx, "error in creating transaction, err: %s", txErr.Error()) + logger.Infof(ctx, "error in handle transaction, err: %s", txErr.Error()) return } }() @@ -96,12 +97,13 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto //check is corevalue present in database _, err = apprSvc.corevaluesRespo.GetCoreValue(ctx, int64(appreciation.CoreValueID)) if err != nil { - logger.Errorf(ctx,"err: %v", err) + logger.Errorf(ctx,"service: err: %v", err) return dto.Appreciation{}, err } // check self appreciation if appreciation.Receiver == sender { + logger.Errorf(ctx,"Self Appreciation Error: %v \n Userid: %d",apperrors.SelfAppreciationError,appreciation.Receiver) return dto.Appreciation{}, apperrors.SelfAppreciationError } @@ -118,6 +120,7 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto return res, nil } + logger.Debug(ctx,"service: createAppreciation result: ",res) quaterTimeStamp := user.GetQuarterStartUnixTime() reqGetUserById := dto.GetUserByIdReq{ @@ -127,14 +130,16 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto senderInfo,err := apprSvc.userRepo.GetUserById(ctx,reqGetUserById) if err != nil{ logger.Info(ctx,"error in getting create appreciation sender info") + return res, nil } reqGetUserById.UserId = appreciation.Receiver receiverInfo,err := apprSvc.userRepo.GetUserById(ctx,reqGetUserById) if err != nil{ logger.Info(ctx,"error in getting create appreciation sender info") + return res, nil } - err = sendAppreciationEmail(apprInfo,senderInfo.Email,receiverInfo.Email) + sendAppreciationEmail(apprInfo,senderInfo.Email,receiverInfo.Email) apprSvc.sendAppreciationNotificationToReceiver(ctx, apprInfo) apprSvc.sendAppreciationNotificationToAll(ctx, apprInfo) return res, nil @@ -142,25 +147,25 @@ func (apprSvc *service) CreateAppreciation(ctx context.Context, appreciation dto func (apprSvc *service) GetAppreciationById(ctx context.Context, appreciationId int32) (dto.AppreciationResponse, error) { - logger.Debug(ctx,"appreciationId: ",appreciationId) + logger.Debug(ctx,"service: appreciationId: ",appreciationId) resAppr, err := apprSvc.appreciationRepo.GetAppreciationById(ctx, nil, appreciationId) - logger.Debug(ctx,"apprSvc: resAppr: ",resAppr," err: ",err) if err != nil { logger.Errorf(ctx,"err: %v", err) return dto.AppreciationResponse{}, err } + logger.Debug(ctx,"service: resAppr: ",resAppr) return mapRepoGetAppreciationInfoToDTOGetAppreciationInfo(resAppr), nil } func (apprSvc *service) ListAppreciations(ctx context.Context, filter dto.AppreciationFilter) (dto.ListAppreciationsResponse, error) { - logger.Debug(ctx," filter: ",filter) + logger.Debug(ctx,"service: filter: ",filter) infos, pagination, err := apprSvc.appreciationRepo.ListAppreciations(ctx, nil, filter) - logger.Debug(ctx," infos: ",infos," pagination: ",pagination," err: ",err) if err != nil { logger.Errorf(ctx,"err: %v", err) return dto.ListAppreciationsResponse{}, err } + logger.Debug(ctx,"service: infos: ",infos," pagination: ",pagination) responses := make([]dto.AppreciationResponse, 0) for _, info := range infos { @@ -172,7 +177,7 @@ func (apprSvc *service) ListAppreciations(ctx context.Context, filter dto.Apprec } func (apprSvc *service) DeleteAppreciation(ctx context.Context, apprId int32) error { - logger.Debug(ctx,"apprSvc: apprId: ",apprId) + logger.Debug(ctx,"service: apprId: ",apprId) return apprSvc.appreciationRepo.DeleteAppreciation(ctx, nil, apprId) } @@ -182,6 +187,7 @@ func (apprSvc *service) UpdateAppreciation(ctx context.Context) (bool, error) { tx, err := apprSvc.appreciationRepo.BeginTx(ctx) if err != nil { + logger.Errorf(ctx,"error in begin transaction: %v",err) return false, err } @@ -189,7 +195,7 @@ func (apprSvc *service) UpdateAppreciation(ctx context.Context) (bool, error) { rvr := recover() defer func() { if rvr != nil { - logger.Info(ctx, "Transaction aborted because of panic: %v, Propagating panic further", rvr) + logger.Infof(ctx, "Transaction aborted because of panic: %v, Propagating panic further", rvr) panic(rvr) } }() @@ -197,7 +203,7 @@ func (apprSvc *service) UpdateAppreciation(ctx context.Context) (bool, error) { txErr := apprSvc.appreciationRepo.HandleTransaction(ctx, tx, err == nil && rvr == nil) if txErr != nil { err = txErr - logger.Info(ctx, "error in creating transaction, err: %s", txErr.Error()) + logger.Infof(ctx, "error in handle transaction, err: %s", txErr.Error()) return } }() @@ -205,16 +211,17 @@ func (apprSvc *service) UpdateAppreciation(ctx context.Context) (bool, error) { _, err = apprSvc.appreciationRepo.UpdateAppreciationTotalRewardsOfYesterday(ctx, tx) if err != nil { - logger.Error(ctx,"err: ", err.Error()) + logger.Errorf(ctx,"err: %v", err) return false, err } + logger.Debug(ctx,"service: UpdateAppreciationTotalRewardsOfYesterday completed") userBadgeDetails, err := apprSvc.appreciationRepo.UpdateUserBadgesBasedOnTotalRewards(ctx, tx) if err != nil { logger.Error(ctx,"err: ", err.Error()) return false, err } - logger.Debug(ctx,"apprSvc: UpdateAppreciation: ",userBadgeDetails) + logger.Debug(ctx,"service: UpdateAppreciation: ",userBadgeDetails) apprSvc.sendEmailForBadgeAllocation(userBadgeDetails) return true, nil } @@ -235,8 +242,7 @@ func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail CoreValueName: emailData.CoreValueName, } - logger.Info(context.Background(),"appreciation sender email: -----------> ",senderEmail) - logger.Info(context.Background(),"appreciation receiver email: -----------> ",receiverEmail) + logger.Infof(context.Background(),"appreciation sender email: %v :receiver email: %v ",senderEmail,receiverEmail) mailReq := email.NewMail([]string{receiverEmail}, []string{senderEmail}, []string{}, fmt.Sprintf("%s %s appreciated %s %s",emailData.SenderFirstName,emailData.SenderLastName,emailData.ReceiverFirstName,emailData.ReceiverLastName)) err := mailReq.ParseTemplate("./internal/app/email/templates/createAppreciation.html", templateData) if err != nil { @@ -253,7 +259,7 @@ func sendAppreciationEmail(emailData repository.AppreciationResponse,senderEmail func (apprSvc *service) sendAppreciationNotificationToReceiver(ctx context.Context, appr repository.AppreciationResponse) { - logger.Debug(ctx,"apprSvc: apprResponse: ",appr) + logger.Debug(ctx,"service: apprResponse: ",appr) notificationTokens, err := apprSvc.userRepo.ListDeviceTokensByUserID(ctx, appr.ReceiverID) if err != nil { logger.Errorf(ctx,"err in getting device tokens: %v", err) @@ -266,6 +272,7 @@ func (apprSvc *service) sendAppreciationNotificationToReceiver(ctx context.Conte Body: fmt.Sprintf("You've been appreciated by %s %s! Well done and keep up the JOSH!", appr.SenderFirstName, appr.SenderLastName), } + logger.Infof(ctx,"message: %v",msg) for _, notificationToken := range notificationTokens { msg.SendNotificationToNotificationToken(notificationToken) } @@ -279,12 +286,13 @@ func (apprSvc *service) sendAppreciationNotificationToAll(ctx context.Context, a Title: "Appreciation", Body: fmt.Sprintf(" %s %s appreciated %s %s", appr.SenderFirstName, appr.SenderLastName, appr.ReceiverFirstName, appr.ReceiverLastName), } + logger.Infof(ctx,"message: %v",msg) msg.SendNotificationToTopic("peerly") } func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repository.UserBadgeDetails) { - logger.Debug(context.Background(),"user Badge Details:---------------->\n ", userBadgeDetails) + logger.Debug(context.Background(),"service: user Badge Details: ", userBadgeDetails) for _, userBadgeDetail := range userBadgeDetails { // Determine the BadgeImageUrl based on the BadgeName @@ -312,18 +320,18 @@ func (apprSvc *service) sendEmailForBadgeAllocation(userBadgeDetails []repositor BadgeImageName: badgeImageUrl, AppreciationPoints: userBadgeDetail.BadgePoints, } - logger.Info(context.Background(),"badge data: ", templateData) + logger.Info(context.Background(),"service: badge data: ", templateData) mailReq := email.NewMail([]string{userBadgeDetail.Email}, []string{}, []string{}, "Received an badge") err := mailReq.ParseTemplate("./internal/app/email/templates/badge.html", templateData) if err != nil { - logger.Errorf(context.Background(),"err in creating html file : %v", err) + logger.Errorf(context.Background(),"service: err in creating html file : %v", err) return } err = mailReq.Send("badge allocation") if err != nil { - logger.Errorf(context.Background(),"err: %v", err) + logger.Errorf(context.Background(),"service: err: %v", err) return } + logger.Infof(context.Background(),"service: mail request: %v",mailReq) } - return } diff --git a/internal/app/cronjob/monthlyUpdateData.go b/internal/app/cronjob/monthlyUpdateData.go index 0ea1a98..f4c7221 100644 --- a/internal/app/cronjob/monthlyUpdateData.go +++ b/internal/app/cronjob/monthlyUpdateData.go @@ -62,6 +62,7 @@ func (cron *MonthlyJob) Task(ctx context.Context) { logger.Error(ctx,"err: ",err) if err == nil { sendRewardQuotaRefilledNotificationToAll() + logger.Info(ctx,"cronjob: monthly task completed") break } } diff --git a/internal/app/cronjob/updateDailyData.go b/internal/app/cronjob/updateDailyData.go index 31b6ed6..4c74f2e 100644 --- a/internal/app/cronjob/updateDailyData.go +++ b/internal/app/cronjob/updateDailyData.go @@ -2,6 +2,7 @@ package cronjob import ( "context" + "fmt" "github.com/go-co-op/gocron/v2" apprSvc "github.com/joshsoftware/peerly-backend/internal/app/appreciation" @@ -55,7 +56,7 @@ func (cron *DailyJob) Schedule() { cron.scheduler.Start() if err != nil { - logger.Warn(context.TODO(), "error occurred while scheduling %s, message %+v", cron.name, err.Error()) + logger.Warn(context.TODO(), fmt.Sprintf("error occurred while scheduling %s, message %+v", cron.name, err.Error())) } } @@ -67,6 +68,7 @@ func (cron *DailyJob) Task(ctx context.Context) { logger.Info(ctx," isSuccess: ",isSuccess," err: ",err) if err==nil && isSuccess{ + logger.Info(ctx,"cronjob: UpdateDaily data completed") break } } diff --git a/internal/app/organizationConfig/service.go b/internal/app/organizationConfig/service.go index b346531..b21451c 100644 --- a/internal/app/organizationConfig/service.go +++ b/internal/app/organizationConfig/service.go @@ -30,13 +30,13 @@ func NewService(organizationConfigRepo repository.OrganizationConfigStorer) Serv func (orgSvc *service) GetOrganizationConfig(ctx context.Context) (dto.OrganizationConfig, error) { - logger.Debug(ctx," orgSvc: GetOrganizationConfig") + logger.Debug(ctx,"orgSvc: GetOrganizationConfig") organization, err := orgSvc.OrganizationConfigRepo.GetOrganizationConfig(ctx,nil) - logger.Debug(context.Background()," orgSvc: GetOrganizationConfig: organization: ",organization," err: ",err) if err != nil { logger.Errorf(context.Background(),"err: %v",err) return dto.OrganizationConfig{}, err } + logger.Debug(ctx,"orgSvc: GetOrganizationConfig: organization: ",organization) org := organizationConfigToDTO(organization) return org, nil @@ -49,13 +49,13 @@ func (orgSvc *service) CreateOrganizationConfig(ctx context.Context, organizatio data := ctx.Value(constants.UserId) userID, ok := data.(int64) if !ok { - logger.Error(context.Background(),"err in parsing userid from token") + logger.Error(context.Background(),"orgsvc: err in parsing userid from token") return dto.OrganizationConfig{},apperrors.InternalServer } organizationConfig.CreatedBy = userID organizationConfig.UpdatedBy = userID - logger.Debug(ctx," organizationConfig: ",organizationConfig) + logger.Debug(ctx,"orgSvc: organizationConfig: ",organizationConfig) _ ,err := orgSvc.OrganizationConfigRepo.GetOrganizationConfig(ctx,nil); if err != apperrors.OrganizationConfigNotFound { return dto.OrganizationConfig{},apperrors.OrganizationConfigAlreadyPresent @@ -63,7 +63,7 @@ func (orgSvc *service) CreateOrganizationConfig(ctx context.Context, organizatio createdOrganizationConfig, err := orgSvc.OrganizationConfigRepo.CreateOrganizationConfig(ctx,nil, organizationConfig) if err != nil { - logger.Errorf(context.Background(),"err: %v",err) + logger.Errorf(ctx,"err: %v",err) return dto.OrganizationConfig{}, err } @@ -92,11 +92,11 @@ func (orgSvc *service) UpdateOrganizationConfig(ctx context.Context, organizatio logger.Debug(ctx," orgSvc: UpdateOrganizationConfig: organizationConfig: ",organizationConfig) updatedOrganization, err := orgSvc.OrganizationConfigRepo.UpdateOrganizationConfig(ctx,nil, organizationConfig) if err != nil { - logger.Errorf(ctx,"err: %v",err) + logger.Errorf(ctx,"orgSvc: err: %v",err) return dto.OrganizationConfig{}, err } org := organizationConfigToDTO(updatedOrganization) - logger.Debug(ctx," org: ",org) + logger.Debug(ctx,"orgSvc: updated organization: ",org) return org, nil } diff --git a/internal/app/reward/service.go b/internal/app/reward/service.go index 83748ff..d45dd16 100644 --- a/internal/app/reward/service.go +++ b/internal/app/reward/service.go @@ -37,48 +37,55 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d data := ctx.Value(constants.UserId) sender, ok := data.(int64) if !ok { - logger.Error(ctx,"err in parsing userid from token") + logger.Error(ctx,"rwrdSvc: err in parsing userid from token") return dto.Reward{}, apperrors.InternalServer } rewardReq.SenderId = sender appr, err := rwrdSvc.appreciationRepo.GetAppreciationById(ctx, nil, int32(rewardReq.AppreciationId)) - logger.Debug(ctx," appr: ",appr) if err != nil { + logger.Errorf(ctx,"rwrdSvc: gerAppreciationById err : %v",err) return dto.Reward{}, err } + logger.Debug(ctx,"rwrdSvc: appr: ",appr) if appr.SenderID == sender { + logger.Error(ctx,"rwrdSvc: SelfAppreciationRewardError") return dto.Reward{}, apperrors.SelfAppreciationRewardError } if appr.ReceiverID == sender { + logger.Error(ctx,"rwrdSvc: SelfRewardError") return dto.Reward{}, apperrors.SelfRewardError } userChk, err := rwrdSvc.rewardRepo.UserHasRewardQuota(ctx, nil, rewardReq.SenderId, rewardReq.Point) - logger.Debug(ctx," userChk: ",userChk," err: ",err) if err != nil { + logger.Errorf(ctx,"rwrdSvc: UserHasRewardQuota: err: %v",err) return dto.Reward{}, err } + logger.Debug(ctx," userChk: ",userChk) if !userChk { + logger.Error(ctx,"rwrdSvc: RewardQuotaIsNotSufficient") return dto.Reward{}, apperrors.RewardQuotaIsNotSufficient } rwrdChk, err := rwrdSvc.rewardRepo.IsUserRewardForAppreciationPresent(ctx, nil, rewardReq.AppreciationId, rewardReq.SenderId) - logger.Debug(ctx," rwrdChk: ",rwrdChk," err: ",err) if err != nil { + logger.Errorf(ctx,"rwrdSvc: IsUserRewardForAppreciationPresent: err: %v",err) return dto.Reward{}, err } - + if rwrdChk { + logger.Error(ctx," rwrdChk: RewardAlreadyPresent") return dto.Reward{}, apperrors.RewardAlreadyPresent } //initializing database transaction tx, err := rwrdSvc.rewardRepo.BeginTx(ctx) if err != nil { + logger.Error(ctx,"rwrdSvc: error in BeginTx") return dto.Reward{}, err } @@ -86,7 +93,7 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d rvr := recover() defer func() { if rvr != nil { - logger.Info(ctx, "Transaction aborted because of panic: %v, Propagating panic further", rvr) + logger.Infof(ctx, "Transaction aborted because of panic: %v, Propagating panic further", rvr) panic(rvr) } }() @@ -94,12 +101,13 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d txErr := rwrdSvc.appreciationRepo.HandleTransaction(ctx, tx, err == nil && rvr == nil) if txErr != nil { err = txErr - logger.Info(ctx, "error in creating transaction, err: %s", txErr.Error()) + logger.Infof(ctx, "error in creating transaction, err: %s", txErr.Error()) return } }() repoRewardRes, err := rwrdSvc.rewardRepo.GiveReward(ctx, tx, rewardReq) if err != nil { + logger.Errorf(ctx,"rwrdSvc: GiveReward: err: %v",err) return dto.Reward{}, err } @@ -107,10 +115,12 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d deduceChk, err := rwrdSvc.rewardRepo.DeduceRewardQuotaOfUser(ctx, tx, rewardReq.SenderId, int(rewardReq.Point)) if err != nil { + logger.Errorf(ctx,"rwrdSvc: DeduceRewardQuotaOfUser: err: %v",err) return dto.Reward{}, err } if !deduceChk { + logger.Error(ctx,"rwrdSvc: DeduceRewardQuotaOfUser") return dto.Reward{}, apperrors.InternalServer } diff --git a/internal/app/users/service.go b/internal/app/users/service.go index d692ed4..489a425 100644 --- a/internal/app/users/service.go +++ b/internal/app/users/service.go @@ -488,6 +488,7 @@ func (us *service) GetUserById(ctx context.Context) (user dto.GetUserByIdResp, e func (us *service) GetActiveUserList(ctx context.Context) ([]dto.ActiveUser, error) { activeUserDb, err := us.userRepo.GetActiveUserList(ctx, nil) if err != nil { + logger.Errorf(ctx,"usrSvc: GetActiveUserList: err: %v",err) return []dto.ActiveUser{}, err } res := make([]dto.ActiveUser, 0) diff --git a/internal/pkg/logger/log.go b/internal/pkg/logger/log.go index 69a55a8..cf19033 100644 --- a/internal/pkg/logger/log.go +++ b/internal/pkg/logger/log.go @@ -23,70 +23,49 @@ var lumberjackLogger = &lumberjack.Logger{ // Error - prints out an error func Error(ctx context.Context, args ...interface{}) { - requestID, ok := ctx.Value(constants.RequestID).(string) - if !ok { - requestID = "" - } - Logger.Error(requestID, args) + log := setRequestId(ctx) + log.Error(args...) } // Errorf - prints out an error with formatted output func Errorf(ctx context.Context, format string, args ...interface{}) { - requestID, ok := ctx.Value(constants.RequestID).(string) - if !ok { - requestID = "" - } - Logger.Errorf("req_id: [%s] "+format, append([]interface{}{requestID}, args...)...) + log := setRequestId(ctx) + log.Errorf(format,args...) } // Warn - prints out a warning func Warn(ctx context.Context, args ...interface{}) { - requestID, ok := ctx.Value(constants.RequestID).(string) - if !ok { - requestID = "" - } - Logger.Warn("req_id: ", requestID, args) + log := setRequestId(ctx) + log.Warn(args...) } // Fatal - will print out the error info and exit the program func Fatal(ctx context.Context, args ...interface{}) { - requestID, ok := ctx.Value(constants.RequestID).(string) - if !ok { - requestID = "" - } - Logger.Fatal("req_id: ", requestID, args) + log := setRequestId(ctx) + log.Fatal(args...) } // Info - prints out basic information func Info(ctx context.Context, args ...interface{}) { - requestID, ok := ctx.Value(constants.RequestID).(string) - if !ok { - requestID = "" - } - Logger.Info("req_id: ", requestID, args) + log := setRequestId(ctx) + log.Info(args...) } // Infof - prints out basic information func Infof(ctx context.Context, format string, args ...interface{}) { - requestID, ok := ctx.Value(constants.RequestID).(string) - if !ok { - requestID = "" - } - Logger.Infof("req_id: [%s] "+format, append([]interface{}{requestID}, args...)...) + log := setRequestId(ctx) + log.Infof(format,args...) } // Debug - prints out debug information func Debug(ctx context.Context, args ...interface{}) { - requestID, ok := ctx.Value(constants.RequestID).(string) - if !ok { - requestID = "" - } - Logger.Debug("req_id: ", requestID, args) + log := setRequestId(ctx) + log.Debug(args...) } func SetupLogger() (*l.Logger, error) { - lumberjackLogger.Filename = fmt.Sprintf("./logs/%s_peerly_backend.log", time.Now().Format("2006-01-02_15-04-05")) + lumberjackLogger.Filename = fmt.Sprintf("/var/log/peerly/%s_peerly_backend.log", time.Now().Format("2006-01-02_15-04-05")) file, err := os.Create(lumberjackLogger.Filename) if err != nil { return nil, fmt.Errorf("failed to create log file: %w", err) @@ -106,3 +85,11 @@ func SetupLogger() (*l.Logger, error) { Logger = logger return logger, nil } + +func setRequestId(ctx context.Context) *l.Entry{ + requestID, ok := ctx.Value(constants.RequestID).(string) + if !ok { + requestID = "N/A" + } + return Logger.WithField("req_id",requestID) +} diff --git a/internal/pkg/middleware/jwtMiddleware.go b/internal/pkg/middleware/jwtMiddleware.go index 9c6bc8e..120b177 100644 --- a/internal/pkg/middleware/jwtMiddleware.go +++ b/internal/pkg/middleware/jwtMiddleware.go @@ -72,8 +72,8 @@ func JwtAuthMiddleware(next http.Handler, roles []string) http.Handler { // RequestIDMiddleware generates a request ID and adds it to the request context. func RequestIDMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reqestId := uuid.NewString() - ctx := context.WithValue(r.Context(), constants.RequestID, reqestId) + requestID := uuid.NewString() + ctx := context.WithValue(r.Context(), constants.RequestID, requestID) r = r.WithContext(ctx) next.ServeHTTP(w, r) }) diff --git a/internal/repository/postgresdb/appreciation.go b/internal/repository/postgresdb/appreciation.go index a4121c6..502f185 100644 --- a/internal/repository/postgresdb/appreciation.go +++ b/internal/repository/postgresdb/appreciation.go @@ -38,7 +38,7 @@ func NewAppreciationRepo(db *sqlx.DB) repository.AppreciationStorer { func (appr *appreciationsStore) CreateAppreciation(ctx context.Context, tx repository.Transaction, appreciation dto.Appreciation) (repository.Appreciation, error) { - logger.Debug(ctx," appr: CreateAppreciation: appreciation: ",appreciation) + logger.Debug(ctx,"repoAppr: CreateAppreciation: appreciation: ",appreciation) queryExecutor := appr.InitiateQueryExecutor(tx) insertQuery, args, err := repository.Sq. @@ -47,25 +47,26 @@ func (appr *appreciationsStore) CreateAppreciation(ctx context.Context, tx repos Suffix("RETURNING id,core_value_id, description,total_reward_points,quarter,sender,receiver,created_at,updated_at"). ToSql() if err != nil { - logger.Errorf(ctx,"error in generating squirrel query, err: %v", err) + logger.Errorf(ctx,"repoAppr: error in generating squirrel query, err: %v", err) return repository.Appreciation{}, apperrors.InternalServerError } - logger.Debug(ctx," insertQuery: ",insertQuery) - logger.Debug(ctx," args: ",args) + logger.Infof(ctx,"repoAppr: insertQuery: %s , args: %v",insertQuery,args) + var resAppr repository.Appreciation err = queryExecutor.QueryRowx(insertQuery, args...).StructScan(&resAppr) if err != nil { - logger.Errorf(ctx,"Error executing create appreciation insert query: %v", err) + logger.Errorf(ctx,"repoAppr: Error executing create appreciation insert query: %v", err) return repository.Appreciation{}, apperrors.InternalServer } + logger.Debug(ctx,"repoAppr: createappreciation response: ",resAppr) return resAppr, nil } func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repository.Transaction, apprId int32) (repository.AppreciationResponse, error) { - logger.Debug(ctx," appr: GetAppreciationById: apprId: ",apprId) + logger.Debug(ctx,"repoAppr: GetAppreciationById: apprId: ",apprId) queryExecutor := appr.InitiateQueryExecutor(tx) // Get logged-in user ID @@ -120,26 +121,26 @@ func (appr *appreciationsStore) GetAppreciationById(ctx context.Context, tx repo return repository.AppreciationResponse{}, apperrors.InternalServer } - logger.Debug(ctx," appr: query: ",query) - logger.Debug(ctx," appr: args: ",args) + logger.Infof(ctx,"repoAppr: insertQuery: %s , args: %v",query,args) + var resAppr repository.AppreciationResponse // Execute the query err = queryExecutor.QueryRowx(query, args...).StructScan(&resAppr) if err != nil { if err == sql.ErrNoRows { - logger.Warn(ctx,fmt.Sprintf("no appreciation found with id: %d", apprId)) + logger.Errorf(ctx,"repoAppr: no appreciation found with id: %d", apprId) return repository.AppreciationResponse{}, apperrors.AppreciationNotFound } - logger.Errorf(ctx,"failed to execute query: %v", err) + logger.Errorf(ctx,"repoAppr: failed to execute query: %v", err) return repository.AppreciationResponse{}, apperrors.InternalServer } - logger.Debug(ctx," resAppr: ",resAppr) + logger.Debug(ctx,"repoAppr: appreciationById: ",resAppr) return resAppr, nil } func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx repository.Transaction, filter dto.AppreciationFilter) ([]repository.AppreciationResponse, repository.Pagination, error) { - logger.Debug(ctx," appr: ListAppreciations: filter: ",filter) + logger.Debug(ctx,"repoAppr: ListAppreciations: filter: ",filter) queryExecutor := appr.InitiateQueryExecutor(tx) // Get logged-in user ID @@ -176,12 +177,11 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi countSql, countArgs, err := queryBuilder.ToSql() if err != nil { - logger.Error(ctx,"failed to build count query: ", err.Error()) + logger.Error(ctx,"repoAppr: failed to build count query: ", err.Error()) return []repository.AppreciationResponse{}, repository.Pagination{}, apperrors.InternalServerError } - logger.Debug(ctx,"countSql: ",countSql) - logger.Debug(ctx,"countArgs: ",countArgs) + logger.Debug(ctx,fmt.Sprintf("repoAppr: listAppreciation: countSql: %s, countArgs: %v",countSql,countArgs)) var totalRecords int32 err = queryExecutor.QueryRowx(countSql, countArgs...).Scan(&totalRecords) @@ -234,7 +234,6 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi } offset := (filter.Page - 1) * filter.Limit - logger.Debug(ctx," offset: ",offset) // Add pagination queryBuilder = queryBuilder.Limit(uint64(filter.Limit)).Offset(uint64(offset)) sql, args, err := queryBuilder.ToSql() @@ -243,20 +242,15 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi return nil, repository.Pagination{}, apperrors.InternalServerError } - logger.Debug(ctx," sqlQuery: ",sql) - logger.Debug(ctx," args: ",args) + logger.Debug(ctx,fmt.Sprintf("repoAppr: listAprreciation: sqlQuery: %s,args: %v",sql,args)) queryExecutor = appr.InitiateQueryExecutor(tx) res := make([]repository.AppreciationResponse, 0) - - logger.Info(ctx,"filter: ", filter) - logger.Info(ctx,"sql: ", sql) - logger.Info(ctx,"args: ", args) err = sqlx.Select(queryExecutor, &res, sql, args...) if err != nil { - logger.Error(ctx,"failed to execute query appreciation: ", err.Error()) - logger.Error(ctx,"err res data: ", res) + logger.Error(ctx,"repoAppr:failed to execute query appreciation: ", err.Error()) return nil, repository.Pagination{}, apperrors.InternalServerError } + logger.Error(ctx,"repoAppr: res data: ", res) id := ctx.Value(constants.UserId) logger.Debug(ctx," id -> ", id) userId, ok := ctx.Value(constants.UserId).(int64) @@ -275,8 +269,7 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi return nil, repository.Pagination{}, apperrors.InternalServerError } - logger.Debug(ctx," query: ",query) - logger.Debug(ctx," args: ",args) + logger.Debug(ctx,fmt.Sprintf("repoAppr: resolutions query: %s,args: %v",query,args)) err = appr.DB.SelectContext(ctx, &userIds, query, args...) if err != nil { logger.Errorf(ctx,"error in reported flag query, err: %s", err.Error()) @@ -285,14 +278,12 @@ func (appr *appreciationsStore) ListAppreciations(ctx context.Context, tx reposi res[idx].ReportedFlag = slices.Contains(userIds, userId) } - logger.Debug(ctx," res: ",res) - logger.Debug(ctx," pagination: ",pagination) + logger.Debug(ctx,fmt.Sprintf("repoAppr: res: %v, pagination : %v",res,pagination)) return res, pagination, nil } func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repository.Transaction, apprId int32) error { - logger.Debug(ctx," appr: ",appr) - logger.Debug(ctx," apprId: ",apprId) + logger.Debug(ctx,"repoAppr: apprId: ",apprId) query, args, err := repository.Sq.Update(appr.AppreciationsTable). Set("is_valid", false). Where(squirrel.And{ @@ -301,8 +292,7 @@ func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repos }). ToSql() - logger.Debug(ctx," query: ",query) - logger.Debug(ctx," args: ",args) + logger.Debug(ctx,fmt.Sprintf("repoAppr: query: %s,args: %v",query,args)) if err != nil { logger.Error(ctx,"Error building SQL: ", err.Error()) return apperrors.InternalServer @@ -332,7 +322,7 @@ func (appr *appreciationsStore) DeleteAppreciation(ctx context.Context, tx repos func (appr *appreciationsStore) IsUserPresent(ctx context.Context, tx repository.Transaction, userID int64) (bool, error) { - logger.Debug(ctx," appr: IsUserPresent: userID: ",userID) + logger.Debug(ctx,"repoAppr: IsUserPresent: userID: ",userID) // Build the SQL query query, args, err := repository.Sq.Select("COUNT(*)"). From(appr.UsersTable). @@ -345,6 +335,7 @@ func (appr *appreciationsStore) IsUserPresent(ctx context.Context, tx repository return false, apperrors.InternalServer } + logger.Debug(ctx,fmt.Sprintf("repoAppr: query: %s,args: %v",query,args)) queryExecutor := appr.InitiateQueryExecutor(tx) var count int @@ -355,13 +346,12 @@ func (appr *appreciationsStore) IsUserPresent(ctx context.Context, tx repository return false, apperrors.InternalServer } - logger.Debug(ctx," count: ",count) + logger.Debug(ctx,"repoAppr: count: ",count) // Check if user is present return count > 0, nil } func (appr *appreciationsStore) UpdateAppreciationTotalRewardsOfYesterday(ctx context.Context, tx repository.Transaction) (bool, error) { - logger.Debug(ctx,"appr: UpdateAppreciationTotalRewardsOfYesterday") logger.Info(ctx,"appr: UpdateAppreciationTotalRewardsOfYesterday") // Initialize query executor queryExecutor := appr.InitiateQueryExecutor(tx) @@ -397,7 +387,7 @@ WHERE app.id = agg.appreciation_id; logger.Error(ctx," err: ",err) return false,nil } - logger.Info(ctx," rowsAffected: ",rowsAffected) + logger.Info(ctx,"repoAppr: rowsAffected: ",rowsAffected) return true, nil } @@ -488,9 +478,10 @@ JOIN badges b ON ib.badge_id = b.id; ` - logger.Debug(ctx," query: ",query) + logger.Debug(ctx,fmt.Sprintf("repoAppr: query: %s, args: %v %v",query,afterTime,afterTime)) rows, err := queryExecutor.Query(query, afterTime, afterTime) if err != nil { + logger.Error(ctx,"repoAppr: error in extecution query") return []repository.UserBadgeDetails{}, err } defer rows.Close() diff --git a/internal/repository/postgresdb/organizationConfig.go b/internal/repository/postgresdb/organizationConfig.go index bb59725..771335c 100644 --- a/internal/repository/postgresdb/organizationConfig.go +++ b/internal/repository/postgresdb/organizationConfig.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "fmt" "time" sq "github.com/Masterminds/squirrel" @@ -29,8 +30,7 @@ func NewOrganizationConfigRepo(db *sqlx.DB) repository.OrganizationConfigStorer func (org *OrganizationConfigStore) CreateOrganizationConfig(ctx context.Context,tx repository.Transaction, orgConfigInfo dto.OrganizationConfig) (createdOrganization repository.OrganizationConfig, err error) { - logger.Info(ctx," org: CreateOrganizationConfig") - logger.Debug(ctx," orgConfigInfo: ",orgConfigInfo) + logger.Infof(ctx,"orgRepo: CreateOrganizationConfig: %v",orgConfigInfo) queryExecutor := org.InitiateQueryExecutor(tx) insertQuery, args, err := repository.Sq. @@ -47,6 +47,8 @@ func (org *OrganizationConfigStore) CreateOrganizationConfig(ctx context.Context logger.Errorf(ctx,"err in creating query: %v",err) return repository.OrganizationConfig{}, apperrors.InternalServer } + + logger.Debug(ctx,fmt.Sprintf("orgRepo: query: %s,args: %v",insertQuery,args)) err = queryExecutor.QueryRowx(insertQuery, args...).StructScan(&createdOrganization) if err != nil { @@ -56,13 +58,12 @@ func (org *OrganizationConfigStore) CreateOrganizationConfig(ctx context.Context } } - logger.Debug(ctx," query: ",insertQuery) - logger.Debug(ctx," args: ",args) + logger.Debug(ctx,fmt.Sprintf("orgRepo: query: %s,args: %v",insertQuery,args)) return } func (org *OrganizationConfigStore) UpdateOrganizationConfig(ctx context.Context, tx repository.Transaction, reqOrganization dto.OrganizationConfig) (updatedOrganization repository.OrganizationConfig, err error) { - logger.Info(ctx," org: UpdateOrganizationConfig: ") + logger.Infof(ctx,"orgRepo: UpdateOrganizationConfig: %v",reqOrganization) queryExecutor := org.InitiateQueryExecutor(tx) updateBuilder := repository.Sq.Update(org.OrganizationConfigTable). @@ -89,12 +90,11 @@ func (org *OrganizationConfigStore) UpdateOrganizationConfig(ctx context.Context return repository.OrganizationConfig{}, err } - logger.Debug(ctx," query: ",query) - logger.Debug(ctx," args: ",args) + logger.Debug(ctx,fmt.Sprintf("orgRepo: query: %s,args: %v",query,args)) err = queryExecutor.QueryRowx(query, args...).StructScan(&updatedOrganization) if err != nil { if err == sql.ErrNoRows { - logger.Errorf(ctx,"err in updating orgconfig : %v ", err) + logger.Errorf(ctx,"orgRepo: err in updating orgconfig : %v ", err) return repository.OrganizationConfig{}, apperrors.InternalServer } } @@ -103,7 +103,7 @@ func (org *OrganizationConfigStore) UpdateOrganizationConfig(ctx context.Context // GetOrganization - returns an organization from the database if it exists based on its ID primary key func (org *OrganizationConfigStore) GetOrganizationConfig(ctx context.Context, tx repository.Transaction) (updatedOrgConfig repository.OrganizationConfig, err error) { - logger.Debug(ctx," org: GetOrganizationConfig") + logger.Debug(ctx,"orgRepo: GetOrganizationConfig") queryExecutor := org.InitiateQueryExecutor(tx) queryBuilder := repository.Sq. @@ -117,6 +117,8 @@ func (org *OrganizationConfigStore) GetOrganizationConfig(ctx context.Context, t return repository.OrganizationConfig{}, err } + logger.Debug(ctx,fmt.Sprintf("orgRepo: query: %s,args: %v",query,args)) + err = queryExecutor.QueryRowx( query, args...).StructScan(&updatedOrgConfig) if err != nil { if errors.Is(err, sql.ErrNoRows) { diff --git a/internal/repository/postgresdb/rewards.go b/internal/repository/postgresdb/rewards.go index 0e3466a..a14a170 100644 --- a/internal/repository/postgresdb/rewards.go +++ b/internal/repository/postgresdb/rewards.go @@ -2,14 +2,15 @@ package repository import ( "context" + "fmt" "github.com/Masterminds/squirrel" "github.com/jmoiron/sqlx" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - "github.com/joshsoftware/peerly-backend/internal/repository" logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" + "github.com/joshsoftware/peerly-backend/internal/repository" ) type rewardStore struct { @@ -24,7 +25,7 @@ func NewRewardRepo(db *sqlx.DB) repository.RewardStorer { func (rwrd *rewardStore) GiveReward(ctx context.Context, tx repository.Transaction, reward dto.Reward) (repository.Reward, error) { - logger.Debug(ctx," rwrd: GiveReward") + logger.Debug(ctx,fmt.Sprintf("rwrdRepo: GiveReward: %v",reward)) queryExecutor := rwrd.InitiateQueryExecutor(tx) insertQuery, args, err := repository.Sq. Insert("rewards"). @@ -38,8 +39,7 @@ func (rwrd *rewardStore) GiveReward(ctx context.Context, tx repository.Transacti return repository.Reward{}, apperrors.InternalServer } - logger.Debug(ctx," insertQuery: ",insertQuery) - logger.Debug(ctx," args: ",args) + logger.Debug(ctx,fmt.Sprintf("rwrdRepo: insertQuery: %s,args: %v",insertQuery,args)) var rewardInfo repository.Reward err = queryExecutor.QueryRowx(insertQuery, args...).Scan(&rewardInfo.Id, &rewardInfo.AppreciationId, &rewardInfo.Point, &rewardInfo.SenderId, &rewardInfo.CreatedAt) if err != nil { @@ -54,8 +54,7 @@ func (rwrd *rewardStore) GiveReward(ctx context.Context, tx repository.Transacti func (rwrd *rewardStore) IsUserRewardForAppreciationPresent(ctx context.Context, tx repository.Transaction, apprId int64, senderId int64) (bool, error) { // Initialize the Squirrel query builder - logger.Info(ctx," appr id: ", apprId) - logger.Info(ctx," sender: ", senderId) + logger.Infof(ctx,"rwrdRepo: appr id: %d,sender: %d", apprId,senderId) // Build the SQL query query, args, err := repository.Sq.Select("COUNT(*)"). From("rewards"). @@ -65,11 +64,11 @@ func (rwrd *rewardStore) IsUserRewardForAppreciationPresent(ctx context.Context, }). ToSql() if err != nil { - logger.Error(ctx,"err ", err.Error()) + logger.Error(ctx,"rwrdRepo: err ", err.Error()) return false, apperrors.InternalServer } - logger.Debug(ctx," query: ", query) + logger.Debug(ctx,fmt.Sprintf("rwrdRepo: query: %s,args: %v", query,args)) queryExecutor := rwrd.InitiateQueryExecutor(tx) @@ -80,7 +79,7 @@ func (rwrd *rewardStore) IsUserRewardForAppreciationPresent(ctx context.Context, logger.Error(ctx,"failed to execute query: ", err.Error()) return false, apperrors.InternalServer } - logger.Info(ctx," count: ", count) + logger.Info(ctx,"rwrdRepo: userCount: ", count) // Check if user and appreciation id is present return count > 0, nil } @@ -99,6 +98,7 @@ func (rwrd *rewardStore) DeduceRewardQuotaOfUser(ctx context.Context, tx reposit return false, err } + logger.Debug(ctx,fmt.Sprintf("rwrdRepo: query: %s,args: %v", updateQuery,args)) // Execute the query within the transaction context result, err := queryExecutor.Exec(updateQuery, args...) if err != nil { @@ -134,8 +134,7 @@ func (rwrd *rewardStore) UserHasRewardQuota(ctx context.Context, tx repository.T // Arguments for the query args := []interface{}{userID, points} - logger.Info(ctx,"id: ", userID, "points: ", points) - logger.Info(ctx,"query: ", query) + logger.Infof(ctx,"rwrdRepo: query: %s,id: %d,points: %d", query,userID, points) queryExecutor := rwrd.InitiateQueryExecutor(tx) @@ -146,7 +145,7 @@ func (rwrd *rewardStore) UserHasRewardQuota(ctx context.Context, tx repository.T logger.Error(ctx,"failed to execute query: ", err.Error()) return false, apperrors.InternalServer } - logger.Info(ctx," count: ", count) + logger.Info(ctx,"rwrdRepo: count: ", count) // Check if user is present return count > 0, nil } From 24abb1479edf229944603b98f7c06c3c53ec531a Mon Sep 17 00:00:00 2001 From: Samnit Patil Date: Mon, 2 Sep 2024 12:24:38 +0530 Subject: [PATCH 22/22] [feature/addEmailAndNotification] data field added in notification --- internal/app/notification/service.go | 33 +++++++++-------- internal/app/reward/service.go | 54 ++++++++++++++-------------- internal/pkg/constants/system.go | 2 ++ 3 files changed, 48 insertions(+), 41 deletions(-) diff --git a/internal/app/notification/service.go b/internal/app/notification/service.go index da319cd..9b9a2e7 100644 --- a/internal/app/notification/service.go +++ b/internal/app/notification/service.go @@ -17,9 +17,10 @@ type NotificationService interface { } type Message struct { - Title string `json:"title,omitempty"` - Body string `json:"body,omitempty"` - ImageURL string `json:"image,omitempty"` + Title string `json:"title,omitempty"` + Body string `json:"body,omitempty"` + ImageURL string `json:"image,omitempty"` + Data map[string]string `json:"data,omitempty"` } func (notificationSvc *Message) SendNotificationToNotificationToken(notificationToken string) (err error) { @@ -31,7 +32,7 @@ func (notificationSvc *Message) SendNotificationToNotificationToken(notification opt := option.WithCredentialsFile(serviceAccountKey) app, err := firebase.NewApp(context.Background(), nil, opt) if err != nil { - logger.Errorf(context.Background(),"Error initializing app: %v", err) + logger.Errorf(context.Background(), "Error initializing app: %v", err) err = apperrors.InternalServerError return } @@ -39,12 +40,12 @@ func (notificationSvc *Message) SendNotificationToNotificationToken(notification // Obtain a messaging client from the Firebase app client, err := app.Messaging(context.Background()) if err != nil { - logger.Errorf(context.Background(),"Error getting Messaging client: %v", err) + logger.Errorf(context.Background(), "Error getting Messaging client: %v", err) err = apperrors.InternalServerError return } - logger.Debug(context.Background()," notificationSvc: ",notificationSvc) + logger.Debug(context.Background(), " notificationSvc: ", notificationSvc) // Create a message to send message := &messaging.Message{ Notification: &messaging.Notification{ @@ -52,18 +53,19 @@ func (notificationSvc *Message) SendNotificationToNotificationToken(notification Body: notificationSvc.Body, }, Token: notificationToken, + Data: notificationSvc.Data, } // Send the message response, err := client.Send(context.Background(), message) - logger.Debug(context.Background()," response: ",response) - logger.Debug(context.Background()," err: ",err) + logger.Debug(context.Background(), " response: ", response) + logger.Debug(context.Background(), " err: ", err) if err != nil { - logger.Errorf(context.Background(),"Error sending message: %v", err) + logger.Errorf(context.Background(), "Error sending message: %v", err) err = apperrors.InternalServerError return } - logger.Infof(context.Background(),"Successfully sent message: %v", response) + logger.Infof(context.Background(), "Successfully sent message: %v", response) return } @@ -76,7 +78,7 @@ func (notificationSvc *Message) SendNotificationToTopic(topic string) (err error opt := option.WithCredentialsFile(serviceAccountKey) app, err := firebase.NewApp(context.Background(), nil, opt) if err != nil { - logger.Errorf(context.Background(),"error initializing app: %v", err) + logger.Errorf(context.Background(), "error initializing app: %v", err) err = apperrors.InternalServerError return } @@ -84,12 +86,12 @@ func (notificationSvc *Message) SendNotificationToTopic(topic string) (err error // Obtain a messaging client from the Firebase app client, err := app.Messaging(context.Background()) if err != nil { - logger.Errorf(context.Background(),"error getting Messaging client: %v", err) + logger.Errorf(context.Background(), "error getting Messaging client: %v", err) err = apperrors.InternalServerError return } - logger.Debug(context.Background()," notificationSvc: ",notificationSvc) + logger.Debug(context.Background(), " notificationSvc: ", notificationSvc) // Create a message to send message := &messaging.Message{ Notification: &messaging.Notification{ @@ -97,17 +99,18 @@ func (notificationSvc *Message) SendNotificationToTopic(topic string) (err error Body: notificationSvc.Body, }, Topic: topic, + Data: notificationSvc.Data, } // Send the message response, err := client.Send(context.Background(), message) if err != nil { - logger.Errorf(context.Background(),"error sending message: %v", err) + logger.Errorf(context.Background(), "error sending message: %v", err) err = apperrors.InternalServerError return } - logger.Infof(context.Background(),"Successfully sent message: %v", response) + logger.Infof(context.Background(), "Successfully sent message: %v", response) return } diff --git a/internal/app/reward/service.go b/internal/app/reward/service.go index 48923f4..f14a346 100644 --- a/internal/app/reward/service.go +++ b/internal/app/reward/service.go @@ -2,14 +2,15 @@ package reward import ( "context" + "strconv" "github.com/joshsoftware/peerly-backend/internal/app/notification" user "github.com/joshsoftware/peerly-backend/internal/app/users" "github.com/joshsoftware/peerly-backend/internal/pkg/apperrors" "github.com/joshsoftware/peerly-backend/internal/pkg/constants" "github.com/joshsoftware/peerly-backend/internal/pkg/dto" - "github.com/joshsoftware/peerly-backend/internal/repository" logger "github.com/joshsoftware/peerly-backend/internal/pkg/logger" + "github.com/joshsoftware/peerly-backend/internal/repository" ) type service struct { @@ -32,18 +33,18 @@ func NewService(rewardRepo repository.RewardStorer, appreciationRepo repository. func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (dto.Reward, error) { - logger.Debug(ctx," rwrdSvc: GiveReward: ",rewardReq) + logger.Debug(ctx, " rwrdSvc: GiveReward: ", rewardReq) //add sender data := ctx.Value(constants.UserId) sender, ok := data.(int64) if !ok { - logger.Error(ctx,"err in parsing userid from token") + logger.Error(ctx, "err in parsing userid from token") return dto.Reward{}, apperrors.InternalServer } rewardReq.SenderId = sender appr, err := rwrdSvc.appreciationRepo.GetAppreciationById(ctx, nil, int32(rewardReq.AppreciationId)) - logger.Debug(ctx," appr: ",appr) + logger.Debug(ctx, " appr: ", appr) if err != nil { return dto.Reward{}, err } @@ -57,7 +58,7 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d } userChk, err := rwrdSvc.rewardRepo.UserHasRewardQuota(ctx, nil, rewardReq.SenderId, rewardReq.Point) - logger.Debug(ctx," userChk: ",userChk," err: ",err) + logger.Debug(ctx, " userChk: ", userChk, " err: ", err) if err != nil { return dto.Reward{}, err } @@ -67,7 +68,7 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d } rwrdChk, err := rwrdSvc.rewardRepo.IsUserRewardForAppreciationPresent(ctx, nil, rewardReq.AppreciationId, rewardReq.SenderId) - logger.Debug(ctx," rwrdChk: ",rwrdChk," err: ",err) + logger.Debug(ctx, " rwrdChk: ", rwrdChk, " err: ", err) if err != nil { return dto.Reward{}, err } @@ -114,67 +115,68 @@ func (rwrdSvc *service) GiveReward(ctx context.Context, rewardReq dto.Reward) (d return dto.Reward{}, apperrors.InternalServer } - - var reward dto.Reward reward.Id = repoRewardRes.Id reward.AppreciationId = repoRewardRes.AppreciationId reward.SenderId = repoRewardRes.SenderId reward.Point = repoRewardRes.Point quaterTimeStamp := user.GetQuarterStartUnixTime() - + req := dto.GetUserByIdReq{ UserId: sender, QuaterTimeStamp: quaterTimeStamp, } - userInfo ,err := rwrdSvc.userRepo.GetUserById(ctx,req) + userInfo, err := rwrdSvc.userRepo.GetUserById(ctx, req) if err != nil { - logger.Errorf(ctx,"err in getting user data: %v",err) + logger.Errorf(ctx, "err in getting user data: %v", err) } - rwrdSvc.sendRewardNotificationToSender(ctx,userInfo) - rwrdSvc.sendRewardNotificationToReceiver(ctx,appr.ReceiverID) + rwrdSvc.sendRewardNotificationToSender(ctx, userInfo, rewardReq.AppreciationId) + rwrdSvc.sendRewardNotificationToReceiver(ctx, appr.ReceiverID, rewardReq.AppreciationId) return reward, nil } +func (rwrdSvc *service) sendRewardNotificationToSender(ctx context.Context, user dto.GetUserByIdResp, apprID int64) { -func (rwrdSvc *service) sendRewardNotificationToSender(ctx context.Context, user dto.GetUserByIdResp) { - - logger.Debug(ctx," rwrdSvc: sendRewardNotificationToSender: user: ",user) + logger.Debug(ctx, " rwrdSvc: sendRewardNotificationToSender: user: ", user) notificationTokens, err := rwrdSvc.userRepo.ListDeviceTokensByUserID(ctx, user.UserId) - logger.Debug(ctx," notificationTokens: ",notificationTokens) + logger.Debug(ctx, " notificationTokens: ", notificationTokens) if err != nil { - logger.Errorf(ctx,"err in gettinsendRewardNotificationToSenderg device tokens: %v", err) - return + logger.Errorf(ctx, "err in gettinsendRewardNotificationToSenderg device tokens: %v", err) + return } + msgData := map[string]string{constants.AppreciationID: strconv.FormatInt(apprID, 10)} msg := notification.Message{ Title: "Reward Given Successfully", Body: "You have successfully given a reward! ", + Data: msgData, } - logger.Debug(ctx," msg: ",msg) + logger.Debug(ctx, " msg: ", msg) for _, notificationToken := range notificationTokens { msg.SendNotificationToNotificationToken(notificationToken) } } -func (rwrdSvc *service) sendRewardNotificationToReceiver(ctx context.Context, userID int64) { +func (rwrdSvc *service) sendRewardNotificationToReceiver(ctx context.Context, userID int64, apprID int64) { - logger.Debug(ctx," rwrdSvc: sendRewardNotificationToReceiver") + logger.Debug(ctx, " rwrdSvc: sendRewardNotificationToReceiver") notificationTokens, err := rwrdSvc.userRepo.ListDeviceTokensByUserID(ctx, userID) - logger.Debug(ctx," notificationTokens: ",notificationTokens) + logger.Debug(ctx, " notificationTokens: ", notificationTokens) if err != nil { - logger.Errorf(ctx," err in getting device tokens: %v", err) - return + logger.Errorf(ctx, " err in getting device tokens: %v", err) + return } + msgData := map[string]string{constants.AppreciationID: strconv.FormatInt(apprID, 10)} msg := notification.Message{ Title: "Reward's incoming!", Body: "You've been awarded a reward! Well done and keep up the JOSH!", + Data: msgData, } - logger.Debug(ctx," rwrdSvc: msg: ",msg) + logger.Debug(ctx, " rwrdSvc: msg: ", msg) for _, notificationToken := range notificationTokens { msg.SendNotificationToNotificationToken(notificationToken) } diff --git a/internal/pkg/constants/system.go b/internal/pkg/constants/system.go index 38efe89..c01e85b 100644 --- a/internal/pkg/constants/system.go +++ b/internal/pkg/constants/system.go @@ -73,5 +73,7 @@ const ( //notificatio service account key file const ServiceAccountKey = "serviceAccountKey.json" +const AppreciationID = "appreciation_id" + // Email Dl group of HRs const HRDLGroup = "dl_peerly.support@joshsoftware.com" \ No newline at end of file