The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
created fe pages and connected some endpoints
dduxff27c0f1105c
diff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.gonew file mode 100644index 00000000..23ed3118--- /dev/null+++ b/backend/app/controllers/dashboard.controller.go@@ -0,0 +1,192 @@+package controllers++import (+ "backend/app/models"+ "backend/app/repositories"+ "net/http"+ "time"++ "github.com/gin-gonic/gin"+)++type dashboardController struct{}++func (d dashboardController) GetDashboard(c *gin.Context) {+ now := time.Now()+ start := now.Add(-24 * time.Hour)+ prevStart := now.Add(-48 * time.Hour)+ prevEnd := start++ metrics := make([]models.DashboardMetric, 0, 6)++ // 1. Requests count+ requestsTrend, err := repositories.TransactionRepository.CountByHour(c, start, now)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }+ requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, start, now)+ requestsPrev, _ := repositories.TransactionRepository.CountBetween(c, prevStart, prevEnd)+ metrics = append(metrics, buildMetric("requests", "Requests", float64(requestsCurrent), "count", requestsTrend, float64(requestsPrev), "requests"))++ // 2. Exceptions count+ exceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByHour(c, start, now)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }+ exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, start, now)+ exceptionsPrev, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, prevStart, prevEnd)+ metrics = append(metrics, buildMetric("exceptions", "Exceptions", float64(exceptionsCurrent), "count", exceptionsTrend, float64(exceptionsPrev), "exceptions"))++ // 3. Average Response Time+ avgDurationTrend, err := repositories.TransactionRepository.AvgDurationByHour(c, start, now)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }+ avgDurationCurrent := getLastValue(avgDurationTrend)+ avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByHour(c, prevStart, prevEnd)+ avgDurationPrev := getAverageValue(avgDurationPrevTrend)+ metrics = append(metrics, buildMetric("avg_response_time", "Avg Response Time", avgDurationCurrent, "ms", avgDurationTrend, avgDurationPrev, "response_time"))++ // 4. Error Rate+ errorRateTrend, err := repositories.TransactionRepository.ErrorRateByHour(c, start, now)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }+ errorRateCurrent := getLastValue(errorRateTrend)+ errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByHour(c, prevStart, prevEnd)+ errorRatePrev := getAverageValue(errorRatePrevTrend)+ metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))++ // 5. CPU Usage+ cpuTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, "cpu", start, now)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }+ cpuCurrent := getLastValue(cpuTrend)+ cpuPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, "cpu", prevStart, prevEnd)+ metrics = append(metrics, buildMetric("cpu_usage", "CPU Usage", cpuCurrent, "%", cpuTrend, cpuPrev, "cpu"))++ // 6. Memory Usage+ memTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, "ram", start, now)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }+ memCurrent := getLastValue(memTrend)+ memPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, "ram", prevStart, prevEnd)+ metrics = append(metrics, buildMetric("memory_usage", "Memory Usage", memCurrent, "MB", memTrend, memPrev, "memory"))++ c.JSON(http.StatusOK, models.DashboardResponse{+ Metrics: metrics,+ LastUpdated: now,+ })+}++func buildMetric(id, name string, current float64, unit string, trend []models.TimeSeriesPoint, prev float64, metricType string) models.DashboardMetric {+ // Convert TimeSeriesPoint to DashboardTrendPoint+ trendPoints := make([]models.DashboardTrendPoint, len(trend))+ for i, p := range trend {+ trendPoints[i] = models.DashboardTrendPoint{+ Timestamp: p.Timestamp,+ Value: p.Value,+ }+ }++ // Calculate percentage change+ var change24h float64+ if prev > 0 {+ change24h = ((current - prev) / prev) * 100+ }++ // Determine status based on metric type+ status := calculateStatus(current, metricType)++ return models.DashboardMetric{+ ID: id,+ Name: name,+ Value: current,+ Unit: unit,+ Trend: trendPoints,+ Change24h: change24h,+ Status: status,+ }+}++func calculateStatus(value float64, metricType string) string {+ switch metricType {+ case "requests":+ // Lower is worse for requests (less traffic may indicate issues)+ if value < 10 {+ return "critical"+ } else if value < 100 {+ return "warning"+ }+ return "healthy"+ case "exceptions":+ // Higher is worse for exceptions+ if value > 50 {+ return "critical"+ } else if value > 10 {+ return "warning"+ }+ return "healthy"+ case "response_time":+ // Higher is worse for response time+ if value > 500 {+ return "critical"+ } else if value > 200 {+ return "warning"+ }+ return "healthy"+ case "error_rate":+ // Higher is worse for error rate+ if value > 5 {+ return "critical"+ } else if value > 2 {+ return "warning"+ }+ return "healthy"+ case "cpu":+ // Higher is worse for CPU+ if value > 90 {+ return "critical"+ } else if value > 70 {+ return "warning"+ }+ return "healthy"+ case "memory":+ // Higher is worse for memory+ if value > 900 {+ return "critical"+ } else if value > 700 {+ return "warning"+ }+ return "healthy"+ }+ return "healthy"+}++func getLastValue(points []models.TimeSeriesPoint) float64 {+ if len(points) == 0 {+ return 0+ }+ return points[len(points)-1].Value+}++func getAverageValue(points []models.TimeSeriesPoint) float64 {+ if len(points) == 0 {+ return 0+ }+ var sum float64+ for _, p := range points {+ sum += p.Value+ }+ return sum / float64(len(points))+}++var DashboardController = dashboardController{}diff --git a/backend/app/controllers/exception_stack_trace.controller.go b/backend/app/controllers/exception_stack_trace.controller.goindex 76d38475..3371411d 100644--- a/backend/app/controllers/exception_stack_trace.controller.go+++ b/backend/app/controllers/exception_stack_trace.controller.go@@ -3,7 +3,7 @@ package controllersimport ("backend/app/models""backend/app/repositories"- "fmt"+ "errors""net/http""time"@@ -20,6 +20,16 @@ type ExceptionSearchRequest struct {Search string `json:"search"`}+type ExceptionDetailRequest struct {+ Pagination PaginationParams `json:"pagination"`+}++type ExceptionDetailResponse struct {+ Group *models.ExceptionGroup `json:"group"`+ Occurrences []models.ExceptionStackTrace `json:"occurrences"`+ Pagination Pagination `json:"pagination"`+}+func (e exceptionStackTraceController) FindGrouppedExceptionStackTraces(c *gin.Context) {var request ExceptionSearchRequestif err := c.ShouldBindJSON(&request); err != nil {@@ -44,4 +54,39 @@ func (e exceptionStackTraceController) FindGrouppedExceptionStackTraces(c *gin.C})}+func (e exceptionStackTraceController) FindByHash(c *gin.Context) {+ exceptionHash := c.Param("hash")+ if exceptionHash == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "exception hash is required"})+ return+ }++ var request ExceptionDetailRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ // Default pagination if not provided+ request.Pagination = PaginationParams{Page: 1, PageSize: 20}+ }++ group, occurrences, total, err := repositories.ExceptionStackTraceRepository.FindByHash(c, exceptionHash, request.Pagination.Page, request.Pagination.PageSize)+ if err != nil {+ if errors.Is(err, repositories.ErrExceptionNotFound) {+ c.JSON(http.StatusNotFound, gin.H{"error": "Exception not found"})+ return+ }+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.JSON(http.StatusOK, ExceptionDetailResponse{+ Group: group,+ Occurrences: occurrences,+ Pagination: Pagination{+ Page: request.Pagination.Page,+ PageSize: request.Pagination.PageSize,+ Total: total,+ TotalPages: (total + int64(request.Pagination.PageSize) - 1) / int64(request.Pagination.PageSize),+ },+ })+}+var ExceptionStackTraceController = exceptionStackTraceController{}diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 38a0eb52..ef465c73 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -28,9 +28,13 @@ func RegisterControllers(router *gin.RouterGroup) {router.POST("/report", middleware.UseClientAuth, middleware.UseGzip, clientcontrollers.ClientController.Report)router.POST("/stats", middleware.UseAppAuth, MetricRecordController.FindHomepageStats)+ router.GET("/dashboard", middleware.UseAppAuth, DashboardController.GetDashboard)router.POST("/transactions", middleware.UseAppAuth, TransactionController.FindAllTransactions)+ router.POST("/transactions/grouped", middleware.UseAppAuth, TransactionController.FindGroupedByEndpoint)+ router.POST("/transactions/endpoint", middleware.UseAppAuth, TransactionController.FindByEndpoint)router.POST("/exception-stack-traces", middleware.UseAppAuth, ExceptionStackTraceController.FindGrouppedExceptionStackTraces)+ router.POST("/exception-stack-traces/:hash", middleware.UseAppAuth, ExceptionStackTraceController.FindByHash)// Authrouter.POST("/login", AuthController.Login)diff --git a/backend/app/controllers/transaction.controller.go b/backend/app/controllers/transaction.controller.goindex 7fd80550..fe984d70 100644--- a/backend/app/controllers/transaction.controller.go+++ b/backend/app/controllers/transaction.controller.go@@ -4,6 +4,7 @@ import ("backend/app/models""backend/app/repositories""net/http"+ "net/url""time""github.com/gin-gonic/gin"@@ -18,6 +19,13 @@ type TransactionSearchRequest struct {Pagination PaginationParams `json:"pagination"`}+type EndpointTransactionsRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ OrderBy string `json:"orderBy"`+ Pagination PaginationParams `json:"pagination"`+}+func (e transactionController) FindAllTransactions(c *gin.Context) {var request TransactionSearchRequestif err := c.ShouldBindJSON(&request); err != nil {@@ -42,4 +50,64 @@ func (e transactionController) FindAllTransactions(c *gin.Context) {})}+func (e transactionController) FindGroupedByEndpoint(c *gin.Context) {+ var request TransactionSearchRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ stats, total, err := repositories.TransactionRepository.FindGroupedByEndpoint(c, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.JSON(http.StatusOK, PaginatedResponse[models.EndpointStats]{+ Data: stats,+ Pagination: Pagination{+ Page: request.Pagination.Page,+ PageSize: request.Pagination.PageSize,+ Total: total,+ TotalPages: (total + int64(request.Pagination.PageSize) - 1) / int64(request.Pagination.PageSize),+ },+ })+}++func (e transactionController) FindByEndpoint(c *gin.Context) {+ rawEndpoint := c.Query("endpoint")+ if rawEndpoint == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "endpoint is required"})+ return+ }++ // URL decode the endpoint (it may contain encoded slashes and spaces)+ endpoint, err := url.PathUnescape(rawEndpoint)+ if err != nil {+ endpoint = rawEndpoint // fallback to raw value if decoding fails+ }++ var request EndpointTransactionsRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ transactions, total, err := repositories.TransactionRepository.FindByEndpoint(c, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.JSON(http.StatusOK, PaginatedResponse[models.Transaction]{+ Data: transactions,+ Pagination: Pagination{+ Page: request.Pagination.Page,+ PageSize: request.Pagination.PageSize,+ Total: total,+ TotalPages: (total + int64(request.Pagination.PageSize) - 1) / int64(request.Pagination.PageSize),+ },+ })+}+var TransactionController = transactionController{}diff --git a/backend/app/models/clientmodels/clientmodels.model.go b/backend/app/models/clientmodels/clientmodels.model.goindex 3ab2d4d6..59fffd12 100644--- a/backend/app/models/clientmodels/clientmodels.model.go+++ b/backend/app/models/clientmodels/clientmodels.model.go@@ -50,8 +50,8 @@ func (c *ClientTransaction) ToTransaction() models.Transaction {Endpoint: c.Endpoint,Duration: c.Duration,RecordedAt: c.RecordedAt,- StatusCode: c.StatusCode,- BodySize: c.BodySize,+ StatusCode: int32(c.StatusCode),+ BodySize: int32(c.BodySize),ClientIP: c.ClientIP,}}diff --git a/backend/app/models/dashboard.model.go b/backend/app/models/dashboard.model.gonew file mode 100644index 00000000..472f815a--- /dev/null+++ b/backend/app/models/dashboard.model.go@@ -0,0 +1,29 @@+package models++import "time"++type DashboardTrendPoint struct {+ Timestamp time.Time `json:"timestamp"`+ Value float64 `json:"value"`+}++type DashboardMetric struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Value float64 `json:"value"`+ Unit string `json:"unit"`+ Trend []DashboardTrendPoint `json:"trend"`+ Change24h float64 `json:"change24h"`+ Status string `json:"status"`+}++type DashboardResponse struct {+ Metrics []DashboardMetric `json:"metrics"`+ LastUpdated time.Time `json:"lastUpdated"`+}++// TimeSeriesPoint is used internally for querying time-bucketed data+type TimeSeriesPoint struct {+ Timestamp time.Time+ Value float64+}diff --git a/backend/app/models/transaction.model.go b/backend/app/models/transaction.model.goindex 0eb142f8..43c5adca 100644--- a/backend/app/models/transaction.model.go+++ b/backend/app/models/transaction.model.go@@ -8,7 +8,16 @@ type Transaction struct {Endpoint string `json:"endpoint" ch:"endpoint"`Duration time.Duration `json:"duration" ch:"duration"`RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`- StatusCode int `json:"statusCode" ch:"status_code"`- BodySize int `json:"bodySize" ch:"body_size"`+ StatusCode int32 `json:"statusCode" ch:"status_code"`+ BodySize int32 `json:"bodySize" ch:"body_size"`ClientIP string `json:"clientIP" ch:"client_ip"`}++type EndpointStats struct {+ Endpoint string `json:"endpoint"`+ Count uint64 `json:"count"`+ P50Duration time.Duration `json:"p50Duration"`+ P95Duration time.Duration `json:"p95Duration"`+ AvgDuration time.Duration `json:"avgDuration"`+ LastSeen time.Time `json:"lastSeen"`+}diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/exception_stack_trace.repository.goindex 603234f0..3f511693 100644--- a/backend/app/repositories/exception_stack_trace.repository.go+++ b/backend/app/repositories/exception_stack_trace.repository.go@@ -4,9 +4,12 @@ import ("backend/app/chdb""backend/app/models""context"+ "errors""time")+var ErrExceptionNotFound = errors.New("exception not found")+type exceptionStackTraceRepository struct{}func (e *exceptionStackTraceRepository) InsertAsync(ctx context.Context, lines []models.ExceptionStackTrace) error {@@ -80,4 +83,66 @@ func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, fromDatreturn groups, int64(count), nil}+func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, exceptionHash string, page, pageSize int) (*models.ExceptionGroup, []models.ExceptionStackTrace, int64, error) {+ offset := (page - 1) * pageSize++ // Get grouped info+ var group models.ExceptionGroup+ err := (*chdb.Conn).QueryRow(ctx,+ "SELECT exception_hash, any(stack_trace), max(recorded_at) as last_seen, min(recorded_at) as first_seen, count() as count FROM exception_stack_traces WHERE exception_hash = ? GROUP BY exception_hash",+ exceptionHash).Scan(&group.ExceptionHash, &group.StackTrace, &group.LastSeen, &group.FirstSeen, &group.Count)+ if err != nil {+ // ClickHouse returns error when no rows found in QueryRow+ return nil, nil, 0, ErrExceptionNotFound+ }++ // Get individual occurrences with pagination+ rows, err := (*chdb.Conn).Query(ctx,+ "SELECT transaction_id, exception_hash, stack_trace, recorded_at FROM exception_stack_traces WHERE exception_hash = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?",+ exceptionHash, pageSize, offset)+ if err != nil {+ return nil, nil, 0, err+ }+ defer rows.Close()++ var occurrences []models.ExceptionStackTrace+ for rows.Next() {+ var o models.ExceptionStackTrace+ if err := rows.Scan(&o.TransactionId, &o.ExceptionHash, &o.StackTrace, &o.RecordedAt); err != nil {+ return nil, nil, 0, err+ }+ occurrences = append(occurrences, o)+ }++ return &group, occurrences, int64(group.Count), nil+}++// CountByHour returns exception counts grouped by hour+func (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfHour(recorded_at) as hour,+ count() as count+ FROM exception_stack_traces+ WHERE recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}+var ExceptionStackTraceRepository = exceptionStackTraceRepository{}diff --git a/backend/app/repositories/metric_record.repository.go b/backend/app/repositories/metric_record.repository.goindex 43ad321b..aa69ba6f 100644--- a/backend/app/repositories/metric_record.repository.go+++ b/backend/app/repositories/metric_record.repository.go@@ -28,4 +28,32 @@ func (e *metricRecordRepository) GetAverageBetween(ctx context.Context, name strreturn avg, err}+// GetAverageByHour returns metric averages grouped by hour+func (e *metricRecordRepository) GetAverageByHour(ctx context.Context, name string, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfHour(recorded_at) as hour,+ avg(value) as avg_value+ FROM metric_records+ WHERE name = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, name, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}+var MetricRecordRepository = metricRecordRepository{}diff --git a/backend/app/repositories/transaction.repository.go b/backend/app/repositories/transaction.repository.goindex a84d1cd7..f32de144 100644--- a/backend/app/repositories/transaction.repository.go+++ b/backend/app/repositories/transaction.repository.go@@ -67,4 +67,184 @@ func (e *transactionRepository) FindAll(ctx context.Context, fromDate, toDate tireturn transactions, int64(count), nil}+func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.EndpointStats, int64, error) {+ // Count unique endpoints+ var count uint64+ err := (*chdb.Conn).QueryRow(ctx, "SELECT uniq(endpoint) FROM transactions WHERE recorded_at >= ? AND recorded_at <= ?", fromDate, toDate).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "count": true,+ "p50_duration": true,+ "p95_duration": true,+ "avg_duration": true,+ "last_seen": true,+ }++ if !allowedOrderBy[orderBy] {+ orderBy = "count"+ }++ query := `SELECT+ endpoint,+ count() as count,+ quantile(0.5)(duration) as p50_duration,+ quantile(0.95)(duration) as p95_duration,+ avg(duration) as avg_duration,+ max(recorded_at) as last_seen+ FROM transactions+ WHERE recorded_at >= ? AND recorded_at <= ?+ GROUP BY endpoint+ ORDER BY ` + orderBy + ` DESC+ LIMIT ? OFFSET ?`++ rows, err := (*chdb.Conn).Query(ctx, query, fromDate, toDate, pageSize, offset)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var stats []models.EndpointStats+ for rows.Next() {+ var s models.EndpointStats+ var p50, p95, avg float64+ if err := rows.Scan(&s.Endpoint, &s.Count, &p50, &p95, &avg, &s.LastSeen); err != nil {+ return nil, 0, err+ }+ s.P50Duration = time.Duration(p50)+ s.P95Duration = time.Duration(p95)+ s.AvgDuration = time.Duration(avg)+ stats = append(stats, s)+ }++ return stats, int64(count), nil+}++func (e *transactionRepository) FindByEndpoint(ctx context.Context, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Transaction, int64, error) {+ var count uint64+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE endpoint = ? AND recorded_at >= ? AND recorded_at <= ?", endpoint, fromDate, toDate).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true,+ "duration": true,+ "status_code": true,+ "body_size": true,+ }++ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ query := "SELECT id, endpoint, duration, recorded_at, status_code, body_size, client_ip FROM transactions WHERE endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"+ rows, err := (*chdb.Conn).Query(ctx, query, endpoint, fromDate, toDate, pageSize, offset)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var transactions []models.Transaction+ for rows.Next() {+ var t models.Transaction+ if err := rows.Scan(&t.Id, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP); err != nil {+ return nil, 0, err+ }+ transactions = append(transactions, t)+ }++ return transactions, int64(count), nil+}++// CountByHour returns transaction counts grouped by hour+func (e *transactionRepository) CountByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfHour(recorded_at) as hour,+ count() as count+ FROM transactions+ WHERE recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}++// AvgDurationByHour returns average response time in ms grouped by hour+func (e *transactionRepository) AvgDurationByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfHour(recorded_at) as hour,+ avg(duration) / 1000000 as avg_duration_ms+ FROM transactions+ WHERE recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}++// ErrorRateByHour returns error rate (percentage) grouped by hour+func (e *transactionRepository) ErrorRateByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfHour(recorded_at) as hour,+ countIf(status_code >= 400) * 100.0 / count() as error_rate+ FROM transactions+ WHERE recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}+var TransactionRepository = transactionRepository{}diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 6586d4eb..8b59d230 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -20,6 +20,7 @@"@sveltejs/kit": "^2.49.1","@sveltejs/vite-plugin-svelte": "^6.2.1","@tailwindcss/vite": "^4.1.17",+ "@types/d3-array": "^3.2.2","@types/d3-scale": "^4.0.9","@types/d3-shape": "^3.1.7","@types/node": "^22",@@ -1660,6 +1661,13 @@"dev": true,"license": "MIT"},+ "node_modules/@types/d3-array": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/d3-path": {"version": "3.1.1","resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 2ecb0010..a01a6f91 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -23,6 +23,7 @@"@sveltejs/kit": "^2.49.1","@sveltejs/vite-plugin-svelte": "^6.2.1","@tailwindcss/vite": "^4.1.17",+ "@types/d3-array": "^3.2.2","@types/d3-scale": "^4.0.9","@types/d3-shape": "^3.1.7","@types/node": "^22",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex f1373a96..0b9b3681 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -30,7 +30,9 @@ async function request(method: string, endpoint: string, data?: any) {}if (!response.ok) {- throw new Error(`API Error: ${response.statusText}`);+ const error = new Error(`API Error: ${response.statusText}`) as Error & { status: number };+ error.status = response.status;+ throw error;}return response.json();diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelteindex 12d70b24..e62a4fa2 100644--- a/frontend/src/lib/components/app-sidebar.svelte+++ b/frontend/src/lib/components/app-sidebar.svelte@@ -9,9 +9,7 @@const sidebarItems = [{Icon: LayoutDashboard, href: "/", title: "Dashboard"},{Icon: Bug, href: "/issues", title: "Issues"},- {Icon: List, href: "/issues", title: "Transactions"},- {Icon: Gauge, href: "/issues", title: "Issues"},-+ {Icon: List, href: "/transactions", title: "Transactions"},]</script>diff --git a/frontend/src/lib/components/dashboard/metric-card.svelte b/frontend/src/lib/components/dashboard/metric-card.svelteindex 68d3aff8..94fed6db 100644--- a/frontend/src/lib/components/dashboard/metric-card.svelte+++ b/frontend/src/lib/components/dashboard/metric-card.svelte@@ -37,8 +37,8 @@value: { label: "Value", color: "var(--chart-1)" },} satisfies Chart.ChartConfig;- const yMin = $derived(min(metric.trend, (d: MetricTrendPoint) => d.value));- const yMax = $derived(max(metric.trend, (d: MetricTrendPoint) => d.value));+ const yMin = $derived(min(metric.trend, (d: MetricTrendPoint) => d.value) ?? 0);+ const yMax = $derived(max(metric.trend, (d: MetricTrendPoint) => d.value) ?? 0);const padding = $derived((yMax - yMin) * 0.1);</script>diff --git a/frontend/src/lib/components/ui/calendar/calendar-caption.svelte b/frontend/src/lib/components/ui/calendar/calendar-caption.sveltenew file mode 100644index 00000000..5c930370--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-caption.svelte@@ -0,0 +1,76 @@+<script lang="ts">+ import type { ComponentProps } from "svelte";+ import type Calendar from "./calendar.svelte";+ import CalendarMonthSelect from "./calendar-month-select.svelte";+ import CalendarYearSelect from "./calendar-year-select.svelte";+ import { DateFormatter, getLocalTimeZone, type DateValue } from "@internationalized/date";++ let {+ captionLayout,+ months,+ monthFormat,+ years,+ yearFormat,+ month,+ locale,+ placeholder = $bindable(),+ monthIndex = 0,+ }: {+ captionLayout: ComponentProps<typeof Calendar>["captionLayout"];+ months: ComponentProps<typeof CalendarMonthSelect>["months"];+ monthFormat: ComponentProps<typeof CalendarMonthSelect>["monthFormat"];+ years: ComponentProps<typeof CalendarYearSelect>["years"];+ yearFormat: ComponentProps<typeof CalendarYearSelect>["yearFormat"];+ month: DateValue;+ placeholder: DateValue | undefined;+ locale: string;+ monthIndex: number;+ } = $props();++ function formatYear(date: DateValue) {+ const dateObj = date.toDate(getLocalTimeZone());+ if (typeof yearFormat === "function") return yearFormat(dateObj.getFullYear());+ return new DateFormatter(locale, { year: yearFormat }).format(dateObj);+ }++ function formatMonth(date: DateValue) {+ const dateObj = date.toDate(getLocalTimeZone());+ if (typeof monthFormat === "function") return monthFormat(dateObj.getMonth() + 1);+ return new DateFormatter(locale, { month: monthFormat }).format(dateObj);+ }+</script>++{#snippet MonthSelect()}+ <CalendarMonthSelect+ {months}+ {monthFormat}+ value={month.month}+ onchange={(e) => {+ if (!placeholder) return;+ const v = Number.parseInt(e.currentTarget.value);+ const newPlaceholder = placeholder.set({ month: v });+ placeholder = newPlaceholder.subtract({ months: monthIndex });+ }}+ />+{/snippet}++{#snippet YearSelect()}+ <CalendarYearSelect {years} {yearFormat} value={month.year} />+{/snippet}++{#if captionLayout === "dropdown"}+ {@render MonthSelect()}+ {@render YearSelect()}+{:else if captionLayout === "dropdown-months"}+ {@render MonthSelect()}+ {#if placeholder}+ {formatYear(placeholder)}+ {/if}+{:else if captionLayout === "dropdown-years"}+ {#if placeholder}+ {formatMonth(placeholder)}+ {/if}+ {@render YearSelect()}+{:else}+ {formatMonth(month)} {formatYear(month)}+{/if}diff --git a/frontend/src/lib/components/ui/calendar/calendar-cell.svelte b/frontend/src/lib/components/ui/calendar/calendar-cell.sveltenew file mode 100644index 00000000..4cdb5481--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-cell.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.CellProps = $props();+</script>++<CalendarPrimitive.Cell+ bind:ref+ class={cn(+ "relative size-(--cell-size) p-0 text-center text-sm focus-within:z-20 [&:first-child[data-selected]_[data-bits-day]]:rounded-s-md [&:last-child[data-selected]_[data-bits-day]]:rounded-e-md",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-day.svelte b/frontend/src/lib/components/ui/calendar/calendar-day.sveltenew file mode 100644index 00000000..19d7bde7--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-day.svelte@@ -0,0 +1,35 @@+<script lang="ts">+ import { buttonVariants } from "$lib/components/ui/button/index.js";+ import { cn } from "$lib/utils.js";+ import { Calendar as CalendarPrimitive } from "bits-ui";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.DayProps = $props();+</script>++<CalendarPrimitive.Day+ bind:ref+ class={cn(+ buttonVariants({ variant: "ghost" }),+ "flex size-(--cell-size) flex-col items-center justify-center gap-1 p-0 leading-none font-normal whitespace-nowrap select-none",+ "[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground [&[data-today][data-disabled]]:text-muted-foreground",+ "data-[selected]:bg-primary dark:data-[selected]:hover:bg-accent/50 data-[selected]:text-primary-foreground",+ // Outside months+ "[&[data-outside-month]:not([data-selected])]:text-muted-foreground [&[data-outside-month]:not([data-selected])]:hover:text-accent-foreground",+ // Disabled+ "data-[disabled]:text-muted-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ // Unavailable+ "data-[unavailable]:text-muted-foreground data-[unavailable]:line-through",+ // hover+ "dark:hover:text-accent-foreground",+ // focus+ "focus:border-ring focus:ring-ring/50 focus:relative",+ // inner spans+ "[&>span]:text-xs [&>span]:opacity-70",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-body.sveltenew file mode 100644index 00000000..8cd86dec--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-body.svelte@@ -0,0 +1,12 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridBodyProps = $props();+</script>++<CalendarPrimitive.GridBody bind:ref class={cn(className)} {...restProps} />diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-head.sveltenew file mode 100644index 00000000..333edc47--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-head.svelte@@ -0,0 +1,12 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridHeadProps = $props();+</script>++<CalendarPrimitive.GridHead bind:ref class={cn(className)} {...restProps} />diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid-row.sveltenew file mode 100644index 00000000..90322369--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid-row.svelte@@ -0,0 +1,12 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridRowProps = $props();+</script>++<CalendarPrimitive.GridRow bind:ref class={cn("flex", className)} {...restProps} />diff --git a/frontend/src/lib/components/ui/calendar/calendar-grid.svelte b/frontend/src/lib/components/ui/calendar/calendar-grid.sveltenew file mode 100644index 00000000..e0c8627f--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-grid.svelte@@ -0,0 +1,16 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.GridProps = $props();+</script>++<CalendarPrimitive.Grid+ bind:ref+ class={cn("mt-4 flex w-full border-collapse flex-col gap-1", className)}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelte b/frontend/src/lib/components/ui/calendar/calendar-head-cell.sveltenew file mode 100644index 00000000..131807e2--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-head-cell.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.HeadCellProps = $props();+</script>++<CalendarPrimitive.HeadCell+ bind:ref+ class={cn(+ "text-muted-foreground w-(--cell-size) rounded-md text-[0.8rem] font-normal",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-header.svelte b/frontend/src/lib/components/ui/calendar/calendar-header.sveltenew file mode 100644index 00000000..c39e955d--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-header.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.HeaderProps = $props();+</script>++<CalendarPrimitive.Header+ bind:ref+ class={cn(+ "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",+ className+ )}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-heading.svelte b/frontend/src/lib/components/ui/calendar/calendar-heading.sveltenew file mode 100644index 00000000..a9b9810c--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-heading.svelte@@ -0,0 +1,16 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: CalendarPrimitive.HeadingProps = $props();+</script>++<CalendarPrimitive.Heading+ bind:ref+ class={cn("px-(--cell-size) text-sm font-medium", className)}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-month-select.svelte b/frontend/src/lib/components/ui/calendar/calendar-month-select.sveltenew file mode 100644index 00000000..8d88deb5--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-month-select.svelte@@ -0,0 +1,44 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";++ let {+ ref = $bindable(null),+ class: className,+ value,+ onchange,+ ...restProps+ }: WithoutChildrenOrChild<CalendarPrimitive.MonthSelectProps> = $props();+</script>++<span+ class={cn(+ "has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]",+ className+ )}+>+ <CalendarPrimitive.MonthSelect bind:ref class="absolute inset-0 opacity-0" {...restProps}>+ {#snippet child({ props, monthItems, selectedMonthItem })}+ <select {...props} {value} {onchange}>+ {#each monthItems as monthItem (monthItem.value)}+ <option+ value={monthItem.value}+ selected={value !== undefined+ ? monthItem.value === value+ : monthItem.value === selectedMonthItem.value}+ >+ {monthItem.label}+ </option>+ {/each}+ </select>+ <span+ class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5"+ aria-hidden="true"+ >+ {monthItems.find((item) => item.value === value)?.label || selectedMonthItem.label}+ <ChevronDownIcon class="size-4" />+ </span>+ {/snippet}+ </CalendarPrimitive.MonthSelect>+</span>diff --git a/frontend/src/lib/components/ui/calendar/calendar-month.svelte b/frontend/src/lib/components/ui/calendar/calendar-month.sveltenew file mode 100644index 00000000..e747fae7--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-month.svelte@@ -0,0 +1,15 @@+<script lang="ts">+ import { type WithElementRef, cn } from "$lib/utils.js";+ import type { HTMLAttributes } from "svelte/elements";++ let {+ ref = $bindable(null),+ class: className,+ children,+ ...restProps+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();+</script>++<div {...restProps} bind:this={ref} class={cn("flex flex-col", className)}>+ {@render children?.()}+</div>diff --git a/frontend/src/lib/components/ui/calendar/calendar-months.svelte b/frontend/src/lib/components/ui/calendar/calendar-months.sveltenew file mode 100644index 00000000..f717a9d9--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-months.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import type { HTMLAttributes } from "svelte/elements";+ import { cn, type WithElementRef } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ children,+ ...restProps+ }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();+</script>++<div+ bind:this={ref}+ class={cn("relative flex flex-col gap-4 md:flex-row", className)}+ {...restProps}+>+ {@render children?.()}+</div>diff --git a/frontend/src/lib/components/ui/calendar/calendar-nav.svelte b/frontend/src/lib/components/ui/calendar/calendar-nav.sveltenew file mode 100644index 00000000..27f33d79--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-nav.svelte@@ -0,0 +1,19 @@+<script lang="ts">+ import { cn, type WithElementRef } from "$lib/utils.js";+ import type { HTMLAttributes } from "svelte/elements";++ let {+ ref = $bindable(null),+ class: className,+ children,+ ...restProps+ }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();+</script>++<nav+ {...restProps}+ bind:this={ref}+ class={cn("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", className)}+>+ {@render children?.()}+</nav>diff --git a/frontend/src/lib/components/ui/calendar/calendar-next-button.svelte b/frontend/src/lib/components/ui/calendar/calendar-next-button.sveltenew file mode 100644index 00000000..5c5a78df--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-next-button.svelte@@ -0,0 +1,31 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import ChevronRightIcon from "@lucide/svelte/icons/chevron-right";+ import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ children,+ variant = "ghost",+ ...restProps+ }: CalendarPrimitive.NextButtonProps & {+ variant?: ButtonVariant;+ } = $props();+</script>++{#snippet Fallback()}+ <ChevronRightIcon class="size-4" />+{/snippet}++<CalendarPrimitive.NextButton+ bind:ref+ class={cn(+ buttonVariants({ variant }),+ "size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180",+ className+ )}+ children={children || Fallback}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelte b/frontend/src/lib/components/ui/calendar/calendar-prev-button.sveltenew file mode 100644index 00000000..33cfd636--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-prev-button.svelte@@ -0,0 +1,31 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import ChevronLeftIcon from "@lucide/svelte/icons/chevron-left";+ import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ children,+ variant = "ghost",+ ...restProps+ }: CalendarPrimitive.PrevButtonProps & {+ variant?: ButtonVariant;+ } = $props();+</script>++{#snippet Fallback()}+ <ChevronLeftIcon class="size-4" />+{/snippet}++<CalendarPrimitive.PrevButton+ bind:ref+ class={cn(+ buttonVariants({ variant }),+ "size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180",+ className+ )}+ children={children || Fallback}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/calendar/calendar-year-select.svelte b/frontend/src/lib/components/ui/calendar/calendar-year-select.sveltenew file mode 100644index 00000000..226efdf4--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar-year-select.svelte@@ -0,0 +1,43 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import ChevronDownIcon from "@lucide/svelte/icons/chevron-down";++ let {+ ref = $bindable(null),+ class: className,+ value,+ ...restProps+ }: WithoutChildrenOrChild<CalendarPrimitive.YearSelectProps> = $props();+</script>++<span+ class={cn(+ "has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]",+ className+ )}+>+ <CalendarPrimitive.YearSelect bind:ref class="absolute inset-0 opacity-0" {...restProps}>+ {#snippet child({ props, yearItems, selectedYearItem })}+ <select {...props} {value}>+ {#each yearItems as yearItem (yearItem.value)}+ <option+ value={yearItem.value}+ selected={value !== undefined+ ? yearItem.value === value+ : yearItem.value === selectedYearItem.value}+ >+ {yearItem.label}+ </option>+ {/each}+ </select>+ <span+ class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5"+ aria-hidden="true"+ >+ {yearItems.find((item) => item.value === value)?.label || selectedYearItem.label}+ <ChevronDownIcon class="size-4" />+ </span>+ {/snippet}+ </CalendarPrimitive.YearSelect>+</span>diff --git a/frontend/src/lib/components/ui/calendar/calendar.svelte b/frontend/src/lib/components/ui/calendar/calendar.sveltenew file mode 100644index 00000000..29b6fff9--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/calendar.svelte@@ -0,0 +1,115 @@+<script lang="ts">+ import { Calendar as CalendarPrimitive } from "bits-ui";+ import * as Calendar from "./index.js";+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import type { ButtonVariant } from "../button/button.svelte";+ import { isEqualMonth, type DateValue } from "@internationalized/date";+ import type { Snippet } from "svelte";++ let {+ ref = $bindable(null),+ value = $bindable(),+ placeholder = $bindable(),+ class: className,+ weekdayFormat = "short",+ buttonVariant = "ghost",+ captionLayout = "label",+ locale = "en-US",+ months: monthsProp,+ years,+ monthFormat: monthFormatProp,+ yearFormat = "numeric",+ day,+ disableDaysOutsideMonth = false,+ ...restProps+ }: WithoutChildrenOrChild<CalendarPrimitive.RootProps> & {+ buttonVariant?: ButtonVariant;+ captionLayout?: "dropdown" | "dropdown-months" | "dropdown-years" | "label";+ months?: CalendarPrimitive.MonthSelectProps["months"];+ years?: CalendarPrimitive.YearSelectProps["years"];+ monthFormat?: CalendarPrimitive.MonthSelectProps["monthFormat"];+ yearFormat?: CalendarPrimitive.YearSelectProps["yearFormat"];+ day?: Snippet<[{ day: DateValue; outsideMonth: boolean }]>;+ } = $props();++ const monthFormat = $derived.by(() => {+ if (monthFormatProp) return monthFormatProp;+ if (captionLayout.startsWith("dropdown")) return "short";+ return "long";+ });+</script>++<!--+Discriminated Unions + Destructing (required for bindable) do not+get along, so we shut typescript up by casting `value` to `never`.+-->+<CalendarPrimitive.Root+ bind:value={value as never}+ bind:ref+ bind:placeholder+ {weekdayFormat}+ {disableDaysOutsideMonth}+ class={cn(+ "bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",+ className+ )}+ {locale}+ {monthFormat}+ {yearFormat}+ {...restProps}+>+ {#snippet children({ months, weekdays })}+ <Calendar.Months>+ <Calendar.Nav>+ <Calendar.PrevButton variant={buttonVariant} />+ <Calendar.NextButton variant={buttonVariant} />+ </Calendar.Nav>+ {#each months as month, monthIndex (month)}+ <Calendar.Month>+ <Calendar.Header>+ <Calendar.Caption+ {captionLayout}+ months={monthsProp}+ {monthFormat}+ {years}+ {yearFormat}+ month={month.value}+ bind:placeholder+ {locale}+ {monthIndex}+ />+ </Calendar.Header>+ <Calendar.Grid>+ <Calendar.GridHead>+ <Calendar.GridRow class="select-none">+ {#each weekdays as weekday (weekday)}+ <Calendar.HeadCell>+ {weekday.slice(0, 2)}+ </Calendar.HeadCell>+ {/each}+ </Calendar.GridRow>+ </Calendar.GridHead>+ <Calendar.GridBody>+ {#each month.weeks as weekDates (weekDates)}+ <Calendar.GridRow class="mt-2 w-full">+ {#each weekDates as date (date)}+ <Calendar.Cell {date} month={month.value}>+ {#if day}+ {@render day({+ day: date,+ outsideMonth: !isEqualMonth(date, month.value),+ })}+ {:else}+ <Calendar.Day />+ {/if}+ </Calendar.Cell>+ {/each}+ </Calendar.GridRow>+ {/each}+ </Calendar.GridBody>+ </Calendar.Grid>+ </Calendar.Month>+ {/each}+ </Calendar.Months>+ {/snippet}+</CalendarPrimitive.Root>diff --git a/frontend/src/lib/components/ui/calendar/index.ts b/frontend/src/lib/components/ui/calendar/index.tsnew file mode 100644index 00000000..f3a16d2d--- /dev/null+++ b/frontend/src/lib/components/ui/calendar/index.ts@@ -0,0 +1,40 @@+import Root from "./calendar.svelte";+import Cell from "./calendar-cell.svelte";+import Day from "./calendar-day.svelte";+import Grid from "./calendar-grid.svelte";+import Header from "./calendar-header.svelte";+import Months from "./calendar-months.svelte";+import GridRow from "./calendar-grid-row.svelte";+import Heading from "./calendar-heading.svelte";+import GridBody from "./calendar-grid-body.svelte";+import GridHead from "./calendar-grid-head.svelte";+import HeadCell from "./calendar-head-cell.svelte";+import NextButton from "./calendar-next-button.svelte";+import PrevButton from "./calendar-prev-button.svelte";+import MonthSelect from "./calendar-month-select.svelte";+import YearSelect from "./calendar-year-select.svelte";+import Month from "./calendar-month.svelte";+import Nav from "./calendar-nav.svelte";+import Caption from "./calendar-caption.svelte";++export {+ Day,+ Cell,+ Grid,+ Header,+ Months,+ GridRow,+ Heading,+ GridBody,+ GridHead,+ HeadCell,+ NextButton,+ PrevButton,+ Nav,+ Month,+ YearSelect,+ MonthSelect,+ Caption,+ //+ Root as Calendar,+};diff --git a/frontend/src/lib/components/ui/date-range-picker/date-range-picker.svelte b/frontend/src/lib/components/ui/date-range-picker/date-range-picker.sveltenew file mode 100644index 00000000..05a10576--- /dev/null+++ b/frontend/src/lib/components/ui/date-range-picker/date-range-picker.svelte@@ -0,0 +1,210 @@+<script lang="ts">+ import * as Popover from "$lib/components/ui/popover";+ import { Calendar } from "$lib/components/ui/calendar";+ import { Button } from "$lib/components/ui/button";+ import { Input } from "$lib/components/ui/input";+ import { Label } from "$lib/components/ui/label";+ import { CalendarDays, ChevronDown } from "@lucide/svelte";+ import { CalendarDate, getLocalTimeZone, today } from "@internationalized/date";+ import type { DateValue } from "@internationalized/date";++ type Props = {+ fromDate: string;+ toDate: string;+ onApply: (from: string, to: string) => void;+ class?: string;+ };++ let { fromDate, toDate, onApply, class: className = '' }: Props = $props();++ let open = $state(false);+ let fromCalendarOpen = $state(false);+ let toCalendarOpen = $state(false);++ // Internal state for dates and times+ let tempFromDate = $state<DateValue | undefined>(undefined);+ let tempFromTime = $state('00:00');+ let tempToDate = $state<DateValue | undefined>(undefined);+ let tempToTime = $state('23:59');++ // Parse the ISO string into CalendarDate and time string+ function parseDateTime(dateTimeStr: string): { date: DateValue | undefined; time: string } {+ if (!dateTimeStr) return { date: undefined, time: '00:00' };+ try {+ const d = new Date(dateTimeStr);+ const calDate = new CalendarDate(d.getFullYear(), d.getMonth() + 1, d.getDate());+ const hours = d.getHours().toString().padStart(2, '0');+ const minutes = d.getMinutes().toString().padStart(2, '0');+ return { date: calDate, time: `${hours}:${minutes}` };+ } catch {+ return { date: undefined, time: '00:00' };+ }+ }++ // Combine CalendarDate and time string into ISO string+ function combineDateTime(calDate: DateValue | undefined, time: string): string {+ if (!calDate) return '';+ const [hours, minutes] = time.split(':').map(Number);+ const jsDate = calDate.toDate(getLocalTimeZone());+ jsDate.setHours(hours || 0, minutes || 0, 0, 0);+ return jsDate.toISOString().slice(0, 16);+ }++ // Sync temp values when popover opens or props change+ $effect(() => {+ if (open) {+ const from = parseDateTime(fromDate);+ const to = parseDateTime(toDate);+ tempFromDate = from.date;+ tempFromTime = from.time;+ tempToDate = to.date;+ tempToTime = to.time;+ }+ });++ function handleApply() {+ const from = combineDateTime(tempFromDate, tempFromTime);+ const to = combineDateTime(tempToDate, tempToTime);+ if (from && to) {+ onApply(from, to);+ }+ open = false;+ }++ function handleCancel() {+ open = false;+ }++ function formatDisplayDate(dateStr: string): string {+ if (!dateStr) return '';+ try {+ const date = new Date(dateStr);+ return date.toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit'+ });+ } catch {+ return dateStr;+ }+ }++ function formatCalendarDate(date: DateValue | undefined): string {+ if (!date) return 'Select date';+ return date.toDate(getLocalTimeZone()).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric'+ });+ }++ const displayText = $derived(() => {+ if (!fromDate || !toDate) return 'Select date range';+ return `${formatDisplayDate(fromDate)} – ${formatDisplayDate(toDate)}`;+ });+</script>++<Popover.Root bind:open>+ <Popover.Trigger>+ {#snippet child({ props })}+ <Button+ variant="outline"+ class="h-9 min-w-[280px] justify-start text-left font-normal {className}"+ {...props}+ >+ <CalendarDays class="mr-2 h-4 w-4 opacity-70" />+ <span class="truncate">{displayText()}</span>+ </Button>+ {/snippet}+ </Popover.Trigger>+ <Popover.Content class="w-auto p-0" align="start">+ <div class="p-4 space-y-4">+ <div class="grid grid-cols-2 gap-6">+ <!-- From Date/Time -->+ <div class="space-y-3">+ <Label class="text-xs font-medium text-muted-foreground">From</Label>++ <!-- Date Picker -->+ <Popover.Root bind:open={fromCalendarOpen}>+ <Popover.Trigger>+ {#snippet child({ props })}+ <Button+ variant="outline"+ class="w-full justify-between font-normal text-sm h-9"+ {...props}+ >+ {formatCalendarDate(tempFromDate)}+ <ChevronDown class="h-4 w-4 opacity-50" />+ </Button>+ {/snippet}+ </Popover.Trigger>+ <Popover.Content class="w-auto p-0" align="start">+ <Calendar+ type="single"+ bind:value={tempFromDate}+ onValueChange={() => {+ fromCalendarOpen = false;+ }}+ captionLayout="dropdown"+ />+ </Popover.Content>+ </Popover.Root>++ <!-- Time Input -->+ <Input+ type="time"+ class="h-9 text-sm bg-background appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"+ bind:value={tempFromTime}+ />+ </div>++ <!-- To Date/Time -->+ <div class="space-y-3">+ <Label class="text-xs font-medium text-muted-foreground">To</Label>++ <!-- Date Picker -->+ <Popover.Root bind:open={toCalendarOpen}>+ <Popover.Trigger>+ {#snippet child({ props })}+ <Button+ variant="outline"+ class="w-full justify-between font-normal text-sm h-9"+ {...props}+ >+ {formatCalendarDate(tempToDate)}+ <ChevronDown class="h-4 w-4 opacity-50" />+ </Button>+ {/snippet}+ </Popover.Trigger>+ <Popover.Content class="w-auto p-0" align="start">+ <Calendar+ type="single"+ bind:value={tempToDate}+ onValueChange={() => {+ toCalendarOpen = false;+ }}+ captionLayout="dropdown"+ />+ </Popover.Content>+ </Popover.Root>++ <!-- Time Input -->+ <Input+ type="time"+ class="h-9 text-sm bg-background appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"+ bind:value={tempToTime}+ />+ </div>+ </div>+ <div class="flex items-center justify-end gap-2 pt-2 border-t">+ <Button variant="ghost" size="sm" onclick={handleCancel}>+ Cancel+ </Button>+ <Button size="sm" onclick={handleApply}>+ Apply+ </Button>+ </div>+ </div>+ </Popover.Content>+</Popover.Root>diff --git a/frontend/src/lib/components/ui/date-range-picker/index.ts b/frontend/src/lib/components/ui/date-range-picker/index.tsnew file mode 100644index 00000000..5e0f2727--- /dev/null+++ b/frontend/src/lib/components/ui/date-range-picker/index.ts@@ -0,0 +1,3 @@+import DateRangePicker from "./date-range-picker.svelte";++export { DateRangePicker };diff --git a/frontend/src/lib/components/ui/error-display/error-display.svelte b/frontend/src/lib/components/ui/error-display/error-display.sveltenew file mode 100644index 00000000..d8a41dc6--- /dev/null+++ b/frontend/src/lib/components/ui/error-display/error-display.svelte@@ -0,0 +1,175 @@+<script lang="ts">+ import { goto } from '$app/navigation';+ import { Button } from "$lib/components/ui/button";++ interface Props {+ status?: 404 | 400 | 422 | number;+ title?: string;+ description?: string;+ backHref?: string;+ backLabel?: string;+ onRetry?: () => void;+ identifier?: string;+ }++ let {+ status = 404,+ title,+ description,+ backHref,+ backLabel = 'Go Back',+ onRetry,+ identifier+ }: Props = $props();++ const defaults: Record<number, { title: string; description: string }> = {+ 404: {+ title: 'Not Found',+ description: "The resource you're looking for doesn't exist or may have been removed."+ },+ 400: {+ title: 'Bad Request',+ description: 'The request was invalid. Please check your input and try again.'+ },+ 422: {+ title: 'Validation Error',+ description: 'The data provided could not be processed. Please verify your input.'+ }+ };++ const displayTitle = $derived(title || defaults[status]?.title || 'Error');+ const displayDescription = $derived(description || defaults[status]?.description || 'Something went wrong.');++ function handleBack() {+ if (backHref) {+ goto(backHref);+ } else {+ history.back();+ }+ }+</script>++<div class="flex flex-col items-center justify-center py-16 px-4">+ <div class="relative mb-8">+ <!-- Glowing background effect -->+ {#if status === 404}+ <div class="absolute inset-0 blur-3xl opacity-20 bg-gradient-to-br from-red-500 via-orange-500 to-yellow-500 rounded-full scale-150"></div>+ {:else if status === 400}+ <div class="absolute inset-0 blur-3xl opacity-20 bg-gradient-to-br from-amber-500 via-orange-500 to-red-500 rounded-full scale-150"></div>+ {:else if status === 422}+ <div class="absolute inset-0 blur-3xl opacity-20 bg-gradient-to-br from-purple-500 via-pink-500 to-red-500 rounded-full scale-150"></div>+ {:else}+ <div class="absolute inset-0 blur-3xl opacity-20 bg-red-500 rounded-full scale-150"></div>+ {/if}++ <!-- Icon container -->+ <div class="relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-muted/80 to-muted border border-border/50 shadow-lg">+ {#if status === 404}+ <!-- X in circle icon -->+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="48"+ height="48"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.5"+ stroke-linecap="round"+ stroke-linejoin="round"+ class="text-muted-foreground"+ >+ <circle cx="12" cy="12" r="10"/>+ <path d="m15 9-6 6"/>+ <path d="m9 9 6 6"/>+ </svg>+ {:else if status === 400}+ <!-- Alert triangle icon -->+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="48"+ height="48"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.5"+ stroke-linecap="round"+ stroke-linejoin="round"+ class="text-amber-500"+ >+ <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/>+ <path d="M12 9v4"/>+ <path d="M12 17h.01"/>+ </svg>+ {:else if status === 422}+ <!-- Alert circle icon -->+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="48"+ height="48"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.5"+ stroke-linecap="round"+ stroke-linejoin="round"+ class="text-purple-500"+ >+ <circle cx="12" cy="12" r="10"/>+ <path d="M12 8v4"/>+ <path d="M12 16h.01"/>+ </svg>+ {:else}+ <!-- Generic error icon -->+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="48"+ height="48"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.5"+ stroke-linecap="round"+ stroke-linejoin="round"+ class="text-red-500"+ >+ <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/>+ <path d="M12 9v4"/>+ <path d="M12 17h.01"/>+ </svg>+ {/if}+ </div>+ </div>++ <div class="text-center space-y-3 max-w-md">+ <h2 class="text-2xl font-semibold tracking-tight">{displayTitle}</h2>+ <p class="text-muted-foreground leading-relaxed">{displayDescription}</p>+ </div>++ <div class="flex items-center gap-3 mt-8">+ <Button variant="outline" onclick={handleBack}>+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2">+ <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>+ </svg>+ {backLabel}+ </Button>+ {#if onRetry}+ <Button onclick={onRetry}>+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2">+ <path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/>+ <path d="M3 3v5h5"/>+ <path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/>+ <path d="M16 16h5v5"/>+ </svg>+ Try Again+ </Button>+ {/if}+ </div>++ {#if identifier}+ <div class="mt-8 px-4 py-2 rounded-lg bg-muted/50 border border-border/50">+ <code class="text-xs text-muted-foreground font-mono">+ {identifier}+ </code>+ </div>+ {/if}+</div>diff --git a/frontend/src/lib/components/ui/error-display/index.ts b/frontend/src/lib/components/ui/error-display/index.tsnew file mode 100644index 00000000..d91d21ca--- /dev/null+++ b/frontend/src/lib/components/ui/error-display/index.ts@@ -0,0 +1,3 @@+import ErrorDisplay from './error-display.svelte';++export { ErrorDisplay };diff --git a/frontend/src/lib/components/ui/popover/index.ts b/frontend/src/lib/components/ui/popover/index.tsnew file mode 100644index 00000000..b79d12e5--- /dev/null+++ b/frontend/src/lib/components/ui/popover/index.ts@@ -0,0 +1,19 @@+import Root from "./popover.svelte";+import Close from "./popover-close.svelte";+import Content from "./popover-content.svelte";+import Trigger from "./popover-trigger.svelte";+import Portal from "./popover-portal.svelte";++export {+ Root,+ Content,+ Trigger,+ Close,+ Portal,+ //+ Root as Popover,+ Content as PopoverContent,+ Trigger as PopoverTrigger,+ Close as PopoverClose,+ Portal as PopoverPortal,+};diff --git a/frontend/src/lib/components/ui/popover/popover-close.svelte b/frontend/src/lib/components/ui/popover/popover-close.sveltenew file mode 100644index 00000000..c360925a--- /dev/null+++ b/frontend/src/lib/components/ui/popover/popover-close.svelte@@ -0,0 +1,7 @@+<script lang="ts">+ import { Popover as PopoverPrimitive } from "bits-ui";++ let { ref = $bindable(null), ...restProps }: PopoverPrimitive.CloseProps = $props();+</script>++<PopoverPrimitive.Close bind:ref data-slot="popover-close" {...restProps} />diff --git a/frontend/src/lib/components/ui/popover/popover-content.svelte b/frontend/src/lib/components/ui/popover/popover-content.sveltenew file mode 100644index 00000000..3d79f3c6--- /dev/null+++ b/frontend/src/lib/components/ui/popover/popover-content.svelte@@ -0,0 +1,31 @@+<script lang="ts">+ import { Popover as PopoverPrimitive } from "bits-ui";+ import PopoverPortal from "./popover-portal.svelte";+ import { cn, type WithoutChildrenOrChild } from "$lib/utils.js";+ import type { ComponentProps } from "svelte";++ let {+ ref = $bindable(null),+ class: className,+ sideOffset = 4,+ align = "center",+ portalProps,+ ...restProps+ }: PopoverPrimitive.ContentProps & {+ portalProps?: WithoutChildrenOrChild<ComponentProps<typeof PopoverPortal>>;+ } = $props();+</script>++<PopoverPortal {...portalProps}>+ <PopoverPrimitive.Content+ bind:ref+ data-slot="popover-content"+ {sideOffset}+ {align}+ class={cn(+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--bits-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",+ className+ )}+ {...restProps}+ />+</PopoverPortal>diff --git a/frontend/src/lib/components/ui/popover/popover-portal.svelte b/frontend/src/lib/components/ui/popover/popover-portal.sveltenew file mode 100644index 00000000..dd8265fe--- /dev/null+++ b/frontend/src/lib/components/ui/popover/popover-portal.svelte@@ -0,0 +1,7 @@+<script lang="ts">+ import { Popover as PopoverPrimitive } from "bits-ui";++ let { ...restProps }: PopoverPrimitive.PortalProps = $props();+</script>++<PopoverPrimitive.Portal {...restProps} />diff --git a/frontend/src/lib/components/ui/popover/popover-trigger.svelte b/frontend/src/lib/components/ui/popover/popover-trigger.sveltenew file mode 100644index 00000000..586323c7--- /dev/null+++ b/frontend/src/lib/components/ui/popover/popover-trigger.svelte@@ -0,0 +1,17 @@+<script lang="ts">+ import { cn } from "$lib/utils.js";+ import { Popover as PopoverPrimitive } from "bits-ui";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: PopoverPrimitive.TriggerProps = $props();+</script>++<PopoverPrimitive.Trigger+ bind:ref+ data-slot="popover-trigger"+ class={cn("", className)}+ {...restProps}+/>diff --git a/frontend/src/lib/components/ui/popover/popover.svelte b/frontend/src/lib/components/ui/popover/popover.sveltenew file mode 100644index 00000000..6b1aa5f9--- /dev/null+++ b/frontend/src/lib/components/ui/popover/popover.svelte@@ -0,0 +1,7 @@+<script lang="ts">+ import { Popover as PopoverPrimitive } from "bits-ui";++ let { open = $bindable(false), ...restProps }: PopoverPrimitive.RootProps = $props();+</script>++<PopoverPrimitive.Root bind:open {...restProps} />diff --git a/frontend/src/lib/components/ui/select/select-group.svelte b/frontend/src/lib/components/ui/select/select-group.svelteindex 5454fdb3..a1f43bf3 100644--- a/frontend/src/lib/components/ui/select/select-group.svelte+++ b/frontend/src/lib/components/ui/select/select-group.svelte@@ -4,4 +4,4 @@let { ref = $bindable(null), ...restProps }: SelectPrimitive.GroupProps = $props();</script>-<SelectPrimitive.Group data-slot="select-group" {...restProps} />+<SelectPrimitive.Group bind:ref data-slot="select-group" {...restProps} />diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelteindex 9ec820b1..9d16ebae 100644--- a/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelte+++ b/frontend/src/lib/components/ui/sidebar/sidebar-menu-button.svelte@@ -2,7 +2,7 @@import { tv, type VariantProps } from "tailwind-variants";export const sidebarMenuButtonVariants = tv({- base: "peer/menu-button ring-sidebar-ring data-[active=false]:hover:bg-gray-100 dark:data-[active=false]:hover:bg-white/10 active:bg-sidebar-accent active:text-sidebar-accent-foreground data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground data-[state=open]:data-[active=false]:hover:bg-gray-100 dark:data-[state=open]:data-[active=false]:hover:bg-white/10 flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-start text-sm outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pe-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:font-medium [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",+ base: "peer/menu-button ring-sidebar-ring data-[active=false]:hover:bg-gray-100 dark:data-[active=false]:hover:bg-white/10 active:bg-sidebar-accent data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground data-[state=open]:data-[active=false]:hover:bg-gray-100 dark:data-[state=open]:data-[active=false]:hover:bg-white/10 flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-start text-sm outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pe-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:font-medium [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",variants: {variant: {default: "data-[active=false]:hover:bg-gray-100 dark:data-[active=false]:hover:bg-white/10",diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelteindex cbd4dcf4..224c3f62 100644--- a/frontend/src/routes/+page.svelte+++ b/frontend/src/routes/+page.svelte@@ -4,27 +4,45 @@import { Skeleton } from '$lib/components/ui/skeleton';import { RefreshCw } from 'lucide-svelte';import MetricCard from '$lib/components/dashboard/metric-card.svelte';- import { generateMockDashboardData } from '$lib/utils/mock-dashboard-data';- import type { DashboardData } from '$lib/types/dashboard';+ import type { DashboardData, DashboardMetric } from '$lib/types/dashboard';import { Card, CardContent } from '$lib/components/ui/card';+ import { api } from '$lib/api';+ import { ErrorDisplay } from '$lib/components/ui/error-display';let dashboardData = $state<DashboardData | null>(null);let loading = $state(true);let error = $state('');+ let errorStatus = $state<number>(0);async function loadDashboard() {loading = true;error = '';+ errorStatus = 0;try {- // Simulate API delay- await new Promise((resolve) => setTimeout(resolve, 500));+ const response = await api.get('/dashboard');- // Mock data - TODO: Replace with real API call- // const response = await api.get('/metrics/dashboard');- // dashboardData = response;- dashboardData = generateMockDashboardData();+ // Transform the API response to match the DashboardData type+ // Convert timestamp strings to Date objects+ const metrics: DashboardMetric[] = response.metrics.map((m: any) => ({+ id: m.id,+ name: m.name,+ value: m.value,+ unit: m.unit,+ trend: m.trend.map((t: any) => ({+ timestamp: new Date(t.timestamp),+ value: t.value+ })),+ change24h: m.change24h,+ status: m.status+ }));++ dashboardData = {+ metrics,+ lastUpdated: new Date(response.lastUpdated)+ };} catch (e: any) {+ errorStatus = e.status || 0;error = e.message || 'Failed to load dashboard data';console.error(e);} finally {@@ -63,16 +81,20 @@</Button></div>- {#if error}- <div class="rounded-md border border-destructive bg-destructive/10 p-4">- <p class="text-sm text-destructive">{error}</p>- </div>+ {#if error && !loading}+ <ErrorDisplay+ status={errorStatus === 404 ? 404 : errorStatus === 400 ? 400 : errorStatus === 422 ? 422 : 400}+ title="Failed to Load Dashboard"+ description={error}+ onRetry={() => loadDashboard()}+ />{/if}<!-- Metrics Grid -->- <div class="grid grid-cols-1 gap-4 md:grid-cols-4">+ {#if !error}+ <div class="grid grid-cols-1 gap-4 md:grid-cols-3">{#if loading}- {#each Array(8) as _}+ {#each Array(6) as _}<Card><CardContent class="flex gap-3 flex-col"><div class="flex items-center justify-between">@@ -91,4 +113,5 @@{/each}{/if}</div>+ {/if}</div>diff --git a/frontend/src/routes/issues/+page.svelte b/frontend/src/routes/issues/+page.svelteindex fb1f8bae..0d42a0a2 100644--- a/frontend/src/routes/issues/+page.svelte+++ b/frontend/src/routes/issues/+page.svelte@@ -1,5 +1,6 @@<script lang="ts">import { onMount } from 'svelte';+ import { goto } from '$app/navigation';import { api } from '$lib/api';import * as Table from "$lib/components/ui/table";import { Input } from "$lib/components/ui/input";@@ -8,8 +9,10 @@import { Skeleton } from "$lib/components/ui/skeleton";type ExceptionGroup = {- issue: string;+ exceptionHash: string;+ stackTrace: string;lastSeen: string;+ firstSeen: string;count: number;};@@ -26,13 +29,12 @@// Filterslet searchQuery = $state('');- let daysBack = $state("1");+ let daysBack = $state("7");// Select options for days backconst daysOptions = [{ value: "1", label: "24 Hours" },- { value: "7", label: "7 Days" },- { value: "30", label: "30 Days" }+ { value: "7", label: "7 Days" }];// Page size options@@ -43,6 +45,10 @@{ value: "100", label: "100" }];+ // Derived labels for select displays+ const daysBackLabel = $derived(daysOptions.find(o => o.value === daysBack)?.label ?? "Select period");+ const pageSizeLabel = $derived(pageSizeOptions.find(o => o.value === pageSize.toString())?.label ?? pageSize.toString());+async function loadData() {loading = true;error = '';@@ -125,24 +131,25 @@oninput={handleSearchInput}/>- <!-- <Select.Root- onOpenChangeComplete={(v) => {+ <Select.Root+ type="single"+ bind:value={daysBack}+ onValueChange={(v) => {if (v) {- daysBack = v.value;- page = 1; // Reset to page 1 on filter change+ page = 1;+ loadData();}}}- selected={{ value: daysBack, label: daysOptions.find(o => o.value === daysBack)?.label }}>- <Select.Trigger class="h-8 w-[180px]">- <Select.Value placeholder="Select period" />+ <Select.Trigger class="h-8 w-[120px]">+ {daysBackLabel}</Select.Trigger><Select.Content>{#each daysOptions as option}- <Select.Item value={option.value}>{option.label}</Select.Item>+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>{/each}</Select.Content>- </Select.Root> -->+ </Select.Root><div class="ml-auto"><Button variant="outline" size="sm" onclick={loadData} class="h-8">Refresh</Button>@@ -183,10 +190,13 @@</Table.Row>{:else}{#each exceptions as exception}- <Table.Row>+ <Table.Row+ class="cursor-pointer hover:bg-muted/50"+ onclick={() => goto(`/issues/${exception.exceptionHash}`)}+ ><Table.Cell class="font-medium truncate max-w-[30px]"></Table.Cell>- <Table.Cell class="truncate" title={exception.issue}>- {exception.issue.substring(0, 100)}...+ <Table.Cell class="truncate" title={exception.stackTrace}>+ {exception.stackTrace.split('\n')[0]}</Table.Cell><Table.Cell>{exception.count}</Table.Cell><Table.Cell>{new Date(exception.lastSeen).toLocaleString()}</Table.Cell>@@ -206,19 +216,20 @@<div class="flex items-center space-x-2"><p class="text-sm font-medium">Rows per page</p><Select.Root- selected={{ value: pageSize.toString(), label: pageSize.toString() }}- onSelectedChange={(v) => {+ type="single"+ value={pageSize.toString()}+ onValueChange={(v) => {if (v) {- handlePageSizeChange(v.value);+ handlePageSizeChange(v);}}}><Select.Trigger class="h-8 w-[70px]">- <Select.Value placeholder={pageSize.toString()} />+ {pageSizeLabel}</Select.Trigger><Select.Content side="top">{#each pageSizeOptions as option}- <Select.Item value={option.value}>{option.label}</Select.Item>+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>{/each}</Select.Content></Select.Root>diff --git a/frontend/src/routes/issues/[exceptionHash]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/+page.sveltenew file mode 100644index 00000000..40351027--- /dev/null+++ b/frontend/src/routes/issues/[exceptionHash]/+page.svelte@@ -0,0 +1,204 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { page } from '$app/state';+ import { goto } from '$app/navigation';+ import { api } from '$lib/api';+ import { Button } from "$lib/components/ui/button";+ import * as Card from "$lib/components/ui/card";+ import * as Table from "$lib/components/ui/table";+ import { Skeleton } from "$lib/components/ui/skeleton";+ import { ErrorDisplay } from "$lib/components/ui/error-display";++ type ExceptionGroup = {+ exceptionHash: string;+ stackTrace: string;+ lastSeen: string;+ firstSeen: string;+ count: number;+ };++ type ExceptionOccurrence = {+ transactionId: string | null;+ exceptionHash: string;+ stackTrace: string;+ recordedAt: string;+ };++ let group = $state<ExceptionGroup | null>(null);+ let occurrences = $state<ExceptionOccurrence[]>([]);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);++ // Pagination+ let currentPage = $state(1);+ let pageSize = $state(20);+ let total = $state(0);+ let totalPages = $state(0);++ async function loadData() {+ loading = true;+ error = '';+ notFound = false;++ try {+ const exceptionHash = page.params.exceptionHash;+ const response = await api.post(`/exception-stack-traces/${exceptionHash}`, {+ pagination: {+ page: currentPage,+ pageSize: pageSize+ }+ });++ group = response.group;+ occurrences = response.occurrences || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e: any) {+ console.error(e);+ if (e.status === 404) {+ notFound = true;+ } else {+ error = e.message || 'Failed to load exception details';+ }+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ currentPage = newPage;+ loadData();+ }+ }++ onMount(() => {+ loadData();+ });+</script>++<div class="space-y-6">+ <!-- Header -->+ <div class="flex items-center gap-4">+ <Button variant="outline" size="sm" onclick={() => goto('/issues')}>+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2">+ <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>+ </svg>+ Back to Issues+ </Button>+ </div>++ {#if loading && !group}+ <!-- Loading skeleton -->+ <Card.Root>+ <Card.Header>+ <Skeleton class="h-6 w-48" />+ </Card.Header>+ <Card.Content>+ <Skeleton class="h-4 w-full mb-2" />+ <Skeleton class="h-4 w-3/4 mb-2" />+ <Skeleton class="h-4 w-1/2" />+ </Card.Content>+ </Card.Root>+ {:else if notFound}+ <ErrorDisplay+ status={404}+ title="Exception Not Found"+ description="The exception you're looking for doesn't exist or may have been removed. It's possible the data has expired or the link is incorrect."+ backHref="/issues"+ backLabel="Back to Issues"+ onRetry={() => loadData()}+ identifier={page.params.exceptionHash}+ />+ {:else if error}+ <ErrorDisplay+ status={400}+ title="Something Went Wrong"+ description={error}+ backHref="/issues"+ backLabel="Back to Issues"+ onRetry={() => loadData()}+ />+ {:else if group}+ <!-- Summary Card -->+ <Card.Root>+ <Card.Header>+ <Card.Title>Exception Details</Card.Title>+ <Card.Description>+ First seen: {new Date(group.firstSeen).toLocaleString()} ·+ Last seen: {new Date(group.lastSeen).toLocaleString()} ·+ Occurrences: {group.count}+ </Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="rounded-md bg-muted p-4 overflow-x-auto">+ <pre class="text-sm whitespace-pre-wrap font-mono">{group.stackTrace}</pre>+ </div>+ </Card.Content>+ </Card.Root>++ <!-- Occurrences Table -->+ <Card.Root>+ <Card.Header>+ <Card.Title>Occurrences</Card.Title>+ <Card.Description>When this exception happened ({total} total)</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="rounded-md border">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head>Recorded At</Table.Head>+ <Table.Head>Transaction ID</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#if occurrences.length === 0}+ <Table.Row>+ <Table.Cell colspan={2} class="h-24 text-center">+ No occurrences found.+ </Table.Cell>+ </Table.Row>+ {:else}+ {#each occurrences as occurrence}+ <Table.Row>+ <Table.Cell>{new Date(occurrence.recordedAt).toLocaleString()}</Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {occurrence.transactionId || '-'}+ </Table.Cell>+ </Table.Row>+ {/each}+ {/if}+ </Table.Body>+ </Table.Root>+ </div>++ <!-- Pagination -->+ {#if totalPages > 1}+ <div class="flex items-center justify-end space-x-2 py-4">+ <div class="text-sm text-muted-foreground">+ Page {currentPage} of {totalPages}+ </div>+ <Button+ variant="outline"+ size="sm"+ onclick={() => handlePageChange(currentPage - 1)}+ disabled={currentPage <= 1}+ >+ Previous+ </Button>+ <Button+ variant="outline"+ size="sm"+ onclick={() => handlePageChange(currentPage + 1)}+ disabled={currentPage >= totalPages}+ >+ Next+ </Button>+ </div>+ {/if}+ </Card.Content>+ </Card.Root>+ {/if}+</div>diff --git a/frontend/src/routes/issues/[exceptionHash]/+page.ts b/frontend/src/routes/issues/[exceptionHash]/+page.tsnew file mode 100644index 00000000..4b5a5749--- /dev/null+++ b/frontend/src/routes/issues/[exceptionHash]/+page.ts@@ -0,0 +1,14 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const prerender = false;++export const load: PageLoad = ({ params }) => {+ if (!authState.isAuthenticated) {+ throw redirect(302, '/login');+ }+ return {+ exceptionHash: params.exceptionHash+ };+};diff --git a/frontend/src/routes/transactions/+page.svelte b/frontend/src/routes/transactions/+page.sveltenew file mode 100644index 00000000..6d0932d7--- /dev/null+++ b/frontend/src/routes/transactions/+page.svelte@@ -0,0 +1,334 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { goto } from '$app/navigation';+ import { api } from '$lib/api';+ import * as Table from "$lib/components/ui/table";+ import { Button } from "$lib/components/ui/button";+ import { Skeleton } from "$lib/components/ui/skeleton";+ import { Input } from "$lib/components/ui/input";+ import { Label } from "$lib/components/ui/label";+ import { ArrowUpDown, ArrowDown } from "@lucide/svelte";++ type EndpointStats = {+ endpoint: string;+ count: number;+ p50Duration: number;+ p95Duration: number;+ avgDuration: number;+ lastSeen: string;+ };++ type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'last_seen';++ let endpoints = $state<EndpointStats[]>([]);+ let loading = $state(true);+ let error = $state('');++ // Pagination State+ let page = $state(1);+ let pageSize = $state(20);+ let total = $state(0);+ let totalPages = $state(0);++ // Date Range State (separate date and time)+ let fromDateValue = $state('');+ let fromTimeValue = $state('');+ let toDateValue = $state('');+ let toTimeValue = $state('');++ // Sorting+ let orderBy = $state<SortField>('count');++ // Initialize dates to last 7 days+ function initDates() {+ const now = new Date();+ const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);++ toDateValue = now.toISOString().slice(0, 10);+ toTimeValue = now.toTimeString().slice(0, 5);+ fromDateValue = sevenDaysAgo.toISOString().slice(0, 10);+ fromTimeValue = sevenDaysAgo.toTimeString().slice(0, 5);+ }++ // Combine date and time into ISO datetime string+ function getFromDateTime(): string {+ if (!fromDateValue) return '';+ return `${fromDateValue}T${fromTimeValue || '00:00'}`;+ }++ function getToDateTime(): string {+ if (!toDateValue) return '';+ return `${toDateValue}T${toTimeValue || '23:59'}`;+ }++ function formatDuration(nanoseconds: number): string {+ const ms = nanoseconds / 1_000_000;+ if (ms < 1) {+ return `${(nanoseconds / 1000).toFixed(2)}µs`;+ } else if (ms < 1000) {+ return `${ms.toFixed(2)}ms`;+ } else {+ return `${(ms / 1000).toFixed(2)}s`;+ }+ }++ async function loadData() {+ loading = true;+ error = '';++ try {+ const requestBody = {+ fromDate: new Date(getFromDateTime()).toISOString(),+ toDate: new Date(getToDateTime()).toISOString(),+ orderBy: orderBy,+ pagination: {+ page: page,+ pageSize: pageSize+ }+ };++ const response = await api.post('/transactions/grouped', requestBody);++ endpoints = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e: any) {+ console.error(e);+ error = e.message || 'Failed to load data';+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData();+ }+ }++ function handleSort(field: SortField) {+ orderBy = field;+ page = 1;+ loadData();+ }++ function navigateToEndpoint(endpoint: string) {+ const params = new URLSearchParams({+ from: getFromDateTime(),+ to: getToDateTime()+ });+ goto(`/transactions/${encodeURIComponent(endpoint)}?${params.toString()}`);+ }++ onMount(() => {+ initDates();+ loadData();+ });+</script>++<div class="space-y-6">+ <div class="flex items-center justify-between">+ <h2 class="text-3xl font-bold tracking-tight">Transactions</h2>+ </div>++ <!-- Filters Bar -->+ <div class="flex flex-wrap items-end gap-4 p-4 rounded-lg border bg-card">+ <div class="flex flex-col gap-1.5">+ <Label for="from-date" class="text-xs text-muted-foreground">From Date</Label>+ <Input+ id="from-date"+ type="date"+ class="h-9 w-[140px]"+ bind:value={fromDateValue}+ />+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="from-time" class="text-xs text-muted-foreground">From Time</Label>+ <Input+ id="from-time"+ type="time"+ class="h-9 w-[110px]"+ bind:value={fromTimeValue}+ />+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="to-date" class="text-xs text-muted-foreground">To Date</Label>+ <Input+ id="to-date"+ type="date"+ class="h-9 w-[140px]"+ bind:value={toDateValue}+ />+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="to-time" class="text-xs text-muted-foreground">To Time</Label>+ <Input+ id="to-time"+ type="time"+ class="h-9 w-[110px]"+ bind:value={toTimeValue}+ />+ </div>+ <Button variant="default" size="sm" onclick={loadData} class="h-9">+ Go+ </Button>+ </div>++ <!-- Endpoints Table -->+ <div class="rounded-md border">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head>Endpoint</Table.Head>+ <Table.Head class="w-[120px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('count')}+ >+ Requests+ {#if orderBy === 'count'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ <Table.Head class="w-[120px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('p50_duration')}+ >+ P50+ {#if orderBy === 'p50_duration'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ <Table.Head class="w-[120px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('p95_duration')}+ >+ P95+ {#if orderBy === 'p95_duration'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ <Table.Head class="w-[180px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('last_seen')}+ >+ Last Seen+ {#if orderBy === 'last_seen'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#if loading}+ {#each Array(5) as _}+ <Table.Row>+ <Table.Cell><Skeleton class="h-4 w-[250px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[60px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[80px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[80px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[140px]" /></Table.Cell>+ </Table.Row>+ {/each}+ {:else if error}+ <Table.Row>+ <Table.Cell colspan={5} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ {:else if endpoints.length === 0}+ <Table.Row>+ <Table.Cell colspan={5} class="h-24 text-center">+ No transactions found in this time range.+ </Table.Cell>+ </Table.Row>+ {:else}+ {#each endpoints as endpoint}+ <Table.Row+ class="cursor-pointer hover:bg-muted/50"+ onclick={() => navigateToEndpoint(endpoint.endpoint)}+ >+ <Table.Cell class="font-mono text-sm">+ {endpoint.endpoint}+ </Table.Cell>+ <Table.Cell class="font-medium">+ {endpoint.count.toLocaleString()}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {formatDuration(endpoint.p50Duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {formatDuration(endpoint.p95Duration)}+ </Table.Cell>+ <Table.Cell class="text-muted-foreground">+ {new Date(endpoint.lastSeen).toLocaleString()}+ </Table.Cell>+ </Table.Row>+ {/each}+ {/if}+ </Table.Body>+ </Table.Root>+ </div>++ <!-- Pagination Footer -->+ <div class="flex items-center justify-between px-2">+ <div class="flex-1 text-sm text-muted-foreground">+ {total} endpoint(s) found.+ </div>+ <div class="flex items-center space-x-6 lg:space-x-8">+ <div class="flex w-[100px] items-center justify-center text-sm font-medium">+ Page {page} of {totalPages || 1}+ </div>+ <div class="flex items-center space-x-2">+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={() => handlePageChange(page - 1)}+ disabled={page <= 1 || loading}+ >+ <span class="sr-only">Go to previous page</span>+ <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15" fill="none" class="h-4 w-4">+ <path d="M8.84182 3.13514C9.04327 3.32401 9.05348 3.64042 8.86462 3.84188L5.43521 7.49991L8.86462 11.1579C9.05348 11.3594 9.04327 11.6758 8.84182 11.8647C8.64036 12.0535 8.32394 12.0433 8.13508 11.8419L4.38508 7.84188C4.20477 7.64955 4.20477 7.35027 4.38508 7.15794L8.13508 3.15794C8.32394 2.95648 8.64036 2.94628 8.84182 3.13514Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>+ </svg>+ </Button>+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={() => handlePageChange(page + 1)}+ disabled={page >= totalPages || loading}+ >+ <span class="sr-only">Go to next page</span>+ <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15" fill="none" class="h-4 w-4">+ <path d="M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>+ </svg>+ </Button>+ </div>+ </div>+ </div>+</div>diff --git a/frontend/src/routes/transactions/+page.ts b/frontend/src/routes/transactions/+page.tsnew file mode 100644index 00000000..9f2ce0c4--- /dev/null+++ b/frontend/src/routes/transactions/+page.ts@@ -0,0 +1,9 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const load: PageLoad = () => {+ if (!authState.isAuthenticated) {+ throw redirect(302, '/login');+ }+};diff --git a/frontend/src/routes/transactions/[endpoint]/+page.svelte b/frontend/src/routes/transactions/[endpoint]/+page.sveltenew file mode 100644index 00000000..dba7ab2d--- /dev/null+++ b/frontend/src/routes/transactions/[endpoint]/+page.svelte@@ -0,0 +1,397 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { goto } from '$app/navigation';+ import { api } from '$lib/api';+ import * as Table from "$lib/components/ui/table";+ import { Button } from "$lib/components/ui/button";+ import { Skeleton } from "$lib/components/ui/skeleton";+ import { Input } from "$lib/components/ui/input";+ import { Label } from "$lib/components/ui/label";+ import { ArrowLeft, ArrowUpDown, ArrowDown } from "@lucide/svelte";+ import { ErrorDisplay } from "$lib/components/ui/error-display";++ type Transaction = {+ id: string;+ endpoint: string;+ duration: number;+ recordedAt: string;+ statusCode: number;+ bodySize: number;+ clientIP: string;+ };++ type SortField = 'recorded_at' | 'duration' | 'status_code' | 'body_size';++ let { data } = $props();++ let transactions = $state<Transaction[]>([]);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);+ let errorStatus = $state<number>(0);++ // Pagination State+ let page = $state(1);+ let pageSize = $state(20);+ let total = $state(0);+ let totalPages = $state(0);++ // Date Range State (separate date and time)+ let fromDateValue = $state('');+ let fromTimeValue = $state('');+ let toDateValue = $state('');+ let toTimeValue = $state('');++ // Sorting State+ let orderBy = $state<SortField>('recorded_at');++ // Combine date and time into ISO datetime string+ function getFromDateTime(): string {+ if (!fromDateValue) return '';+ return `${fromDateValue}T${fromTimeValue || '00:00'}`;+ }++ function getToDateTime(): string {+ if (!toDateValue) return '';+ return `${toDateValue}T${toTimeValue || '23:59'}`;+ }++ // Parse datetime string into date and time parts+ function parseDateTimeParts(dateTimeStr: string): { date: string; time: string } {+ if (!dateTimeStr) return { date: '', time: '' };+ const parts = dateTimeStr.split('T');+ return {+ date: parts[0] || '',+ time: parts[1] || '00:00'+ };+ }++ function formatDuration(nanoseconds: number): string {+ const ms = nanoseconds / 1_000_000;+ if (ms < 1) {+ return `${(nanoseconds / 1000).toFixed(2)}µs`;+ } else if (ms < 1000) {+ return `${ms.toFixed(2)}ms`;+ } else {+ return `${(ms / 1000).toFixed(2)}s`;+ }+ }++ function formatBytes(bytes: number): string {+ if (bytes < 1024) {+ return `${bytes} B`;+ } else if (bytes < 1024 * 1024) {+ return `${(bytes / 1024).toFixed(1)} KB`;+ } else {+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;+ }+ }++ function getStatusColor(statusCode: number): string {+ if (statusCode >= 200 && statusCode < 300) {+ return 'text-green-500';+ } else if (statusCode >= 300 && statusCode < 400) {+ return 'text-blue-500';+ } else if (statusCode >= 400 && statusCode < 500) {+ return 'text-yellow-500';+ } else {+ return 'text-red-500';+ }+ }++ async function loadData() {+ loading = true;+ error = '';+ notFound = false;+ errorStatus = 0;++ try {+ const requestBody = {+ fromDate: new Date(getFromDateTime()).toISOString(),+ toDate: new Date(getToDateTime()).toISOString(),+ orderBy: orderBy,+ pagination: {+ page: page,+ pageSize: pageSize+ }+ };++ const response = await api.post(`/transactions/endpoint?endpoint=${encodeURIComponent(data.endpoint)}`, requestBody);++ transactions = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e: any) {+ console.error(e);+ errorStatus = e.status || 0;+ if (e.status === 404) {+ notFound = true;+ } else {+ error = e.message || 'Failed to load data';+ }+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData();+ }+ }++ function handleSort(field: SortField) {+ orderBy = field;+ page = 1;+ loadData();+ }++ function goBack() {+ goto('/transactions');+ }++ onMount(() => {+ // Initialize dates from URL params or default to last 7 days+ if (data.from && data.to) {+ const fromParts = parseDateTimeParts(data.from);+ const toParts = parseDateTimeParts(data.to);+ fromDateValue = fromParts.date;+ fromTimeValue = fromParts.time;+ toDateValue = toParts.date;+ toTimeValue = toParts.time;+ } else {+ const now = new Date();+ const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);+ toDateValue = now.toISOString().slice(0, 10);+ toTimeValue = now.toTimeString().slice(0, 5);+ fromDateValue = sevenDaysAgo.toISOString().slice(0, 10);+ fromTimeValue = sevenDaysAgo.toTimeString().slice(0, 5);+ }+ loadData();+ });+</script>++<div class="space-y-6">+ {#if notFound}+ <ErrorDisplay+ status={404}+ title="Endpoint Not Found"+ description="The endpoint you're looking for doesn't exist or has no recorded transactions."+ backHref="/transactions"+ backLabel="Back to Transactions"+ onRetry={() => loadData()}+ identifier={decodeURIComponent(data.endpoint)}+ />+ {:else if error && !loading}+ <ErrorDisplay+ status={errorStatus === 400 ? 400 : errorStatus === 422 ? 422 : 400}+ title="Failed to Load Transactions"+ description={error}+ backHref="/transactions"+ backLabel="Back to Transactions"+ onRetry={() => loadData()}+ />+ {:else}+ <div class="flex items-center gap-4">+ <Button variant="ghost" size="sm" onclick={goBack} class="h-8 w-8 p-0">+ <ArrowLeft class="h-4 w-4" />+ </Button>+ <div>+ <h2 class="text-2xl font-bold tracking-tight font-mono">{decodeURIComponent(data.endpoint)}</h2>+ <p class="text-sm text-muted-foreground">Transaction instances for this endpoint</p>+ </div>+ </div>++ <!-- Date Range Filters -->+ <div class="flex flex-wrap items-end gap-4 p-4 rounded-lg border bg-card">+ <div class="flex flex-col gap-1.5">+ <Label for="from-date" class="text-xs text-muted-foreground">From Date</Label>+ <Input+ id="from-date"+ type="date"+ class="h-9 w-[140px]"+ bind:value={fromDateValue}+ />+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="from-time" class="text-xs text-muted-foreground">From Time</Label>+ <Input+ id="from-time"+ type="time"+ class="h-9 w-[110px]"+ bind:value={fromTimeValue}+ />+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="to-date" class="text-xs text-muted-foreground">To Date</Label>+ <Input+ id="to-date"+ type="date"+ class="h-9 w-[140px]"+ bind:value={toDateValue}+ />+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="to-time" class="text-xs text-muted-foreground">To Time</Label>+ <Input+ id="to-time"+ type="time"+ class="h-9 w-[110px]"+ bind:value={toTimeValue}+ />+ </div>+ <Button variant="default" size="sm" onclick={loadData} class="h-9">+ Go+ </Button>+ </div>++ <!-- Transactions Table -->+ <div class="rounded-md border">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head class="w-[180px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('recorded_at')}+ >+ Recorded At+ {#if orderBy === 'recorded_at'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ <Table.Head class="w-[120px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('duration')}+ >+ Duration+ {#if orderBy === 'duration'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ <Table.Head class="w-[100px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('status_code')}+ >+ Status+ {#if orderBy === 'status_code'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ <Table.Head class="w-[100px]">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('body_size')}+ >+ Body Size+ {#if orderBy === 'body_size'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUpDown class="ml-2 h-4 w-4" />+ {/if}+ </Button>+ </Table.Head>+ <Table.Head class="w-[140px]">Client IP</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#if loading}+ {#each Array(5) as _}+ <Table.Row>+ <Table.Cell><Skeleton class="h-4 w-[140px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[80px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[50px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[60px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[100px]" /></Table.Cell>+ </Table.Row>+ {/each}+ {:else if transactions.length === 0}+ <Table.Row>+ <Table.Cell colspan={5} class="h-24 text-center">+ No transactions found in this time range.+ </Table.Cell>+ </Table.Row>+ {:else}+ {#each transactions as transaction}+ <Table.Row>+ <Table.Cell class="text-muted-foreground">+ {new Date(transaction.recordedAt).toLocaleString()}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {formatDuration(transaction.duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm {getStatusColor(transaction.statusCode)}">+ {transaction.statusCode}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {formatBytes(transaction.bodySize)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {transaction.clientIP}+ </Table.Cell>+ </Table.Row>+ {/each}+ {/if}+ </Table.Body>+ </Table.Root>+ </div>++ <!-- Pagination Footer -->+ <div class="flex items-center justify-between px-2">+ <div class="flex-1 text-sm text-muted-foreground">+ {total} transaction(s) found.+ </div>+ <div class="flex items-center space-x-6 lg:space-x-8">+ <div class="flex w-[100px] items-center justify-center text-sm font-medium">+ Page {page} of {totalPages || 1}+ </div>+ <div class="flex items-center space-x-2">+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={() => handlePageChange(page - 1)}+ disabled={page <= 1 || loading}+ >+ <span class="sr-only">Go to previous page</span>+ <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15" fill="none" class="h-4 w-4">+ <path d="M8.84182 3.13514C9.04327 3.32401 9.05348 3.64042 8.86462 3.84188L5.43521 7.49991L8.86462 11.1579C9.05348 11.3594 9.04327 11.6758 8.84182 11.8647C8.64036 12.0535 8.32394 12.0433 8.13508 11.8419L4.38508 7.84188C4.20477 7.64955 4.20477 7.35027 4.38508 7.15794L8.13508 3.15794C8.32394 2.95648 8.64036 2.94628 8.84182 3.13514Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>+ </svg>+ </Button>+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={() => handlePageChange(page + 1)}+ disabled={page >= totalPages || loading}+ >+ <span class="sr-only">Go to next page</span>+ <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15" fill="none" class="h-4 w-4">+ <path d="M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>+ </svg>+ </Button>+ </div>+ </div>+ </div>+ {/if}+</div>diff --git a/frontend/src/routes/transactions/[endpoint]/+page.ts b/frontend/src/routes/transactions/[endpoint]/+page.tsnew file mode 100644index 00000000..fb736733--- /dev/null+++ b/frontend/src/routes/transactions/[endpoint]/+page.ts@@ -0,0 +1,17 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const prerender = false;++export const load: PageLoad = ({ params, url }) => {+ if (!authState.isAuthenticated) {+ throw redirect(302, '/login');+ }++ return {+ endpoint: params.endpoint,+ from: url.searchParams.get('from') || '',+ to: url.searchParams.get('to') || ''+ };+};