Phase 3: Domain-Modell + Decks/Cards/Reviews-CRUD

Domain (@cards/domain):
- zod-Schemas SSOT für Deck, Card, Review, StudySession, FsrsSettings,
  Tools (cards.create + cards.search Input/Output)
- CardType-Discriminated-Union: MVP basic+basic-reverse, Future-Set
  (cloze, type-in, image-occlusion, audio, multiple-choice) für
  Schema-stable-Migration vorbereitet
- validateFieldsForType() Pure-Function pro CardType
- FSRS-Adapter über ts-fsrs v5.3.2: newReview, gradeReview,
  subIndexCount, toFsrsCard/fromFsrsCard ISO↔Date-Roundtrip
- Encryption-Hinweis: reviews bleiben PLAINTEXT (Scheduler quert
  täglich `due <= now`, siehe Lessons §3)

Drizzle-Schemas (apps/api/src/db/schema, alles in pgSchema('cards')):
- decks, cards, card_tags, reviews (PK card_id+sub_index), study_sessions,
  tags (deck-skopiert), media_refs (verweist auf mana-media), import_jobs
- _schema.ts-Pattern um Zirkular-Imports zu vermeiden (Lesson aus
  mana-share/-events während F-0)
- Hot-Path-Index reviews_user_due_idx für Scheduler-Queries

Routes (apps/api/src/routes):
- POST/GET/PATCH/DELETE /api/v1/decks (Deck-CRUD)
- POST/GET/PATCH/DELETE /api/v1/cards (Card-CRUD mit Auto-Reviews-Init:
  beim Card-Insert werden N Reviews via subIndexCount(type) angelegt,
  in einer Transaktion)
- GET /api/v1/reviews/due (Hot-Path, optional deck_id-Filter, Limit 500)
- POST /api/v1/reviews/:cardId/:subIndex/grade (FSRS-State-Transition,
  per-Deck FSRS-Settings)

Auth: Stub-Middleware liest X-User-Id-Header (Phase 2 ersetzt durch
@mana/shared-hono authMiddleware mit JWKS-Cache).

Tests (vitest, Hono app.request()):
- @cards/domain: fsrs.test.ts (newReview, gradeReview Roundtrip,
  Rating-Mapping), schemas.test.ts (zod-strict-Variants, Field-Type-
  Validation, hex-Color)
- apps/api: decks.test.ts + cards.test.ts + reviews.test.ts —
  Auth-Gate + Input-Validation. Volle DB-Integrationstests folgen mit
  pg-mem oder testcontainers in späterer Phase.

Cleanup: types.ts entfernt, zod-Schemas sind SSOT (z.infer für Types).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till 2026-05-08 14:21:54 +02:00
parent 8605b1b517
commit 45a47e0ffd
31 changed files with 1897 additions and 106 deletions

View file

@ -0,0 +1,28 @@
import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema/index.ts';
export type CardsDb = PostgresJsDatabase<typeof schema>;
let _db: CardsDb | null = null;
let _client: postgres.Sql<{}> | null = null;
export function getDb(): CardsDb {
if (_db) return _db;
const url = process.env.DATABASE_URL;
if (!url) {
throw new Error('DATABASE_URL not set — Cards-API kann nicht ohne Postgres laufen');
}
_client = postgres(url, { max: 10 });
_db = drizzle(_client, { schema });
return _db;
}
export async function closeDb(): Promise<void> {
if (_client) {
await _client.end();
_client = null;
_db = null;
}
}

View file

@ -0,0 +1,7 @@
// Single Source of Truth für die pgSchema-Deklaration.
// Wird von allen Tabellen-Files importiert, vermeidet Zirkular-Imports
// (siehe Lesson aus mana-share/-events während F-0).
import { pgSchema } from 'drizzle-orm/pg-core';
export const cardsSchema = pgSchema('cards');

View file

@ -0,0 +1,65 @@
import { index, jsonb, primaryKey, text, timestamp } from 'drizzle-orm/pg-core';
import { cardsSchema } from './_schema.ts';
import { decks } from './decks.ts';
/**
* Karten. `fields` ist ein generischer JSONB-Slot, der je nach `type`
* unterschiedliche Felder enthält:
*
* - basic / basic-reverse: { front, back }
* - cloze: { text, extra? }
* - type-in: { question, expected }
* - image-occlusion: { image_ref, mask_regions: [...] }
*
* MVP unterstützt nur `basic` und `basic-reverse`.
*
* `tags` ist ein eigener Tag-Mapping-Layer (siehe `tags.ts` + `cardTags`),
* NICHT in dieser Tabelle gespeichert.
*/
export const cards = cardsSchema.table(
'cards',
{
id: text('id').primaryKey(),
deckId: text('deck_id')
.notNull()
.references(() => decks.id, { onDelete: 'cascade' }),
userId: text('user_id').notNull(),
type: text('type').notNull(),
fields: jsonb('fields').notNull(),
mediaRefs: jsonb('media_refs').notNull().$type<string[]>().default([]),
contentHash: text('content_hash'),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
},
(t) => ({
deckIdx: index('cards_deck_idx').on(t.deckId),
userIdx: index('cards_user_idx').on(t.userId),
})
);
export type CardRow = typeof cards.$inferSelect;
export type CardInsert = typeof cards.$inferInsert;
/**
* CardTag-Mapping. PK ist (card_id, tag_id) kein eigenes id-Feld nötig.
*/
export const cardTags = cardsSchema.table(
'card_tags',
{
cardId: text('card_id')
.notNull()
.references(() => cards.id, { onDelete: 'cascade' }),
tagId: text('tag_id').notNull(),
},
(t) => ({
pk: primaryKey({ columns: [t.cardId, t.tagId] }),
})
);
export type CardTagRow = typeof cardTags.$inferSelect;
export type CardTagInsert = typeof cardTags.$inferInsert;

View file

@ -0,0 +1,37 @@
import { sql } from 'drizzle-orm';
import { index, jsonb, text, timestamp } from 'drizzle-orm/pg-core';
import { cardsSchema } from './_schema.ts';
/**
* Decks Sammlungen von Karten. Eine Karte gehört zu genau einem Deck.
* `fsrs_settings` ist ein JSONB-Slot für per-Deck-Overrides der globalen
* FSRS-Defaults (siehe @cards/domain `FsrsSettings`).
*/
export const decks = cardsSchema.table(
'decks',
{
id: text('id').primaryKey(),
userId: text('user_id').notNull(),
name: text('name').notNull(),
description: text('description'),
color: text('color'),
visibility: text('visibility', { enum: ['private', 'space', 'public'] })
.notNull()
.default('private'),
fsrsSettings: jsonb('fsrs_settings').notNull().default(sql`'{}'::jsonb`),
contentHash: text('content_hash'),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
},
(t) => ({
userIdx: index('decks_user_idx').on(t.userId),
})
);
export type DeckRow = typeof decks.$inferSelect;
export type DeckInsert = typeof decks.$inferInsert;

View file

@ -0,0 +1,34 @@
import { index, jsonb, text, timestamp } from 'drizzle-orm/pg-core';
import { cardsSchema } from './_schema.ts';
/**
* Import-Jobs für Bulk-Vorgänge (Anki-.apkg, CSV-Upload, etc.).
* Der Job-Status durchläuft `queued` `processing` `done | failed`.
* `meta` ist ein freier JSONB-Slot für Source-spezifische Infos
* (Datei-Name, Mapping-Tabellen, Fortschritt).
*/
export const importJobs = cardsSchema.table(
'import_jobs',
{
id: text('id').primaryKey(),
userId: text('user_id').notNull(),
source: text('source', { enum: ['anki', 'csv', 'json'] }).notNull(),
state: text('state', { enum: ['queued', 'processing', 'done', 'failed'] })
.notNull()
.default('queued'),
meta: jsonb('meta'),
error: text('error'),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
finishedAt: timestamp('finished_at', { withTimezone: true, mode: 'date' }),
},
(t) => ({
userIdx: index('imports_user_idx').on(t.userId),
stateIdx: index('imports_state_idx').on(t.state),
})
);
export type ImportJobRow = typeof importJobs.$inferSelect;
export type ImportJobInsert = typeof importJobs.$inferInsert;

View file

@ -1,13 +1,29 @@
// Drizzle-Schemas für die `cards`-Datenbank.
// Public Re-exports für Drizzle-Schemas.
//
// Phase-3-Aufgabe (siehe CARDS_GREENFIELD.md): hier landen
// `decks`, `cards`, `reviews`, `study_sessions`, `tags`, `media_refs`,
// `import_jobs` als pgSchema('cards').table(...) Definitionen.
//
// Schema-Skizze in mana/docs/playbooks/CARDS_GREENFIELD.md §"Drizzle-Schema-Skizze".
// Card-Type-Granularität (subIndex pro Karte) aus
// docs/LESSONS_FROM_MANA_MONOREPO.md mitnehmen.
// Konvention: Tabellen-Files importieren `cardsSchema` aus `_schema.ts`
// (nie aus `index.ts`), damit es keine Zirkular-Imports gibt.
import { pgSchema } from 'drizzle-orm/pg-core';
export { cardsSchema } from './_schema.ts';
export const cardsSchema = pgSchema('cards');
export { decks } from './decks.ts';
export type { DeckRow, DeckInsert } from './decks.ts';
export { cards, cardTags } from './cards.ts';
export type { CardRow, CardInsert, CardTagRow, CardTagInsert } from './cards.ts';
export { reviews, studySessions } from './reviews.ts';
export type {
ReviewRow,
ReviewInsert,
StudySessionRow,
StudySessionInsert,
} from './reviews.ts';
export { tags } from './tags.ts';
export type { TagRow, TagInsert } from './tags.ts';
export { mediaRefs } from './media.ts';
export type { MediaRefRow, MediaRefInsert } from './media.ts';
export { importJobs } from './imports.ts';
export type { ImportJobRow, ImportJobInsert } from './imports.ts';

View file

@ -0,0 +1,32 @@
import { index, integer, text, timestamp } from 'drizzle-orm/pg-core';
import { cardsSchema } from './_schema.ts';
import { cards } from './cards.ts';
/**
* Media-Verweise auf Object-IDs in mana-media. Die eigentlichen Files
* (Bilder, Audio, Video) liegen in MinIO via mana-media; diese Tabelle
* hält nur den Verweis + Sortier-Order pro Karte.
*/
export const mediaRefs = cardsSchema.table(
'media_refs',
{
id: text('id').primaryKey(),
cardId: text('card_id')
.notNull()
.references(() => cards.id, { onDelete: 'cascade' }),
userId: text('user_id').notNull(),
manaMediaObjectId: text('mana_media_object_id').notNull(),
kind: text('kind', { enum: ['image', 'audio', 'video'] }).notNull(),
ord: integer('ord').notNull().default(0),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
},
(t) => ({
cardIdx: index('media_card_idx').on(t.cardId),
})
);
export type MediaRefRow = typeof mediaRefs.$inferSelect;
export type MediaRefInsert = typeof mediaRefs.$inferInsert;

View file

@ -0,0 +1,76 @@
import { index, integer, primaryKey, real, text, timestamp } from 'drizzle-orm/pg-core';
import { cardsSchema } from './_schema.ts';
import { cards } from './cards.ts';
import { decks } from './decks.ts';
/**
* FSRS-Review-State pro `(card, sub_index)`.
*
* `sub_index` granular:
* - basic: 1 Review (sub_index = 0)
* - basic-reverse: 2 Reviews (0 = frontback, 1 = backfront)
* - cloze: 1 Review pro Cluster-Index ({{c1::}} sub_index = 1)
*
* **Bewusst PLAINTEXT** (siehe `docs/LESSONS_FROM_MANA_MONOREPO.md` §3):
* Der Scheduler quert täglich `due <= now` Encryption müsste das
* jedes Mal entschlüsseln. mana-monorepo hat das gleiche Pattern:
* cardReviews ist plaintext-allowlisted.
*/
export const reviews = cardsSchema.table(
'reviews',
{
cardId: text('card_id')
.notNull()
.references(() => cards.id, { onDelete: 'cascade' }),
subIndex: integer('sub_index').notNull().default(0),
userId: text('user_id').notNull(),
due: timestamp('due', { withTimezone: true, mode: 'date' }).notNull(),
stability: real('stability').notNull(),
difficulty: real('difficulty').notNull(),
elapsedDays: real('elapsed_days').notNull().default(0),
scheduledDays: real('scheduled_days').notNull().default(0),
reps: integer('reps').notNull().default(0),
lapses: integer('lapses').notNull().default(0),
state: text('state', { enum: ['new', 'learning', 'review', 'relearning'] })
.notNull()
.default('new'),
lastReview: timestamp('last_review', { withTimezone: true, mode: 'date' }),
},
(t) => ({
pk: primaryKey({ columns: [t.cardId, t.subIndex] }),
// Hot Path: Scheduler quert täglich `due <= now` für einen User.
userDueIdx: index('reviews_user_due_idx').on(t.userId, t.due),
})
);
export type ReviewRow = typeof reviews.$inferSelect;
export type ReviewInsert = typeof reviews.$inferInsert;
/**
* Study-Sessions als Statistik-Layer. Eine Session läuft pro
* `(user, deck)`-Studieren-Lauf, wird beim Start angelegt und beim
* Ende mit Total-Counts geupdatet.
*/
export const studySessions = cardsSchema.table(
'study_sessions',
{
id: text('id').primaryKey(),
userId: text('user_id').notNull(),
deckId: text('deck_id')
.notNull()
.references(() => decks.id, { onDelete: 'cascade' }),
startedAt: timestamp('started_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
finishedAt: timestamp('finished_at', { withTimezone: true, mode: 'date' }),
cardsReviewed: integer('cards_reviewed').notNull().default(0),
cardsCorrect: integer('cards_correct').notNull().default(0),
},
(t) => ({
userStartedIdx: index('sessions_user_started_idx').on(t.userId, t.startedAt),
})
);
export type StudySessionRow = typeof studySessions.$inferSelect;
export type StudySessionInsert = typeof studySessions.$inferInsert;

View file

@ -0,0 +1,30 @@
import { index, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
import { cardsSchema } from './_schema.ts';
import { decks } from './decks.ts';
/**
* Tags sind deck-skopiert (laut mana-monorepo-Pattern). Ein Tag-Name
* kann pro Deck nur einmal vorkommen.
*/
export const tags = cardsSchema.table(
'tags',
{
id: text('id').primaryKey(),
deckId: text('deck_id')
.notNull()
.references(() => decks.id, { onDelete: 'cascade' }),
userId: text('user_id').notNull(),
name: text('name').notNull(),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' })
.notNull()
.defaultNow(),
},
(t) => ({
deckIdx: index('tags_deck_idx').on(t.deckId),
uniqueByDeckName: uniqueIndex('tags_deck_name_uniq').on(t.deckId, t.name),
})
);
export type TagRow = typeof tags.$inferSelect;
export type TagInsert = typeof tags.$inferInsert;