feat(apps): create Hono compute servers for Traces, Planta, NutriPhi

Add lightweight Hono + Bun servers for server-only compute endpoints.
CRUD is handled by mana-sync, these handle AI + file upload only.

Traces: AI guide generation, location sync (Port 3026)
Planta: Photo upload (S3), AI plant analysis (Port 3022)
NutriPhi: AI meal analysis (photo+text), recommendations (Port 3023)

Each uses @manacore/shared-hono for auth/health/errors. ~100-200 LOC.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till JS 2026-03-28 16:16:57 +01:00
parent 4d26196590
commit d3d11e661d
30 changed files with 1161 additions and 221 deletions

View file

@ -0,0 +1,17 @@
{
"name": "@nutriphi/server",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "bun run --watch src/index.ts",
"start": "bun run src/index.ts"
},
"dependencies": {
"@manacore/shared-hono": "workspace:*",
"hono": "^4.7.0"
},
"devDependencies": {
"typescript": "^5.9.3"
}
}

View file

@ -0,0 +1,154 @@
/**
* NutriPhi Hono Server Compute-only endpoints
*
* Server-side logic:
* - AI meal analysis (photo + text) via mana-llm (Gemini)
* - Nutritional recommendations engine
*
* CRUD for meals, goals, favorites handled by mana-sync.
*/
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { authMiddleware, healthRoute, errorHandler, notFoundHandler } from '@manacore/shared-hono';
const PORT = parseInt(process.env.PORT || '3023', 10);
const LLM_URL = process.env.MANA_LLM_URL || 'http://localhost:3025';
const CORS_ORIGINS = (process.env.CORS_ORIGINS || 'http://localhost:5180').split(',');
const ANALYSIS_PROMPT = `Du bist ein Ernährungsexperte. Analysiere die Mahlzeit und gib ein JSON zurück mit:
{
"foods": [{"name": "...", "quantity": "...", "calories": 0}],
"totalNutrition": {"calories": 0, "protein": 0, "carbohydrates": 0, "fat": 0, "fiber": 0, "sugar": 0},
"description": "Kurze Beschreibung der Mahlzeit",
"confidence": 0.0-1.0,
"warnings": [],
"suggestions": []
}`;
const app = new Hono();
app.onError(errorHandler);
app.notFound(notFoundHandler);
app.use('*', cors({ origin: CORS_ORIGINS, credentials: true }));
app.route('/health', healthRoute('nutriphi-server'));
app.use('/api/*', authMiddleware());
// ─── Photo Analysis (server-only: Gemini Vision) ────────────
app.post('/api/v1/analysis/photo', async (c) => {
const { imageBase64, mimeType } = await c.req.json();
if (!imageBase64) return c.json({ error: 'imageBase64 required' }, 400);
try {
const res = await fetch(`${LLM_URL}/api/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [
{ role: 'system', content: ANALYSIS_PROMPT },
{
role: 'user',
content: [
{ type: 'text', text: 'Analysiere diese Mahlzeit.' },
{
type: 'image_url',
image_url: { url: `data:${mimeType || 'image/jpeg'};base64,${imageBase64}` },
},
],
},
],
model: process.env.GEMINI_MODEL || 'gemini-2.0-flash',
response_format: { type: 'json_object' },
temperature: 0.3,
}),
});
if (!res.ok) return c.json({ error: 'AI analysis failed' }, 502);
const data = await res.json();
const content = data.choices?.[0]?.message?.content;
const analysis = typeof content === 'string' ? JSON.parse(content) : content;
return c.json(analysis);
} catch (err) {
console.error('Photo analysis failed:', err);
return c.json({ error: 'Analysis failed' }, 500);
}
});
// ─── Text Analysis (server-only: Gemini) ─────────────────────
app.post('/api/v1/analysis/text', async (c) => {
const { description } = await c.req.json();
if (!description) return c.json({ error: 'description required' }, 400);
try {
const res = await fetch(`${LLM_URL}/api/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [
{ role: 'system', content: ANALYSIS_PROMPT },
{ role: 'user', content: `Analysiere diese Mahlzeit: ${description}` },
],
model: process.env.GEMINI_MODEL || 'gemini-2.0-flash',
response_format: { type: 'json_object' },
temperature: 0.3,
}),
});
if (!res.ok) return c.json({ error: 'AI analysis failed' }, 502);
const data = await res.json();
const content = data.choices?.[0]?.message?.content;
const analysis = typeof content === 'string' ? JSON.parse(content) : content;
return c.json(analysis);
} catch (err) {
console.error('Text analysis failed:', err);
return c.json({ error: 'Analysis failed' }, 500);
}
});
// ─── Recommendations (server-only: rule engine) ──────────────
app.post('/api/v1/recommendations/generate', async (c) => {
const { dailyNutrition } = await c.req.json();
const hints: Array<{ type: string; priority: string; message: string; nutrient?: string }> = [];
if (dailyNutrition) {
if (dailyNutrition.protein < 25) {
hints.push({
type: 'hint',
priority: 'medium',
message:
'Deine Proteinzufuhr ist niedrig. Versuche Hülsenfrüchte, Eier oder Joghurt einzubauen.',
nutrient: 'protein',
});
}
if (dailyNutrition.fiber < 10) {
hints.push({
type: 'hint',
priority: 'medium',
message: 'Mehr Ballaststoffe! Vollkornprodukte, Gemüse und Obst helfen.',
nutrient: 'fiber',
});
}
if (dailyNutrition.sugar > 50) {
hints.push({
type: 'hint',
priority: 'high',
message:
'Dein Zuckerkonsum ist hoch. Achte auf versteckten Zucker in Getränken und Fertigprodukten.',
nutrient: 'sugar',
});
}
}
return c.json({ recommendations: hints });
});
console.log(`nutriphi-server starting on port ${PORT}...`);
export default { port: PORT, fetch: app.fetch };

View file

@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"]
}

View file

@ -0,0 +1,20 @@
{
"name": "@planta/server",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "bun run --watch src/index.ts",
"start": "bun run src/index.ts"
},
"dependencies": {
"@manacore/shared-hono": "workspace:*",
"@manacore/shared-storage": "workspace:*",
"hono": "^4.7.0",
"drizzle-orm": "^0.38.3",
"postgres": "^3.4.5"
},
"devDependencies": {
"typescript": "^5.9.3"
}
}

View file

@ -0,0 +1,104 @@
/**
* Planta Hono Server Compute-only endpoints
*
* Server-side logic:
* - Photo upload to S3/MinIO
* - AI plant analysis via mana-llm (Gemini Vision)
* - Watering upcoming computation
*
* CRUD for plants, photos, watering handled by mana-sync.
*/
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { authMiddleware, healthRoute, errorHandler, notFoundHandler } from '@manacore/shared-hono';
const PORT = parseInt(process.env.PORT || '3022', 10);
const LLM_URL = process.env.MANA_LLM_URL || 'http://localhost:3025';
const CORS_ORIGINS = (process.env.CORS_ORIGINS || 'http://localhost:5173').split(',');
const app = new Hono();
app.onError(errorHandler);
app.notFound(notFoundHandler);
app.use('*', cors({ origin: CORS_ORIGINS, credentials: true }));
app.route('/health', healthRoute('planta-server'));
app.use('/api/*', authMiddleware());
// ─── Photo Upload (server-only: S3 storage) ─────────────────
app.post('/api/v1/photos/upload', async (c) => {
const userId = c.get('userId');
const formData = await c.req.formData();
const file = formData.get('file') as File | null;
const plantId = formData.get('plantId') as string | null;
if (!file) return c.json({ error: 'No file provided' }, 400);
if (file.size > 10 * 1024 * 1024) return c.json({ error: 'File too large (max 10MB)' }, 400);
try {
const { createPlantaStorage, generateUserFileKey, getContentType } = await import(
'@manacore/shared-storage'
);
const storage = createPlantaStorage();
const key = generateUserFileKey(userId, file.name);
const buffer = Buffer.from(await file.arrayBuffer());
const result = await storage.upload(key, buffer, {
contentType: getContentType(file.name),
public: true,
});
return c.json({ storagePath: key, publicUrl: result.url, plantId }, 201);
} catch (err) {
console.error('Upload failed:', err);
return c.json({ error: 'Upload failed' }, 500);
}
});
// ─── AI Analysis (server-only: Gemini Vision) ───────────────
app.post('/api/v1/analysis/identify', async (c) => {
const { photoUrl } = await c.req.json();
if (!photoUrl) return c.json({ error: 'photoUrl required' }, 400);
try {
const res = await fetch(`${LLM_URL}/api/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [
{
role: 'system',
content:
'Du bist ein Pflanzenexperte. Analysiere das Bild und gib JSON zurück: {scientificName, commonNames[], confidence, healthAssessment, wateringAdvice, lightAdvice, generalTips[]}',
},
{
role: 'user',
content: [
{ type: 'text', text: 'Analysiere diese Pflanze.' },
{ type: 'image_url', image_url: { url: photoUrl } },
],
},
],
model: process.env.VISION_MODEL || 'gemini-2.0-flash',
response_format: { type: 'json_object' },
}),
});
if (!res.ok) return c.json({ error: 'AI analysis failed' }, 502);
const data = await res.json();
const content = data.choices?.[0]?.message?.content;
const analysis = typeof content === 'string' ? JSON.parse(content) : content;
return c.json(analysis);
} catch (err) {
console.error('Analysis failed:', err);
return c.json({ error: 'Analysis failed' }, 500);
}
});
console.log(`planta-server starting on port ${PORT}...`);
export default { port: PORT, fetch: app.fetch };

View file

@ -0,0 +1,40 @@
import { pgTable, uuid, text, timestamp, jsonb, integer } from 'drizzle-orm/pg-core';
import { plantPhotos } from './plant-photos.schema';
import { plants } from './plants.schema';
export const plantAnalyses = pgTable('plant_analyses', {
id: uuid('id').primaryKey().defaultRandom(),
photoId: uuid('photo_id')
.references(() => plantPhotos.id, { onDelete: 'cascade' })
.notNull(),
plantId: uuid('plant_id').references(() => plants.id, { onDelete: 'cascade' }),
userId: text('user_id').notNull(),
// AI Analysis Results
identifiedSpecies: text('identified_species'),
scientificName: text('scientific_name'),
commonNames: jsonb('common_names').$type<string[]>(),
confidence: integer('confidence'),
// Plant condition
healthAssessment: text('health_assessment'),
healthDetails: text('health_details'),
issues: jsonb('issues').$type<string[]>(),
// Care recommendations
wateringAdvice: text('watering_advice'),
lightAdvice: text('light_advice'),
fertilizingAdvice: text('fertilizing_advice'),
generalTips: jsonb('general_tips').$type<string[]>(),
// Raw AI response for debugging
rawResponse: jsonb('raw_response'),
model: text('model'),
tokensUsed: integer('tokens_used'),
// Timestamps
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export type PlantAnalysis = typeof plantAnalyses.$inferSelect;
export type NewPlantAnalysis = typeof plantAnalyses.$inferInsert;

View file

@ -0,0 +1,30 @@
import { pgTable, uuid, text, timestamp, boolean, integer } from 'drizzle-orm/pg-core';
import { plants } from './plants.schema';
export const plantPhotos = pgTable('plant_photos', {
id: uuid('id').primaryKey().defaultRandom(),
plantId: uuid('plant_id').references(() => plants.id, { onDelete: 'cascade' }),
userId: text('user_id').notNull(),
// Storage
storagePath: text('storage_path').notNull(),
publicUrl: text('public_url'),
filename: text('filename').notNull(),
mimeType: text('mime_type'),
fileSize: integer('file_size'),
// Image metadata
width: integer('width'),
height: integer('height'),
// Flags
isPrimary: boolean('is_primary').default(false).notNull(),
isAnalyzed: boolean('is_analyzed').default(false).notNull(),
// Timestamps
takenAt: timestamp('taken_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export type PlantPhoto = typeof plantPhotos.$inferSelect;
export type NewPlantPhoto = typeof plantPhotos.$inferInsert;

View file

@ -0,0 +1,32 @@
import { pgTable, uuid, text, timestamp, boolean, integer } from 'drizzle-orm/pg-core';
export const plants = pgTable('plants', {
id: uuid('id').primaryKey().defaultRandom(),
userId: text('user_id').notNull(),
// Plant identity
name: text('name').notNull(),
scientificName: text('scientific_name'),
commonName: text('common_name'),
species: text('species'),
// Care info (from AI)
lightRequirements: text('light_requirements'),
wateringFrequencyDays: integer('watering_frequency_days'),
humidity: text('humidity'),
temperature: text('temperature'),
soilType: text('soil_type'),
careNotes: text('care_notes'),
// Status
isActive: boolean('is_active').default(true).notNull(),
healthStatus: text('health_status'),
// Timestamps
acquiredAt: timestamp('acquired_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
});
export type Plant = typeof plants.$inferSelect;
export type NewPlant = typeof plants.$inferInsert;

View file

@ -0,0 +1,45 @@
import { pgTable, uuid, text, timestamp, boolean, integer } from 'drizzle-orm/pg-core';
import { plants } from './plants.schema';
export const wateringSchedules = pgTable('watering_schedules', {
id: uuid('id').primaryKey().defaultRandom(),
plantId: uuid('plant_id')
.references(() => plants.id, { onDelete: 'cascade' })
.notNull(),
userId: text('user_id').notNull(),
// Schedule config
frequencyDays: integer('frequency_days').notNull(),
// Tracking
lastWateredAt: timestamp('last_watered_at', { withTimezone: true }),
nextWateringAt: timestamp('next_watering_at', { withTimezone: true }),
// Notification preferences
reminderEnabled: boolean('reminder_enabled').default(true).notNull(),
reminderHoursBefore: integer('reminder_hours_before').default(24),
// Timestamps
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
});
export type WateringSchedule = typeof wateringSchedules.$inferSelect;
export type NewWateringSchedule = typeof wateringSchedules.$inferInsert;
// Watering log for history tracking
export const wateringLogs = pgTable('watering_logs', {
id: uuid('id').primaryKey().defaultRandom(),
plantId: uuid('plant_id')
.references(() => plants.id, { onDelete: 'cascade' })
.notNull(),
userId: text('user_id').notNull(),
wateredAt: timestamp('watered_at', { withTimezone: true }).defaultNow().notNull(),
notes: text('notes'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export type WateringLog = typeof wateringLogs.$inferSelect;
export type NewWateringLog = typeof wateringLogs.$inferInsert;

View file

@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"]
}

View file

@ -0,0 +1,19 @@
{
"name": "@traces/server",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "bun run --watch src/index.ts",
"start": "bun run src/index.ts"
},
"dependencies": {
"@manacore/shared-hono": "workspace:*",
"hono": "^4.7.0",
"drizzle-orm": "^0.38.3",
"postgres": "^3.4.5"
},
"devDependencies": {
"typescript": "^5.9.3"
}
}

View file

@ -0,0 +1,15 @@
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
let db: ReturnType<typeof drizzle<typeof schema>> | null = null;
export function getDb(url: string) {
if (!db) {
const client = postgres(url, { max: 10 });
db = drizzle(client, { schema });
}
return db;
}
export type Database = ReturnType<typeof getDb>;

View file

@ -0,0 +1,108 @@
/**
* Traces Hono Server Compute-only endpoints
*
* Handles server-side logic that can't run in the browser:
* - AI guide generation (mana-llm)
* - POI discovery (mana-search)
* - Location sync with city detection
*
* CRUD for locations, cities, places, POIs handled by mana-sync.
*/
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { authMiddleware, healthRoute, errorHandler, notFoundHandler } from '@manacore/shared-hono';
import { getDb } from './db';
import { GuideService } from './services/guide';
const PORT = parseInt(process.env.PORT || '3026', 10);
const DB_URL =
process.env.DATABASE_URL || 'postgresql://manacore:devpassword@localhost:5432/traces';
const LLM_URL = process.env.MANA_LLM_URL || 'http://localhost:3025';
const SEARCH_URL = process.env.MANA_SEARCH_URL || 'http://localhost:3021';
const CORS_ORIGINS = (process.env.CORS_ORIGINS || 'http://localhost:5173').split(',');
const db = getDb(DB_URL);
const guideService = new GuideService(db, LLM_URL, SEARCH_URL);
const app = new Hono();
app.onError(errorHandler);
app.notFound(notFoundHandler);
app.use('*', cors({ origin: CORS_ORIGINS, credentials: true }));
// Health
app.route('/health', healthRoute('traces-server'));
// All compute routes require auth
app.use('/api/*', authMiddleware());
// ─── Guide Generation (server-only: AI + search) ────────────
app.post('/api/v1/guides/generate', async (c) => {
const userId = c.get('userId');
const body = await c.req.json();
const guide = await guideService.generateGuide(userId, body);
return c.json(guide, 201);
});
app.get('/api/v1/guides', async (c) => {
const userId = c.get('userId');
return c.json(await guideService.getUserGuides(userId));
});
app.get('/api/v1/guides/:id', async (c) => {
const userId = c.get('userId');
const guide = await guideService.getGuideDetail(userId, c.req.param('id'));
if (!guide) return c.json({ error: 'Not found' }, 404);
return c.json(guide);
});
app.delete('/api/v1/guides/:id', async (c) => {
const userId = c.get('userId');
await guideService.deleteGuide(userId, c.req.param('id'));
return c.json({ success: true });
});
// ─── Location Sync (server-only: city detection) ────────────
app.post('/api/v1/locations/sync', async (c) => {
const userId = c.get('userId');
const { items } = await c.req.json();
// Bulk insert locations + detect cities
const { locations } = await import('./schema');
let synced = 0;
for (const item of items || []) {
try {
await db
.insert(locations)
.values({
userId,
latitude: item.latitude,
longitude: item.longitude,
recordedAt: new Date(item.recordedAt),
accuracy: item.accuracy,
altitude: item.altitude,
speed: item.speed,
source: item.source || 'foreground',
addressFormatted: item.address,
city: item.city,
country: item.country,
countryCode: item.countryCode,
})
.onConflictDoNothing();
synced++;
} catch {
// Skip duplicates
}
}
return c.json({ synced, total: items?.length || 0 });
});
// ─── Start ──────────────────────────────────────────────────
console.log(`traces-server starting on port ${PORT}...`);
export default { port: PORT, fetch: app.fetch };

View file

@ -0,0 +1,231 @@
import {
pgTable,
uuid,
text,
doublePrecision,
timestamp,
integer,
pgEnum,
index,
uniqueIndex,
} from 'drizzle-orm/pg-core';
// ============================================
// Enums
// ============================================
export const locationSourceEnum = pgEnum('location_source', [
'foreground',
'background',
'manual',
'photo-import',
]);
export const deviceMotionEnum = pgEnum('device_motion', [
'stationary',
'walking',
'driving',
'unknown',
]);
export const poiCategoryEnum = pgEnum('poi_category', [
'building',
'monument',
'church',
'museum',
'palace',
'bridge',
'park',
'square',
'sculpture',
'fountain',
'historic_site',
'other',
]);
export const guideStatusEnum = pgEnum('guide_status', ['generating', 'ready', 'error']);
// ============================================
// Tables
// ============================================
export const locations = pgTable(
'locations',
{
id: uuid('id').defaultRandom().primaryKey(),
userId: text('user_id').notNull(),
latitude: doublePrecision('latitude').notNull(),
longitude: doublePrecision('longitude').notNull(),
recordedAt: timestamp('recorded_at', { withTimezone: true }).notNull(),
accuracy: doublePrecision('accuracy'),
altitude: doublePrecision('altitude'),
speed: doublePrecision('speed'),
source: locationSourceEnum('source').default('foreground'),
deviceMotion: deviceMotionEnum('device_motion'),
addressFormatted: text('address_formatted'),
street: text('street'),
houseNumber: text('house_number'),
city: text('city'),
postalCode: text('postal_code'),
country: text('country'),
countryCode: text('country_code'),
cityId: uuid('city_id').references(() => cities.id),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('locations_user_id_idx').on(table.userId),
index('locations_recorded_at_idx').on(table.recordedAt),
index('locations_city_id_idx').on(table.cityId),
index('locations_user_recorded_idx').on(table.userId, table.recordedAt),
]
);
export const cities = pgTable(
'cities',
{
id: uuid('id').defaultRandom().primaryKey(),
name: text('name').notNull(),
country: text('country').notNull(),
countryCode: text('country_code').notNull(),
latitude: doublePrecision('latitude').notNull(),
longitude: doublePrecision('longitude').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [uniqueIndex('cities_name_country_code_idx').on(table.name, table.countryCode)]
);
export const cityVisits = pgTable(
'city_visits',
{
id: uuid('id').defaultRandom().primaryKey(),
userId: text('user_id').notNull(),
cityId: uuid('city_id')
.notNull()
.references(() => cities.id, { onDelete: 'cascade' }),
firstVisitAt: timestamp('first_visit_at', { withTimezone: true }).notNull(),
lastVisitAt: timestamp('last_visit_at', { withTimezone: true }).notNull(),
totalDurationMs: integer('total_duration_ms').default(0).notNull(),
visitCount: integer('visit_count').default(1).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
uniqueIndex('city_visits_user_city_idx').on(table.userId, table.cityId),
index('city_visits_user_id_idx').on(table.userId),
]
);
export const places = pgTable(
'places',
{
id: uuid('id').defaultRandom().primaryKey(),
userId: text('user_id').notNull(),
name: text('name').notNull(),
latitude: doublePrecision('latitude').notNull(),
longitude: doublePrecision('longitude').notNull(),
radiusMeters: integer('radius_meters').default(100).notNull(),
addressFormatted: text('address_formatted'),
cityId: uuid('city_id').references(() => cities.id),
visitCount: integer('visit_count').default(0).notNull(),
totalDurationMs: integer('total_duration_ms').default(0).notNull(),
firstVisitAt: timestamp('first_visit_at', { withTimezone: true }),
lastVisitAt: timestamp('last_visit_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('places_user_id_idx').on(table.userId),
index('places_city_id_idx').on(table.cityId),
]
);
export const pois = pgTable(
'pois',
{
id: uuid('id').defaultRandom().primaryKey(),
name: text('name').notNull(),
description: text('description'),
latitude: doublePrecision('latitude').notNull(),
longitude: doublePrecision('longitude').notNull(),
category: poiCategoryEnum('category').default('other').notNull(),
cityId: uuid('city_id')
.notNull()
.references(() => cities.id),
imageUrl: text('image_url'),
sourceUrls: text('source_urls').array(),
aiSummary: text('ai_summary'),
aiSummaryLanguage: text('ai_summary_language'),
aiSummaryGeneratedAt: timestamp('ai_summary_generated_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('pois_city_id_idx').on(table.cityId),
index('pois_lat_lng_idx').on(table.latitude, table.longitude),
]
);
export const guides = pgTable(
'guides',
{
id: uuid('id').defaultRandom().primaryKey(),
userId: text('user_id').notNull(),
cityId: uuid('city_id')
.notNull()
.references(() => cities.id),
title: text('title').notNull(),
description: text('description'),
status: guideStatusEnum('status').default('generating').notNull(),
routePolyline: text('route_polyline'),
estimatedDurationMin: integer('estimated_duration_min'),
distanceMeters: integer('distance_meters'),
language: text('language').default('de').notNull(),
creditsCost: integer('credits_cost'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('guides_user_id_idx').on(table.userId),
index('guides_city_id_idx').on(table.cityId),
]
);
export const guidePois = pgTable(
'guide_pois',
{
id: uuid('id').defaultRandom().primaryKey(),
guideId: uuid('guide_id')
.notNull()
.references(() => guides.id, { onDelete: 'cascade' }),
poiId: uuid('poi_id')
.notNull()
.references(() => pois.id),
sortOrder: integer('sort_order').notNull(),
aiNarrative: text('ai_narrative'),
narrativeLanguage: text('narrative_language').default('de'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
},
(table) => [
index('guide_pois_guide_id_idx').on(table.guideId),
index('guide_pois_poi_id_idx').on(table.poiId),
]
);
// ============================================
// Type Exports
// ============================================
export type Location = typeof locations.$inferSelect;
export type NewLocation = typeof locations.$inferInsert;
export type City = typeof cities.$inferSelect;
export type NewCity = typeof cities.$inferInsert;
export type CityVisit = typeof cityVisits.$inferSelect;
export type NewCityVisit = typeof cityVisits.$inferInsert;
export type Place = typeof places.$inferSelect;
export type NewPlace = typeof places.$inferInsert;
export type Poi = typeof pois.$inferSelect;
export type NewPoi = typeof pois.$inferInsert;
export type Guide = typeof guides.$inferSelect;
export type NewGuide = typeof guides.$inferInsert;
export type GuidePoi = typeof guidePois.$inferSelect;
export type NewGuidePoi = typeof guidePois.$inferInsert;

View file

@ -0,0 +1,168 @@
/**
* Guide Generation Service AI-powered city guides
*
* Server-only: calls mana-llm for POI summaries and narratives,
* mana-search for POI discovery, and computes optimal routes.
*/
import { eq, and } from 'drizzle-orm';
import type { Database } from '../db';
export class GuideService {
constructor(
private db: Database,
private llmUrl: string,
private searchUrl: string
) {}
async generateGuide(
userId: string,
params: {
cityId: string;
title: string;
language?: string;
maxPois?: number;
}
) {
const { guides, cities } = await import('../schema');
// Get city
const [city] = await this.db.select().from(cities).where(eq(cities.id, params.cityId)).limit(1);
if (!city) throw new Error('City not found');
// Create guide in 'generating' state
const [guide] = await this.db
.insert(guides)
.values({
userId,
cityId: params.cityId,
title: params.title || `Guide: ${city.name}`,
status: 'generating',
language: params.language || 'de',
})
.returning();
// Fire-and-forget async pipeline
this.runPipeline(guide.id, userId, city, params.language || 'de', params.maxPois || 10).catch(
(err) => {
console.error('Guide generation failed:', err);
this.db
.update(guides)
.set({ status: 'error' })
.where(eq(guides.id, guide.id))
.catch(() => {});
}
);
return guide;
}
private async runPipeline(
guideId: string,
userId: string,
city: { id: string; name: string; latitude: number | null; longitude: number | null },
language: string,
maxPois: number
) {
const { guides } = await import('../schema');
// 1. Find nearby POIs
const nearbyPois = await this.db
.select()
.from(pois)
.where(eq(pois.cityId, city.id))
.limit(maxPois);
if (nearbyPois.length === 0) {
await this.db.update(guides).set({ status: 'ready' }).where(eq(guides.id, guideId));
return;
}
// 2. Generate AI narratives for each POI
for (let i = 0; i < nearbyPois.length; i++) {
const poi = nearbyPois[i];
let narrative = poi.aiSummary || '';
if (!narrative) {
try {
narrative = await this.generateNarrative(poi.name, city.name, language);
} catch {
narrative = poi.description || poi.name;
}
}
await this.db.insert(guidePois).values({
guideId,
poiId: poi.id,
sortOrder: i,
aiNarrative: narrative,
narrativeLanguage: language,
});
}
// 3. Mark as ready
await this.db
.update(guides)
.set({
status: 'ready',
estimatedDurationMin: nearbyPois.length * 15,
})
.where(eq(guides.id, guideId));
}
private async generateNarrative(
poiName: string,
cityName: string,
language: string
): Promise<string> {
const res = await fetch(`${this.llmUrl}/api/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [
{
role: 'system',
content: `Du bist ein Stadtführer in ${cityName}. Schreibe einen kurzen, informativen Text (max 200 Wörter) über die Sehenswürdigkeit. Sprache: ${language === 'de' ? 'Deutsch' : 'English'}.`,
},
{ role: 'user', content: `Erzähle mir über: ${poiName}` },
],
model: 'gemma3:4b',
max_tokens: 300,
}),
});
if (!res.ok) throw new Error('LLM failed');
const data = await res.json();
return data.choices?.[0]?.message?.content?.trim() || poiName;
}
async getUserGuides(userId: string) {
const { guides } = await import('../schema');
return this.db.select().from(guides).where(eq(guides.userId, userId));
}
async getGuideDetail(userId: string, guideId: string) {
const { guides } = await import('../schema');
const [guide] = await this.db
.select()
.from(guides)
.where(and(eq(guides.id, guideId), eq(guides.userId, userId)))
.limit(1);
if (!guide) return null;
const waypoints = await this.db
.select()
.from(guidePois)
.innerJoin(pois, eq(guidePois.poiId, pois.id))
.where(eq(guidePois.guideId, guideId))
.orderBy(guidePois.sortOrder);
return { ...guide, waypoints };
}
async deleteGuide(userId: string, guideId: string) {
const { guides } = await import('../schema');
await this.db.delete(guides).where(and(eq(guides.id, guideId), eq(guides.userId, userId)));
}
}

View file

@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"]
}