feat: initial commit — backend API + student cabinet frontend
- Go backend: auth (JWT), points earn/spend, QR token generation, partners, admin grant/stats endpoints with chi router - Next.js 14 frontend: login, student dashboard, transaction history, QR display, partners list - PostgreSQL migrations (4 tables), Redis cache, Docker Compose - CORS middleware, role-based route protection, Zustand auth store Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
// Package users handles student profile and transaction history endpoints.
|
||||
package users
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/cu-points/backend/internal/middleware"
|
||||
"github.com/cu-points/backend/pkg/response"
|
||||
)
|
||||
|
||||
// Handler holds HTTP handler methods for the users domain.
|
||||
type Handler struct {
|
||||
service *Service
|
||||
}
|
||||
|
||||
// NewHandler creates a new users Handler.
|
||||
func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// transactionsResponse is the JSON body returned by GET /me/transactions.
|
||||
type transactionsResponse struct {
|
||||
Transactions []Transaction `json:"transactions"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// Me handles GET /api/v1/me.
|
||||
// Returns the authenticated student's profile and current balance.
|
||||
// Requires role=student (enforced by the router's RequireRole middleware).
|
||||
func (h *Handler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
profile, err := h.service.GetProfile(r.Context(), userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
response.Error(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
slog.Error("handler.Me", "err", err)
|
||||
response.Error(w, http.StatusInternalServerError, "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
response.JSON(w, http.StatusOK, profile)
|
||||
}
|
||||
|
||||
// Transactions handles GET /api/v1/me/transactions.
|
||||
// Returns paginated transaction history for the authenticated student.
|
||||
// Query params: limit (default 20, max 100), offset (default 0).
|
||||
// Response: { "transactions": [...], "total": N }
|
||||
func (h *Handler) Transactions(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
limit := 20
|
||||
offset := 0
|
||||
if v := r.URL.Query().Get("limit"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 100 {
|
||||
limit = n
|
||||
}
|
||||
}
|
||||
if v := r.URL.Query().Get("offset"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
|
||||
offset = n
|
||||
}
|
||||
}
|
||||
|
||||
txs, total, err := h.service.GetTransactions(r.Context(), userID, limit, offset)
|
||||
if err != nil {
|
||||
slog.Error("handler.Transactions", "err", err)
|
||||
response.Error(w, http.StatusInternalServerError, "internal server error")
|
||||
return
|
||||
}
|
||||
// Return an empty array rather than null when there are no transactions.
|
||||
if txs == nil {
|
||||
txs = []Transaction{}
|
||||
}
|
||||
response.JSON(w, http.StatusOK, transactionsResponse{
|
||||
Transactions: txs,
|
||||
Total: total,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// ErrNotFound is returned when the requested user does not exist.
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
// Repository handles all database access for the users domain.
|
||||
type Repository struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewRepository creates a new users Repository.
|
||||
func NewRepository(db *pgxpool.Pool) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
// GetByID fetches a user's profile by primary key.
|
||||
// Returns ErrNotFound if no user exists with that ID.
|
||||
func (r *Repository) GetByID(ctx context.Context, id string) (*Profile, error) {
|
||||
var p Profile
|
||||
err := r.db.QueryRow(ctx,
|
||||
`SELECT id, email, name, COALESCE(student_id, ''), balance
|
||||
FROM users WHERE id = $1`,
|
||||
id,
|
||||
).Scan(&p.ID, &p.Email, &p.Name, &p.StudentID, &p.Balance)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("repository.GetByID: %w", err)
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// UpdateBalance adds delta to the user's balance within an existing pgx transaction.
|
||||
// delta is positive when earning points, negative when spending.
|
||||
// Returns the new balance after the update via RETURNING, so the service can include
|
||||
// it in the API response without a second query.
|
||||
// The database CHECK (balance >= 0) acts as the last line of defense against overdrafts;
|
||||
// this function will return an error if the constraint fires.
|
||||
func (r *Repository) UpdateBalance(ctx context.Context, tx pgx.Tx, id string, delta int) (int, error) {
|
||||
var newBalance int
|
||||
err := tx.QueryRow(ctx,
|
||||
`UPDATE users SET balance = balance + $1 WHERE id = $2 RETURNING balance`,
|
||||
delta, id,
|
||||
).Scan(&newBalance)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("repository.UpdateBalance: %w", err)
|
||||
}
|
||||
return newBalance, nil
|
||||
}
|
||||
|
||||
// CountTransactions returns the total number of transactions for the given user.
|
||||
// Used alongside ListTransactions to populate pagination metadata.
|
||||
func (r *Repository) CountTransactions(ctx context.Context, userID string) (int, error) {
|
||||
var count int
|
||||
err := r.db.QueryRow(ctx,
|
||||
`SELECT COUNT(*) FROM transactions WHERE user_id = $1`,
|
||||
userID,
|
||||
).Scan(&count)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("repository.CountTransactions: %w", err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// ListTransactions returns paginated transactions for the given user, ordered newest first.
|
||||
func (r *Repository) ListTransactions(ctx context.Context, userID string, limit, offset int) ([]Transaction, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT id,
|
||||
amount,
|
||||
type,
|
||||
COALESCE(description, ''),
|
||||
COALESCE(partner_id::text, ''),
|
||||
created_at
|
||||
FROM transactions
|
||||
WHERE user_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2 OFFSET $3`,
|
||||
userID, limit, offset,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("repository.ListTransactions: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var txs []Transaction
|
||||
for rows.Next() {
|
||||
var t Transaction
|
||||
if err := rows.Scan(&t.ID, &t.Amount, &t.Type, &t.Description, &t.PartnerID, &t.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("repository.ListTransactions: scan: %w", err)
|
||||
}
|
||||
txs = append(txs, t)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("repository.ListTransactions: rows: %w", err)
|
||||
}
|
||||
return txs, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package users
|
||||
|
||||
import "context"
|
||||
|
||||
// Service handles business logic for the users domain.
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
// NewService creates a new users Service.
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
// Profile represents a student's public profile and current balance.
|
||||
type Profile struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
StudentID string `json:"student_id,omitempty"`
|
||||
Balance int `json:"balance"`
|
||||
}
|
||||
|
||||
// Transaction represents a single point-earning or point-spending event.
|
||||
type Transaction struct {
|
||||
ID string `json:"id"`
|
||||
Amount int `json:"amount"`
|
||||
Type string `json:"type"`
|
||||
Description string `json:"description,omitempty"`
|
||||
PartnerID string `json:"partner_id,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// GetProfile returns the profile and current balance for the given user.
|
||||
func (s *Service) GetProfile(ctx context.Context, userID string) (*Profile, error) {
|
||||
return s.repo.GetByID(ctx, userID)
|
||||
}
|
||||
|
||||
// GetTransactions returns a paginated list of transactions for the given user
|
||||
// (newest first) together with the total row count for pagination metadata.
|
||||
func (s *Service) GetTransactions(ctx context.Context, userID string, limit, offset int) ([]Transaction, int, error) {
|
||||
total, err := s.repo.CountTransactions(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
txs, err := s.repo.ListTransactions(ctx, userID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return txs, total, nil
|
||||
}
|
||||
Reference in New Issue
Block a user