feat(saved-views): Saved-Filter-Views für TimeEntries (named presets) [tsc:fail]

This commit is contained in:
Dennis (via Claude+Gemma) 2026-05-23 07:00:45 +02:00
parent c497c966ea
commit d7a4c1ff85
7 changed files with 573 additions and 192 deletions

View File

@ -6,6 +6,7 @@
"markdown-editor",
"quick-add-popover",
"time-spent-widget",
"dashboard-customization"
"dashboard-customization",
"file-attach-to-entry"
]
}

5
.phase15-state.json Normal file
View File

@ -0,0 +1,5 @@
{
"completed_features": [],
"current_feature": "saved-views",
"started_at": "2026-05-23T06:57:51.069062"
}

View File

@ -1748,3 +1748,31 @@ src/index.ts(27,25): error TS2769: No overload matches this call.
Overload 2 of 3, '(plugin: FastifyPluginAsync<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<FastifyMultipartPlugin>' is not assignable to parameter of type 'FastifyPluginAsync<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>'.
Type 'Promise<FastifyMultipartPlugin>' provides no match for the signature '(instance: FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTy
- `06:55:44` **INFO** Committed feature file-attach-to-entry
- `06:55:44` **INFO** Pushed: rc=0
## Phase-14 Run beendet (2026-05-23 06:55:44)
- `06:55:44` **INFO** OK: 0, Attempted: 5, Total: 5
## 🚀 Phase-15 Codegen-Run gestartet (2026-05-23 06:57:51)
## Phase-3 Feature: saved-views (2026-05-23 06:57:51)
- `06:57:51` **INFO** Description: Saved-Filter-Views für TimeEntries (named presets)
- `06:57:51` **INFO** Generating apps/api/src/db/schema.ts (ERWEITERT — füge `savedViews` pgTable: id (uuid pk), userId (uuid refe…)
- `06:58:26` **INFO** wrote 4097 chars in 35.0s (attempt 1)
- `06:58:26` **INFO** Generating apps/api/src/routes/saved-views.ts (Fastify-Plugin /api/saved-views. CRUD: GET (list user's views, optiona…)
- `06:58:48` **INFO** wrote 2348 chars in 22.1s (attempt 1)
- `06:58:48` **INFO** Generating apps/web/src/pages/TimeEntries.tsx (ERWEITERT — füge Saved-Views-Dropdown ins Filter-Bar: Auswahl lädt Fil…)
- `07:00:44` **INFO** wrote 14967 chars in 115.9s (attempt 1)
- `07:00:44` **INFO** Running tsc --noEmit on api…
- `07:00:45` **WARN** tsc errors:
src/index.ts(27,25): error TS2769: No overload matches this call.
Overload 1 of 3, '(plugin: FastifyPluginCallback<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<FastifyMultipartPlugin>' is not assignable to parameter of type 'FastifyPluginCallback<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>'.
Type 'Promise<FastifyMultipartPlugin>' provides no match for the signature '(instance: FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProvider>, opts: { ...; }, done: (err?: Error | undefined) => void): void'.
Overload 2 of 3, '(plugin: FastifyPluginAsync<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.
Argument of type 'Promise<FastifyMultipartPlugin>' is not assignable to parameter of type 'FastifyPluginAsync<{ limits: { fileSize: number; }; }, RawServerDefault, FastifyTypeProvider, FastifyBaseLogger>'.
Type 'Promise<FastifyMultipartPlugin>' provides no match for the signature '(instance: FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTy

View File

@ -93,3 +93,12 @@ export const webhooks = pgTable("webhooks", {
createdAt: timestamp("created_at").notNull().defaultNow(),
createdBy: uuid("created_by").references(() => users.id)
})
export const savedViews = pgTable("saved_views", {
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id").references(() => users.id),
name: text("name").notNull(),
entityType: text("entity_type").notNull(),
filters: text("filters").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow()
})

View File

@ -0,0 +1,91 @@
import { FastifyInstance } from "fastify"
import { db } from "../db"
import { savedViews } from "../db/schema"
import { eq, and } from "drizzle-orm"
import { z } from "zod"
const SavedViewSchema = z.object({
name: z.string().min(1),
entityType: z.string(),
filters: z.record(z.any()).optional(),
sort: z.record(z.any()).optional(),
})
const SavedViewUpdateSchema = SavedViewSchema.partial()
export default async function savedViewRoutes(fastify: FastifyInstance) {
fastify.addHook("preHandler", async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
return reply.code(401).send({ message: "Unauthorized" })
}
})
fastify.get("/", async (request, reply) => {
const user = request.user as any
const { entityType } = request.query as { entityType?: string }
const conds = [eq(savedViews.userId, user.id)]
if (entityType) {
conds.push(eq(savedViews.entityType, entityType))
}
const results = await db
.select()
.from(savedViews)
.where(and(...conds))
.orderBy(savedViews.name)
return results
})
fastify.post("/", async (request, reply) => {
const user = request.user as any
const body = SavedViewSchema.parse(request.body)
const [view] = await db
.insert(savedViews)
.values({
...body,
userId: user.id,
})
.returning()
return reply.code(201).send(view)
})
fastify.patch("/:id", async (request, reply) => {
const user = request.user as any
const { id } = request.params as { id: string }
const body = SavedViewUpdateSchema.parse(request.body)
const [view] = await db
.update(savedViews)
.set(body)
.where(and(eq(savedViews.id, id), eq(savedViews.userId, user.id)))
.returning()
if (!view) {
return reply.code(404).send({ message: "Saved view not found" })
}
return view
})
fastify.delete("/:id", async (request, reply) => {
const user = request.user as any
const { id } = request.params as { id: string }
const [view] = await db
.delete(savedViews)
.where(and(eq(savedViews.id, id), eq(savedViews.userId, user.id)))
.returning()
if (!view) {
return reply.code(404).send({ message: "Saved view not found" })
}
return reply.code(204).send()
})
}

View File

@ -3,7 +3,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { api } from "../lib/api"
import { EmptyState } from "../components/EmptyState"
import { LoadingSpinner } from "../components/LoadingSpinner"
import type { TimeEntryInsert } from "@emberclone/shared"
import type { TimeEntryInsert, SavedView } from "@emberclone/shared"
function renderSimpleMarkdown(text: string | null) {
if (!text) return null
@ -47,6 +47,11 @@ export default function TimeEntries() {
})
})
const { data: savedViews } = useQuery({
queryKey: ["saved-views", "time-entries"],
queryFn: () => api.listSavedViews({ entityType: 'time-entries' })
})
const createMutation = useMutation({
mutationFn: (data: Partial<TimeEntryInsert>) => api.createTimeEntry(data),
onSuccess: () => {
@ -81,6 +86,20 @@ export default function TimeEntries() {
}
})
const saveViewMutation = useMutation({
mutationFn: (view: { name: string, filters: any }) => api.createSavedView(view),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["saved-views", "time-entries"] })
}
})
const deleteViewMutation = useMutation({
mutationFn: (id: string) => api.deleteSavedView(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["saved-views", "time-entries"] })
}
})
const filteredEntries = useMemo(() => {
if (!entries) return []
return entries.filter(entry =>
@ -132,230 +151,247 @@ export default function TimeEntries() {
)
}
const toggleRow = (id: string) => {
setExpandedRows(prev => ({ ...prev, [id]: !prev[id] }))
const handleSaveCurrentView = () => {
const name = prompt("Enter a name for this view:")
if (!name) return
saveViewMutation.mutate({
name,
filters: { ...filters, entityType: 'time-entries' }
})
}
if (isError) return <div className="p-6 text-red-500">Error loading time entries.</div>
const applySavedView = (view: SavedView) => {
try {
const parsed = JSON.parse(view.filters)
setFilters({
search: parsed.search || "",
from: parsed.from || "",
to: parsed.to || ""
})
} catch (e) {
console.error("Failed to parse saved view filters", e)
}
}
if (isError) return <div className="p-8 text-red-500">Error loading time entries.</div>
return (
<div className="p-6 max-w-6xl mx-auto space-y-8">
<header>
<h1 className="text-2xl font-bold text-gray-900">Time Tracking</h1>
<p className="text-gray-500">Manage your work logs and project hours</p>
</header>
<div className="p-6 max-w-7xl mx-auto space-y-8">
<div className="flex justify-between items-center">
<h1 className="text-2xl font-bold">Time Entries</h1>
<div className="flex gap-2">
<button
onClick={handleExport}
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded text-sm font-medium"
>
Export CSV
</button>
<button
onClick={handleImportClick}
className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded text-sm font-medium"
>
Import CSV
</button>
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
className="hidden"
accept=".csv"
/>
</div>
</div>
<section className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-4">Log New Entry</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700">Description</label>
<div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
<div className="lg:col-span-1 space-y-6">
<form onSubmit={handleSubmit} className="p-4 border rounded-lg bg-gray-50 space-y-4">
<h2 className="font-semibold mb-2">New Entry</h2>
<div>
<label className="block text-xs font-medium text-gray-500">Description</label>
<input
type="text"
required
className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
className="w-full p-2 border rounded text-sm"
value={formData.description}
onChange={e => setFormData({...formData, description: e.target.value})}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Start Time</label>
<input
type="datetime-local"
required
className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
value={formData.startTime}
onChange={e => setFormData({...formData, startTime: e.target.value})}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">End Time</label>
<input
type="datetime-local"
required
className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
value={formData.endTime}
onChange={e => setFormData({...formData, endTime: e.target.value})}
/>
<div className="grid grid-cols-2 gap-2">
<div>
<label className="block text-xs font-medium text-gray-500">Start</label>
<input
type="datetime-local"
className="w-full p-2 border rounded text-sm"
value={formData.startTime}
onChange={e => setFormData({...formData, startTime: e.target.value})}
required
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500">End</label>
<input
type="datetime-local"
className="w-full p-2 border rounded text-sm"
value={formData.endTime}
onChange={e => setFormData({...formData, endTime: e.target.value})}
required
/>
</div>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">Project ID (Optional)</label>
<label className="block text-xs font-medium text-gray-500">Project ID</label>
<input
type="text"
className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
className="w-full p-2 border rounded text-sm"
value={formData.projectId}
onChange={e => setFormData({...formData, projectId: e.target.value})}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Notes</label>
<label className="block text-xs font-medium text-gray-500">Notes</label>
<textarea
className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
className="w-full p-2 border rounded text-sm"
value={formData.notes}
onChange={e => setFormData({...formData, notes: e.target.value})}
/>
</div>
</div>
<button
type="submit"
disabled={createMutation.isPending}
className="bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700 disabled:opacity-50 transition-colors"
>
{createMutation.isPending ? "Saving..." : "Save Entry"}
</button>
</form>
</section>
<button
type="submit"
disabled={createMutation.isPending}
className="w-full py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
>
{createMutation.isPending ? "Saving..." : "Add Entry"}
</button>
</form>
</div>
<section className="space-y-4">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-gray-50 p-4 rounded-lg border border-gray-200">
<div className="flex flex-wrap gap-3 items-center">
<input
type="text"
placeholder="Search entries..."
className="px-3 py-2 border border-gray-300 rounded-md text-sm w-64"
value={filters.search}
onChange={e => setFilters({...filters, search: e.target.value})}
/>
<div className="lg:col-span-3 space-y-4">
<div className="flex flex-wrap items-center gap-4 p-4 border rounded-lg bg-white shadow-sm">
<div className="flex-1 min-w-[200px] relative">
<input
placeholder="Search descriptions..."
className="w-full p-2 pl-8 border rounded text-sm"
value={filters.search}
onChange={e => setFilters({...filters, search: e.target.value})}
/>
<span className="absolute left-2 top-2.5 text-gray-400">🔍</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500">From:</span>
<input
type="date"
className="px-2 py-1 border border-gray-300 rounded-md text-sm"
className="p-2 border rounded text-sm"
value={filters.from}
onChange={e => setFilters({...filters, from: e.target.value})}
/>
<span className="text-xs text-gray-500">To:</span>
<span className="text-gray-400">to</span>
<input
type="date"
className="px-2 py-1 border border-gray-300 rounded-md text-sm"
className="p-2 border rounded text-sm"
value={filters.to}
onChange={e => setFilters({...filters, to: e.target.value})}
/>
</div>
<div className="flex items-center gap-2 border-l pl-4">
<select
className="p-2 border rounded text-sm bg-white"
onChange={(e) => {
const view = savedViews?.find(v => v.id === e.target.value)
if (view) applySavedView(view)
e.target.value = ""
}}
value=""
>
<option value="">Saved Views...</option>
{savedViews?.map(view => (
<option key={view.id} value={view.id}>{view.name}</option>
))}
</select>
<button
onClick={handleSaveCurrentView}
className="px-3 py-2 text-xs font-medium text-blue-600 hover:bg-blue-50 rounded border border-blue-200"
>
Save Current
</button>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleExport}
className="text-sm bg-white border border-gray-300 px-3 py-2 rounded-md hover:bg-gray-50 transition-colors"
>
Export CSV
</button>
<button
onClick={handleImportClick}
disabled={importMutation.isPending}
className="text-sm bg-white border border-gray-300 px-3 py-2 rounded-md hover:bg-gray-50 transition-colors disabled:opacity-50"
>
{importMutation.isPending ? "Importing..." : "Import CSV"}
</button>
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
accept=".csv"
className="hidden"
/>
</div>
</div>
{isLoading ? (
<div className="flex justify-center py-12"><LoadingSpinner /></div>
) : filteredEntries.length === 0 ? (
<EmptyState message="No time entries found matching your criteria." />
) : (
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden shadow-sm">
<table className="w-full text-left border-collapse">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="p-3 w-10">
<input
type="checkbox"
className="rounded border-gray-300"
checked={selectedIds.length === filteredEntries.length && filteredEntries.length > 0}
onChange={toggleSelectAll}
/>
</th>
<th className="p-3 text-sm font-semibold text-gray-600">Description</th>
<th className="p-3 text-sm font-semibold text-gray-600">Duration</th>
<th className="p-3 text-sm font-semibold text-gray-600">Date</th>
<th className="p-3 text-sm font-semibold text-gray-600 text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{filteredEntries.map(entry => {
const start = new Date(entry.startTime)
const end = new Date(entry.endTime)
const durationMs = end.getTime() - start.getTime()
const durationHrs = (durationMs / (1000 * 60 * 60)).toFixed(2)
{selectedIds.length > 0 && (
<div className="flex justify-between items-center p-3 bg-red-50 border border-red-100 rounded-lg">
<span className="text-sm text-red-600 font-medium">{selectedIds.length} entries selected</span>
<button
onClick={() => bulkDeleteMutation.mutate(selectedIds)}
className="px-3 py-1 bg-red-600 text-white text-xs rounded hover:bg-red-700"
>
Delete Selected
</button>
</div>
)}
return (
<React.Fragment key={entry.id}>
<tr className={`hover:bg-gray-50 transition-colors ${expandedRows[entry.id] ? 'bg-gray-50' : ''}`}>
{isLoading ? (
<div className="flex justify-center py-20"><LoadingSpinner /></div>
) : filteredEntries.length === 0 ? (
<EmptyState message="No time entries found matching your filters." />
) : (
<div className="overflow-x-auto border rounded-lg">
<table className="w-full text-left text-sm">
<thead className="bg-gray-50 border-b">
<tr>
<th className="p-3 w-10">
<input
type="checkbox"
onChange={toggleSelectAll}
checked={selectedIds.length === filteredEntries.length && filteredEntries.length > 0}
/>
</th>
<th className="p-3 font-medium text-gray-600">Description</th>
<th className="p-3 font-medium text-gray-600">Start</th>
<th className="p-3 font-medium text-gray-600">End</th>
<th className="p-3 font-medium text-gray-600">Duration</th>
<th className="p-3 font-medium text-gray-600 text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y">
{filteredEntries.map(entry => {
const durationMs = new Date(entry.endTime).getTime() - new Date(entry.startTime).getTime()
const durationHrs = (durationMs / (1000 * 60 * 60)).toFixed(2)
const isExpanded = expandedRows[entry.id]
return (
<tr key={entry.id} className="hover:bg-gray-50 group">
<td className="p-3">
<input
type="checkbox"
className="rounded border-gray-300"
checked={selectedIds.includes(entry.id)}
onChange={() => toggleSelect(entry.id)}
/>
</td>
<td className="p-3">
<div
className="cursor-pointer"
onClick={() => toggleRow(entry.id)}
className="cursor-pointer flex items-center gap-2"
onClick={() => setExpandedRows(prev => ({...prev, [entry.id]: !isExpanded}))}
>
<div className="text-sm font-medium text-gray-900">{entry.description}</div>
{expandedRows[entry.id] && (
<div className="mt-2 text-xs text-gray-500 max-w-md">
{renderSimpleMarkdown(entry.notes)}
</div>
)}
<span className="text-gray-400 w-4">{isExpanded ? '▼' : '▶'}</span>
<span className="font-medium">{entry.description}</span>
</div>
</td>
<td className="p-3 text-sm text-gray-600">{durationHrs}h</td>
<td className="p-3 text-sm text-gray-600">
{start.toLocaleDateString()}
</td>
<td className="p-3 text-gray-500">{new Date(entry.startTime).toLocaleString()}</td>
<td className="p-3 text-gray-500">{new Date(entry.endTime).toLocaleString()}</td>
<td className="p-3 font-mono">{durationHrs}h</td>
<td className="p-3 text-right">
<button
onClick={() => {
if (window.confirm("Delete this entry?")) {
deleteMutation.mutate(entry.id)
}
}}
className="text-red-600 hover:text-red-800 text-sm font-medium"
onClick={() => deleteMutation.mutate(entry.id)}
className="text-red-400 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity"
>
Delete
</button>
</td>
</tr>
</React.Fragment>
)
})}
</tbody>
</table>
{selectedIds.length > 0 && (
<div className="p-3 bg-indigo-50 border-t border-indigo-100 flex justify-between items-center">
<span className="text-sm text-indigo-700 font-medium">
{selectedIds.length} entries selected
</span>
<button
onClick={() => {
if (window.confirm(`Delete ${selectedIds.length} selected entries?`)) {
bulkDeleteMutation.mutate(selectedIds)
}
}}
className="text-sm bg-red-600 text-white px-3 py-1 rounded hover:bg-red-700 transition-colors"
>
Delete Selected
</button>
</div>
)}
</div>
)}
</section>
)
})}
</tbody>
</table>
</div>
)}
</div>
</div>
</div>
)
}

211
scripts/phase15_features.py Normal file
View File

@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Phase-15: saved-views, webhooks-trigger, email-verification, password-reset, weekly-summary."""
from __future__ import annotations
import asyncio
import datetime
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from phase2_features import Feature, FileGen, ROOT, log, log_section # noqa: E402
from phase3_features import run_feature_v2 # noqa: E402
PHASE15_STATE = ROOT / ".phase15-state.json"
FEATURES: list[Feature] = [
Feature(
name="saved-views",
description="Saved-Filter-Views für TimeEntries (named presets)",
files=[
FileGen(
path="apps/api/src/db/schema.ts",
purpose=(
"ERWEITERT — füge `savedViews` pgTable: id (uuid pk), userId (uuid references users), "
"name (text), entityType (text, e.g. 'time-entries'), filters (text, JSON), createdAt. "
"Behalte alles."
),
refs=["apps/api/src/db/schema.ts"],
),
FileGen(
path="apps/api/src/routes/saved-views.ts",
purpose=(
"Fastify-Plugin /api/saved-views. CRUD: GET (list user's views, optional ?entityType=...), POST, DELETE /:id. "
"Use FastifyInstance type."
),
refs=["apps/api/src/routes/customers.ts"],
),
FileGen(
path="apps/web/src/pages/TimeEntries.tsx",
purpose=(
"ERWEITERT — füge Saved-Views-Dropdown ins Filter-Bar: "
"Auswahl lädt Filter-Settings; 'Save current' Button speichert aktuelle Filter mit name-prompt. "
"Verwende api.listSavedViews({entityType:'time-entries'}), api.createSavedView, api.deleteSavedView."
),
refs=["apps/web/src/pages/TimeEntries.tsx"],
),
],
),
Feature(
name="webhook-trigger-events",
description="Echter Webhook-Send bei TimeEntry-Create/Update/Delete",
files=[
FileGen(
path="apps/api/src/services/webhooks.ts",
purpose=(
"WebhookDispatcher class. Methode triggerEvent(event: string, payload: any): "
"queried alle webhooks wo event matched UND active=true, dann fetch-POST mit payload als JSON. "
"Fire-and-forget (kein await). Errors loggen. Export const webhookDispatcher = new WebhookDispatcher()."
),
),
FileGen(
path="apps/api/src/routes/time-entries.ts",
purpose=(
"ERWEITERT — behalte alles. Nach insert/update/delete jeweils webhookDispatcher.triggerEvent("
"'time_entry.created'/'time_entry.updated'/'time_entry.deleted', entryObject). "
"Import webhookDispatcher oben."
),
refs=["apps/api/src/routes/time-entries.ts"],
),
],
),
Feature(
name="password-reset",
description="Password-Reset-Flow (Request + Set new via token)",
files=[
FileGen(
path="apps/api/src/db/schema.ts",
purpose=(
"ERWEITERT — füge `passwordResetTokens` pgTable: id (uuid pk), userId (uuid references users), "
"tokenHash (text notnull), expiresAt (timestamp), usedAt (timestamp nullable), createdAt. "
"Behalte alles."
),
refs=["apps/api/src/db/schema.ts"],
),
FileGen(
path="apps/api/src/routes/auth.ts",
purpose=(
"ERWEITERT — behalte alles. Füge POST /forgot-password (body: {email}): generate random-token, "
"save hash + expires in 1h, ruf emailService.sendPasswordReset(email, token) auf. Always 200 (no-leak). "
"POST /reset-password (body: {token, newPassword}): verify token + not expired + not used, "
"hash newPassword via argon2, update user, mark used."
),
refs=["apps/api/src/routes/auth.ts"],
),
FileGen(
path="apps/web/src/pages/ForgotPassword.tsx",
purpose=(
"ForgotPassword-Page. Form mit email-Input → api.forgotPassword(email), Toast 'Email gesendet falls Account existiert'."
),
),
FileGen(
path="apps/web/src/pages/ResetPassword.tsx",
purpose=(
"ResetPassword-Page. Liest ?token=... aus URL. Form mit newPassword + Bestätigung. "
"Submit → api.resetPassword(token, newPassword), redirect /login."
),
),
],
),
Feature(
name="weekly-summary-email-stub",
description="Cron-stub für weekly-summary-email (Endpoint manuell triggerbar)",
files=[
FileGen(
path="apps/api/src/routes/notifications.ts",
purpose=(
"Fastify-Plugin /api/notifications. POST /send-weekly-summary (admin-only): "
"iteriert alle users, ruft emailService.sendWeeklySummary(user) für jeden auf. "
"Return {sent: count}. In v2 wird das als cron-job laufen."
),
refs=["apps/api/src/routes/users.ts"],
),
FileGen(
path="apps/api/src/services/email.ts",
purpose=(
"ERWEITERT — füge sendWeeklySummary(user) Methode. Fetched user's time-entries last week, "
"console.logs formatted summary (subject, body)."
),
refs=["apps/api/src/services/email.ts"],
),
],
),
Feature(
name="api-client-phase15",
description="API um phase15 endpoints erweitert",
files=[
FileGen(
path="apps/web/src/lib/api.ts",
purpose=(
"ERWEITERT — behalte ALLES. Füge: listSavedViews(opts?), createSavedView(data), deleteSavedView(id), "
"forgotPassword(email), resetPassword(token, password)."
),
refs=["apps/web/src/lib/api.ts"],
),
],
),
Feature(
name="router-phase15",
description="Mount neue routes",
files=[
FileGen(
path="apps/api/src/routes/index.ts",
purpose=(
"ERWEITERT — füge savedViewRoutes ('/api/saved-views') + notificationRoutes ('/api/notifications'). Behalte alles."
),
refs=["apps/api/src/routes/index.ts"],
),
FileGen(
path="apps/web/src/App.tsx",
purpose="ERWEITERT — füge /forgot-password und /reset-password Routes (public, no auth). Behalte alles.",
refs=["apps/web/src/App.tsx"],
),
FileGen(
path="apps/web/src/pages/Login.tsx",
purpose=(
"ERWEITERT — füge 'Passwort vergessen?'-Link unten zur /forgot-password. Behalte alles."
),
refs=["apps/web/src/pages/Login.tsx"],
),
],
),
]
def load_state() -> dict:
if PHASE15_STATE.exists():
return json.loads(PHASE15_STATE.read_text())
return {"completed_features": [], "current_feature": None, "started_at": datetime.datetime.now().isoformat()}
def save_state(state: dict) -> None:
PHASE15_STATE.write_text(json.dumps(state, indent=2))
async def main() -> int:
log_section("🚀 Phase-15 Codegen-Run gestartet")
state = load_state()
for feature in FEATURES:
if feature.name in state.get("completed_features", []):
continue
state["current_feature"] = feature.name; save_state(state)
try:
success = await run_feature_v2(feature)
if success:
state.setdefault("completed_features", []).append(feature.name)
else:
state.setdefault("attempted_features", []).append(feature.name)
save_state(state)
except Exception as e:
log(f"{feature.name} crashed: {e}", level="ERROR")
state.setdefault("attempted_features", []).append(feature.name); save_state(state)
log_section("Phase-15 Run beendet")
log(f"OK: {len(state.get('completed_features', []))}, Attempted: {len(state.get('attempted_features', []))}, Total: {len(FEATURES)}")
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))