Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion cmd/server/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
gacha_usecase "github.com/Financial-Partner/server/internal/module/gacha/usecase"
goal_usecase "github.com/Financial-Partner/server/internal/module/goal/usecase"
investment_usecase "github.com/Financial-Partner/server/internal/module/investment/usecase"
report_usecase "github.com/Financial-Partner/server/internal/module/report/usecase"
transaction_usecase "github.com/Financial-Partner/server/internal/module/transaction/usecase"
user_repository "github.com/Financial-Partner/server/internal/module/user/repository"
user_usecase "github.com/Financial-Partner/server/internal/module/user/usecase"
Expand Down Expand Up @@ -91,16 +92,21 @@ func ProvideGachaService() *gacha_usecase.Service {
return gacha_usecase.NewService()
}

func ProvideReportService() *report_usecase.Service {
return report_usecase.NewService()
}

func ProvideHandler(
userService *user_usecase.Service,
authService *auth_usecase.Service,
goalService *goal_usecase.Service,
investmentService *investment_usecase.Service,
transactionService *transaction_usecase.Service,
gachaService *gacha_usecase.Service,
reportService *report_usecase.Service,
log loggerInfra.Logger,
) *handler.Handler {
return handler.NewHandler(userService, authService, goalService, investmentService, transactionService, gachaService, log)
return handler.NewHandler(userService, authService, goalService, investmentService, transactionService, gachaService, reportService, log)
}

func ProvideAuthMiddleware(jwtManager *authInfra.JWTManager, cfg *config.Config, log loggerInfra.Logger) *middleware.AuthMiddleware {
Expand Down
4 changes: 4 additions & 0 deletions cmd/server/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,8 @@ func setupProtectedRoutes(router *mux.Router, handlers *handler.Handler) {
gachaRoutes := router.PathPrefix("/gacha").Subrouter()
gachaRoutes.HandleFunc("/draw", handlers.DrawGacha).Methods(http.MethodPost)
gachaRoutes.HandleFunc("/preview", handlers.PreviewGachas).Methods(http.MethodGet)

reportRoutes := router.PathPrefix("/reports").Subrouter()
reportRoutes.HandleFunc("/finance", handlers.GetReport).Methods(http.MethodGet)
reportRoutes.HandleFunc("/analysis", handlers.GetReportSummary).Methods(http.MethodGet)
}
1 change: 1 addition & 0 deletions cmd/server/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ func InitializeServer(cfgFile string) (*Server, error) {
ProvideInvestmentService,
ProvideTransactionService,
ProvideGachaService,
ProvideReportService,
ProvideHandler,
ProvideAuthMiddleware,
ProvideRouter,
Expand Down
3 changes: 2 additions & 1 deletion cmd/server/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions internal/entities/report.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package entities

type Report struct {
Revenue int64 `bson:"revenue" json:"revenue"`
Expenses int64 `bson:"expenses" json:"expenses"`
NetProfit int64 `bson:"net_profit" json:"net_profit"`
Categories []string `bson:"categories" json:"categories"`
Amounts []int64 `bson:"amounts" json:"amounts"`
Percentages []float64 `bson:"percentages" json:"percentages"`
}

type ReportSummary struct {
Summary string `bson:"summary" json:"summary"`
}
14 changes: 14 additions & 0 deletions internal/interfaces/http/dto/report.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package dto

type ReportResponse struct {
Revenue int64 `json:"revenue" example:"10000" binding:"required"`
Expenses int64 `json:"expenses" example:"5000" binding:"required"`
NetProfit int64 `json:"net_profit" example:"5000" binding:"required"`
Categories []string `json:"categories" example:"Food,Transport" binding:"required"`
Amounts []int64 `json:"amounts" example:"1000,2000" binding:"required"`
Percentages []float64 `json:"percentages" example:"0.33,0.67" binding:"required"`
}

type ReportSummaryResponse struct {
Summary string `json:"summary" example:"Report generated by AI"`
}
3 changes: 3 additions & 0 deletions internal/interfaces/http/error/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package httperror

const (
ErrInvalidRequest = "Invalid request format"
ErrInvalidParameter = "Invalid parameter format"
ErrUnauthorized = "Unauthorized"
ErrEmailNotFound = "Email not found"
ErrUserIDNotFound = "User ID not found"
Expand All @@ -24,4 +25,6 @@ const (
ErrFailedToCreateTransaction = "Failed to create a transaction"
ErrFailedToDrawGacha = "Failed to draw a gacha"
ErrFailedToPreviewGachas = "Failed to preview gachas"
ErrFailedToGetReport = "Failed to get report"
ErrFailedToGetReportSummary = "Failed to get report summary"
)
4 changes: 3 additions & 1 deletion internal/interfaces/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,19 @@ type Handler struct {
investmentService InvestmentService
transactionService TransactionService
gachaService GachaService
reportService ReportService
log logger.Logger
}

func NewHandler(us UserService, as AuthService, gs GoalService, is InvestmentService, ts TransactionService, gcs GachaService, log logger.Logger) *Handler {
func NewHandler(us UserService, as AuthService, gs GoalService, is InvestmentService, ts TransactionService, gcs GachaService, rs ReportService, log logger.Logger) *Handler {
return &Handler{
userService: us,
authService: as,
goalService: gs,
investmentService: is,
transactionService: ts,
gachaService: gcs,
reportService: rs,
log: log,
}
}
4 changes: 3 additions & 1 deletion internal/interfaces/http/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type MockServices struct {
InvestmentService *handler.MockInvestmentService
TransactionService *handler.MockTransactionService
GachaService *handler.MockGachaService
ReportService *handler.MockReportService
}

func newTestHandler(t *testing.T) (*handler.Handler, *MockServices) {
Expand All @@ -31,8 +32,9 @@ func newTestHandler(t *testing.T) (*handler.Handler, *MockServices) {
InvestmentService: handler.NewMockInvestmentService(ctrl),
TransactionService: handler.NewMockTransactionService(ctrl),
GachaService: handler.NewMockGachaService(ctrl),
ReportService: handler.NewMockReportService(ctrl),
}
h := handler.NewHandler(ms.UserService, ms.AuthService, ms.GoalService, ms.InvestmentService, ms.TransactionService, ms.GachaService, logger.NewNopLogger())
h := handler.NewHandler(ms.UserService, ms.AuthService, ms.GoalService, ms.InvestmentService, ms.TransactionService, ms.GachaService, ms.ReportService, logger.NewNopLogger())

return h, ms
}
Expand Down
121 changes: 121 additions & 0 deletions internal/interfaces/http/report.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package handler

import (
"context"
"net/http"
"strconv"
"time"

"github.com/Financial-Partner/server/internal/contextutil"
"github.com/Financial-Partner/server/internal/entities"
"github.com/Financial-Partner/server/internal/interfaces/http/dto"
httperror "github.com/Financial-Partner/server/internal/interfaces/http/error"
responde "github.com/Financial-Partner/server/internal/interfaces/http/respond"
)

//go:generate mockgen -source=report.go -destination=report_mock.go -package=handler

type ReportService interface {
GetReport(ctx context.Context, userID string, startTime time.Time, endTime time.Time, reportType string) (*entities.Report, error)
GetReportSummary(ctx context.Context, userID string) (*entities.ReportSummary, error)
}

// @Summary Get report
// @Description Get report for a user
// @Tags reports
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer {token}" default
// @Param type query string true "Type of report (summary or detailed)"
// @Param start query int64 false "Start time as Unix timestamp (seconds since epoch)"
// @Param end query int64 false "End time as Unix timestamp (seconds since epoch)"
// @Success 200 {object} dto.ReportResponse
// @Failure 400 {object} dto.ErrorResponse
// @Failure 401 {object} dto.ErrorResponse
// @Failure 500 {object} dto.ErrorResponse
// @Router /reports/finance [get]
func (h *Handler) GetReport(w http.ResponseWriter, r *http.Request) {
// Parse query parameters
reportType := r.URL.Query().Get("type")
start := r.URL.Query().Get("start")
end := r.URL.Query().Get("end")

var startDate, endDate time.Time
var err error
if start != "" {
startTimestamp, err := strconv.ParseInt(start, 10, 64) // Parse Unix timestamp
if err != nil {
h.log.Warnf("Invalid start timestamp format. Use a valid Unix timestamp.")
responde.WithError(w, r, h.log, err, httperror.ErrInvalidParameter, http.StatusBadRequest)
return
}
startDate = time.Unix(startTimestamp, 0).UTC() // Convert to time.Time in UTC
}

if end != "" {
endTimestamp, err := strconv.ParseInt(end, 10, 64) // Parse Unix timestamp
if err != nil {
h.log.Warnf("Invalid end timestamp format. Use a valid Unix timestamp.")
responde.WithError(w, r, h.log, err, httperror.ErrInvalidParameter, http.StatusBadRequest)
return
}
endDate = time.Unix(endTimestamp, 0).UTC() // Convert to time.Time in UTC
}

userID, ok := contextutil.GetUserID(r.Context())
if !ok {
h.log.Warnf("failed to get user ID from context")
responde.WithError(w, r, h.log, nil, httperror.ErrUnauthorized, http.StatusUnauthorized)
return
}

report, err := h.reportService.GetReport(r.Context(), userID, startDate, endDate, reportType)
if err != nil {
h.log.Errorf("failed to get report")
responde.WithError(w, r, h.log, err, httperror.ErrFailedToGetReport, http.StatusInternalServerError)
return
}

resp := dto.ReportResponse{
Revenue: report.Revenue,
Expenses: report.Expenses,
NetProfit: report.NetProfit,
Categories: report.Categories,
Amounts: report.Amounts,
Percentages: report.Percentages,
}

responde.WithJSON(w, r, resp, http.StatusOK)
}

// @Summary Get report summary
// @Description Get report summary generated by AI for a user
// @Tags reports
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer {token}" default
// @Success 200 {object} dto.ReportSummaryResponse
// @Failure 401 {object} dto.ErrorResponse
// @Failure 500 {object} dto.ErrorResponse
// @Router /reports/analysis [get]
func (h *Handler) GetReportSummary(w http.ResponseWriter, r *http.Request) {
userID, ok := contextutil.GetUserID(r.Context())
if !ok {
h.log.Warnf("failed to get user ID from context")
responde.WithError(w, r, h.log, nil, httperror.ErrUnauthorized, http.StatusUnauthorized)
return
}

reportSummary, err := h.reportService.GetReportSummary(r.Context(), userID)
if err != nil {
h.log.Errorf("failed to get report summary")
responde.WithError(w, r, h.log, err, httperror.ErrFailedToGetReportSummary, http.StatusInternalServerError)
return
}

resp := dto.ReportSummaryResponse{
Summary: reportSummary.Summary,
}

responde.WithJSON(w, r, resp, http.StatusOK)
}
73 changes: 73 additions & 0 deletions internal/interfaces/http/report_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading