Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52cfb075e3 | ||
|
|
57c50cfb7f | ||
|
|
ca6181b58f |
+30
-1
@@ -138,6 +138,24 @@ Bedienung über Tastatur: Pfeile wählen, `Enter` öffnet, `Esc` schließt. Die
|
||||
wird beim ersten Öffnen geholt und dann behalten — sie bei jedem Tastendruck neu zu laden
|
||||
wäre Verschwendung.
|
||||
|
||||
### Projektvorlagen
|
||||
|
||||
Ein Projekt, das sich bewährt hat, lässt sich im Projektkopf über **Als Vorlage sichern**
|
||||
festhalten: Status, Priorität, Farbe, Tags, Notizen und offene Aufgaben. Beim Anlegen eines
|
||||
neuen Projekts steht die Vorlage oben im Dialog zur Auswahl.
|
||||
|
||||
Bewusst benutzereigen statt fest eingebaut — welche Tags und welche Startaufgaben sinnvoll
|
||||
sind, weiß nur, wer damit arbeitet. Eine mitgelieferte Liste wäre geraten.
|
||||
|
||||
- **Erledigte Aufgaben kommen nicht mit.** Eine Vorlage beschreibt, was zu tun ist, nicht
|
||||
was einmal getan wurde.
|
||||
- **Repositories gehen nicht mit.** Eine Vorlage, die jedes neue Projekt an dasselbe
|
||||
Repository hängt, wäre eine Falle.
|
||||
- Die Stammdaten füllt der Dialog **sichtbar** in die Felder, damit sie vor dem Speichern
|
||||
noch änderbar sind; bereits Getipptes wird nicht überschrieben. Notizen und Aufgaben legt
|
||||
erst der Server an — im Dialog ließen sie sich nicht darstellen.
|
||||
- Vorlagen überleben das Löschen ihres Ursprungsprojekts.
|
||||
|
||||
### Mehrfachauswahl
|
||||
|
||||
Ein Kästchen auf jeder Karte — es erscheint erst beim Überfahren, damit nicht auf jeder
|
||||
@@ -301,6 +319,7 @@ Firmen-Gitea nebeneinander.
|
||||
| Tags | bis zu 25, mit SHA, Nachricht und Datum |
|
||||
| Commits | die letzten 15 zur Anzeige; geholt werden 100 für die Aktivitätskurve |
|
||||
| **Commit-Aktivität** | Balkenreihe der letzten Tage, auf Karte und Projektseite |
|
||||
| **Commit-Heatmap** | Ein Feld je Tag über bis zu ein Jahr, auf der Projektseite |
|
||||
| Releases | bis zu 10, inklusive Pre-Release- und Draft-Kennzeichnung |
|
||||
| Sprachen | Verteilung als Balken mit Prozentwerten |
|
||||
|
||||
@@ -327,9 +346,19 @@ bewusste Entscheidung sein. Einschalten in den Admin-Einstellungen.
|
||||
| Einstellung | Bedeutung |
|
||||
| --- | --- |
|
||||
| Abstand | 15 Minuten bis täglich |
|
||||
| Projekte je Durchlauf | 1–100, Voreinstellung 25 |
|
||||
| Repositories je Durchlauf | 1–100, Voreinstellung 25 |
|
||||
| Fertige und archivierte auslassen | Dort ändert sich selten noch etwas |
|
||||
|
||||
Gezählt und begrenzt wird je **Repository**, nicht je Projekt: sonst zöge ein Projekt mit
|
||||
fünf Repos fünfmal so viele Anfragen nach sich, wie sein Platz im Kontingent hergibt.
|
||||
|
||||
Die Daten für die **Heatmap** kommen getrennt und höchstens einmal am Tag — an einem
|
||||
Jahresüberblick ändert sich von Stunde zu Stunde nichts Sichtbares. Bei GitHub genügt dafür
|
||||
ein Aufruf der Jahresstatistik; GitLab und Gitea kennen keine, dort werden bis zu fünf
|
||||
Seiten Commits geholt. Reicht das nicht ein Jahr zurück, **beginnt die Heatmap beim
|
||||
ältesten bekannten Commit** und sagt es dazu — leere Felder für Zeiträume zu zeichnen, über
|
||||
die nichts bekannt ist, wäre eine Lüge.
|
||||
|
||||
Wie der Durchlauf arbeitet:
|
||||
|
||||
- Der Zeitgeber läuft im Serverprozess selbst (`instrumentation.ts`), prüft minütlich, ob
|
||||
|
||||
@@ -341,6 +341,9 @@ ausschließlich Daten des angemeldeten Kontos.
|
||||
| `GET` | `/api/projects/export` | Alle eigenen Projekte als JSON |
|
||||
| `GET` | `/api/projects/:id/export` | Ein Projekt (`?format=md` für Markdown) |
|
||||
| `POST` | `/api/projects/import` | Import, mit `dryRun` für die Vorschau |
|
||||
| `GET` `POST` | `/api/templates` | Projektvorlagen auflisten / anlegen |
|
||||
| `PATCH` `DELETE` | `/api/templates/:id` | Vorlage ändern / löschen |
|
||||
| `POST` | `/api/templates/from-project` | Aus einem Projekt eine Vorlage machen |
|
||||
| `GET` | `/api/admin/backup` | Vollständige Sicherung als JSON (Admin) |
|
||||
| `GET` | `/api/search?q=` | Volltextsuche über die eigenen Notizen |
|
||||
| `GET` `POST` | `/api/notifications` | Benachrichtigungsziele |
|
||||
@@ -348,6 +351,8 @@ ausschließlich Daten des angemeldeten Kontos.
|
||||
| `POST` | `/api/notifications/:id/test` | Testnachricht senden |
|
||||
| `GET` `PATCH` `DELETE` | `/api/projects/:id` | Projekt lesen / ändern / löschen |
|
||||
| `POST` | `/api/projects/:id/sync` | Alle Repositories des Projekts abgleichen |
|
||||
| `PATCH` | `/api/projects/reorder` | Neue Reihenfolge im Brett |
|
||||
| `POST` | `/api/projects/bulk` | Status, Tags oder Löschen für mehrere |
|
||||
| `GET` | `/api/projects/:id/activity` | Verlauf des Projekts (`?limit=`) |
|
||||
| `GET` `POST` | `/api/projects/:id/repositories` | Repositories des Projekts |
|
||||
| `PATCH` `DELETE` | `/api/repositories/:id` | Repository ändern / vom Projekt lösen |
|
||||
|
||||
+6
-16
@@ -20,37 +20,26 @@ erreichbar ist. Der Zeitplan bleibt als Rückfalllösung.
|
||||
|
||||
---
|
||||
|
||||
## 2 · Danach
|
||||
## 2 · Größere Brocken
|
||||
|
||||
### 2.1 Commit-Aktivität als Heatmap `S`
|
||||
|
||||
Die Sparkline gibt es auf Karte und Projektseite. Eine Heatmap über ein Jahr
|
||||
wäre die nächste Ausbaustufe — dafür braucht es allerdings mehr als eine
|
||||
Seite Commits, also Paginierung oder die Statistik-Endpunkte.
|
||||
|
||||
---
|
||||
|
||||
## 3 · Größere Brocken
|
||||
|
||||
### 3.1 Passwort-Zurücksetzen per E-Mail `M`
|
||||
### 2.1 Passwort-Zurücksetzen per E-Mail `M`
|
||||
|
||||
Heute setzt ein Administrator das Passwort neu. Selbstbedienung braucht SMTP
|
||||
und damit eine weitere Konfiguration — lohnt erst im Mehrbenutzerbetrieb.
|
||||
|
||||
### 3.2 Mehrsprachigkeit `L`
|
||||
### 2.2 Mehrsprachigkeit `L`
|
||||
|
||||
Die Oberfläche ist durchgängig deutsch verdrahtet. Englisch dazu wäre eine
|
||||
Voraussetzung, falls du das Projekt veröffentlichen willst.
|
||||
|
||||
---
|
||||
|
||||
## 4 · Kleinigkeiten
|
||||
## 3 · Kleinigkeiten
|
||||
|
||||
| Idee | Aufwand | Nutzen |
|
||||
| --- | --- | --- |
|
||||
| Suchtreffer in Notizen hervorheben | `S` | In der Notiz selbst, nicht nur in der Trefferliste |
|
||||
| Wiederkehrende Aufgaben | `M` | Etwa „jeden Montag Abhängigkeiten prüfen" |
|
||||
| Projektvorlagen | `S` | Neues Projekt mit vorgefüllten Tags und Notizen |
|
||||
| Hell/Dunkel umschaltbar | `M` | Aktuell nur dunkel |
|
||||
| Eigenes Logo und Farbe | `S` | Ergänzt `APP_NAME` |
|
||||
| Barrierefreiheits-Durchsicht | `M` | Fokusreihenfolge, Screenreader, Kontraste |
|
||||
@@ -58,7 +47,7 @@ Voraussetzung, falls du das Projekt veröffentlichen willst.
|
||||
|
||||
---
|
||||
|
||||
## 5 · Bewusst nicht
|
||||
## 4 · Bewusst nicht
|
||||
|
||||
Damit klar ist, was **nicht** kommt und warum:
|
||||
|
||||
@@ -94,6 +83,7 @@ Damit klar ist, was **nicht** kommt und warum:
|
||||
| **v0.9.0** Schnellsuche per `Strg+K`, Aufgaben aus Git-Issues | ✓ |
|
||||
| **v1.0.0** Aktivitätsverlauf je Projekt, Zwei-Faktor per TOTP, mehrere Repositories je Projekt | ✓ |
|
||||
| **v1.1.0** Freie Reihenfolge im Brett, Mehrfachauswahl, installierbar als App, Änderungsverlauf | ✓ |
|
||||
| **v1.2.0** Commit-Heatmap über ein Jahr, Projektvorlagen | ✓ |
|
||||
|
||||
Zur Entscheidung beim Export: Git-Tokens gehen **nicht** mit. Die Verbindung wird nur
|
||||
beschrieben, das Token ist nach dem Import neu zu hinterlegen. Snapshots bleiben
|
||||
|
||||
@@ -374,6 +374,94 @@ test("Brett: Reihenfolge und Mehrfachauswahl", async ({ request, playwright }) =
|
||||
expect((await geloescht.json()).changed).toBe(3);
|
||||
});
|
||||
|
||||
test("Projektvorlagen: aus Projekt sichern und anwenden", async ({ request, playwright }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
// Ein Projekt herrichten, das als Vorlage taugt.
|
||||
const quelle = (
|
||||
await (
|
||||
await request.post("/api/projects", {
|
||||
data: { name: "Vorlagenquelle", status: "PLANNING", priority: 3, tags: ["web", "docker"] },
|
||||
})
|
||||
).json()
|
||||
).project;
|
||||
|
||||
await request.post(`/api/projects/${quelle.id}/notes`, {
|
||||
data: { content: "Checkliste vor dem Start." },
|
||||
});
|
||||
const erledigt = (
|
||||
await (
|
||||
await request.post(`/api/projects/${quelle.id}/tasks`, { data: { title: "Schon fertig" } })
|
||||
).json()
|
||||
).task;
|
||||
await request.patch(`/api/tasks/${erledigt.id}`, { data: { status: "DONE" } });
|
||||
await request.post(`/api/projects/${quelle.id}/tasks`, { data: { title: "Repo anlegen" } });
|
||||
await request.post(`/api/projects/${quelle.id}/tasks`, { data: { title: "CI einrichten" } });
|
||||
|
||||
const gesichert = await request.post("/api/templates/from-project", {
|
||||
data: { projectId: quelle.id, name: "Web-App", description: "Mit Docker und CI" },
|
||||
});
|
||||
expect(gesichert.status()).toBe(201);
|
||||
const vorlage = (await gesichert.json()).template;
|
||||
|
||||
expect(vorlage.tags).toEqual(["web", "docker"]);
|
||||
expect(vorlage.status).toBe("PLANNING");
|
||||
expect(vorlage.notes).toHaveLength(1);
|
||||
// Erledigte Aufgaben kommen nicht mit: eine Vorlage beschreibt, was zu tun ist.
|
||||
expect(vorlage.tasks).toHaveLength(2);
|
||||
expect(vorlage.tasks.map((task: { title: string }) => task.title)).not.toContain("Schon fertig");
|
||||
|
||||
// Derselbe Name ein zweites Mal wird abgewiesen.
|
||||
const doppelt = await request.post("/api/templates/from-project", {
|
||||
data: { projectId: quelle.id, name: "Web-App" },
|
||||
});
|
||||
expect(doppelt.status()).toBe(409);
|
||||
|
||||
// Anwenden: Notizen und Aufgaben entstehen mit dem Projekt.
|
||||
const neu = (
|
||||
await (
|
||||
await request.post("/api/projects", {
|
||||
data: { name: "Aus Vorlage", status: "IDEA", templateId: vorlage.id },
|
||||
})
|
||||
).json()
|
||||
).project;
|
||||
|
||||
const geladen = (await (await request.get(`/api/projects/${neu.id}`)).json()).project;
|
||||
expect(geladen.notes).toHaveLength(1);
|
||||
expect(geladen.tasks).toHaveLength(2);
|
||||
// Die Reihenfolge der Vorlage bleibt erhalten.
|
||||
expect(geladen.tasks.map((task: { title: string }) => task.title)).toEqual([
|
||||
"Repo anlegen",
|
||||
"CI einrichten",
|
||||
]);
|
||||
// Der ausdrueckliche Status gewinnt gegen den der Vorlage.
|
||||
expect(geladen.status).toBe("IDEA");
|
||||
|
||||
// Der Verlauf haelt die Herkunft fest.
|
||||
const verlauf = (await (await request.get(`/api/projects/${neu.id}/activity`)).json()).activities;
|
||||
expect(verlauf.some((entry: { summary: string }) => entry.summary.includes("Web-App"))).toBe(true);
|
||||
|
||||
// Eine fremde Vorlage laesst sich nicht unterschieben.
|
||||
const fremd = await playwright.request.newContext({
|
||||
baseURL: test.info().project.use.baseURL,
|
||||
});
|
||||
await login(fremd, ZWEITER);
|
||||
expect((await (await fremd.get("/api/templates")).json()).templates).toHaveLength(0);
|
||||
const untergeschoben = await fremd.post("/api/projects", {
|
||||
data: { name: "Klau", templateId: vorlage.id },
|
||||
});
|
||||
expect(untergeschoben.status()).toBe(404);
|
||||
expect((await fremd.delete(`/api/templates/${vorlage.id}`)).status()).toBe(404);
|
||||
await fremd.dispose();
|
||||
|
||||
// Und die Vorlage ueberlebt das Loeschen ihres Ursprungsprojekts.
|
||||
await request.delete(`/api/projects/${quelle.id}`);
|
||||
const nochDa = (await (await request.get("/api/templates")).json()).templates;
|
||||
expect(nochDa).toHaveLength(1);
|
||||
|
||||
expect((await request.delete(`/api/templates/${vorlage.id}`)).ok()).toBeTruthy();
|
||||
});
|
||||
|
||||
test("Export enthaelt keine Geheimnisse, Import beachtet die Strategie", async ({ request }) => {
|
||||
await login(request, ADMIN);
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nebula",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"private": true,
|
||||
"description": "Nebula – Dashboard fuer Vibe-Coding Projekte mit Git-Anbindung (GitHub, GitLab, Gitea)",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "RepoSnapshot" ADD COLUMN "commitCalendar" JSONB NOT NULL DEFAULT '{}',
|
||||
ADD COLUMN "commitCalendarAt" TIMESTAMP(3);
|
||||
@@ -0,0 +1,29 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProjectTemplate" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ownerId" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"summary" TEXT,
|
||||
"projectDescription" TEXT,
|
||||
"status" "ProjectStatus" NOT NULL DEFAULT 'IDEA',
|
||||
"priority" INTEGER NOT NULL DEFAULT 2,
|
||||
"accent" TEXT NOT NULL DEFAULT 'violet',
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"progressFromTasks" BOOLEAN NOT NULL DEFAULT false,
|
||||
"notes" JSONB NOT NULL DEFAULT '[]',
|
||||
"tasks" JSONB NOT NULL DEFAULT '[]',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ProjectTemplate_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ProjectTemplate_ownerId_idx" ON "ProjectTemplate"("ownerId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ProjectTemplate_ownerId_name_key" ON "ProjectTemplate"("ownerId", "name");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ProjectTemplate" ADD CONSTRAINT "ProjectTemplate_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -127,6 +127,7 @@ model User {
|
||||
activities Activity[]
|
||||
recoveryCodes RecoveryCode[]
|
||||
pendingLogins PendingLogin[]
|
||||
templates ProjectTemplate[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -466,6 +467,41 @@ model Task {
|
||||
@@index([projectId, status, position])
|
||||
}
|
||||
|
||||
/// Eine Vorlage fuer neue Projekte: Stammdaten, Tags, Notizen und Aufgaben.
|
||||
///
|
||||
/// Bewusst benutzereigen und nicht fest eingebaut. Welche Tags und welche
|
||||
/// Startaufgaben sinnvoll sind, weiss nur, wer damit arbeitet – eine
|
||||
/// mitgelieferte Liste waere geraten.
|
||||
model ProjectTemplate {
|
||||
id String @id @default(cuid())
|
||||
ownerId String
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
|
||||
name String
|
||||
/// Wozu die Vorlage gut ist – erscheint in der Auswahl.
|
||||
description String?
|
||||
|
||||
// ── Was die Vorlage in das neue Projekt schreibt ───────────
|
||||
summary String?
|
||||
projectDescription String?
|
||||
status ProjectStatus @default(IDEA)
|
||||
priority Int @default(2)
|
||||
accent String @default("violet")
|
||||
tags String[] @default([])
|
||||
progressFromTasks Boolean @default(false)
|
||||
|
||||
/// [{ title, content, pinned }]
|
||||
notes Json @default("[]")
|
||||
/// [{ title, description, status, labels }]
|
||||
tasks Json @default("[]")
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([ownerId, name])
|
||||
@@index([ownerId])
|
||||
}
|
||||
|
||||
/// Ein Eintrag im Verlauf eines Projekts: was ist wann passiert.
|
||||
model Activity {
|
||||
id String @id @default(cuid())
|
||||
@@ -550,6 +586,13 @@ model RepoSnapshot {
|
||||
/// Commits je Tag der letzten 30 Tage, aeltester zuerst.
|
||||
commitActivity Json @default("[]")
|
||||
|
||||
/// Commits je Tag ueber bis zu ein Jahr – die Heatmap.
|
||||
/// { from, to, days: { "2026-07-26": 3 }, source, truncated }
|
||||
/// Getrennt vom uebrigen Stand, weil das Holen zusaetzliche Aufrufe kostet
|
||||
/// und deshalb hoechstens einmal am Tag geschieht.
|
||||
commitCalendar Json @default("{}")
|
||||
commitCalendarAt DateTime?
|
||||
|
||||
// ── Letzter CI-Lauf auf dem Default-Branch ─────────────────
|
||||
/// success | failure | running | pending | cancelled
|
||||
ciState String?
|
||||
|
||||
@@ -74,6 +74,20 @@ export async function POST(request: Request) {
|
||||
if (!connection) return jsonError("Git-Verbindung nicht gefunden.", 404);
|
||||
}
|
||||
|
||||
// Aus der Vorlage kommen nur Notizen und Aufgaben. Die Stammdaten hat die
|
||||
// Oberflaeche schon in die Felder uebernommen, damit man sie vor dem
|
||||
// Speichern noch sieht und aendern kann.
|
||||
const vorlage = data.templateId
|
||||
? await prisma.projectTemplate.findFirst({
|
||||
where: { id: data.templateId, ownerId: auth.user.id },
|
||||
select: { name: true, notes: true, tasks: true },
|
||||
})
|
||||
: null;
|
||||
if (data.templateId && !vorlage) return jsonError("Vorlage nicht gefunden.", 404);
|
||||
|
||||
const notes = templateNotes(vorlage?.notes);
|
||||
const tasks = templateTasks(vorlage?.tasks);
|
||||
|
||||
const angelegt = await prisma.project.create({
|
||||
data: {
|
||||
ownerId: auth.user.id,
|
||||
@@ -87,8 +101,11 @@ export async function POST(request: Request) {
|
||||
accent: data.accent,
|
||||
tags: data.tags,
|
||||
favorite: data.favorite,
|
||||
progressFromTasks: data.progressFromTasks,
|
||||
// Hinten an die Statusspalte des Bretts.
|
||||
position: await nextProjectPosition(auth.user.id, data.status),
|
||||
notes: { create: notes },
|
||||
tasks: { create: tasks },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
@@ -111,12 +128,56 @@ export async function POST(request: Request) {
|
||||
projectId: project.id,
|
||||
userId: auth.user.id,
|
||||
kind: "PROJECT_CREATED",
|
||||
summary:
|
||||
data.status === "IDEA"
|
||||
summary: vorlage
|
||||
? `Aus Vorlage „${vorlage.name}“ angelegt`
|
||||
: data.status === "IDEA"
|
||||
? "Als Idee angelegt"
|
||||
: `Angelegt mit Status „${statusOf(data.status).label}“`,
|
||||
meta: { status: data.status },
|
||||
meta: {
|
||||
status: data.status,
|
||||
...(vorlage ? { template: vorlage.name, notes: notes.length, tasks: tasks.length } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ project }, { status: 201 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Vorlage kommt als JSON aus der Datenbank und ist damit fuer TypeScript
|
||||
* unbekannt. Hier wird sie auf das Noetige zurechtgeschnitten – lieber einen
|
||||
* Eintrag auslassen als am Anlegen scheitern.
|
||||
*/
|
||||
function templateNotes(value: unknown) {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.filter((entry): entry is Record<string, unknown> => Boolean(entry) && typeof entry === "object")
|
||||
.filter((entry) => typeof entry.content === "string" && entry.content.trim().length > 0)
|
||||
.slice(0, 50)
|
||||
.map((entry) => ({
|
||||
title: typeof entry.title === "string" ? entry.title : null,
|
||||
content: entry.content as string,
|
||||
pinned: entry.pinned === true,
|
||||
}));
|
||||
}
|
||||
|
||||
function templateTasks(value: unknown) {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.filter((entry): entry is Record<string, unknown> => Boolean(entry) && typeof entry === "object")
|
||||
.filter((entry) => typeof entry.title === "string" && entry.title.trim().length > 0)
|
||||
.slice(0, 100)
|
||||
.map((entry, index) => ({
|
||||
title: entry.title as string,
|
||||
description: typeof entry.description === "string" ? entry.description : null,
|
||||
status: (["TODO", "DOING", "BLOCKED"] as const).includes(
|
||||
entry.status as "TODO" | "DOING" | "BLOCKED",
|
||||
)
|
||||
? (entry.status as "TODO" | "DOING" | "BLOCKED")
|
||||
: ("TODO" as const),
|
||||
// Reihenfolge wie in der Vorlage.
|
||||
position: index,
|
||||
labels: Array.isArray(entry.labels)
|
||||
? entry.labels.filter((label): label is string => typeof label === "string").slice(0, 8)
|
||||
: [],
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { formatZodError, templateUpdateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function PATCH(request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
const existing = await prisma.projectTemplate.findFirst({
|
||||
where: { id, ownerId: auth.user.id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) return jsonError("Vorlage nicht gefunden", 404);
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = templateUpdateSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
|
||||
if (data.name) {
|
||||
const doppelt = await prisma.projectTemplate.findFirst({
|
||||
where: { ownerId: auth.user.id, name: data.name, id: { not: id } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (doppelt) return jsonError(`Eine Vorlage „${data.name}“ gibt es bereits.`, 409);
|
||||
}
|
||||
|
||||
const template = await prisma.projectTemplate.update({ where: { id }, data });
|
||||
return NextResponse.json({ template });
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, { params }: Params) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
// deleteMany mit Besitzerbedingung: trifft fremde Vorlagen gar nicht erst.
|
||||
const result = await prisma.projectTemplate.deleteMany({
|
||||
where: { id, ownerId: auth.user.id },
|
||||
});
|
||||
if (result.count === 0) return jsonError("Vorlage nicht gefunden", 404);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { formatZodError, templateFromProjectSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Aus einem vorhandenen Projekt eine Vorlage machen.
|
||||
*
|
||||
* Das ist der Weg, auf dem Vorlagen ueblicherweise entstehen: man richtet ein
|
||||
* Projekt so ein, wie es passt, und haelt das dann fest. Eine Vorlage von
|
||||
* Grund auf zu tippen kann man auch – ueber POST /api/templates.
|
||||
*
|
||||
* Nicht mitgenommen wird alles Projektbezogene: Name, Slug, Fortschritt,
|
||||
* Favorit und vor allem die Repositories. Eine Vorlage, die jedes neue
|
||||
* Projekt an dasselbe Repository haengt, waere eine Falle.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = templateFromProjectSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const { projectId, name, description, withNotes, withTasks } = parsed.data;
|
||||
|
||||
const project = await prisma.project.findFirst({
|
||||
where: { id: projectId, ownerId: auth.user.id },
|
||||
include: {
|
||||
notes: { orderBy: [{ pinned: "desc" }, { createdAt: "asc" }] },
|
||||
tasks: { orderBy: [{ status: "asc" }, { position: "asc" }] },
|
||||
},
|
||||
});
|
||||
if (!project) return jsonError("Projekt nicht gefunden", 404);
|
||||
|
||||
const doppelt = await prisma.projectTemplate.findFirst({
|
||||
where: { ownerId: auth.user.id, name },
|
||||
select: { id: true },
|
||||
});
|
||||
if (doppelt) return jsonError(`Eine Vorlage „${name}“ gibt es bereits.`, 409);
|
||||
|
||||
const template = await prisma.projectTemplate.create({
|
||||
data: {
|
||||
ownerId: auth.user.id,
|
||||
name,
|
||||
description: description ?? null,
|
||||
summary: project.summary,
|
||||
projectDescription: project.description,
|
||||
status: project.status,
|
||||
priority: project.priority,
|
||||
accent: project.accent,
|
||||
tags: project.tags,
|
||||
progressFromTasks: project.progressFromTasks,
|
||||
notes: withNotes
|
||||
? project.notes.map((note) => ({
|
||||
title: note.title,
|
||||
content: note.content,
|
||||
pinned: note.pinned,
|
||||
}))
|
||||
: [],
|
||||
// Erledigte Aufgaben kommen nicht mit: eine Vorlage beschreibt, was zu
|
||||
// tun ist, nicht was einmal getan wurde.
|
||||
tasks: withTasks
|
||||
? project.tasks
|
||||
.filter((task) => task.status !== "DONE")
|
||||
.map((task) => ({
|
||||
title: task.title,
|
||||
description: task.description,
|
||||
status: task.status,
|
||||
labels: task.labels,
|
||||
}))
|
||||
: [],
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ template }, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { requireUserApi } from "@/lib/auth/guard";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { jsonError, readJsonBody } from "@/lib/security/request";
|
||||
import { formatZodError, templateCreateSchema } from "@/lib/validation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Hoechstzahl je Konto. Wer mehr braucht, hat keine Vorlagen mehr, sondern Projekte. */
|
||||
const MAX_TEMPLATES = 30;
|
||||
|
||||
export async function GET() {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const templates = await prisma.projectTemplate.findMany({
|
||||
where: { ownerId: auth.user.id },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
return NextResponse.json({ templates });
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireUserApi();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!body.ok) return body.response;
|
||||
|
||||
const parsed = templateCreateSchema.safeParse(body.data);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const vorhanden = await prisma.projectTemplate.count({ where: { ownerId: auth.user.id } });
|
||||
if (vorhanden >= MAX_TEMPLATES) {
|
||||
return jsonError(`Mehr als ${MAX_TEMPLATES} Vorlagen sind nicht vorgesehen.`, 409);
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
|
||||
// Der Name ist je Konto eindeutig; ein Duplikat soll eine verstaendliche
|
||||
// Meldung geben statt eines Datenbankfehlers.
|
||||
const doppelt = await prisma.projectTemplate.findFirst({
|
||||
where: { ownerId: auth.user.id, name: data.name },
|
||||
select: { id: true },
|
||||
});
|
||||
if (doppelt) return jsonError(`Eine Vorlage „${data.name}“ gibt es bereits.`, 409);
|
||||
|
||||
const template = await prisma.projectTemplate.create({
|
||||
data: {
|
||||
ownerId: auth.user.id,
|
||||
name: data.name,
|
||||
description: data.description ?? null,
|
||||
summary: data.summary ?? null,
|
||||
projectDescription: data.projectDescription ?? null,
|
||||
status: data.status,
|
||||
priority: data.priority,
|
||||
accent: data.accent,
|
||||
tags: data.tags,
|
||||
progressFromTasks: data.progressFromTasks,
|
||||
notes: data.notes,
|
||||
tasks: data.tasks,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ template }, { status: 201 });
|
||||
}
|
||||
@@ -24,10 +24,11 @@ import {
|
||||
Unlink,
|
||||
} from "lucide-react";
|
||||
import { CiBadge } from "@/components/CiBadge";
|
||||
import { Heatmap } from "@/components/Heatmap";
|
||||
import { RepositoryDialog } from "@/components/RepositoryDialog";
|
||||
import { Sparkline } from "@/components/Sparkline";
|
||||
import { repoTitle } from "@/lib/git/meta";
|
||||
import { asArray, asRecord } from "@/types";
|
||||
import { asArray, asCalendar, asRecord } from "@/types";
|
||||
import type {
|
||||
BranchInfo,
|
||||
CommitInfo,
|
||||
@@ -109,6 +110,7 @@ export function GitPanel({
|
||||
const pulls = asArray<TicketInfo>(snapshot?.pullRequests);
|
||||
const issues = asArray<TicketInfo>(snapshot?.issues);
|
||||
const activity = asArray<number>(snapshot?.commitActivity);
|
||||
const calendar = asCalendar(snapshot?.commitCalendar);
|
||||
|
||||
/** Ein einzelnes Repository oder – ohne Argument – alle. */
|
||||
async function sync(nurDieses?: string) {
|
||||
@@ -416,6 +418,9 @@ export function GitPanel({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Der Jahresueberblick, sobald er einmal geholt wurde. */}
|
||||
{calendar ? <Heatmap calendar={calendar} /> : null}
|
||||
|
||||
{/* Sprachen */}
|
||||
{languageTotal > 0 ? (
|
||||
<div className="glass p-4">
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import { CalendarRange } from "lucide-react";
|
||||
import type { CommitCalendar } from "@/lib/git/calendar";
|
||||
import { formatDate } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Commits je Tag als Kalender – ein Feld pro Tag, Wochen als Spalten.
|
||||
*
|
||||
* Wie die Verlaufslinie ohne Diagrammbibliothek: es sind Quadrate in einem
|
||||
* Raster, dafuer braucht es keine Achsen und keine Legende ausser der
|
||||
* Farbskala.
|
||||
*
|
||||
* Gezeichnet wird nur der Zeitraum, fuer den wirklich Daten vorliegen.
|
||||
* Wo die Seiten des Anbieters nur ein paar Monate zurueckreichen, faengt die
|
||||
* Heatmap dort an – ein leeres Feld wuerde sonst behaupten, an dem Tag sei
|
||||
* nicht gearbeitet worden, obwohl darueber nichts bekannt ist.
|
||||
*/
|
||||
|
||||
const WOCHENTAGE = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
|
||||
const MONATE = [
|
||||
"Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
|
||||
"Jul", "Aug", "Sep", "Okt", "Nov", "Dez",
|
||||
];
|
||||
|
||||
/** Fuenf Stufen, damit ein einzelner Ausreisser nicht alles andere platt macht. */
|
||||
function stufe(anzahl: number, hoch: number): number {
|
||||
if (anzahl <= 0) return 0;
|
||||
if (hoch <= 1) return 4;
|
||||
const anteil = anzahl / hoch;
|
||||
if (anteil > 0.75) return 4;
|
||||
if (anteil > 0.5) return 3;
|
||||
if (anteil > 0.25) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
const FARBEN = [
|
||||
"fill-white/6",
|
||||
"fill-violet-500/25",
|
||||
"fill-violet-500/45",
|
||||
"fill-violet-400/70",
|
||||
"fill-violet-300",
|
||||
];
|
||||
|
||||
/** Montag der Woche, in der dieser Tag liegt (UTC). */
|
||||
function wochenanfang(tag: Date): Date {
|
||||
const kopie = new Date(tag);
|
||||
// getUTCDay: 0 = Sonntag. Die Woche soll am Montag beginnen.
|
||||
const versatz = (kopie.getUTCDay() + 6) % 7;
|
||||
kopie.setUTCDate(kopie.getUTCDate() - versatz);
|
||||
kopie.setUTCHours(0, 0, 0, 0);
|
||||
return kopie;
|
||||
}
|
||||
|
||||
export function Heatmap({ calendar }: { calendar: CommitCalendar }) {
|
||||
const von = new Date(`${calendar.from}T00:00:00.000Z`);
|
||||
const bis = new Date(`${calendar.to}T00:00:00.000Z`);
|
||||
if (Number.isNaN(von.getTime()) || Number.isNaN(bis.getTime()) || von > bis) return null;
|
||||
|
||||
const start = wochenanfang(von);
|
||||
const wochen: Array<Array<{ key: string; anzahl: number; ausserhalb: boolean }>> = [];
|
||||
|
||||
let hoechstwert = 0;
|
||||
for (const wert of Object.values(calendar.days)) {
|
||||
if (wert > hoechstwert) hoechstwert = wert;
|
||||
}
|
||||
|
||||
const zeiger = new Date(start);
|
||||
while (zeiger <= bis) {
|
||||
const woche: Array<{ key: string; anzahl: number; ausserhalb: boolean }> = [];
|
||||
for (let tag = 0; tag < 7; tag += 1) {
|
||||
const key = zeiger.toISOString().slice(0, 10);
|
||||
// Vor dem ersten bekannten Tag und nach heute wird nichts gezeichnet.
|
||||
const ausserhalb = zeiger < von || zeiger > bis;
|
||||
woche.push({ key, anzahl: calendar.days[key] ?? 0, ausserhalb });
|
||||
zeiger.setUTCDate(zeiger.getUTCDate() + 1);
|
||||
}
|
||||
wochen.push(woche);
|
||||
}
|
||||
|
||||
const gesamt = Object.values(calendar.days).reduce((sum, wert) => sum + wert, 0);
|
||||
const tageMitCommits = Object.keys(calendar.days).length;
|
||||
|
||||
// Masse in SVG-Einheiten; die Breite ergibt sich aus der Zahl der Wochen.
|
||||
const feld = 11;
|
||||
const luecke = 3;
|
||||
const kopf = 14;
|
||||
const spalte = feld + luecke;
|
||||
const breite = wochen.length * spalte - luecke;
|
||||
const hoehe = kopf + 7 * spalte - luecke;
|
||||
|
||||
// Monatsbeschriftung an der Woche, in der ein neuer Monat beginnt.
|
||||
const monate: Array<{ x: number; label: string }> = [];
|
||||
let letzterMonat = -1;
|
||||
wochen.forEach((woche, index) => {
|
||||
const ersterTag = new Date(`${woche[0].key}T00:00:00.000Z`);
|
||||
const monat = ersterTag.getUTCMonth();
|
||||
if (monat !== letzterMonat) {
|
||||
letzterMonat = monat;
|
||||
monate.push({ x: index * spalte, label: MONATE[monat] });
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="glass p-4">
|
||||
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
|
||||
<p className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500">
|
||||
<CalendarRange className="h-3 w-3" />
|
||||
Commits je Tag
|
||||
</p>
|
||||
<p className="text-[11px] text-slate-500">
|
||||
{gesamt} an {tageMitCommits} {tageMitCommits === 1 ? "Tag" : "Tagen"} ·{" "}
|
||||
{/* Der Zeitraum gehoert dazu: er ist nicht immer ein Jahr. */}
|
||||
seit {formatDate(calendar.from)}
|
||||
{calendar.truncated ? " (Älteres nicht abgerufen)" : ""}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<svg
|
||||
viewBox={`0 0 ${breite + 22} ${hoehe}`}
|
||||
width={breite + 22}
|
||||
height={hoehe}
|
||||
className="max-w-full"
|
||||
role="img"
|
||||
aria-label={`Commits je Tag seit ${formatDate(calendar.from)}: ${gesamt} an ${tageMitCommits} Tagen`}
|
||||
>
|
||||
{monate.map((monat, index) => (
|
||||
<text
|
||||
key={`${monat.label}-${index}`}
|
||||
x={monat.x + 22}
|
||||
y={9}
|
||||
className="fill-slate-500 text-[8px]"
|
||||
>
|
||||
{monat.label}
|
||||
</text>
|
||||
))}
|
||||
|
||||
{/* Nur jeder zweite Wochentag, sonst steht es zu eng. */}
|
||||
{WOCHENTAGE.map((tag, index) =>
|
||||
index % 2 === 1 ? (
|
||||
<text
|
||||
key={tag}
|
||||
x={0}
|
||||
y={kopf + index * spalte + feld - 2}
|
||||
className="fill-slate-600 text-[7px]"
|
||||
>
|
||||
{tag}
|
||||
</text>
|
||||
) : null,
|
||||
)}
|
||||
|
||||
{wochen.map((woche, x) =>
|
||||
woche.map((tag, y) =>
|
||||
tag.ausserhalb ? null : (
|
||||
<rect
|
||||
key={tag.key}
|
||||
x={x * spalte + 22}
|
||||
y={kopf + y * spalte}
|
||||
width={feld}
|
||||
height={feld}
|
||||
rx={2}
|
||||
className={FARBEN[stufe(tag.anzahl, hoechstwert)]}
|
||||
>
|
||||
<title>
|
||||
{`${formatDate(tag.key)}: ${tag.anzahl} ${tag.anzahl === 1 ? "Commit" : "Commits"}`}
|
||||
</title>
|
||||
</rect>
|
||||
),
|
||||
),
|
||||
)}
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex items-center justify-end gap-1.5 text-[10px] text-slate-600">
|
||||
<span>weniger</span>
|
||||
{FARBEN.map((farbe, index) => (
|
||||
<svg key={index} width={9} height={9} aria-hidden>
|
||||
<rect width={9} height={9} rx={2} className={farbe} />
|
||||
</svg>
|
||||
))}
|
||||
<span>mehr</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, RefreshCw, Search } from "lucide-react";
|
||||
import { Loader2, RefreshCw, Search, Trash2 } from "lucide-react";
|
||||
import type { ProjectStatus } from "@prisma/client";
|
||||
import { Modal } from "@/components/ui/Modal";
|
||||
import { ACCENTS, PRIORITY_META, STATUS_META, STATUS_ORDER } from "@/lib/status";
|
||||
@@ -17,6 +17,33 @@ interface ProjectDialogProps {
|
||||
project?: ProjectListItem | null;
|
||||
}
|
||||
|
||||
/** Eine Vorlage, so wie sie /api/templates liefert. */
|
||||
export interface ProjectTemplateEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
summary: string | null;
|
||||
projectDescription: string | null;
|
||||
status: ProjectStatus;
|
||||
priority: number;
|
||||
accent: string;
|
||||
tags: string[];
|
||||
progressFromTasks: boolean;
|
||||
notes: unknown[];
|
||||
tasks: unknown[];
|
||||
}
|
||||
|
||||
/** "3 Notizen, 5 Aufgaben" – oder was davon zutrifft. */
|
||||
function beschreibeVorlage(vorlage: ProjectTemplateEntry): string {
|
||||
const teile: string[] = [];
|
||||
const notizen = Array.isArray(vorlage.notes) ? vorlage.notes.length : 0;
|
||||
const aufgaben = Array.isArray(vorlage.tasks) ? vorlage.tasks.length : 0;
|
||||
if (notizen > 0) teile.push(`${notizen} ${notizen === 1 ? "Notiz" : "Notizen"}`);
|
||||
if (aufgaben > 0) teile.push(`${aufgaben} ${aufgaben === 1 ? "Aufgabe" : "Aufgaben"}`);
|
||||
if (vorlage.tags.length > 0) teile.push(vorlage.tags.map((tag) => `#${tag}`).join(" "));
|
||||
return teile.length > 0 ? teile.join(" · ") : "nur Stammdaten";
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
name: string;
|
||||
summary: string;
|
||||
@@ -33,6 +60,8 @@ interface FormState {
|
||||
repoName: string;
|
||||
autoSync: boolean;
|
||||
progressFromTasks: boolean;
|
||||
/** Nur beim Anlegen: aus welcher Vorlage Notizen und Aufgaben kommen. */
|
||||
templateId: string;
|
||||
}
|
||||
|
||||
const EMPTY: FormState = {
|
||||
@@ -51,6 +80,7 @@ const EMPTY: FormState = {
|
||||
repoName: "",
|
||||
autoSync: true,
|
||||
progressFromTasks: false,
|
||||
templateId: "",
|
||||
};
|
||||
|
||||
export function ProjectDialog({ open, onClose, connections, project }: ProjectDialogProps) {
|
||||
@@ -60,14 +90,72 @@ export function ProjectDialog({ open, onClose, connections, project }: ProjectDi
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
|
||||
const isEdit = Boolean(project);
|
||||
|
||||
const [templates, setTemplates] = useState<ProjectTemplateEntry[]>([]);
|
||||
const gewaehlteVorlage = templates.find((entry) => entry.id === form.templateId) ?? null;
|
||||
|
||||
/**
|
||||
* Die Vorlagen werden erst geladen, wenn der Dialog aufgeht – und nur zum
|
||||
* Anlegen. Beim Bearbeiten waeren sie nur Ballast.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!open || isEdit) return;
|
||||
let abgebrochen = false;
|
||||
fetch("/api/templates")
|
||||
.then((response) => (response.ok ? response.json() : { templates: [] }))
|
||||
.then((payload) => {
|
||||
if (!abgebrochen) setTemplates(payload.templates ?? []);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
abgebrochen = true;
|
||||
};
|
||||
}, [open, isEdit]);
|
||||
|
||||
/**
|
||||
* Uebernimmt die Stammdaten sichtbar in die Felder. Notizen und Aufgaben
|
||||
* bleiben der Serverseite ueberlassen: sie liessen sich hier nicht
|
||||
* darstellen, und wer die Vorlage wieder abwaehlt, soll sie auch nicht
|
||||
* mitgeschleppt bekommen.
|
||||
*
|
||||
* Bereits Getipptes wird nicht ueberschrieben – nur leere Felder werden
|
||||
* gefuellt.
|
||||
*/
|
||||
function applyTemplate(templateId: string) {
|
||||
const vorlage = templates.find((entry) => entry.id === templateId);
|
||||
if (!vorlage) {
|
||||
update("templateId", "");
|
||||
return;
|
||||
}
|
||||
|
||||
setForm((previous) => ({
|
||||
...previous,
|
||||
templateId,
|
||||
name: previous.name || vorlage.name,
|
||||
summary: previous.summary || (vorlage.summary ?? ""),
|
||||
description: previous.description || (vorlage.projectDescription ?? ""),
|
||||
status: vorlage.status,
|
||||
priority: vorlage.priority,
|
||||
accent: vorlage.accent,
|
||||
tags: previous.tags || vorlage.tags.join(", "),
|
||||
progressFromTasks: vorlage.progressFromTasks,
|
||||
}));
|
||||
}
|
||||
|
||||
async function removeTemplate(vorlage: ProjectTemplateEntry) {
|
||||
if (!window.confirm(`Vorlage „${vorlage.name}“ loeschen?`)) return;
|
||||
await fetch(`/api/templates/${vorlage.id}`, { method: "DELETE" }).catch(() => undefined);
|
||||
setTemplates((current) => current.filter((entry) => entry.id !== vorlage.id));
|
||||
update("templateId", "");
|
||||
}
|
||||
|
||||
const [repoPickerOpen, setRepoPickerOpen] = useState(false);
|
||||
const [repos, setRepos] = useState<RepoListEntry[]>([]);
|
||||
const [reposLoading, setReposLoading] = useState(false);
|
||||
const [repoFilter, setRepoFilter] = useState("");
|
||||
const [repoError, setRepoError] = useState<string | null>(null);
|
||||
|
||||
const isEdit = Boolean(project);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
@@ -96,6 +184,7 @@ export function ProjectDialog({ open, onClose, connections, project }: ProjectDi
|
||||
repoName: project.repositories[0]?.repoName ?? "",
|
||||
autoSync: project.repositories[0]?.autoSync ?? true,
|
||||
progressFromTasks: project.progressFromTasks,
|
||||
templateId: "",
|
||||
}
|
||||
: EMPTY,
|
||||
);
|
||||
@@ -165,6 +254,8 @@ export function ProjectDialog({ open, onClose, connections, project }: ProjectDi
|
||||
repoName: form.repoName,
|
||||
autoSync: form.autoSync,
|
||||
progressFromTasks: form.progressFromTasks,
|
||||
// Nur beim Anlegen; beim Bearbeiten kennt das Schema das Feld nicht.
|
||||
...(isEdit ? {} : { templateId: form.templateId || null }),
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -203,6 +294,52 @@ export function ProjectDialog({ open, onClose, connections, project }: ProjectDi
|
||||
}
|
||||
>
|
||||
<form onSubmit={submit} className="space-y-5">
|
||||
{/* Nur beim Anlegen. Ein bestehendes Projekt nachtraeglich aus einer
|
||||
Vorlage zu befuellen wuerde Notizen und Aufgaben verdoppeln. */}
|
||||
{!isEdit && templates.length > 0 ? (
|
||||
<div className="glass-soft p-4">
|
||||
<label className="field-label" htmlFor="project-template">
|
||||
Aus Vorlage
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<select
|
||||
id="project-template"
|
||||
className="field w-auto min-w-[14rem] flex-1"
|
||||
value={form.templateId}
|
||||
onChange={(event) => applyTemplate(event.target.value)}
|
||||
>
|
||||
<option value="">– ohne Vorlage –</option>
|
||||
{templates.map((template) => (
|
||||
<option key={template.id} value={template.id}>
|
||||
{template.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{gewaehlteVorlage ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost px-2.5 py-1.5 text-xs text-rose-200"
|
||||
onClick={() => removeTemplate(gewaehlteVorlage)}
|
||||
title="Diese Vorlage loeschen"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
{gewaehlteVorlage ? (
|
||||
<p className="mt-1.5 text-xs text-slate-500">
|
||||
{gewaehlteVorlage.description ? `${gewaehlteVorlage.description} · ` : ""}
|
||||
{beschreibeVorlage(gewaehlteVorlage)}
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-1.5 text-xs text-slate-500">
|
||||
Vorlagen entstehen aus einem bestehenden Projekt – im Projektkopf unter
|
||||
„Als Vorlage sichern“.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="field-label" htmlFor="project-name">
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
ArrowLeft,
|
||||
BookmarkPlus,
|
||||
CalendarDays,
|
||||
CheckSquare,
|
||||
Download,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { ProjectDialog } from "@/components/ProjectDialog";
|
||||
import { SaveTemplateDialog } from "@/components/SaveTemplateDialog";
|
||||
import { StatusSelect } from "@/components/StatusSelect";
|
||||
import { Popover } from "@/components/ui/Popover";
|
||||
import { repoTitle } from "@/lib/git/meta";
|
||||
@@ -36,6 +38,7 @@ export function ProjectHeader({
|
||||
const priority = PRIORITY_META[project.priority] ?? PRIORITY_META[2];
|
||||
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [templateOpen, setTemplateOpen] = useState(false);
|
||||
const [exportOpen, setExportOpen] = useState(false);
|
||||
const exportButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const [favorite, setFavorite] = useState(project.favorite);
|
||||
@@ -179,6 +182,14 @@ export function ProjectHeader({
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost px-2.5 py-1.5 text-xs"
|
||||
onClick={() => setTemplateOpen(true)}
|
||||
title="Als Vorlage sichern"
|
||||
>
|
||||
<BookmarkPlus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost px-3 py-1.5 text-xs"
|
||||
@@ -284,6 +295,16 @@ export function ProjectHeader({
|
||||
connections={connections}
|
||||
project={project}
|
||||
/>
|
||||
|
||||
<SaveTemplateDialog
|
||||
open={templateOpen}
|
||||
onClose={() => setTemplateOpen(false)}
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
noteCount={project.notes.length}
|
||||
// Erledigte kommen nicht mit – hier steht, was wirklich uebernommen wird.
|
||||
taskCount={project.tasks.filter((task) => task.status !== "DONE").length}
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { BookmarkPlus, Check, Loader2 } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/Modal";
|
||||
|
||||
/**
|
||||
* Aus dem offenen Projekt eine Vorlage machen.
|
||||
*
|
||||
* Bewusst hier und nicht in einer eigenen Verwaltungsseite: Vorlagen
|
||||
* entstehen aus einem Projekt, das sich bewaehrt hat. Sie von Grund auf zu
|
||||
* tippen kann man ueber die API, taeglich braucht das niemand.
|
||||
*/
|
||||
export function SaveTemplateDialog({
|
||||
open,
|
||||
onClose,
|
||||
projectId,
|
||||
projectName,
|
||||
noteCount,
|
||||
taskCount,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
noteCount: number;
|
||||
taskCount: number;
|
||||
}) {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [withNotes, setWithNotes] = useState(true);
|
||||
const [withTasks, setWithTasks] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setName(projectName);
|
||||
setDescription("");
|
||||
setWithNotes(true);
|
||||
setWithTasks(true);
|
||||
setError(null);
|
||||
setDone(false);
|
||||
}, [open, projectName]);
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch("/api/templates/from-project", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ projectId, name, description, withNotes, withTasks }),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(payload.error ?? "Speichern fehlgeschlagen.");
|
||||
setDone(true);
|
||||
// Kurz stehen lassen, damit die Bestaetigung ankommt.
|
||||
setTimeout(onClose, 900);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : String(caught));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
width="md"
|
||||
title="Als Vorlage sichern"
|
||||
description="Neue Projekte starten damit mit denselben Tags, Notizen und Aufgaben."
|
||||
>
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div>
|
||||
<label className="field-label" htmlFor="template-name">
|
||||
Name der Vorlage *
|
||||
</label>
|
||||
<input
|
||||
id="template-name"
|
||||
className="field"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
maxLength={80}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="field-label" htmlFor="template-description">
|
||||
Wofür ist sie gut? (optional)
|
||||
</label>
|
||||
<input
|
||||
id="template-description"
|
||||
className="field"
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
placeholder="z. B. Kleine Web-App mit Docker und CI"
|
||||
maxLength={280}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="flex cursor-pointer items-start gap-2.5 text-sm text-slate-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={withNotes}
|
||||
onChange={(event) => setWithNotes(event.target.checked)}
|
||||
disabled={noteCount === 0}
|
||||
className="mt-0.5 h-4 w-4 accent-violet-500"
|
||||
/>
|
||||
<span>
|
||||
Notizen übernehmen
|
||||
<span className="mt-0.5 block text-[11px] text-slate-600">
|
||||
{noteCount === 0
|
||||
? "Dieses Projekt hat keine Notizen."
|
||||
: `${noteCount} ${noteCount === 1 ? "Notiz" : "Notizen"}`}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label className="flex cursor-pointer items-start gap-2.5 text-sm text-slate-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={withTasks}
|
||||
onChange={(event) => setWithTasks(event.target.checked)}
|
||||
disabled={taskCount === 0}
|
||||
className="mt-0.5 h-4 w-4 accent-violet-500"
|
||||
/>
|
||||
<span>
|
||||
Aufgaben übernehmen
|
||||
<span className="mt-0.5 block text-[11px] text-slate-600">
|
||||
{taskCount === 0
|
||||
? "Dieses Projekt hat keine offenen Aufgaben."
|
||||
: `${taskCount} offene ${taskCount === 1 ? "Aufgabe" : "Aufgaben"} — erledigte kommen nicht mit`}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p className="rounded-lg border border-white/8 bg-black/25 px-3 py-2 text-xs text-slate-500">
|
||||
Repositories gehen <strong>nicht</strong> mit. Eine Vorlage, die jedes neue Projekt
|
||||
an dasselbe Repository hängt, wäre eine Falle.
|
||||
</p>
|
||||
|
||||
{error ? (
|
||||
<p className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex justify-end gap-3 pt-1">
|
||||
<button type="button" className="btn btn-ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary" disabled={saving || done}>
|
||||
{saving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : done ? (
|
||||
<Check className="h-4 w-4" />
|
||||
) : (
|
||||
<BookmarkPlus className="h-4 w-4" />
|
||||
)}
|
||||
{done ? "Gesichert" : "Sichern"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -41,6 +41,38 @@ export const KIND_META: Record<ChangeKind, { label: string; className: string }>
|
||||
};
|
||||
|
||||
export const CHANGELOG: Release[] = [
|
||||
{
|
||||
version: "1.2.0",
|
||||
date: "2026-07-26",
|
||||
headline: "Ein Jahr auf einen Blick, und ein Start ohne Leerlauf.",
|
||||
changes: [
|
||||
{
|
||||
kind: "neu",
|
||||
text:
|
||||
"Commit-Heatmap auf der Projektseite: ein Feld je Tag über bis zu ein Jahr, " +
|
||||
"mit Farbskala und Datum im Tooltip.",
|
||||
},
|
||||
{
|
||||
kind: "neu",
|
||||
text:
|
||||
"Projektvorlagen. Ein bewährtes Projekt über „Als Vorlage sichern“ festhalten — " +
|
||||
"Tags, Notizen und offene Aufgaben stehen dann beim nächsten Projekt bereit.",
|
||||
},
|
||||
{
|
||||
kind: "besser",
|
||||
text:
|
||||
"Die Heatmap-Daten kommen höchstens einmal am Tag und getrennt vom übrigen " +
|
||||
"Abgleich. Bei GitHub genügt ein Aufruf der Jahresstatistik, bei GitLab und " +
|
||||
"Gitea werden bis zu fünf Seiten Commits geholt.",
|
||||
},
|
||||
{
|
||||
kind: "besser",
|
||||
text:
|
||||
"Reicht die Historie nicht ein Jahr zurück, beginnt die Heatmap beim ältesten " +
|
||||
"bekannten Commit — leere Felder für unbekannte Zeiträume wären eine Lüge.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
version: "1.1.0",
|
||||
date: "2026-07-26",
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
CALENDAR_MAX_PAGES,
|
||||
CALENDAR_PAGE_SIZE,
|
||||
calendarByPaging,
|
||||
calendarSince,
|
||||
calendarTotal,
|
||||
dayKey,
|
||||
} from "./calendar";
|
||||
|
||||
/**
|
||||
* Der Kalender darf ueber den Zeitraum nicht luegen. Reichen die geholten
|
||||
* Seiten nur ein paar Monate zurueck, faengt die Heatmap dort an – sie zeigt
|
||||
* dann keine leeren Felder fuer Zeiten, ueber die schlicht nichts bekannt ist.
|
||||
* Genau diesen Fehler hatte die Verlaufslinie schon einmal.
|
||||
*/
|
||||
|
||||
const JETZT = new Date("2026-07-26T12:00:00.000Z");
|
||||
const TAG = 86_400_000;
|
||||
|
||||
/** Erzeugt n Commit-Zeitpunkte, beginnend vor `abTagen` Tagen, einer je Tag. */
|
||||
function commits(anzahl: number, abTagen: number): string[] {
|
||||
return Array.from({ length: anzahl }, (_, index) =>
|
||||
new Date(JETZT.getTime() - (abTagen + index) * TAG).toISOString(),
|
||||
);
|
||||
}
|
||||
|
||||
describe("dayKey", () => {
|
||||
it("liefert das Datum ohne Uhrzeit", () => {
|
||||
expect(dayKey(new Date("2026-07-26T23:59:00.000Z"))).toBe("2026-07-26");
|
||||
});
|
||||
});
|
||||
|
||||
describe("calendarSince", () => {
|
||||
it("liegt ein Jahr zurueck", () => {
|
||||
const seit = calendarSince(JETZT);
|
||||
expect(Math.round((JETZT.getTime() - seit.getTime()) / TAG)).toBe(365);
|
||||
});
|
||||
});
|
||||
|
||||
describe("calendarByPaging", () => {
|
||||
it("liefert null, wenn es keine Commits gibt", async () => {
|
||||
expect(await calendarByPaging(async () => [], JETZT)).toBeNull();
|
||||
});
|
||||
|
||||
it("zaehlt mehrere Commits desselben Tages zusammen", async () => {
|
||||
const heute = JETZT.toISOString();
|
||||
const kalender = await calendarByPaging(async () => [heute, heute, heute], JETZT);
|
||||
expect(kalender?.days["2026-07-26"]).toBe(3);
|
||||
expect(calendarTotal(kalender!)).toBe(3);
|
||||
});
|
||||
|
||||
it("beginnt beim aeltesten bekannten Commit, nicht vor einem Jahr", async () => {
|
||||
// Nur eine halbe Seite, zehn Tage zurueck: alles davor ist unbekannt.
|
||||
const kalender = await calendarByPaging(async () => commits(10, 0), JETZT);
|
||||
expect(kalender?.from).toBe("2026-07-17");
|
||||
expect(kalender?.to).toBe("2026-07-26");
|
||||
expect(kalender?.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("hoert auf, sobald eine Seite nicht mehr voll ist", async () => {
|
||||
const ladeSeite = vi.fn(async (seite: number) =>
|
||||
seite === 1 ? commits(CALENDAR_PAGE_SIZE, 0) : commits(5, CALENDAR_PAGE_SIZE),
|
||||
);
|
||||
await calendarByPaging(ladeSeite, JETZT);
|
||||
expect(ladeSeite).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("deckelt die Zahl der Seiten und sagt es", async () => {
|
||||
// Immer volle Seiten innerhalb des Zeitraums: ohne Deckel liefe das ewig.
|
||||
const ladeSeite = vi.fn(async () =>
|
||||
Array.from({ length: CALENDAR_PAGE_SIZE }, () =>
|
||||
new Date(JETZT.getTime() - 3 * TAG).toISOString(),
|
||||
),
|
||||
);
|
||||
const kalender = await calendarByPaging(ladeSeite, JETZT);
|
||||
expect(ladeSeite).toHaveBeenCalledTimes(CALENDAR_MAX_PAGES);
|
||||
expect(kalender?.truncated).toBe(true);
|
||||
});
|
||||
|
||||
it("bricht ab, wenn eine ganze Seite aelter ist als der Zeitraum", async () => {
|
||||
const ladeSeite = vi.fn(async (seite: number) =>
|
||||
seite === 1
|
||||
? commits(CALENDAR_PAGE_SIZE, 0)
|
||||
: Array.from({ length: CALENDAR_PAGE_SIZE }, () =>
|
||||
new Date(JETZT.getTime() - 400 * TAG).toISOString(),
|
||||
),
|
||||
);
|
||||
await calendarByPaging(ladeSeite, JETZT);
|
||||
expect(ladeSeite).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("uebergeht Commits mit Datum in der Zukunft", async () => {
|
||||
// Falsch gestellte Uhren gibt es; sie duerfen den Zeitraum nicht verlaengern.
|
||||
const kalender = await calendarByPaging(
|
||||
async () => [
|
||||
new Date(JETZT.getTime() + 5 * TAG).toISOString(),
|
||||
JETZT.toISOString(),
|
||||
],
|
||||
JETZT,
|
||||
);
|
||||
expect(kalender?.to).toBe("2026-07-26");
|
||||
expect(calendarTotal(kalender!)).toBe(1);
|
||||
});
|
||||
|
||||
it("uebergeht Unbrauchbares, statt daran zu scheitern", async () => {
|
||||
const kalender = await calendarByPaging(
|
||||
async () => [null, "gestern", "", JETZT.toISOString()],
|
||||
JETZT,
|
||||
);
|
||||
expect(calendarTotal(kalender!)).toBe(1);
|
||||
});
|
||||
|
||||
it("laesst Tage ohne Commits weg", async () => {
|
||||
// Ein Jahr als Liste waeren 365 Eintraege, die meisten davon Nullen.
|
||||
const kalender = await calendarByPaging(
|
||||
async () => [JETZT.toISOString(), new Date(JETZT.getTime() - 30 * TAG).toISOString()],
|
||||
JETZT,
|
||||
);
|
||||
expect(Object.keys(kalender!.days)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Commits je Tag ueber ein Jahr – die Grundlage der Heatmap.
|
||||
*
|
||||
* Getrennt vom uebrigen Abgleich, weil es zusaetzliche Aufrufe kostet: der
|
||||
* Kalender wird hoechstens einmal am Tag geholt. Von Stunde zu Stunde
|
||||
* aendert sich an einem Jahresueberblick ohnehin nichts Sichtbares.
|
||||
*
|
||||
* Wichtig ist die Ehrlichkeit ueber den Zeitraum. Wo es keine
|
||||
* Jahresstatistik gibt, reichen die Daten nur so weit zurueck wie die
|
||||
* abgerufenen Seiten – dann faengt die Heatmap dort an und tut nicht so, als
|
||||
* waere ein Jahr lang nichts passiert. Diesen Fehler hatte die Verlaufslinie
|
||||
* schon einmal.
|
||||
*/
|
||||
|
||||
/** Wie weit die Heatmap hoechstens zurueckreicht. */
|
||||
export const CALENDAR_DAYS = 365;
|
||||
|
||||
/**
|
||||
* Hoechstzahl Seiten, wo seitenweise geholt werden muss. Fuenf Seiten sind
|
||||
* 500 Commits – genug fuer die allermeisten Repositories und wenig genug,
|
||||
* um kein fremdes Kontingent zu sprengen.
|
||||
*/
|
||||
export const CALENDAR_MAX_PAGES = 5;
|
||||
export const CALENDAR_PAGE_SIZE = 100;
|
||||
|
||||
export interface CommitCalendar {
|
||||
/** Erster Tag, fuer den wirklich Daten vorliegen (yyyy-mm-dd). */
|
||||
from: string;
|
||||
/** Letzter beruecksichtigter Tag (yyyy-mm-dd). */
|
||||
to: string;
|
||||
/** Nur Tage mit Commits: { "2026-07-26": 3 }. Die Nullen ergaenzt die Anzeige. */
|
||||
days: Record<string, number>;
|
||||
/**
|
||||
* "stats" = Jahresstatistik des Anbieters, der Zeitraum ist vollstaendig.
|
||||
* "commits" = so weit, wie die Seiten zurueckreichten.
|
||||
*/
|
||||
source: "stats" | "commits";
|
||||
/** Der Deckel hat gegriffen; aeltere Commits fehlen. */
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/** Tag im Format yyyy-mm-dd, in UTC – so liefern es die Anbieter. */
|
||||
export function dayKey(value: Date): string {
|
||||
return value.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** Der Tag, ab dem der Kalender hoechstens reicht. */
|
||||
export function calendarSince(now: Date = new Date()): Date {
|
||||
return new Date(now.getTime() - CALENDAR_DAYS * 86_400_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Holt seitenweise Commit-Zeitpunkte und zaehlt sie zu Tagen zusammen.
|
||||
*
|
||||
* Abgebrochen wird, sobald eine Seite nicht mehr voll ist (dann gibt es
|
||||
* nichts weiter), sobald die Seite vollstaendig aus der Zeit vor dem
|
||||
* Zeitraum stammt, oder wenn der Deckel greift.
|
||||
*/
|
||||
export async function calendarByPaging(
|
||||
ladeSeite: (seite: number) => Promise<Array<string | null>>,
|
||||
now: Date = new Date(),
|
||||
): Promise<CommitCalendar | null> {
|
||||
const grenze = calendarSince(now).getTime();
|
||||
const days: Record<string, number> = {};
|
||||
let aeltester: number | null = null;
|
||||
let gedeckelt = false;
|
||||
|
||||
for (let seite = 1; seite <= CALENDAR_MAX_PAGES; seite += 1) {
|
||||
const daten = await ladeSeite(seite);
|
||||
if (daten.length === 0) break;
|
||||
|
||||
let innerhalb = 0;
|
||||
for (const value of daten) {
|
||||
if (!value) continue;
|
||||
const time = Date.parse(value);
|
||||
if (Number.isNaN(time)) continue;
|
||||
// Ein Commit-Datum in der Zukunft kommt vor – falsch gestellte Uhren.
|
||||
if (time > now.getTime()) continue;
|
||||
if (time < grenze) continue;
|
||||
|
||||
innerhalb += 1;
|
||||
const key = dayKey(new Date(time));
|
||||
days[key] = (days[key] ?? 0) + 1;
|
||||
if (aeltester === null || time < aeltester) aeltester = time;
|
||||
}
|
||||
|
||||
// Nicht mehr voll: das war die letzte Seite.
|
||||
if (daten.length < CALENDAR_PAGE_SIZE) break;
|
||||
// Die ganze Seite lag schon vor dem Zeitraum – weiter zurueck lohnt nicht.
|
||||
if (innerhalb === 0) break;
|
||||
|
||||
if (seite === CALENDAR_MAX_PAGES) gedeckelt = true;
|
||||
}
|
||||
|
||||
if (aeltester === null) return null;
|
||||
|
||||
return {
|
||||
from: dayKey(new Date(aeltester)),
|
||||
to: dayKey(now),
|
||||
days,
|
||||
source: "commits",
|
||||
truncated: gedeckelt,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wie viele Commits der Kalender insgesamt kennt. */
|
||||
export function calendarTotal(calendar: CommitCalendar): number {
|
||||
return Object.values(calendar.days).reduce((sum, value) => sum + value, 0);
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import { getJson, getJsonSafe, normalizeBaseUrl, shortSha, toIso } from "./http";
|
||||
import {
|
||||
CALENDAR_PAGE_SIZE,
|
||||
calendarByPaging,
|
||||
calendarSince,
|
||||
type CommitCalendar,
|
||||
} from "./calendar";
|
||||
import type {
|
||||
BranchInfo,
|
||||
CiInfo,
|
||||
@@ -219,6 +225,27 @@ export class GiteaClient implements GitClient {
|
||||
commitActivity: bucketCommitActivity(mappedCommits.map((commit) => commit.date)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gitea kennt keine Jahresstatistik ueber die API, also seitenweise.
|
||||
* `stat=false` und `verification=false` sparen dabei spuerbar Rechenzeit
|
||||
* auf der Gegenseite – gebraucht wird nur das Datum.
|
||||
*/
|
||||
async fetchCommitCalendar(ref: RepoRef): Promise<CommitCalendar | null> {
|
||||
const base = `${this.apiBase}/repos/${encodeURIComponent(ref.owner)}/${encodeURIComponent(ref.name)}`;
|
||||
const seit = calendarSince().toISOString();
|
||||
|
||||
// getJson und nicht getJsonSafe: ein Rate-Limit darf nicht als "keine
|
||||
// Daten" durchgehen – siehe maybeRefreshCalendar.
|
||||
return calendarByPaging(async (seite) => {
|
||||
const commits = await getJson<GiteaCommit[]>(
|
||||
`${base}/commits?limit=${CALENDAR_PAGE_SIZE}&page=${seite}` +
|
||||
`&stat=false&verification=false&files=false&since=${encodeURIComponent(seit)}`,
|
||||
{ headers: this.headers() },
|
||||
);
|
||||
return commits.map((commit) => toIso(commit.commit?.author?.date));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function mapCommitStatus(state: string): CiState {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
BranchInfo,
|
||||
CiInfo,
|
||||
CiState,
|
||||
CommitCalendar,
|
||||
CommitInfo,
|
||||
ConnectionCheck,
|
||||
GitClient,
|
||||
@@ -14,6 +15,7 @@ import type {
|
||||
TagInfo,
|
||||
TicketInfo,
|
||||
} from "./types";
|
||||
import { dayKey } from "./calendar";
|
||||
import { GitApiError, bucketCommitActivity } from "./types";
|
||||
|
||||
/**
|
||||
@@ -206,6 +208,58 @@ export class GitHubClient implements GitClient {
|
||||
commitActivity: bucketCommitActivity(mappedCommits.map((commit) => commit.date)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub fuehrt die Statistik selbst: /stats/commit_activity liefert 52
|
||||
* Wochen mit Tageswerten in einem einzigen Aufruf. Das ist deutlich
|
||||
* sparsamer, als ein Jahr Commits seitenweise abzuholen.
|
||||
*
|
||||
* Die Statistik wird bei Bedarf erst berechnet; dann antwortet GitHub mit
|
||||
* 202 und einem leeren Rumpf – daher der leere Fall unten.
|
||||
*
|
||||
* Bewusst getJson und nicht getJsonSafe: ein Rate-Limit oder ein Ausfall
|
||||
* darf nicht als "keine Daten" durchgehen. Der Fehler geht nach oben, und
|
||||
* der naechste Abgleich versucht es erneut.
|
||||
*/
|
||||
async fetchCommitCalendar(ref: RepoRef): Promise<CommitCalendar | null> {
|
||||
const base = `${this.apiBase}/repos/${encodeURIComponent(ref.owner)}/${encodeURIComponent(ref.name)}`;
|
||||
const wochen = await getJson<GitHubWeek[]>(`${base}/stats/commit_activity`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
|
||||
if (!Array.isArray(wochen) || wochen.length === 0) {
|
||||
// Entweder rechnet GitHub noch, oder das Repository hat keine Commits.
|
||||
// Ersatzweise aus den geholten Commits zu bauen waere irrefuehrend –
|
||||
// das taete so, als reichte der Zeitraum ein Jahr zurueck.
|
||||
return null;
|
||||
}
|
||||
|
||||
const days: Record<string, number> = {};
|
||||
let von: string | null = null;
|
||||
const heute = dayKey(new Date());
|
||||
|
||||
for (const woche of wochen) {
|
||||
if (!woche?.week || !Array.isArray(woche.days)) continue;
|
||||
woche.days.forEach((anzahl, index) => {
|
||||
const tag = dayKey(new Date((woche.week + index * 86_400) * 1000));
|
||||
if (tag > heute) return;
|
||||
if (von === null || tag < von) von = tag;
|
||||
if (anzahl > 0) days[tag] = anzahl;
|
||||
});
|
||||
}
|
||||
|
||||
if (von === null) return null;
|
||||
|
||||
return { from: von, to: heute, days, source: "stats", truncated: false };
|
||||
}
|
||||
}
|
||||
|
||||
interface GitHubWeek {
|
||||
/** Unix-Zeit des Wochenanfangs (Sonntag). */
|
||||
week: number;
|
||||
/** Sieben Werte, Sonntag bis Samstag. */
|
||||
days: number[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** GitHub trennt Lauf-Status und Ergebnis; hier auf einen Wert zusammenfuehren. */
|
||||
|
||||
+32
-3
@@ -1,4 +1,10 @@
|
||||
import { getJson, getJsonSafe, normalizeBaseUrl, shortSha, toIso } from "./http";
|
||||
import {
|
||||
CALENDAR_PAGE_SIZE,
|
||||
calendarByPaging,
|
||||
calendarSince,
|
||||
type CommitCalendar,
|
||||
} from "./calendar";
|
||||
import type {
|
||||
BranchInfo,
|
||||
CiInfo,
|
||||
@@ -76,10 +82,13 @@ export class GitLabClient implements GitClient {
|
||||
});
|
||||
}
|
||||
|
||||
/** "gruppe/sub/projekt" URL-kodiert – so adressiert GitLab ein Projekt. */
|
||||
private projectPath(ref: RepoRef): string {
|
||||
return encodeURIComponent([ref.owner, ref.name].filter(Boolean).join("/"));
|
||||
}
|
||||
|
||||
async fetchRepo(ref: RepoRef): Promise<RepoSnapshotData> {
|
||||
const path = [ref.owner, ref.name].filter(Boolean).join("/");
|
||||
const encoded = encodeURIComponent(path);
|
||||
const base = `${this.apiBase}/projects/${encoded}`;
|
||||
const base = `${this.apiBase}/projects/${this.projectPath(ref)}`;
|
||||
const headers = this.headers();
|
||||
|
||||
const project = await getJson<GitLabProject>(`${base}?statistics=true`, { headers });
|
||||
@@ -198,6 +207,26 @@ export class GitLabClient implements GitClient {
|
||||
commitActivity: bucketCommitActivity(mappedCommits.map((commit) => commit.date)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GitLab kennt keine fertige Jahresstatistik, also seitenweise mit `since`.
|
||||
* Der Deckel in calendarByPaging begrenzt das auf wenige Aufrufe.
|
||||
*/
|
||||
async fetchCommitCalendar(ref: RepoRef): Promise<CommitCalendar | null> {
|
||||
const base = `${this.apiBase}/projects/${this.projectPath(ref)}`;
|
||||
const seit = calendarSince().toISOString();
|
||||
|
||||
// getJson und nicht getJsonSafe: ein Rate-Limit darf nicht als "keine
|
||||
// Daten" durchgehen – siehe maybeRefreshCalendar.
|
||||
return calendarByPaging(async (seite) => {
|
||||
const commits = await getJson<GitLabCommit[]>(
|
||||
`${base}/repository/commits?per_page=${CALENDAR_PAGE_SIZE}&page=${seite}` +
|
||||
`&since=${encodeURIComponent(seit)}`,
|
||||
{ headers: this.headers() },
|
||||
);
|
||||
return commits.map((commit) => toIso(commit.committed_date ?? commit.created_at));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function mapPipelineState(status: string | null): CiState {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { GitProvider } from "@prisma/client";
|
||||
import type { CommitCalendar } from "./calendar";
|
||||
|
||||
export type { CommitCalendar };
|
||||
|
||||
export type ProviderKind = GitProvider;
|
||||
|
||||
@@ -171,6 +174,13 @@ export interface GitClient {
|
||||
listRepos(query?: string): Promise<RepoListItem[]>;
|
||||
/** Vollstaendiger Stand eines Repositories. */
|
||||
fetchRepo(ref: RepoRef): Promise<RepoSnapshotData>;
|
||||
/**
|
||||
* Commits je Tag ueber ein Jahr – fuer die Heatmap.
|
||||
*
|
||||
* Getrennt von fetchRepo, weil es zusaetzliche Aufrufe kostet und nur
|
||||
* hoechstens einmal am Tag noetig ist. null heisst: nichts zu holen.
|
||||
*/
|
||||
fetchCommitCalendar(ref: RepoRef): Promise<CommitCalendar | null>;
|
||||
}
|
||||
|
||||
/** Fehler mit HTTP-Kontext, damit die UI verstaendliche Meldungen zeigen kann. */
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Repository } from "@prisma/client";
|
||||
import { recordActivity, shorten } from "@/lib/activity";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { clientForConnection, createClient, parseRepoUrl } from "@/lib/git";
|
||||
import type { GitClient } from "@/lib/git/types";
|
||||
import { notifyAfterSync } from "@/lib/notify";
|
||||
import { repoTitle } from "@/lib/repositories";
|
||||
import type { RepoSnapshotData } from "@/lib/git/types";
|
||||
@@ -57,6 +58,9 @@ export async function syncRepository(repositoryId: string): Promise<SyncResult>
|
||||
try {
|
||||
const data = await client.fetchRepo(ref);
|
||||
await persistSnapshot(repository, data);
|
||||
// Erst nach dem Snapshot: die Zeile muss existieren, bevor der Kalender
|
||||
// hineingeschrieben werden kann.
|
||||
await maybeRefreshCalendar(repository.id, client, ref);
|
||||
// Nach dem Speichern, damit die Meldung den neuen Stand sieht.
|
||||
await notifyAfterSync(repository.id);
|
||||
return {
|
||||
@@ -141,6 +145,57 @@ export async function syncProject(projectId: string): Promise<ProjectSyncResult>
|
||||
};
|
||||
}
|
||||
|
||||
/** Wie lange ein geholter Kalender genuegt. */
|
||||
const CALENDAR_TTL_MS = 20 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Holt die Jahresuebersicht fuer die Heatmap – hoechstens einmal am Tag.
|
||||
*
|
||||
* Sie kostet zusaetzliche Aufrufe, bei GitLab und Gitea sogar mehrere. An
|
||||
* einem Jahresueberblick aendert sich von Stunde zu Stunde aber nichts
|
||||
* Sichtbares, und der Abgleich laeuft im Zweifel stuendlich.
|
||||
*
|
||||
* Fehler bleiben hier: der Kalender ist Beiwerk. Wenn er nicht zu holen ist,
|
||||
* soll deshalb nicht der ganze Abgleich als gescheitert gelten.
|
||||
*/
|
||||
async function maybeRefreshCalendar(
|
||||
repositoryId: string,
|
||||
client: GitClient,
|
||||
ref: { owner: string; name: string },
|
||||
): Promise<void> {
|
||||
try {
|
||||
const snapshot = await prisma.repoSnapshot.findUnique({
|
||||
where: { repositoryId },
|
||||
select: { commitCalendarAt: true },
|
||||
});
|
||||
|
||||
const zuletzt = snapshot?.commitCalendarAt?.getTime() ?? 0;
|
||||
if (Date.now() - zuletzt < CALENDAR_TTL_MS) return;
|
||||
|
||||
const calendar = await client.fetchCommitCalendar(ref);
|
||||
|
||||
// Nichts erhalten: entweder rechnet GitHub die Statistik gerade erst,
|
||||
// oder das Repository hat keine Commits. Der Zeitstempel bleibt dann
|
||||
// ungesetzt, damit es der naechste Abgleich erneut versucht – ihn hier zu
|
||||
// setzen wuerde die Heatmap fuer einen Tag unterdruecken, obwohl sie
|
||||
// vielleicht schon in Minuten bereitsteht.
|
||||
if (!calendar) return;
|
||||
|
||||
await prisma.repoSnapshot.update({
|
||||
where: { repositoryId },
|
||||
data: {
|
||||
commitCalendar: calendar as unknown as object,
|
||||
commitCalendarAt: new Date(),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
// Rate-Limit, Zeitueberschreitung, Ausfall: der Kalender ist Beiwerk und
|
||||
// soll den Abgleich nicht scheitern lassen. Ohne Zeitstempel versucht es
|
||||
// der naechste Durchgang von selbst wieder.
|
||||
console.error("[nebula] Commit-Kalender konnte nicht geholt werden:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Owner/Name aus den Feldern oder ersatzweise aus der URL bestimmen. */
|
||||
export function resolveRepoRef(
|
||||
repository: Pick<Repository, "repoOwner" | "repoName" | "repoUrl">,
|
||||
|
||||
+54
-3
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
const STATUS = ["IDEA", "OPEN", "PLANNING", "IN_DEVELOPMENT", "DONE", "ARCHIVED"] as const;
|
||||
const PROVIDERS = ["GITHUB", "GITLAB", "GITEA"] as const;
|
||||
const ACCENTS = ["violet", "cyan", "emerald", "amber", "rose", "blue"] as const;
|
||||
const TASK_STATUS = ["TODO", "DOING", "BLOCKED", "DONE"] as const;
|
||||
|
||||
const emptyToNull = (value: unknown) =>
|
||||
typeof value === "string" && value.trim() === "" ? null : value;
|
||||
@@ -31,9 +32,17 @@ export const projectCreateSchema = z.object({
|
||||
autoSync: z.boolean().default(true),
|
||||
/** Fortschritt aus dem Verhaeltnis erledigter Aufgaben berechnen. */
|
||||
progressFromTasks: z.boolean().default(false),
|
||||
/**
|
||||
* Aus welcher Vorlage. Die Stammdaten hat die Oberflaeche bereits in die
|
||||
* Felder oben uebernommen – hier zaehlen nur noch Notizen und Aufgaben,
|
||||
* die sich im Dialog nicht darstellen lassen.
|
||||
*/
|
||||
templateId: z.preprocess(emptyToNull, z.string().trim().nullable().optional()),
|
||||
});
|
||||
|
||||
export const projectUpdateSchema = projectCreateSchema.partial();
|
||||
// templateId gilt nur beim Anlegen. Ein bestehendes Projekt nachtraeglich
|
||||
// "aus einer Vorlage" zu befuellen wuerde Notizen und Aufgaben verdoppeln.
|
||||
export const projectUpdateSchema = projectCreateSchema.partial().omit({ templateId: true });
|
||||
|
||||
/**
|
||||
* Neue Reihenfolge im Brett. Uebergeben wird je betroffener Spalte die
|
||||
@@ -70,6 +79,50 @@ export const projectBulkSchema = z
|
||||
path: ["favorite"],
|
||||
});
|
||||
|
||||
// ── Projektvorlagen ──────────────────────────────────────────
|
||||
|
||||
const templateNoteSchema = z.object({
|
||||
title: z.preprocess(emptyToNull, z.string().trim().max(160).nullable().optional()),
|
||||
content: z.string().trim().min(1).max(20000),
|
||||
pinned: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
const templateTaskSchema = z.object({
|
||||
title: z.string().trim().min(1).max(200),
|
||||
description: z.preprocess(emptyToNull, z.string().trim().max(5000).nullable().optional()),
|
||||
status: z.enum(TASK_STATUS).optional().default("TODO"),
|
||||
labels: z.array(z.string().trim().min(1).max(30)).max(8).optional().default([]),
|
||||
});
|
||||
|
||||
export const templateCreateSchema = z.object({
|
||||
name: z.string().trim().min(1, "Name darf nicht leer sein").max(80),
|
||||
description: z.preprocess(emptyToNull, z.string().trim().max(280).nullable().optional()),
|
||||
summary: z.preprocess(emptyToNull, z.string().trim().max(280).nullable().optional()),
|
||||
projectDescription: z.preprocess(
|
||||
emptyToNull,
|
||||
z.string().trim().max(20000).nullable().optional(),
|
||||
),
|
||||
status: z.enum(STATUS).default("IDEA"),
|
||||
priority: z.coerce.number().int().min(1).max(4).default(2),
|
||||
accent: z.enum(ACCENTS).default("violet"),
|
||||
tags: z.array(z.string().trim().min(1).max(30)).max(12).default([]),
|
||||
progressFromTasks: z.boolean().default(false),
|
||||
notes: z.array(templateNoteSchema).max(50).default([]),
|
||||
tasks: z.array(templateTaskSchema).max(100).default([]),
|
||||
});
|
||||
|
||||
export const templateUpdateSchema = templateCreateSchema.partial();
|
||||
|
||||
/** Aus einem vorhandenen Projekt eine Vorlage machen. */
|
||||
export const templateFromProjectSchema = z.object({
|
||||
projectId: z.string().min(1),
|
||||
name: z.string().trim().min(1).max(80),
|
||||
description: z.preprocess(emptyToNull, z.string().trim().max(280).nullable().optional()),
|
||||
/** Notizen und Aufgaben mitnehmen – oder nur die Stammdaten. */
|
||||
withNotes: z.boolean().default(true),
|
||||
withTasks: z.boolean().default(true),
|
||||
});
|
||||
|
||||
// ── Repositories ─────────────────────────────────────────────
|
||||
|
||||
export const repositoryCreateSchema = z.object({
|
||||
@@ -88,8 +141,6 @@ export const repositoryUpdateSchema = repositoryCreateSchema.partial().extend({
|
||||
|
||||
// ── Aufgaben ─────────────────────────────────────────────────
|
||||
|
||||
const TASK_STATUS = ["TODO", "DOING", "BLOCKED", "DONE"] as const;
|
||||
|
||||
const dueDateField = z.preprocess(
|
||||
emptyToNull,
|
||||
z
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
Task,
|
||||
TaskStatus,
|
||||
} from "@prisma/client";
|
||||
import type { CommitCalendar } from "@/lib/git/calendar";
|
||||
import type {
|
||||
BranchInfo,
|
||||
CiInfo,
|
||||
@@ -83,6 +84,7 @@ export interface RepoListEntry {
|
||||
export type {
|
||||
ActivityKind,
|
||||
BranchInfo,
|
||||
CommitCalendar,
|
||||
CiInfo,
|
||||
CommitInfo,
|
||||
Note,
|
||||
@@ -101,6 +103,25 @@ export function asArray<T>(value: unknown): T[] {
|
||||
return Array.isArray(value) ? (value as T[]) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Der Commit-Kalender aus dem Snapshot. Prisma liefert Json als unknown, und
|
||||
* ein Datensatz aus der Zeit vor der Heatmap hat dort ein leeres Objekt –
|
||||
* beides muss hier zu null werden, statt die Anzeige zu zerlegen.
|
||||
*/
|
||||
export function asCalendar(value: unknown): CommitCalendar | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const kandidat = value as Partial<CommitCalendar>;
|
||||
if (typeof kandidat.from !== "string" || typeof kandidat.to !== "string") return null;
|
||||
if (!kandidat.days || typeof kandidat.days !== "object") return null;
|
||||
return {
|
||||
from: kandidat.from,
|
||||
to: kandidat.to,
|
||||
days: kandidat.days as Record<string, number>,
|
||||
source: kandidat.source === "stats" ? "stats" : "commits",
|
||||
truncated: Boolean(kandidat.truncated),
|
||||
};
|
||||
}
|
||||
|
||||
export function asRecord(value: unknown): Record<string, number> {
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
return value as Record<string, number>;
|
||||
|
||||
Reference in New Issue
Block a user