From c742cb01c3e4f864423e51cbb3fe7379c741665e Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Sat, 20 Jun 2026 02:50:35 -0700 Subject: [PATCH] feat: comprehensive activity logging and fix question type definition persistence Add activity log coverage across mutating APIs with shared recordActivity helper and expanded action/resource constants. Fix question type definition logs to use correct QUESTION_TYPE_DEFINITION actions. Persist question_type_definition_id inside CreateQuestion transaction. Co-authored-by: Cursor --- internal/domain/activity_log.go | 98 +++++++++++++- internal/domain/rbac.go | 2 + internal/repository/questions.go | 18 ++- .../handlers/activity_log_helper.go | 34 +++++ internal/web_server/handlers/arifpay.go | 25 ++++ internal/web_server/handlers/auth_handler.go | 27 ++++ internal/web_server/handlers/chapa.go | 17 +++ .../web_server/handlers/email_template.go | 7 + .../exam_prep_catalog_course_handler.go | 6 +- .../handlers/exam_prep_lesson_handler.go | 5 + .../handlers/exam_prep_module_handler.go | 5 + .../handlers/exam_prep_practice_handler.go | 4 + .../handlers/exam_prep_unit_handler.go | 5 + internal/web_server/handlers/faq.go | 7 + internal/web_server/handlers/field_option.go | 7 + internal/web_server/handlers/file_handler.go | 20 +++ .../web_server/handlers/initial_assessment.go | 3 + .../web_server/handlers/lesson_handler.go | 4 + .../handlers/lms_persona_handler.go | 4 + .../handlers/mobile_app_version_handler.go | 7 + .../handlers/notification_handler.go | 121 +++++++++++++++++- .../handlers/practice_full_update_handler.go | 26 ++++ .../handlers/question_type_builder.go | 60 ++------- internal/web_server/handlers/questions.go | 4 + internal/web_server/handlers/ratings.go | 5 + internal/web_server/handlers/rbac_handler.go | 2 + .../web_server/handlers/referal_handlers.go | 2 + .../web_server/handlers/settings_handler.go | 6 + internal/web_server/handlers/subscriptions.go | 10 ++ internal/web_server/handlers/team_handler.go | 8 ++ .../handlers/team_invitation_handler.go | 11 ++ .../handlers/transaction_approver.go | 2 + internal/web_server/handlers/user.go | 17 ++- .../handlers/video_engagement_handler.go | 10 ++ internal/web_server/handlers/vimeo.go | 18 +++ 35 files changed, 546 insertions(+), 61 deletions(-) create mode 100644 internal/web_server/handlers/activity_log_helper.go diff --git a/internal/domain/activity_log.go b/internal/domain/activity_log.go index 3762a7c6..23995955 100644 --- a/internal/domain/activity_log.go +++ b/internal/domain/activity_log.go @@ -58,6 +58,81 @@ const ( ActionPracticeCreated ActivityAction = "PRACTICE_CREATED" ActionPracticeUpdated ActivityAction = "PRACTICE_UPDATED" ActionPracticeDeleted ActivityAction = "PRACTICE_DELETED" + ActionQuestionTypeDefinitionCreated ActivityAction = "QUESTION_TYPE_DEFINITION_CREATED" + ActionQuestionTypeDefinitionUpdated ActivityAction = "QUESTION_TYPE_DEFINITION_UPDATED" + ActionQuestionTypeDefinitionDeleted ActivityAction = "QUESTION_TYPE_DEFINITION_DELETED" + ActionQuestionTypeDefinitionGroupCreated ActivityAction = "QUESTION_TYPE_DEFINITION_GROUP_CREATED" + ActionQuestionTypeDefinitionGroupUpdated ActivityAction = "QUESTION_TYPE_DEFINITION_GROUP_UPDATED" + ActionQuestionTypeDefinitionGroupDeleted ActivityAction = "QUESTION_TYPE_DEFINITION_GROUP_DELETED" + ActionExamPrepCatalogCourseCreated ActivityAction = "EXAM_PREP_CATALOG_COURSE_CREATED" + ActionExamPrepCatalogCourseUpdated ActivityAction = "EXAM_PREP_CATALOG_COURSE_UPDATED" + ActionExamPrepCatalogCourseDeleted ActivityAction = "EXAM_PREP_CATALOG_COURSE_DELETED" + ActionExamPrepCatalogCourseReordered ActivityAction = "EXAM_PREP_CATALOG_COURSE_REORDERED" + ActionExamPrepUnitCreated ActivityAction = "EXAM_PREP_UNIT_CREATED" + ActionExamPrepUnitUpdated ActivityAction = "EXAM_PREP_UNIT_UPDATED" + ActionExamPrepUnitDeleted ActivityAction = "EXAM_PREP_UNIT_DELETED" + ActionExamPrepUnitReordered ActivityAction = "EXAM_PREP_UNIT_REORDERED" + ActionExamPrepModuleCreated ActivityAction = "EXAM_PREP_MODULE_CREATED" + ActionExamPrepModuleUpdated ActivityAction = "EXAM_PREP_MODULE_UPDATED" + ActionExamPrepModuleDeleted ActivityAction = "EXAM_PREP_MODULE_DELETED" + ActionExamPrepModuleReordered ActivityAction = "EXAM_PREP_MODULE_REORDERED" + ActionExamPrepLessonCreated ActivityAction = "EXAM_PREP_LESSON_CREATED" + ActionExamPrepLessonUpdated ActivityAction = "EXAM_PREP_LESSON_UPDATED" + ActionExamPrepLessonDeleted ActivityAction = "EXAM_PREP_LESSON_DELETED" + ActionExamPrepLessonReordered ActivityAction = "EXAM_PREP_LESSON_REORDERED" + ActionExamPrepPracticeCreated ActivityAction = "EXAM_PREP_PRACTICE_CREATED" + ActionExamPrepPracticeUpdated ActivityAction = "EXAM_PREP_PRACTICE_UPDATED" + ActionExamPrepPracticeDeleted ActivityAction = "EXAM_PREP_PRACTICE_DELETED" + ActionPersonaCreated ActivityAction = "PERSONA_CREATED" + ActionPersonaUpdated ActivityAction = "PERSONA_UPDATED" + ActionPersonaDeleted ActivityAction = "PERSONA_DELETED" + ActionFAQCreated ActivityAction = "FAQ_CREATED" + ActionFAQUpdated ActivityAction = "FAQ_UPDATED" + ActionFAQDeleted ActivityAction = "FAQ_DELETED" + ActionAppVersionCreated ActivityAction = "APP_VERSION_CREATED" + ActionAppVersionUpdated ActivityAction = "APP_VERSION_UPDATED" + ActionAppVersionDeleted ActivityAction = "APP_VERSION_DELETED" + ActionEmailTemplateCreated ActivityAction = "EMAIL_TEMPLATE_CREATED" + ActionEmailTemplateUpdated ActivityAction = "EMAIL_TEMPLATE_UPDATED" + ActionEmailTemplateDeleted ActivityAction = "EMAIL_TEMPLATE_DELETED" + ActionFieldOptionCreated ActivityAction = "FIELD_OPTION_CREATED" + ActionFieldOptionUpdated ActivityAction = "FIELD_OPTION_UPDATED" + ActionFieldOptionDeleted ActivityAction = "FIELD_OPTION_DELETED" + ActionNotificationCreated ActivityAction = "NOTIFICATION_CREATED" + ActionNotificationUpdated ActivityAction = "NOTIFICATION_UPDATED" + ActionNotificationDeleted ActivityAction = "NOTIFICATION_DELETED" + ActionNotificationBulkSent ActivityAction = "NOTIFICATION_BULK_SENT" + ActionScheduledNotificationCancelled ActivityAction = "SCHEDULED_NOTIFICATION_CANCELLED" + ActionRatingSubmitted ActivityAction = "RATING_SUBMITTED" + ActionRatingDeleted ActivityAction = "RATING_DELETED" + ActionSubscriptionCreated ActivityAction = "SUBSCRIPTION_CREATED" + ActionSubscriptionCancelled ActivityAction = "SUBSCRIPTION_CANCELLED" + ActionSubscriptionAutoRenewUpdated ActivityAction = "SUBSCRIPTION_AUTO_RENEW_UPDATED" + ActionPaymentInitiated ActivityAction = "PAYMENT_INITIATED" + ActionPaymentVerified ActivityAction = "PAYMENT_VERIFIED" + ActionPaymentCancelled ActivityAction = "PAYMENT_CANCELLED" + ActionPaymentWebhookReceived ActivityAction = "PAYMENT_WEBHOOK_RECEIVED" + ActionAssessmentQuestionCreated ActivityAction = "ASSESSMENT_QUESTION_CREATED" + ActionFileUploaded ActivityAction = "FILE_UPLOADED" + ActionFilePresignCreated ActivityAction = "FILE_PRESIGN_CREATED" + ActionAuthLogin ActivityAction = "AUTH_LOGIN" + ActionAuthLogout ActivityAction = "AUTH_LOGOUT" + ActionAuthRegister ActivityAction = "AUTH_REGISTER" + ActionAuthTokenRefreshed ActivityAction = "AUTH_TOKEN_REFRESHED" + ActionUserPasswordReset ActivityAction = "USER_PASSWORD_RESET" + ActionUserProfilePictureUpdated ActivityAction = "USER_PROFILE_PICTURE_UPDATED" + ActionQuestionAudioAnswerSubmitted ActivityAction = "QUESTION_AUDIO_ANSWER_SUBMITTED" + ActionSMSSent ActivityAction = "SMS_SENT" + ActionLessonCompleted ActivityAction = "LESSON_COMPLETED" + ActionPracticeCompleted ActivityAction = "PRACTICE_COMPLETED" + ActionVideoEngagementRecorded ActivityAction = "VIDEO_ENGAGEMENT_RECORDED" + ActionDeviceRegistered ActivityAction = "DEVICE_REGISTERED" + ActionDeviceUnregistered ActivityAction = "DEVICE_UNREGISTERED" + ActionTeamInvitationResent ActivityAction = "TEAM_INVITATION_RESENT" + ActionTeamInvitationRevoked ActivityAction = "TEAM_INVITATION_REVOKED" + ActionTeamMemberPasswordChanged ActivityAction = "TEAM_MEMBER_PASSWORD_CHANGED" + ActionReferralCodeCreated ActivityAction = "REFERRAL_CODE_CREATED" + ActionUsersPurged ActivityAction = "USERS_PURGED" ) type ResourceType string @@ -78,7 +153,28 @@ const ( ResourceProgram ResourceType = "PROGRAM" ResourceModule ResourceType = "MODULE" ResourceLesson ResourceType = "LESSON" - ResourcePractice ResourceType = "PRACTICE" + ResourcePractice ResourceType = "PRACTICE" + ResourceQuestionTypeDefinition ResourceType = "QUESTION_TYPE_DEFINITION" + ResourceQuestionTypeDefinitionGroup ResourceType = "QUESTION_TYPE_DEFINITION_GROUP" + ResourceExamPrepCatalogCourse ResourceType = "EXAM_PREP_CATALOG_COURSE" + ResourceExamPrepUnit ResourceType = "EXAM_PREP_UNIT" + ResourceExamPrepModule ResourceType = "EXAM_PREP_MODULE" + ResourceExamPrepLesson ResourceType = "EXAM_PREP_LESSON" + ResourceExamPrepPractice ResourceType = "EXAM_PREP_PRACTICE" + ResourcePersona ResourceType = "PERSONA" + ResourceFAQ ResourceType = "FAQ" + ResourceAppVersion ResourceType = "APP_VERSION" + ResourceEmailTemplate ResourceType = "EMAIL_TEMPLATE" + ResourceFieldOption ResourceType = "FIELD_OPTION" + ResourceNotification ResourceType = "NOTIFICATION" + ResourceRating ResourceType = "RATING" + ResourceSubscription ResourceType = "SUBSCRIPTION" + ResourcePayment ResourceType = "PAYMENT" + ResourceAssessmentQuestion ResourceType = "ASSESSMENT_QUESTION" + ResourceFile ResourceType = "FILE" + ResourceAuth ResourceType = "AUTH" + ResourceDevice ResourceType = "DEVICE" + ResourceReferral ResourceType = "REFERRAL" ) type ActivityLog struct { diff --git a/internal/domain/rbac.go b/internal/domain/rbac.go index 549bbf37..8258ed91 100644 --- a/internal/domain/rbac.go +++ b/internal/domain/rbac.go @@ -59,5 +59,7 @@ const ( ActionRoleUpdated ActivityAction = "ROLE_UPDATED" ActionRoleDeleted ActivityAction = "ROLE_DELETED" ActionRolePermissionsSet ActivityAction = "ROLE_PERMISSIONS_SET" + ActionPermissionsSynced ActivityAction = "PERMISSIONS_SYNCED" ResourceRole ResourceType = "ROLE" + ResourcePermission ResourceType = "PERMISSION" ) diff --git a/internal/repository/questions.go b/internal/repository/questions.go index 41c259bd..de2816b5 100644 --- a/internal/repository/questions.go +++ b/internal/repository/questions.go @@ -11,6 +11,7 @@ import ( "Yimaru-Backend/internal/domain" "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" ) @@ -105,8 +106,13 @@ func encodeDynamicPayload(payload *domain.DynamicQuestionPayload) []byte { return b } -func (s *Store) setQuestionTypeDefinitionID(ctx context.Context, questionID int64, definitionID *int64) error { - _, err := s.conn.Exec(ctx, ` +func (s *Store) setQuestionTypeDefinitionID(ctx context.Context, exec interface { + Exec(context.Context, string, ...any) (pgconn.CommandTag, error) +}, questionID int64, definitionID *int64) error { + if exec == nil { + exec = s.conn + } + _, err := exec.Exec(ctx, ` UPDATE questions SET question_type_definition_id = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $1 @@ -626,7 +632,7 @@ func (s *Store) CreateQuestion(ctx context.Context, input domain.CreateQuestionI } } - if err = s.setQuestionTypeDefinitionID(ctx, question.ID, input.QuestionTypeDefinitionID); err != nil { + if err = s.setQuestionTypeDefinitionID(ctx, tx, question.ID, input.QuestionTypeDefinitionID); err != nil { return domain.Question{}, err } @@ -634,9 +640,7 @@ func (s *Store) CreateQuestion(ctx context.Context, input domain.CreateQuestionI return domain.Question{}, err } - created := questionToDomain(question) - created.QuestionTypeDefinitionID = input.QuestionTypeDefinitionID - return created, nil + return s.GetQuestionByID(ctx, question.ID) } func (s *Store) GetQuestionByID(ctx context.Context, id int64) (domain.Question, error) { @@ -819,7 +823,7 @@ func (s *Store) UpdateQuestion(ctx context.Context, id int64, input domain.Creat } if input.QuestionTypeDefinitionID != nil { - if err := s.setQuestionTypeDefinitionID(ctx, id, input.QuestionTypeDefinitionID); err != nil { + if err := s.setQuestionTypeDefinitionID(ctx, s.conn, id, input.QuestionTypeDefinitionID); err != nil { return err } } diff --git a/internal/web_server/handlers/activity_log_helper.go b/internal/web_server/handlers/activity_log_helper.go new file mode 100644 index 00000000..d522ca9c --- /dev/null +++ b/internal/web_server/handlers/activity_log_helper.go @@ -0,0 +1,34 @@ +package handlers + +import ( + "context" + "encoding/json" + + "Yimaru-Backend/internal/domain" + + "github.com/gofiber/fiber/v2" +) + +func activityActorFromCtx(c *fiber.Ctx) (actorID *int64, actorRole *string, ip *string, ua *string) { + ipStr := c.IP() + uaStr := c.Get("User-Agent") + ip = &ipStr + ua = &uaStr + if uid, ok := c.Locals("user_id").(int64); ok && uid > 0 { + actorID = &uid + } + if role, ok := c.Locals("role").(domain.Role); ok { + roleStr := string(role) + actorRole = &roleStr + } + return actorID, actorRole, ip, ua +} + +func (h *Handler) recordActivity(c *fiber.Ctx, action domain.ActivityAction, resourceType domain.ResourceType, resourceID *int64, message string, metadata json.RawMessage) { + actorID, actorRole, ip, ua := activityActorFromCtx(c) + go h.activityLogSvc.RecordAction(context.Background(), actorID, actorRole, action, resourceType, resourceID, message, metadata, ip, ua) +} + +func (h *Handler) recordActivityWithActor(actorID *int64, actorRole *string, ip, ua *string, action domain.ActivityAction, resourceType domain.ResourceType, resourceID *int64, message string, metadata json.RawMessage) { + go h.activityLogSvc.RecordAction(context.Background(), actorID, actorRole, action, resourceType, resourceID, message, metadata, ip, ua) +} diff --git a/internal/web_server/handlers/arifpay.go b/internal/web_server/handlers/arifpay.go index bd7c2b28..48abc623 100644 --- a/internal/web_server/handlers/arifpay.go +++ b/internal/web_server/handlers/arifpay.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "encoding/json" "errors" "fmt" @@ -93,6 +94,9 @@ func (h *Handler) InitiateSubscriptionPayment(c *fiber.Ctx) error { }) } + paymentID := result.PaymentID + h.recordActivity(c, domain.ActionPaymentInitiated, domain.ResourcePayment, &paymentID, fmt.Sprintf("Initiated subscription payment ID: %d", paymentID), nil) + return c.JSON(domain.Response{ Message: "Payment initiated successfully", Data: result, @@ -129,6 +133,9 @@ func (h *Handler) VerifyPayment(c *fiber.Ctx) error { h.sendInAppNotification(payment.UserID, domain.NOTIFICATION_TYPE_PAYMENT_VERIFIED, "Payment Successful", "Your payment has been verified successfully. Your subscription is now active.") } + paymentID := payment.ID + h.recordActivity(c, domain.ActionPaymentVerified, domain.ResourcePayment, &paymentID, fmt.Sprintf("Verified payment ID: %d", paymentID), nil) + return c.JSON(domain.Response{ Message: "Payment status retrieved", Data: paymentToRes(payment), @@ -248,6 +255,8 @@ func (h *Handler) CancelPayment(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionPaymentCancelled, domain.ResourcePayment, &id, fmt.Sprintf("Cancelled payment ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "Payment cancelled successfully", }) @@ -389,6 +398,13 @@ func (h *Handler) HandleArifpayWebhook(c *fiber.Ctx) error { }) } + var paymentID *int64 + if payment, lookupErr := h.chapaSvc.LookupPayment(c.Context(), req.Nonce); lookupErr == nil && payment != nil { + paymentID = &payment.ID + } + webhookMeta, _ := json.Marshal(map[string]string{"nonce": req.Nonce, "provider": "arifpay"}) + h.recordActivity(c, domain.ActionPaymentWebhookReceived, domain.ResourcePayment, paymentID, "ArifPay webhook processed", webhookMeta) + return c.JSON(domain.Response{ Message: "Webhook processed successfully", }) @@ -470,6 +486,9 @@ func (h *Handler) InitiateDirectPayment(c *fiber.Ctx) error { }) } + paymentID := result.PaymentID + h.recordActivity(c, domain.ActionPaymentInitiated, domain.ResourcePayment, &paymentID, fmt.Sprintf("Initiated direct payment ID: %d", paymentID), nil) + return c.JSON(domain.Response{ Message: "Direct payment initiated successfully", Data: result, @@ -524,6 +543,12 @@ func (h *Handler) VerifyDirectPaymentOTP(c *fiber.Ctx) error { }) } + var paymentID *int64 + if result.PaymentID > 0 { + paymentID = &result.PaymentID + } + h.recordActivity(c, domain.ActionPaymentVerified, domain.ResourcePayment, paymentID, "Direct payment OTP verified", nil) + return c.JSON(domain.Response{ Message: result.Message, Data: result, diff --git a/internal/web_server/handlers/auth_handler.go b/internal/web_server/handlers/auth_handler.go index 5462f9ed..3ba356a6 100644 --- a/internal/web_server/handlers/auth_handler.go +++ b/internal/web_server/handlers/auth_handler.go @@ -77,6 +77,9 @@ func (h *Handler) GoogleAndroidLogin(c *fiber.Ctx) error { }) } + userID := loginRes.UserId + h.recordActivity(c, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Google Android login (user ID: %d)", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Login successful", Data: loginUserRes{ @@ -148,6 +151,9 @@ func (h *Handler) AppleLogin(c *fiber.Ctx) error { }) } + userID := loginRes.UserId + h.recordActivity(c, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Apple login (user ID: %d)", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Login successful", Data: loginUserRes{ @@ -221,6 +227,9 @@ func (h *Handler) GoogleCallback(c *fiber.Ctx) error { }) } + userID := loginRes.UserId + h.recordActivity(c, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Google OAuth login (user ID: %d)", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Login successful", Data: loginUserRes{ @@ -356,6 +365,9 @@ func (h *Handler) LoginUser(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + userID := successRes.UserId + h.recordActivity(c, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("User login (user ID: %d)", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Login successful", Data: res, @@ -471,6 +483,9 @@ func (h *Handler) LoginAdmin(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + userID := successRes.UserId + h.recordActivity(c, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Admin login (user ID: %d)", userID), nil) + return response.WriteJSON(c, fiber.StatusOK, "Login successful", res, nil) } @@ -569,6 +584,9 @@ func (h *Handler) LoginSuper(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + userID := successRes.UserId + h.recordActivity(c, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Super-admin login (user ID: %d)", userID), nil) + return response.WriteJSON(c, fiber.StatusOK, "Login successful", res, nil) } @@ -688,6 +706,9 @@ func (h *Handler) RefreshToken(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + userID := user.ID + h.recordActivity(c, domain.ActionAuthTokenRefreshed, domain.ResourceAuth, &userID, fmt.Sprintf("Token refreshed for user %d", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Token refreshed successfully", Data: res, @@ -788,5 +809,11 @@ func (h *Handler) LogOutuser(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + var resourceID *int64 + if userID, ok := c.Locals("user_id").(int64); ok && userID > 0 { + resourceID = &userID + } + h.recordActivity(c, domain.ActionAuthLogout, domain.ResourceAuth, resourceID, "User logout", nil) + return response.WriteJSON(c, fiber.StatusOK, "Logout successful", nil, nil) } diff --git a/internal/web_server/handlers/chapa.go b/internal/web_server/handlers/chapa.go index 53a7731e..39bd2f75 100644 --- a/internal/web_server/handlers/chapa.go +++ b/internal/web_server/handlers/chapa.go @@ -3,6 +3,7 @@ package handlers import ( "encoding/json" "errors" + "fmt" "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/chapa" @@ -43,6 +44,7 @@ func (h *Handler) HandleChapaWebhook(c *fiber.Ctx) error { if err := h.chapaSvc.ProcessPaymentWebhook(c.Context(), payload); err != nil { if errors.Is(err, chapa.ErrPaymentAlreadyPaid) { + h.logChapaWebhookActivity(c, payload) return c.JSON(domain.Response{Message: "Webhook already processed"}) } h.logger.Error("Failed to process Chapa webhook", "error", err, "tx_ref", payload.TxRef) @@ -52,11 +54,26 @@ func (h *Handler) HandleChapaWebhook(c *fiber.Ctx) error { }) } + h.logChapaWebhookActivity(c, payload) + return c.JSON(domain.Response{ Message: "Webhook processed successfully", }) } +func (h *Handler) logChapaWebhookActivity(c *fiber.Ctx, payload domain.ChapaWebhookPayload) { + var paymentID *int64 + if payment, lookupErr := h.chapaSvc.LookupPayment(c.Context(), payload.TxRef); lookupErr == nil && payment != nil { + paymentID = &payment.ID + } + webhookMeta, _ := json.Marshal(map[string]string{ + "tx_ref": payload.TxRef, + "event": payload.Event, + "status": payload.Status, + }) + h.recordActivity(c, domain.ActionPaymentWebhookReceived, domain.ResourcePayment, paymentID, fmt.Sprintf("Chapa webhook received for tx_ref: %s", payload.TxRef), webhookMeta) +} + // HandleChapaCallback godoc // @Summary Chapa payment callback // @Description Verifies payment after Chapa redirects to callback_url diff --git a/internal/web_server/handlers/email_template.go b/internal/web_server/handlers/email_template.go index c4b01b7a..67a9db19 100644 --- a/internal/web_server/handlers/email_template.go +++ b/internal/web_server/handlers/email_template.go @@ -3,6 +3,7 @@ package handlers import ( "Yimaru-Backend/internal/domain" "errors" + "fmt" "strconv" "strings" @@ -259,6 +260,8 @@ func (h *Handler) CreateEmailTemplate(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionEmailTemplateCreated, domain.ResourceEmailTemplate, &tmpl.ID, "Created email template: "+tmpl.Name, nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Email template created successfully", Data: mapEmailTemplateToRes(tmpl), @@ -315,6 +318,8 @@ func (h *Handler) UpdateEmailTemplate(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionEmailTemplateUpdated, domain.ResourceEmailTemplate, &tmpl.ID, "Updated email template: "+tmpl.Name, nil) + return c.JSON(domain.Response{ Message: "Email template updated successfully", Data: mapEmailTemplateToRes(tmpl), @@ -353,6 +358,8 @@ func (h *Handler) DeleteEmailTemplate(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionEmailTemplateDeleted, domain.ResourceEmailTemplate, &id, fmt.Sprintf("Deleted email template ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "Email template deleted successfully", Data: fiber.Map{"id": id}, diff --git a/internal/web_server/handlers/exam_prep_catalog_course_handler.go b/internal/web_server/handlers/exam_prep_catalog_course_handler.go index 7daa50b5..7dc9c722 100644 --- a/internal/web_server/handlers/exam_prep_catalog_course_handler.go +++ b/internal/web_server/handlers/exam_prep_catalog_course_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/examprep" "errors" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -40,6 +41,7 @@ func (h *Handler) CreateExamPrepCatalogCourse(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepCatalogCourseCreated, domain.ResourceExamPrepCatalogCourse, &out.ID, "Created exam prep catalog course: "+out.Name, nil) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Catalog course created successfully", Data: out, @@ -122,8 +124,8 @@ func (h *Handler) ReorderExamPrepCatalogCourses(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepCatalogCourseReordered, domain.ResourceExamPrepCatalogCourse, nil, "Reordered exam prep catalog courses", nil) return c.JSON(domain.Response{ - Message: "Catalog courses reordered successfully", Success: true, StatusCode: fiber.StatusOK, }) @@ -215,6 +217,7 @@ func (h *Handler) UpdateExamPrepCatalogCourse(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepCatalogCourseUpdated, domain.ResourceExamPrepCatalogCourse, &out.ID, "Updated exam prep catalog course: "+out.Name, nil) return c.JSON(domain.Response{ Message: "Catalog course updated successfully", Data: out, @@ -249,6 +252,7 @@ func (h *Handler) DeleteExamPrepCatalogCourse(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepCatalogCourseDeleted, domain.ResourceExamPrepCatalogCourse, &id, fmt.Sprintf("Deleted exam prep catalog course ID: %d", id), nil) return c.JSON(domain.Response{ Message: "Catalog course deleted successfully", Success: true, diff --git a/internal/web_server/handlers/exam_prep_lesson_handler.go b/internal/web_server/handlers/exam_prep_lesson_handler.go index 391b8a8c..d1d1963a 100644 --- a/internal/web_server/handlers/exam_prep_lesson_handler.go +++ b/internal/web_server/handlers/exam_prep_lesson_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/examprep" "errors" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -49,6 +50,7 @@ func (h *Handler) CreateExamPrepLesson(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepLessonCreated, domain.ResourceExamPrepLesson, &les.ID, "Created exam prep lesson: "+les.Title, nil) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Lesson created successfully", Data: les, @@ -165,6 +167,7 @@ func (h *Handler) ReorderExamPrepLessonsInUnitModule(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepLessonReordered, domain.ResourceExamPrepLesson, &moduleID, "Reordered exam prep lessons in module", nil) return c.JSON(domain.Response{ Message: "Lessons reordered successfully", Success: true, @@ -254,6 +257,7 @@ func (h *Handler) UpdateExamPrepLesson(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepLessonUpdated, domain.ResourceExamPrepLesson, &les.ID, "Updated exam prep lesson: "+les.Title, nil) return c.JSON(domain.Response{ Message: "Lesson updated successfully", Data: les, @@ -286,6 +290,7 @@ func (h *Handler) DeleteExamPrepLesson(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepLessonDeleted, domain.ResourceExamPrepLesson, &id, fmt.Sprintf("Deleted exam prep lesson ID: %d", id), nil) return c.JSON(domain.Response{ Message: "Lesson deleted successfully", Success: true, diff --git a/internal/web_server/handlers/exam_prep_module_handler.go b/internal/web_server/handlers/exam_prep_module_handler.go index 181070f9..13ed897f 100644 --- a/internal/web_server/handlers/exam_prep_module_handler.go +++ b/internal/web_server/handlers/exam_prep_module_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/examprep" "errors" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -49,6 +50,7 @@ func (h *Handler) CreateExamPrepModule(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepModuleCreated, domain.ResourceExamPrepModule, &out.ID, "Created exam prep module: "+out.Name, nil) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Module created successfully", Data: out, @@ -165,6 +167,7 @@ func (h *Handler) ReorderExamPrepModulesInUnit(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepModuleReordered, domain.ResourceExamPrepModule, &unitID, "Reordered exam prep modules in unit", nil) return c.JSON(domain.Response{ Message: "Modules reordered successfully", Success: true, @@ -254,6 +257,7 @@ func (h *Handler) UpdateExamPrepModule(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepModuleUpdated, domain.ResourceExamPrepModule, &out.ID, "Updated exam prep module: "+out.Name, nil) return c.JSON(domain.Response{ Message: "Module updated successfully", Data: out, @@ -286,6 +290,7 @@ func (h *Handler) DeleteExamPrepModule(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepModuleDeleted, domain.ResourceExamPrepModule, &id, fmt.Sprintf("Deleted exam prep module ID: %d", id), nil) return c.JSON(domain.Response{ Message: "Module deleted successfully", Success: true, diff --git a/internal/web_server/handlers/exam_prep_practice_handler.go b/internal/web_server/handlers/exam_prep_practice_handler.go index f3a57be9..37777826 100644 --- a/internal/web_server/handlers/exam_prep_practice_handler.go +++ b/internal/web_server/handlers/exam_prep_practice_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/examprep" "errors" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -55,6 +56,7 @@ func (h *Handler) CreateExamPrepPractice(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepPracticeCreated, domain.ResourceExamPrepPractice, &p.ID, "Created exam prep practice: "+p.Title, nil) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Practice created successfully", Data: p, @@ -184,6 +186,7 @@ func (h *Handler) UpdateExamPrepPractice(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &p.ID, "Updated exam prep practice: "+p.Title, nil) return c.JSON(domain.Response{ Message: "Practice updated successfully", Data: p, @@ -217,6 +220,7 @@ func (h *Handler) DeleteExamPrepPractice(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepPracticeDeleted, domain.ResourceExamPrepPractice, &id, fmt.Sprintf("Deleted exam prep practice ID: %d", id), nil) return c.JSON(domain.Response{ Message: "Practice deleted successfully", Success: true, diff --git a/internal/web_server/handlers/exam_prep_unit_handler.go b/internal/web_server/handlers/exam_prep_unit_handler.go index 9b1579c9..a3ce7ce5 100644 --- a/internal/web_server/handlers/exam_prep_unit_handler.go +++ b/internal/web_server/handlers/exam_prep_unit_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/examprep" "errors" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -53,6 +54,7 @@ func (h *Handler) CreateExamPrepUnit(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepUnitCreated, domain.ResourceExamPrepUnit, &out.ID, "Created exam prep unit: "+out.Name, nil) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Unit created successfully", Data: out, @@ -172,6 +174,7 @@ func (h *Handler) ReorderExamPrepUnitsInCatalogCourse(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepUnitReordered, domain.ResourceExamPrepUnit, &catalogCourseID, "Reordered exam prep units in catalog course", nil) return c.JSON(domain.Response{ Message: "Units reordered successfully", Success: true, @@ -264,6 +267,7 @@ func (h *Handler) UpdateExamPrepUnit(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepUnitUpdated, domain.ResourceExamPrepUnit, &out.ID, "Updated exam prep unit: "+out.Name, nil) return c.JSON(domain.Response{ Message: "Unit updated successfully", Data: out, @@ -297,6 +301,7 @@ func (h *Handler) DeleteExamPrepUnit(c *fiber.Ctx) error { Error: err.Error(), }) } + h.recordActivity(c, domain.ActionExamPrepUnitDeleted, domain.ResourceExamPrepUnit, &id, fmt.Sprintf("Deleted exam prep unit ID: %d", id), nil) return c.JSON(domain.Response{ Message: "Unit deleted successfully", Success: true, diff --git a/internal/web_server/handlers/faq.go b/internal/web_server/handlers/faq.go index bb0ee5af..6c67f4a7 100644 --- a/internal/web_server/handlers/faq.go +++ b/internal/web_server/handlers/faq.go @@ -3,6 +3,7 @@ package handlers import ( "Yimaru-Backend/internal/domain" "errors" + "fmt" "strconv" "strings" @@ -296,6 +297,8 @@ func (h *Handler) CreateFAQ(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionFAQCreated, domain.ResourceFAQ, &faq.ID, "Created FAQ: "+faq.Question, nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "FAQ created successfully", Data: mapFAQToRes(faq), @@ -351,6 +354,8 @@ func (h *Handler) UpdateFAQ(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionFAQUpdated, domain.ResourceFAQ, &faq.ID, "Updated FAQ: "+faq.Question, nil) + return c.JSON(domain.Response{ Message: "FAQ updated successfully", Data: mapFAQToRes(faq), @@ -389,6 +394,8 @@ func (h *Handler) DeleteFAQ(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionFAQDeleted, domain.ResourceFAQ, &id, fmt.Sprintf("Deleted FAQ ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "FAQ deleted successfully", Data: fiber.Map{"id": id}, diff --git a/internal/web_server/handlers/field_option.go b/internal/web_server/handlers/field_option.go index e201e40f..c0c8d110 100644 --- a/internal/web_server/handlers/field_option.go +++ b/internal/web_server/handlers/field_option.go @@ -3,6 +3,7 @@ package handlers import ( "Yimaru-Backend/internal/domain" "errors" + "fmt" "strconv" "strings" @@ -211,6 +212,8 @@ func (h *Handler) CreateFieldOption(c *fiber.Ctx) error { return fieldOptionError(c, err, "Failed to create field option") } + h.recordActivity(c, domain.ActionFieldOptionCreated, domain.ResourceFieldOption, &option.ID, "Created field option: "+option.FieldKey+"."+option.Code, nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Field option created successfully", Data: mapFieldOptionToRes(option), @@ -252,6 +255,8 @@ func (h *Handler) UpdateFieldOption(c *fiber.Ctx) error { return fieldOptionError(c, err, "Failed to update field option") } + h.recordActivity(c, domain.ActionFieldOptionUpdated, domain.ResourceFieldOption, &option.ID, "Updated field option: "+option.FieldKey+"."+option.Code, nil) + return c.JSON(domain.Response{ Message: "Field option updated successfully", Data: mapFieldOptionToRes(option), @@ -278,6 +283,8 @@ func (h *Handler) DeleteFieldOption(c *fiber.Ctx) error { return fieldOptionError(c, err, "Failed to delete field option") } + h.recordActivity(c, domain.ActionFieldOptionDeleted, domain.ResourceFieldOption, &id, fmt.Sprintf("Deleted field option ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "Field option deleted successfully", Success: true, diff --git a/internal/web_server/handlers/file_handler.go b/internal/web_server/handlers/file_handler.go index 120f06c3..3d5a15bb 100644 --- a/internal/web_server/handlers/file_handler.go +++ b/internal/web_server/handlers/file_handler.go @@ -5,6 +5,7 @@ import ( "Yimaru-Backend/internal/domain" minioservice "Yimaru-Backend/internal/services/minio" "bytes" + "encoding/json" "errors" "fmt" "io" @@ -271,6 +272,9 @@ func (h *Handler) CreatePresignedUpload(c *fiber.Ctx) error { } reference := "minio://" + result.ObjectKey + meta, _ := json.Marshal(map[string]interface{}{"object_key": result.ObjectKey, "media_type": mediaType}) + h.recordActivity(c, domain.ActionFilePresignCreated, domain.ResourceFile, nil, "Created presigned upload URL", meta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Presigned upload URL created successfully", Data: presignedUploadRes{ @@ -360,6 +364,9 @@ func (h *Handler) CompletePresignedUpload(c *fiber.Ctx) error { } storedPath := "minio://" + objectKey + meta, _ := json.Marshal(map[string]interface{}{"object_key": objectKey, "media_type": mediaType}) + h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Completed presigned file upload", meta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "File uploaded successfully", Data: uploadMediaRes{ @@ -540,6 +547,9 @@ func (h *Handler) UploadMedia(c *fiber.Ctx) error { }) } + meta, _ := json.Marshal(map[string]interface{}{"media_type": mediaType, "vimeo_id": vimeoUpload.VimeoID}) + h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Uploaded video file", meta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Video uploaded successfully", Data: uploadMediaRes{ @@ -571,6 +581,9 @@ func (h *Handler) UploadMedia(c *fiber.Ctx) error { } storedPath := "minio://" + uploadResult.ObjectKey + meta, _ := json.Marshal(map[string]interface{}{"object_key": uploadResult.ObjectKey, "media_type": mediaType}) + h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Uploaded file", meta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "File uploaded successfully", Data: uploadMediaRes{ @@ -744,6 +757,9 @@ func (h *Handler) UploadAudio(c *fiber.Ctx) error { storedPath := "minio://" + result.ObjectKey + meta, _ := json.Marshal(map[string]interface{}{"object_key": result.ObjectKey, "media_type": "audio"}) + h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Uploaded audio file", meta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Audio file uploaded successfully", Data: map[string]string{ @@ -813,6 +829,8 @@ func (h *Handler) SubmitAudioAnswer(c *fiber.Ctx) error { } audioURL := h.resolveFileURL(c, "minio://"+req.ObjectKey) + qid := req.QuestionID + h.recordActivity(c, domain.ActionQuestionAudioAnswerSubmitted, domain.ResourceQuestion, &qid, fmt.Sprintf("Submitted audio answer for question %d", req.QuestionID), nil) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Audio answer submitted successfully", Data: map[string]interface{}{ @@ -916,6 +934,8 @@ func (h *Handler) SubmitAudioAnswer(c *fiber.Ctx) error { } audioURL := h.resolveFileURL(c, "minio://"+uploadResult.ObjectKey) + qid := questionID + h.recordActivity(c, domain.ActionQuestionAudioAnswerSubmitted, domain.ResourceQuestion, &qid, fmt.Sprintf("Submitted audio answer for question %d", questionID), nil) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Audio answer submitted successfully", diff --git a/internal/web_server/handlers/initial_assessment.go b/internal/web_server/handlers/initial_assessment.go index e791bf77..1e4513d1 100644 --- a/internal/web_server/handlers/initial_assessment.go +++ b/internal/web_server/handlers/initial_assessment.go @@ -2,6 +2,7 @@ package handlers import ( "Yimaru-Backend/internal/domain" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -77,6 +78,8 @@ func (h *Handler) CreateAssessmentQuestion(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionAssessmentQuestionCreated, domain.ResourceAssessmentQuestion, &question.ID, fmt.Sprintf("Created assessment question ID: %d", question.ID), nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Assessment question created successfully", StatusCode: fiber.StatusCreated, diff --git a/internal/web_server/handlers/lesson_handler.go b/internal/web_server/handlers/lesson_handler.go index 189c9f56..c4f8d771 100644 --- a/internal/web_server/handlers/lesson_handler.go +++ b/internal/web_server/handlers/lesson_handler.go @@ -6,6 +6,7 @@ import ( "Yimaru-Backend/internal/services/modules" "context" "errors" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -321,6 +322,9 @@ func (h *Handler) CompleteLesson(c *fiber.Ctx) error { Error: err.Error(), }) } + + h.recordActivity(c, domain.ActionLessonCompleted, domain.ResourceLesson, &id, fmt.Sprintf("Completed lesson ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "Lesson marked complete", Success: true, diff --git a/internal/web_server/handlers/lms_persona_handler.go b/internal/web_server/handlers/lms_persona_handler.go index 8800352d..06fd3c9b 100644 --- a/internal/web_server/handlers/lms_persona_handler.go +++ b/internal/web_server/handlers/lms_persona_handler.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "errors" personasservice "Yimaru-Backend/internal/services/personas" + "fmt" "strconv" "strings" @@ -45,6 +46,7 @@ func (h *Handler) CreatePersona(c *fiber.Ctx) error { } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to create persona", Error: err.Error()}) } + h.recordActivity(c, domain.ActionPersonaCreated, domain.ResourcePersona, &p.ID, "Created persona: "+p.Name, nil) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Persona created successfully", Data: p, @@ -142,6 +144,7 @@ func (h *Handler) UpdatePersona(c *fiber.Ctx) error { } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to update persona", Error: err.Error()}) } + h.recordActivity(c, domain.ActionPersonaUpdated, domain.ResourcePersona, &p.ID, "Updated persona: "+p.Name, nil) return c.JSON(domain.Response{Message: "Persona updated successfully", Data: p, Success: true, StatusCode: fiber.StatusOK}) } @@ -162,5 +165,6 @@ func (h *Handler) DeletePersona(c *fiber.Ctx) error { if err := h.personaSvc.Delete(c.Context(), id); err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to delete persona", Error: err.Error()}) } + h.recordActivity(c, domain.ActionPersonaDeleted, domain.ResourcePersona, &id, fmt.Sprintf("Deleted persona ID: %d", id), nil) return c.JSON(domain.Response{Message: "Persona deleted successfully", Success: true, StatusCode: fiber.StatusOK}) } diff --git a/internal/web_server/handlers/mobile_app_version_handler.go b/internal/web_server/handlers/mobile_app_version_handler.go index df3bbbae..f903793a 100644 --- a/internal/web_server/handlers/mobile_app_version_handler.go +++ b/internal/web_server/handlers/mobile_app_version_handler.go @@ -3,6 +3,7 @@ package handlers import ( "Yimaru-Backend/internal/domain" "errors" + "fmt" "strconv" "strings" @@ -277,6 +278,8 @@ func (h *Handler) CreateMobileAppVersion(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionAppVersionCreated, domain.ResourceAppVersion, &version.ID, "Created app version: "+version.Platform+" "+version.VersionName, nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "App version created successfully", Data: mapMobileAppVersionToRes(version), @@ -341,6 +344,8 @@ func (h *Handler) UpdateMobileAppVersion(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionAppVersionUpdated, domain.ResourceAppVersion, &version.ID, "Updated app version: "+version.Platform+" "+version.VersionName, nil) + return c.JSON(domain.Response{ Message: "App version updated successfully", Data: mapMobileAppVersionToRes(version), @@ -382,6 +387,8 @@ func (h *Handler) DeleteMobileAppVersion(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionAppVersionDeleted, domain.ResourceAppVersion, &id, fmt.Sprintf("Deleted app version ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "App version deleted successfully", Success: true, diff --git a/internal/web_server/handlers/notification_handler.go b/internal/web_server/handlers/notification_handler.go index 46b35ad6..3cbbd05a 100644 --- a/internal/web_server/handlers/notification_handler.go +++ b/internal/web_server/handlers/notification_handler.go @@ -214,6 +214,8 @@ func (h *Handler) MarkNotificationAsRead(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &id, fmt.Sprintf("Marked notification %d as read", id), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Notification marked as read", Success: true, @@ -244,6 +246,8 @@ func (h *Handler) MarkAllNotificationsAsRead(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &userID, fmt.Sprintf("Marked all notifications as read for user %d", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "All notifications marked as read", Success: true, @@ -275,6 +279,8 @@ func (h *Handler) MarkNotificationAsUnread(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &id, fmt.Sprintf("Marked notification %d as unread", id), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Notification marked as unread", Success: true, @@ -305,6 +311,8 @@ func (h *Handler) MarkAllNotificationsAsUnread(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionNotificationUpdated, domain.ResourceNotification, &userID, fmt.Sprintf("Marked all notifications as unread for user %d", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "All notifications marked as unread", Success: true, @@ -334,8 +342,10 @@ func (h *Handler) DeleteUserNotifications(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionNotificationDeleted, domain.ResourceNotification, &userID, fmt.Sprintf("Deleted all notifications for user ID: %d", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ - Message: "Notifications deleted successfully", + Message: "All notifications deleted successfully", Success: true, StatusCode: fiber.StatusOK, }) @@ -391,6 +401,8 @@ func (h *Handler) DeleteInAppNotification(c *fiber.Ctx) error { } } + h.recordActivity(c, domain.ActionNotificationDeleted, domain.ResourceNotification, &id, fmt.Sprintf("Deleted in-app notification ID: %d", id), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "In-app notification deleted successfully", Success: true, @@ -450,8 +462,13 @@ func (h *Handler) DeleteInAppNotifications(c *fiber.Ctx) error { }) } + deleteMeta, _ := json.Marshal(map[string]interface{}{ + "deleted_count": deletedCount, + "requested_ids": len(req.IDs), + }) + h.recordActivity(c, domain.ActionNotificationDeleted, domain.ResourceNotification, nil, fmt.Sprintf("Deleted %d in-app notifications", deletedCount), deleteMeta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ - Message: "In-app notifications deleted successfully", Success: true, StatusCode: fiber.StatusOK, Data: fiber.Map{ @@ -534,6 +551,13 @@ func (h *Handler) CreateAndSendNotification(c *fiber.Ctx) error { zap.String("type", string(req.Type)), zap.Time("timestamp", time.Now()), ) + singleMeta, _ := json.Marshal(map[string]interface{}{ + "notification_id": notification.ID, + "recipient_id": req.RecipientID, + "type": req.Type, + "channel": req.DeliveryChannel, + }) + h.recordActivity(c, domain.ActionNotificationCreated, domain.ResourceNotification, nil, "Single notification sent", singleMeta) return c.Status(fiber.StatusCreated).JSON(fiber.Map{"message": "Single notification sent successfully", "notification_id": notification.ID}) case domain.NotificationDeliverySchemeBulk: @@ -592,6 +616,13 @@ func (h *Handler) CreateAndSendNotification(c *fiber.Ctx) error { zap.Error(err), zap.Time("timestamp", time.Now()), ) + bulkMeta, _ := json.Marshal(map[string]interface{}{ + "recipient_count": len(recipients), + "notification_ids": notificationIDs, + "type": req.Type, + "channel": req.DeliveryChannel, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk notification sent to %d recipients", len(recipients)), bulkMeta) return c.Status(fiber.StatusCreated).JSON(fiber.Map{ "message": "Bulk notification sent successfully", "recipient_count": len(recipients), @@ -831,6 +862,8 @@ func (h *Handler) SendSingleAfroSMS(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionSMSSent, domain.ResourceNotification, nil, "Sent SMS to "+req.Recipient, nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "SMS sent successfully", Success: true, @@ -895,6 +928,12 @@ func (h *Handler) RegisterDeviceToken(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + deviceMeta, _ := json.Marshal(map[string]interface{}{ + "user_id": userID, + "platform": req.Platform, + }) + h.recordActivity(c, domain.ActionDeviceRegistered, domain.ResourceDevice, &userID, fmt.Sprintf("Device registered for user ID: %d", userID), deviceMeta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Device token registered successfully", Success: true, @@ -991,6 +1030,8 @@ func (h *Handler) SendTestPushNotification(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + h.recordActivity(c, domain.ActionNotificationCreated, domain.ResourceNotification, &userID, fmt.Sprintf("Test push notification sent to user %d", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Test push notification sent successfully", Success: true, @@ -1085,6 +1126,15 @@ func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error { }) } + scheduledID := created.ID + scheduleMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "push", + "target_users": len(userIDs), + "target_role": role, + "scheduled_at": scheduledAtRaw, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled push notification ID: %d", scheduledID), scheduleMeta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Push notification scheduled", Success: true, @@ -1185,6 +1235,15 @@ func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error { responseData["failures"] = delivery.Failures } + bulkPushMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "push", + "target_users": len(userIDs), + "devices_targeted": delivery.DevicesTargeted, + "sent": delivery.Sent, + "failed": delivery.Failed, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk push notification sent to %d users", len(userIDs)), bulkPushMeta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: responseMessage, Success: true, @@ -1275,6 +1334,15 @@ func (h *Handler) SendBulkSMS(c *fiber.Ctx) error { }) } + scheduledID := created.ID + scheduleMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "sms", + "target_users": len(req.UserIDs), + "target_role": req.Role, + "scheduled_at": req.ScheduledAt, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled SMS notification ID: %d", scheduledID), scheduleMeta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "SMS scheduled", Success: true, @@ -1348,6 +1416,14 @@ func (h *Handler) SendBulkSMS(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + bulkSMSMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "sms", + "total_recipients": len(recipients), + "sent": sent, + "failed": failed, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk SMS sent to %d recipients", len(recipients)), bulkSMSMeta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Bulk SMS sent", Success: true, @@ -1451,6 +1527,15 @@ func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error { }) } + scheduledID := created.ID + scheduleMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "in_app", + "target_users": len(req.UserIDs), + "target_role": req.Role, + "scheduled_at": req.ScheduledAt, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled in-app notification ID: %d", scheduledID), scheduleMeta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "In-app notification scheduled", Success: true, @@ -1488,6 +1573,14 @@ func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + bulkInAppMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "in_app", + "total_recipients": len(userIDs), + "sent": sent, + "failed": failed, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk in-app notification sent to %d users", len(userIDs)), bulkInAppMeta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Bulk in-app notification sent", Success: true, @@ -1636,6 +1729,8 @@ func (h *Handler) CancelScheduledNotification(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionScheduledNotificationCancelled, domain.ResourceNotification, &id, fmt.Sprintf("Cancelled scheduled notification ID: %d", id), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Scheduled notification cancelled", Success: true, @@ -1715,6 +1810,9 @@ func (h *Handler) SendSingleEmail(c *fiber.Ctx) error { }) } + emailMeta, _ := json.Marshal(map[string]string{"recipient": recipient}) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Email sent to %s", recipient), emailMeta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Email sent successfully", Success: true, @@ -1823,6 +1921,15 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { }) } + scheduledID := created.ID + scheduleMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "email", + "target_users": len(userIDs), + "target_role": role, + "scheduled_at": scheduledAtRaw, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled email notification ID: %d", scheduledID), scheduleMeta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Email scheduled", Success: true, @@ -1892,6 +1999,14 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + bulkEmailMeta, _ := json.Marshal(map[string]interface{}{ + "channel": "email", + "total_recipients": len(recipients), + "sent": sent, + "failed": failed, + }) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk email sent to %d recipients", len(recipients)), bulkEmailMeta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Bulk email sent", Success: true, @@ -1943,6 +2058,8 @@ func (h *Handler) UnregisterDeviceToken(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + h.recordActivity(c, domain.ActionDeviceUnregistered, domain.ResourceDevice, &userID, fmt.Sprintf("Device unregistered for user ID: %d", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Device token unregistered successfully", Success: true, diff --git a/internal/web_server/handlers/practice_full_update_handler.go b/internal/web_server/handlers/practice_full_update_handler.go index 75dca37a..9f2fcf52 100644 --- a/internal/web_server/handlers/practice_full_update_handler.go +++ b/internal/web_server/handlers/practice_full_update_handler.go @@ -4,7 +4,9 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/practicecontent" "context" + "encoding/json" "errors" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -280,6 +282,18 @@ func (h *Handler) UpdateLmsPracticeFull(c *fiber.Ctx) error { }) } + meta, _ := json.Marshal(map[string]interface{}{ + "update_type": "full", + "practice_id": id, + "question_set_id": result.QuestionSet.ID, + "question_count": len(result.Questions), + }) + msg := fmt.Sprintf("Full update practice ID: %d", id) + if p, ok := result.Practice.(domain.Practice); ok { + msg = "Full update practice: " + p.Title + } + h.recordActivity(c, domain.ActionPracticeUpdated, domain.ResourcePractice, &id, msg, meta) + return c.JSON(domain.Response{ Message: "Practice updated successfully", Data: data, @@ -342,6 +356,18 @@ func (h *Handler) UpdateExamPrepPracticeFull(c *fiber.Ctx) error { }) } + meta, _ := json.Marshal(map[string]interface{}{ + "update_type": "full", + "practice_id": id, + "question_set_id": result.QuestionSet.ID, + "question_count": len(result.Questions), + }) + msg := fmt.Sprintf("Full update exam-prep practice ID: %d", id) + if p, ok := result.Practice.(domain.ExamPrepPractice); ok { + msg = "Full update exam-prep practice: " + p.Title + } + h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &id, msg, meta) + return c.JSON(domain.Response{ Message: "Practice updated successfully", Data: data, diff --git a/internal/web_server/handlers/question_type_builder.go b/internal/web_server/handlers/question_type_builder.go index 030429c2..530f547e 100644 --- a/internal/web_server/handlers/question_type_builder.go +++ b/internal/web_server/handlers/question_type_builder.go @@ -2,7 +2,6 @@ package handlers import ( "Yimaru-Backend/internal/domain" - "context" "encoding/json" "errors" "fmt" @@ -200,26 +199,11 @@ func (h *Handler) CreateQuestionTypeDefinition(c *fiber.Ctx) error { }) } - actorID := c.Locals("user_id").(int64) - actorRole := string(c.Locals("role").(domain.Role)) - ip := c.IP() - ua := c.Get("User-Agent") meta, _ := json.Marshal(map[string]interface{}{ "question_type_definition_id": def.ID, "key": def.Key, }) - go h.activityLogSvc.RecordAction( - context.Background(), - &actorID, - &actorRole, - domain.ActionQuestionCreated, - domain.ResourceQuestion, - &def.ID, - "Created question type definition: "+def.DisplayName, - meta, - &ip, - &ua, - ) + h.recordActivity(c, domain.ActionQuestionTypeDefinitionCreated, domain.ResourceQuestionTypeDefinition, &def.ID, "Created question type definition: "+def.DisplayName, meta) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Question type definition created", @@ -453,25 +437,10 @@ func (h *Handler) UpdateQuestionTypeDefinition(c *fiber.Ctx) error { }) } - actorID := c.Locals("user_id").(int64) - actorRole := string(c.Locals("role").(domain.Role)) - ip := c.IP() - ua := c.Get("User-Agent") meta, _ := json.Marshal(map[string]interface{}{ "question_type_definition_id": id, }) - go h.activityLogSvc.RecordAction( - context.Background(), - &actorID, - &actorRole, - domain.ActionQuestionUpdated, - domain.ResourceQuestion, - &id, - fmt.Sprintf("Updated question type definition ID: %d", id), - meta, - &ip, - &ua, - ) + h.recordActivity(c, domain.ActionQuestionTypeDefinitionUpdated, domain.ResourceQuestionTypeDefinition, &id, fmt.Sprintf("Updated question type definition ID: %d", id), meta) return c.JSON(domain.Response{ Message: "Question type definition updated", @@ -504,25 +473,10 @@ func (h *Handler) DeleteQuestionTypeDefinition(c *fiber.Ctx) error { }) } - actorID := c.Locals("user_id").(int64) - actorRole := string(c.Locals("role").(domain.Role)) - ip := c.IP() - ua := c.Get("User-Agent") meta, _ := json.Marshal(map[string]interface{}{ "question_type_definition_id": id, }) - go h.activityLogSvc.RecordAction( - context.Background(), - &actorID, - &actorRole, - domain.ActionQuestionDeleted, - domain.ResourceQuestion, - &id, - fmt.Sprintf("Deleted question type definition ID: %d", id), - meta, - &ip, - &ua, - ) + h.recordActivity(c, domain.ActionQuestionTypeDefinitionDeleted, domain.ResourceQuestionTypeDefinition, &id, fmt.Sprintf("Deleted question type definition ID: %d", id), meta) return c.JSON(domain.Response{ Message: "Question type definition deleted", @@ -566,6 +520,9 @@ func (h *Handler) CreateQuestionTypeDefinitionGroup(c *fiber.Ctx) error { }) } + rid := group.ID + h.recordActivity(c, domain.ActionQuestionTypeDefinitionGroupCreated, domain.ResourceQuestionTypeDefinitionGroup, &rid, "Created question type definition group: "+group.Name, nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Question type definition group created", Data: group, @@ -715,6 +672,9 @@ func (h *Handler) UpdateQuestionTypeDefinitionGroup(c *fiber.Ctx) error { }) } + rid := group.ID + h.recordActivity(c, domain.ActionQuestionTypeDefinitionGroupUpdated, domain.ResourceQuestionTypeDefinitionGroup, &rid, "Updated question type definition group: "+group.Name, nil) + return c.JSON(domain.Response{ Message: "Question type definition group updated", Data: group, @@ -750,6 +710,8 @@ func (h *Handler) DeleteQuestionTypeDefinitionGroup(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionQuestionTypeDefinitionGroupDeleted, domain.ResourceQuestionTypeDefinitionGroup, &id, fmt.Sprintf("Deleted question type definition group ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "Question type definition group deleted", Data: fiber.Map{"id": id}, diff --git a/internal/web_server/handlers/questions.go b/internal/web_server/handlers/questions.go index 16b7d229..b76c7ae0 100644 --- a/internal/web_server/handlers/questions.go +++ b/internal/web_server/handlers/questions.go @@ -1731,6 +1731,10 @@ func (h *Handler) CompletePractice(c *fiber.Ctx) error { if h.learnerNotifSvc != nil { h.learnerNotifSvc.NotifyLMSPracticeMilestones(userID, result) } + + practiceID := id + h.recordActivity(c, domain.ActionPracticeCompleted, domain.ResourcePractice, &practiceID, fmt.Sprintf("Completed practice ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "Practice completed", }) diff --git a/internal/web_server/handlers/ratings.go b/internal/web_server/handlers/ratings.go index f2df1fd6..ffa8a571 100644 --- a/internal/web_server/handlers/ratings.go +++ b/internal/web_server/handlers/ratings.go @@ -2,6 +2,7 @@ package handlers import ( "Yimaru-Backend/internal/domain" + "fmt" "strconv" "github.com/gofiber/fiber/v2" @@ -93,6 +94,8 @@ func (h *Handler) SubmitRating(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionRatingSubmitted, domain.ResourceRating, &rating.ID, fmt.Sprintf("Submitted %d-star rating", req.Stars), nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Rating submitted successfully", Data: mapRatingToRes(rating), @@ -321,6 +324,8 @@ func (h *Handler) DeleteRating(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionRatingDeleted, domain.ResourceRating, &ratingID, fmt.Sprintf("Deleted rating ID: %d", ratingID), nil) + return c.JSON(domain.Response{ Message: "Rating deleted successfully", }) diff --git a/internal/web_server/handlers/rbac_handler.go b/internal/web_server/handlers/rbac_handler.go index 500f4aac..ed730033 100644 --- a/internal/web_server/handlers/rbac_handler.go +++ b/internal/web_server/handlers/rbac_handler.go @@ -569,6 +569,8 @@ func (h *Handler) SyncPermissions(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + h.recordActivity(c, domain.ActionPermissionsSynced, domain.ResourcePermission, nil, "Synced permissions and reloaded RBAC cache", nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Permissions synced and cache reloaded successfully", Success: true, diff --git a/internal/web_server/handlers/referal_handlers.go b/internal/web_server/handlers/referal_handlers.go index 57c17705..ded291aa 100644 --- a/internal/web_server/handlers/referal_handlers.go +++ b/internal/web_server/handlers/referal_handlers.go @@ -40,6 +40,8 @@ func (h *Handler) CreateReferralCode(c *fiber.Ctx) error { fmt.Printf("Successfully created referral!") + h.recordActivity(c, domain.ActionReferralCodeCreated, domain.ResourceReferral, &userID, fmt.Sprintf("Created referral code for user ID: %d", userID), nil) + // res := domain.ConvertReferralCodeRes(referralCode) return response.WriteJSON(c, fiber.StatusOK, "Referral created successfully", nil, nil) diff --git a/internal/web_server/handlers/settings_handler.go b/internal/web_server/handlers/settings_handler.go index a324f34a..5649bf15 100644 --- a/internal/web_server/handlers/settings_handler.go +++ b/internal/web_server/handlers/settings_handler.go @@ -226,6 +226,9 @@ func (h *Handler) DeleteCompanySetting(c *fiber.Ctx) error { // return fiber.NewError(fiber.StatusInternalServerError, "Failed to delete company override settings:"+err.Error()) // } + meta, _ := json.Marshal(map[string]interface{}{"company_id": companyID.Value, "setting_key": settingKey}) + h.recordActivity(c, domain.ActionSettingsUpdated, domain.ResourceSettings, &companyID.Value, "Deleted company setting: "+settingKey, meta) + return response.WriteJSON(c, fiber.StatusOK, "setting deleted", nil, nil) } @@ -247,5 +250,8 @@ func (h *Handler) DeleteAllCompanySetting(c *fiber.Ctx) error { // return fiber.NewError(fiber.StatusInternalServerError, "Failed to delete company override settings:"+err.Error()) // } + meta, _ := json.Marshal(map[string]interface{}{"company_id": companyID.Value, "delete_all": true}) + h.recordActivity(c, domain.ActionSettingsUpdated, domain.ResourceSettings, &companyID.Value, "Deleted all company settings", meta) + return response.WriteJSON(c, fiber.StatusOK, "setting deleted", nil, nil) } diff --git a/internal/web_server/handlers/subscriptions.go b/internal/web_server/handlers/subscriptions.go index 327bf14b..8e6535a9 100644 --- a/internal/web_server/handlers/subscriptions.go +++ b/internal/web_server/handlers/subscriptions.go @@ -375,6 +375,8 @@ func (h *Handler) Subscribe(c *fiber.Ctx) error { h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name) } + h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &sub.ID, fmt.Sprintf("Created subscription ID: %d", sub.ID), nil) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Subscription created successfully", Data: subscriptionToRes(sub), @@ -431,6 +433,9 @@ func (h *Handler) SubscribeWithPayment(c *fiber.Ctx) error { }) } + paymentID := result.PaymentID + h.recordActivity(c, domain.ActionPaymentInitiated, domain.ResourcePayment, &paymentID, fmt.Sprintf("Initiated subscription payment ID: %d", paymentID), nil) + return c.JSON(domain.Response{ Message: "Payment initiated. Complete payment to activate subscription.", Data: result, @@ -580,6 +585,8 @@ func (h *Handler) CancelSubscription(c *fiber.Ctx) error { } } + h.recordActivity(c, domain.ActionSubscriptionCancelled, domain.ResourceSubscription, &id, fmt.Sprintf("Cancelled subscription ID: %d", id), nil) + return c.JSON(domain.Response{ Message: "Subscription cancelled successfully", }) @@ -639,6 +646,9 @@ func (h *Handler) SetAutoRenew(c *fiber.Ctx) error { } } + autoRenewMeta, _ := json.Marshal(map[string]bool{"auto_renew": req.AutoRenew}) + h.recordActivity(c, domain.ActionSubscriptionAutoRenewUpdated, domain.ResourceSubscription, &id, fmt.Sprintf("Updated auto-renew for subscription ID: %d", id), autoRenewMeta) + return c.JSON(domain.Response{ Message: "Auto-renew setting updated successfully", }) diff --git a/internal/web_server/handlers/team_handler.go b/internal/web_server/handlers/team_handler.go index 1173ad93..319252c8 100644 --- a/internal/web_server/handlers/team_handler.go +++ b/internal/web_server/handlers/team_handler.go @@ -169,6 +169,9 @@ func (h *Handler) TeamMemberLogin(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + memberID := loginRes.ID + h.recordActivity(c, domain.ActionAuthLogin, domain.ResourceTeamMember, &memberID, fmt.Sprintf("Team member login (ID: %d)", loginRes.ID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Login successful", Data: teamMemberLoginRes{ @@ -244,6 +247,9 @@ func (h *Handler) TeamMemberRefresh(c *fiber.Ctx) error { }) } + memberID := member.ID + h.recordActivity(c, domain.ActionAuthTokenRefreshed, domain.ResourceTeamMember, &memberID, fmt.Sprintf("Team member token refreshed (ID: %d)", member.ID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Token refreshed successfully", Data: teamMemberLoginRes{ @@ -854,6 +860,8 @@ func (h *Handler) ChangeTeamMemberPassword(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + h.recordActivity(c, domain.ActionTeamMemberPasswordChanged, domain.ResourceTeamMember, &memberID, fmt.Sprintf("Changed password for team member ID: %d", memberID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Password changed successfully", Success: true, diff --git a/internal/web_server/handlers/team_invitation_handler.go b/internal/web_server/handlers/team_invitation_handler.go index d42835c6..30169b54 100644 --- a/internal/web_server/handlers/team_invitation_handler.go +++ b/internal/web_server/handlers/team_invitation_handler.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "strconv" "strings" "time" @@ -131,6 +132,10 @@ func (h *Handler) ResendTeamInvitation(c *fiber.Ctx) error { return h.teamInvitationError(c, err, "Failed to resend team invitation") } + resourceID := res.TeamMemberID + meta, _ := json.Marshal(map[string]interface{}{"email": res.Email, "team_member_id": res.TeamMemberID}) + h.recordActivity(c, domain.ActionTeamInvitationResent, domain.ResourceTeamMember, &resourceID, "Resent team invitation: "+res.Email, meta) + return c.JSON(domain.Response{ Message: "Team invitation resent successfully", Data: res, @@ -201,6 +206,9 @@ func (h *Handler) RevokeTeamInvitation(c *fiber.Ctx) error { return h.teamInvitationError(c, err, "Failed to revoke team invitation") } + resourceID := invitationID + h.recordActivity(c, domain.ActionTeamInvitationRevoked, domain.ResourceTeamMember, &resourceID, fmt.Sprintf("Revoked team invitation ID: %d", invitationID), nil) + return c.JSON(domain.Response{ Message: "Team invitation revoked successfully", Data: fiber.Map{"id": invitationID}, @@ -268,6 +276,9 @@ func (h *Handler) AcceptTeamInvitation(c *fiber.Ctx) error { return h.teamInvitationError(c, err, "Failed to accept team invitation") } + rid := member.ID + h.recordActivity(c, domain.ActionTeamMemberUpdated, domain.ResourceTeamMember, &rid, "Accepted team invitation: "+member.Email, nil) + return c.JSON(domain.Response{ Message: "Team account activated successfully. You can now sign in.", Data: toTeamMemberResponse(&member), diff --git a/internal/web_server/handlers/transaction_approver.go b/internal/web_server/handlers/transaction_approver.go index d3e61efd..fd18b48c 100644 --- a/internal/web_server/handlers/transaction_approver.go +++ b/internal/web_server/handlers/transaction_approver.go @@ -424,5 +424,7 @@ func (h *Handler) UpdateTransactionApprover(c *fiber.Ctx) error { zap.Time("timestamp", time.Now()), ) + h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &approverID, fmt.Sprintf("Updated transaction approver ID: %d", approverID), nil) + return response.WriteJSON(c, fiber.StatusOK, "Transaction approver updated successfully", nil, nil) } diff --git a/internal/web_server/handlers/user.go b/internal/web_server/handlers/user.go index c72d8edb..b2ecf10a 100644 --- a/internal/web_server/handlers/user.go +++ b/internal/web_server/handlers/user.go @@ -228,6 +228,9 @@ func (h *Handler) UpdateUserKnowledgeLevel(c *fiber.Ctx) error { h.sendInAppNotification(userID, domain.NOTIFICATION_TYPE_KNOWLEDGE_LEVEL_UPDATE, "Knowledge Level Updated", "Your knowledge level has been updated to: "+req.KnowledgeLevel) + meta, _ := json.Marshal(map[string]interface{}{"knowledge_level": req.KnowledgeLevel}) + h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &userID, fmt.Sprintf("Updated knowledge level for user ID: %d", userID), meta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "User knowledge level updated successfully", }) @@ -1162,7 +1165,9 @@ func (h *Handler) RegisterUser(c *fiber.Ctx) error { Error: err.Error(), }) } - _ = created + userID := created.ID + h.recordActivity(c, domain.ActionUserCreated, domain.ResourceUser, &userID, fmt.Sprintf("Registered user ID: %d", userID), nil) + h.recordActivity(c, domain.ActionAuthRegister, domain.ResourceAuth, &userID, fmt.Sprintf("User registration (user ID: %d)", userID), nil) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Registration successful", @@ -1388,6 +1393,8 @@ func (h *Handler) ResetPassword(c *fiber.Ctx) error { return fiber.NewError(fiber.StatusInternalServerError, "Failed to reset password:"+err.Error()) } + h.recordActivity(c, domain.ActionUserPasswordReset, domain.ResourceUser, nil, "Password reset completed", nil) + return response.WriteJSON(c, fiber.StatusOK, "Password reset successful", nil, nil) } @@ -2053,6 +2060,12 @@ func (h *Handler) PurgeDueDeletedUsers(c *fiber.Ctx) error { return fiber.NewError(fiber.StatusInternalServerError, "Failed to purge due user deletions: "+err.Error()) } + purgeMeta, _ := json.Marshal(map[string]interface{}{ + "deleted_count": deletedCount, + "batch_limit": limit, + }) + h.recordActivity(c, domain.ActionUsersPurged, domain.ResourceUser, nil, fmt.Sprintf("Purged %d due user deletions", deletedCount), purgeMeta) + return response.WriteJSON(c, fiber.StatusOK, "Due user deletions purged successfully", map[string]interface{}{ "deleted_count": deletedCount, "batch_limit": limit, @@ -2255,6 +2268,8 @@ func (h *Handler) UploadProfilePicture(c *fiber.Ctx) error { }) } + h.recordActivity(c, domain.ActionUserProfilePictureUpdated, domain.ResourceUser, &userID, fmt.Sprintf("Updated profile picture for user %d", userID), nil) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Profile picture uploaded successfully", Data: map[string]string{"profile_picture_url": h.resolveFileURL(c, publicPath)}, diff --git a/internal/web_server/handlers/video_engagement_handler.go b/internal/web_server/handlers/video_engagement_handler.go index 42a35168..8817b2ef 100644 --- a/internal/web_server/handlers/video_engagement_handler.go +++ b/internal/web_server/handlers/video_engagement_handler.go @@ -1,6 +1,7 @@ package handlers import ( + "encoding/json" "errors" "Yimaru-Backend/internal/domain" @@ -97,6 +98,15 @@ func (h *Handler) RecordVideoEngagementHeartbeat(c *fiber.Ctx) error { }) } + contentID := req.ContentID + meta, _ := json.Marshal(map[string]interface{}{ + "content_kind": req.ContentKind, + "content_id": req.ContentID, + "position_sec": req.PositionSec, + "ended": req.Ended, + }) + h.recordActivity(c, domain.ActionVideoEngagementRecorded, domain.ResourceVideo, &contentID, "Recorded video engagement heartbeat", meta) + return c.JSON(domain.Response{ Message: "Video engagement recorded", Data: res, diff --git a/internal/web_server/handlers/vimeo.go b/internal/web_server/handlers/vimeo.go index 1beab71f..cdee8d44 100644 --- a/internal/web_server/handlers/vimeo.go +++ b/internal/web_server/handlers/vimeo.go @@ -4,6 +4,7 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/pkgs/vimeo" vimeoservice "Yimaru-Backend/internal/services/vimeo" + "encoding/json" "fmt" "strconv" @@ -266,6 +267,13 @@ func (h *Handler) CreatePullUpload(c *fiber.Ctx) error { }) } + meta, _ := json.Marshal(map[string]interface{}{ + "vimeo_id": result.VimeoID, + "upload_type": "pull", + "name": req.Name, + }) + h.recordActivity(c, domain.ActionVideoUploaded, domain.ResourceVideo, nil, "Uploaded video via pull: "+req.Name, meta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Vimeo upload created successfully", Data: result, @@ -316,6 +324,13 @@ func (h *Handler) CreateTusUpload(c *fiber.Ctx) error { }) } + meta, _ := json.Marshal(map[string]interface{}{ + "vimeo_id": result.VimeoID, + "upload_type": "tus", + "name": req.Name, + }) + h.recordActivity(c, domain.ActionVideoUploaded, domain.ResourceVideo, nil, "Uploaded video via TUS: "+req.Name, meta) + return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Vimeo TUS upload created successfully", Data: result, @@ -430,6 +445,9 @@ func (h *Handler) DeleteVimeoVideo(c *fiber.Ctx) error { }) } + meta, _ := json.Marshal(map[string]interface{}{"vimeo_id": videoID}) + h.recordActivity(c, domain.ActionVideoDeleted, domain.ResourceVideo, nil, "Deleted Vimeo video: "+videoID, meta) + return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Video deleted successfully", Success: true,