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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/internal/hub/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func RegisterRoutes(router *gin.Engine, cfg Config) error {
protected.POST("/notifications", routes.CreateNotificationHandler)
protected.GET("/notifications", routes.ListNotificationsHandler)
protected.PUT("/notifications/:id", routes.UpdateNotificationHandler)
protected.PUT("/notifications/:id/enabled", routes.SetNotificationEnabledHandler)
protected.DELETE("/notifications/:id", routes.DeleteNotificationHandler)
protected.POST("/notifications/:id/test", routes.TestNotificationHandler)

Expand Down
2 changes: 2 additions & 0 deletions backend/internal/hub/routes/applications.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ type applicationListResponse struct {
LastSyncError *string `json:"lastSyncError,omitempty"`
AgentId string `json:"agentId"`
AgentName string `json:"agentName"`
RepositoryId string `json:"repositoryId"`
RepositoryName string `json:"repositoryName"`
}

Expand Down Expand Up @@ -541,6 +542,7 @@ func toApplicationListResponse(app *models.Application) applicationListResponse
LastSyncedAt: formatTimestamp(app.LastSyncedAt),
LastSyncError: normalizeSyncError(app.LastSyncError),
Path: app.Path,
RepositoryId: app.RepositoryId,
RepositoryName: app.Repository.Name,
AgentId: app.AgentId,
AgentName: app.Agent.Name.String(),
Expand Down
3 changes: 3 additions & 0 deletions backend/internal/hub/routes/applications_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ func TestListApplicationsHandler_ReturnsSummaryFields(t *testing.T) {
if item["name"] != "Summary App" {
t.Errorf("expected name %q, got %v", "Summary App", item["name"])
}
if item["repositoryId"] != repo.Id {
t.Errorf("expected repositoryId %q, got %v", repo.Id, item["repositoryId"])
}
if item["repositoryName"] != repo.Name {
t.Errorf("expected repositoryName %q, got %v", repo.Name, item["repositoryName"])
}
Expand Down
42 changes: 42 additions & 0 deletions backend/internal/hub/routes/notifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ type createNotificationRequest struct {
RepositoryIds []string `json:"repositoryIds"`
}

type setNotificationEnabledRequest struct {
Enabled *bool `json:"enabled"`
}

type updateNotificationRequest struct {
Enabled *bool `json:"enabled"`
AllApplications *bool `json:"allApplications"`
Expand Down Expand Up @@ -274,6 +278,44 @@ func UpdateNotificationHandler(c *gin.Context) {
sse.PublishUpdate(sse.TopicNotifications)
}

// SetNotificationEnabledHandler only toggles the enabled flag, so it cannot overwrite a concurrent
// edit of the subscription.
func SetNotificationEnabledHandler(c *gin.Context) {
id := c.Param("id")

var req setNotificationEnabledRequest
if err := c.ShouldBindJSON(&req); err != nil || req.Enabled == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request: enabled is required"})
return
}

ctx := c.Request.Context()
rowsAffected, err := gorm.G[models.Notification](db.DB).
Where("id = ?", id).
Update(ctx, "enabled", *req.Enabled)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
return
}
if rowsAffected == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "notification not found"})
return
}

notification, err := getNotificationById(ctx, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "notification not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
return
}

c.JSON(http.StatusOK, toNotificationResponse(&notification))
sse.PublishUpdate(sse.TopicNotifications)
}

func DeleteNotificationHandler(c *gin.Context) {
id := c.Param("id")

Expand Down
76 changes: 76 additions & 0 deletions backend/internal/hub/routes/notifications_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,82 @@ func TestUpdateNotificationHandler_RejectsInvalidEvents(t *testing.T) {
}
}

func setNotificationEnabled(t *testing.T, id string, body any) *httptest.ResponseRecorder {
t.Helper()

reqBody, _ := json.Marshal(body)
router := gin.New()
router.PUT("/api/v1/notifications/:id/enabled", SetNotificationEnabledHandler)

w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/api/v1/notifications/"+id+"/enabled", bytes.NewReader(reqBody))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
return w
}

func TestSetNotificationEnabledHandler_TogglesOnlyEnabled(t *testing.T) {
setupTestDBWithNotifications(t)

repo := seedNotificationRepository(t)
agent := seedNotificationAgent(t)
app := seedNotificationApplication(t, repo.Id, agent.Id, "App A")
notification := createNotificationRecord(t, []string{app.Id})

for _, enabled := range []bool{false, true} {
w := setNotificationEnabled(t, notification.Id, map[string]any{"enabled": enabled})
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}

var body notificationResponse
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if body.Enabled != enabled {
t.Fatalf("expected enabled=%v, got %v", enabled, body.Enabled)
}
if !slices.Equal(body.ApplicationIds, []string{app.Id}) {
t.Fatalf("expected applicationIds [%s] to be kept, got %v", app.Id, body.ApplicationIds)
}
if !slices.Equal(body.Events, models.NotificationEvents) {
t.Fatalf("expected events to be kept, got %v", body.Events)
}
}

stored, err := gorm.G[models.Notification](db.DB).Where("id = ?", notification.Id).First(t.Context())
if err != nil {
t.Fatalf("failed to load stored notification: %v", err)
}
if !stored.Enabled {
t.Fatal("expected stored notification to be enabled")
}
if stored.Config.String() != validDiscordConfig {
t.Fatalf("expected stored config to remain unchanged, got %q", stored.Config.String())
}
}

func TestSetNotificationEnabledHandler_NotFound(t *testing.T) {
setupTestDBWithNotifications(t)

w := setNotificationEnabled(t, "missing", map[string]any{"enabled": true})
if w.Code != http.StatusNotFound {
t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())
}
}

func TestSetNotificationEnabledHandler_InvalidRequest(t *testing.T) {
setupTestDBWithNotifications(t)

notification := createNotificationRecord(t, nil)
for _, body := range []any{map[string]any{}, map[string]any{"enabled": "yes"}} {
w := setNotificationEnabled(t, notification.Id, body)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for %v, got %d: %s", body, w.Code, w.Body.String())
}
}
}

func TestDeleteNotificationHandler_Success(t *testing.T) {
setupTestDBWithNotifications(t)

Expand Down
2 changes: 1 addition & 1 deletion e2e/tests/repositories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ test.describe("Live updates", () => {
syncType: "polling",
pollingIntervalSeconds: 3600,
});
await expect(card.getByText("Polling", { exact: true })).toBeVisible();
await expect(card.getByText("Polling every 1h", { exact: true })).toBeVisible();

await api(page, "DELETE", `/repositories/${repo.id}`);
await expect(card).toHaveCount(0);
Expand Down
14 changes: 11 additions & 3 deletions frontend/messages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,19 @@
"totalRepositoriesCount": "Es gibt insgesamt {count} Repositories",
"totalNotificationsCount": "Es gibt insgesamt {count} Benachrichtigungen",
"notificationProviderAlt": "Benachrichtigungs-Anbieter",
"appsCount": "Anzahl Apps",
"notAvailableShort": "k. A.",
"cardActions": "Kartenaktionen",
"cardStageRevision": "Revision",
"cardStageSync": "Sync",
"cardStageHealth": "Zustand",
"cardAgentNoApplications": "Noch keine Anwendungen bereitgestellt",
"cardPollingEvery": "Polling alle {interval}",
"cardRepositoryUnused": "Von keiner Anwendung verwendet",
"cardScopeApplications": "Anwendungen: {count}",
"cardScopeAgents": "Agenten: {count}",
"cardScopeRepositories": "Repositories: {count}",
"cardSubscribedEvents": "{count} von {total} Ereignissen",
"cardLastDelivery": "Letzte Zustellung",
"deleteAgentCardTitle": "Agentenkarte lΓΆschen?",
"deleteAgentCardDescription": "Dadurch wird \"{name}\" dauerhaft gelΓΆscht. Diese Aktion kann nicht rΓΌckgΓ€ngig gemacht werden.",
"deleteRepositoryTitle": "Repository lΓΆschen?",
Expand Down Expand Up @@ -722,8 +732,6 @@
"eventStatusSucceeded": "Erfolgreich",
"eventStatusFailed": "Fehlgeschlagen",
"eventStatusNoChange": "Keine Γ„nderung",
"agentVersion": "Agent-Version",
"dockerVersion": "Docker-Version",
"columnAgentVersion": "Agent-Version",
"columnDockerVersion": "Docker-Version",
"agentVersionOutdated": "Veraltet",
Expand Down
14 changes: 11 additions & 3 deletions frontend/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,19 @@
"totalRepositoriesCount": "There are {count} repositories in total",
"totalNotificationsCount": "There are {count} notifications in total",
"notificationProviderAlt": "Notification provider",
"appsCount": "Apps count",
"notAvailableShort": "n/a",
"cardActions": "Card actions",
"cardStageRevision": "Revision",
"cardStageSync": "Sync",
"cardStageHealth": "Health",
"cardAgentNoApplications": "No applications deployed yet",
"cardPollingEvery": "Polling every {interval}",
"cardRepositoryUnused": "Not used by any application",
"cardScopeApplications": "Applications: {count}",
"cardScopeAgents": "Agents: {count}",
"cardScopeRepositories": "Repositories: {count}",
"cardSubscribedEvents": "{count} of {total} events",
"cardLastDelivery": "Last delivery",
"deleteAgentCardTitle": "Delete agent card?",
"deleteAgentCardDescription": "This will permanently delete \"{name}\". This action cannot be undone.",
"deleteRepositoryTitle": "Delete repository?",
Expand Down Expand Up @@ -722,8 +732,6 @@
"eventStatusSucceeded": "Succeeded",
"eventStatusFailed": "Failed",
"eventStatusNoChange": "No change",
"agentVersion": "Agent version",
"dockerVersion": "Docker version",
"columnAgentVersion": "Agent Version",
"columnDockerVersion": "Docker Version",
"agentVersionOutdated": "Outdated",
Expand Down
8 changes: 8 additions & 0 deletions frontend/src/components/badges/application-status-badge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ const healthConfig: Record<
},
};

export function getSyncStatusLabel(status: SyncStatus): string {
return syncConfig[status].label();
}

export function getHealthStatusLabel(status: HealthStatus): string {
return healthConfig[status].label();
}

export function ApplicationStatusBadge(props: StatusBadgeProps) {
let config =
props.type === "sync"
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/badges/notification-status-badge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { NotificationStatus } from "@/lib/notifications";
import { m } from "@/lib/paraglide/messages";
import { Badge } from "../ui/badge";

function getStatusLabel(status: NotificationStatus): string {
export function getNotificationStatusLabel(status: NotificationStatus): string {
switch (status) {
case "success":
return m.successAlertTitle();
Expand Down Expand Up @@ -44,7 +44,7 @@ export function NotificationStatusBadge({ status }: { status: NotificationStatus
<div className="flex items-center gap-2">
<Badge variant={badgeVariant}>
<span className={`h-2 w-2 rounded-full ${getStatusDotClass(status)}`} aria-hidden="true" />
{getStatusLabel(status)}
{getNotificationStatusLabel(status)}
</Badge>
</div>
);
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/badges/repository-status-badge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function getSyncStatusColor(syncStatus: RepositorySyncStatus): string {
}
}

function getSyncStatusLabel(syncStatus: RepositorySyncStatus): string {
export function getRepositorySyncStatusLabel(syncStatus: RepositorySyncStatus): string {
switch (syncStatus) {
case "syncing":
return m.repoSyncStatusSyncing();
Expand All @@ -29,7 +29,7 @@ function getSyncStatusLabel(syncStatus: RepositorySyncStatus): string {
}

export function RepositoryStatusBadge({ status }: { status: RepositorySyncStatus }) {
const statusLabel = getSyncStatusLabel(status);
const statusLabel = getRepositorySyncStatusLabel(status);
const statusDotClass = getSyncStatusColor(status);
const badgeVariant =
status === "success" ? "success" : status === "failed" ? "destructive" : "secondary";
Expand Down
Loading
Loading