chore: remove legacy workspace and restructure API + modular admin UI
This commit is contained in:
1583
package-lock.json
generated
1583
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "planner",
|
"name": "planner",
|
||||||
"private": true,
|
"private": true,
|
||||||
"workspaces": ["packages/*"],
|
"workspaces": [
|
||||||
|
"packages/admin",
|
||||||
|
"packages/server"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "concurrently \"npm:dev:server\" \"npm:dev:admin\"",
|
"dev": "concurrently \"npm:dev:server\" \"npm:dev:admin\"",
|
||||||
"dev:server": "npm --workspace @planner/server run dev",
|
"dev:server": "npm --workspace @planner/server run dev",
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"lucide-react": "^0.577.0",
|
||||||
"react": "^19.2.4",
|
"react": "^19.2.4",
|
||||||
"react-dom": "^19.2.4",
|
"react-dom": "^19.2.4",
|
||||||
"react-router-dom": "^7.13.1"
|
"react-router-dom": "^7.13.1"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
||||||
import { Sidebar } from "./components/Sidebar";
|
|
||||||
import { ProtectedRoute } from "./components/ProtectedRoute";
|
import { ProtectedRoute } from "./components/ProtectedRoute";
|
||||||
|
import { PageShell } from "./ui/PageShell";
|
||||||
import { LoginPage } from "./pages/Login";
|
import { LoginPage } from "./pages/Login";
|
||||||
import { DashboardPage } from "./pages/Dashboard";
|
import { DashboardPage } from "./pages/Dashboard";
|
||||||
import { GuestsPage } from "./pages/Guests";
|
import { GuestsPage } from "./pages/Guests";
|
||||||
@@ -11,49 +11,55 @@ import "./index.css";
|
|||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<div className="min-h-screen bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100">
|
|
||||||
<div className="min-h-screen flex">
|
|
||||||
<Sidebar />
|
|
||||||
<main className="flex-1">
|
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<LoginPage />} />
|
<Route path="/login" element={<LoginPage />} />
|
||||||
|
|
||||||
<Route
|
<Route
|
||||||
path="/"
|
path="/"
|
||||||
element={
|
element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
|
<PageShell title="Dashboard">
|
||||||
<DashboardPage />
|
<DashboardPage />
|
||||||
|
</PageShell>
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Route
|
<Route
|
||||||
path="/guests"
|
path="/guests"
|
||||||
element={
|
element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
|
<PageShell title="Guests">
|
||||||
<GuestsPage />
|
<GuestsPage />
|
||||||
|
</PageShell>
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Route
|
<Route
|
||||||
path="/gifts"
|
path="/gifts"
|
||||||
element={
|
element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
|
<PageShell title="Gifts">
|
||||||
<GiftsPage />
|
<GiftsPage />
|
||||||
|
</PageShell>
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Route
|
<Route
|
||||||
path="/todos"
|
path="/todos"
|
||||||
element={
|
element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
|
<PageShell title="Todos">
|
||||||
<TodosPage />
|
<TodosPage />
|
||||||
|
</PageShell>
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,41 @@
|
|||||||
|
import { Home, Gift, ListChecks, Users } from "lucide-react";
|
||||||
import { NavLink } from "react-router-dom";
|
import { NavLink } from "react-router-dom";
|
||||||
|
|
||||||
const linkClasses = ({ isActive }: { isActive: boolean }) =>
|
const linkClasses = ({ isActive }: { isActive: boolean }) =>
|
||||||
`block px-4 py-2 rounded-lg transition hover:bg-slate-200 dark:hover:bg-slate-800 ${
|
`flex items-center gap-2 rounded-xl px-4 py-3 text-sm font-medium transition hover:bg-slate-100 dark:hover:bg-slate-900 ${
|
||||||
isActive ? "bg-slate-200 dark:bg-slate-800 font-semibold" : ""
|
isActive ? "bg-slate-100 dark:bg-slate-900 text-slate-900 dark:text-white" : "text-slate-600 dark:text-slate-300"
|
||||||
}`;
|
}`;
|
||||||
|
|
||||||
export function Sidebar() {
|
export function Sidebar() {
|
||||||
return (
|
return (
|
||||||
<nav className="w-64 p-4 border-r border-slate-200 dark:border-slate-800">
|
<nav className="flex h-screen w-64 flex-col border-r border-slate-200 bg-white py-6 dark:border-slate-800 dark:bg-slate-950">
|
||||||
<h2 className="text-xl font-bold mb-4">Planner Admin</h2>
|
<div className="px-6">
|
||||||
<div className="space-y-2">
|
<h2 className="text-xl font-bold tracking-tight text-slate-900 dark:text-white">Planner</h2>
|
||||||
|
<p className="mt-1 text-xs text-slate-500 dark:text-slate-400">Admin console</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6 flex-1 space-y-1 px-2">
|
||||||
<NavLink to="/" className={linkClasses} end>
|
<NavLink to="/" className={linkClasses} end>
|
||||||
Dashboard
|
<Home className="h-4 w-4" />
|
||||||
|
<span>Dashboard</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
<NavLink to="/guests" className={linkClasses}>
|
<NavLink to="/guests" className={linkClasses}>
|
||||||
Guests
|
<Users className="h-4 w-4" />
|
||||||
|
<span>Guests</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
<NavLink to="/gifts" className={linkClasses}>
|
<NavLink to="/gifts" className={linkClasses}>
|
||||||
Gifts
|
<Gift className="h-4 w-4" />
|
||||||
|
<span>Gifts</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
<NavLink to="/todos" className={linkClasses}>
|
<NavLink to="/todos" className={linkClasses}>
|
||||||
Todos
|
<ListChecks className="h-4 w-4" />
|
||||||
|
<span>Todos</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="border-t border-slate-200 px-6 pt-4 text-xs text-slate-500 dark:border-slate-800 dark:text-slate-400">
|
||||||
|
<p>Tip: Use the sidebar to navigate between sections.</p>
|
||||||
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
28
packages/admin/src/hooks/useDarkMode.ts
Normal file
28
packages/admin/src/hooks/useDarkMode.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
const STORAGE_KEY = "planner_admin_dark";
|
||||||
|
|
||||||
|
export function useDarkMode() {
|
||||||
|
const [dark, setDark] = useState(() => {
|
||||||
|
if (typeof window === "undefined") return false;
|
||||||
|
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||||
|
if (stored !== null) return stored === "true";
|
||||||
|
return window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false;
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const root = document.documentElement;
|
||||||
|
if (dark) {
|
||||||
|
root.classList.add("dark");
|
||||||
|
} else {
|
||||||
|
root.classList.remove("dark");
|
||||||
|
}
|
||||||
|
window.localStorage.setItem(STORAGE_KEY, dark ? "true" : "false");
|
||||||
|
}, [dark]);
|
||||||
|
|
||||||
|
function toggle() {
|
||||||
|
setDark((prev) => !prev);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { dark, toggle };
|
||||||
|
}
|
||||||
@@ -55,11 +55,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
#root {
|
#root {
|
||||||
width: 1126px;
|
width: 100%;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
margin: 0 auto;
|
margin: 0;
|
||||||
text-align: center;
|
padding: 0;
|
||||||
border-inline: 1px solid var(--border);
|
text-align: left;
|
||||||
min-height: 100svh;
|
min-height: 100svh;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ export function clearToken() {
|
|||||||
localStorage.removeItem(TOKEN_KEY);
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function logout() {
|
||||||
|
clearToken();
|
||||||
|
window.location.href = "/login";
|
||||||
|
}
|
||||||
|
|
||||||
export function isLoggedIn() {
|
export function isLoggedIn() {
|
||||||
return Boolean(getToken());
|
return Boolean(getToken());
|
||||||
}
|
}
|
||||||
|
|||||||
12
packages/admin/src/modules/auth/api.ts
Normal file
12
packages/admin/src/modules/auth/api.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { fetchJson } from "../../lib/api";
|
||||||
|
|
||||||
|
export type AuthTokenResponse = {
|
||||||
|
token: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function login(email: string, password: string) {
|
||||||
|
return fetchJson<AuthTokenResponse>("/api/organizador/auth/login", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
});
|
||||||
|
}
|
||||||
19
packages/admin/src/modules/gifts/api.ts
Normal file
19
packages/admin/src/modules/gifts/api.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { fetchJson } from "../../lib/api";
|
||||||
|
|
||||||
|
export type Gift = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
status?: string;
|
||||||
|
ownerId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function listGifts() {
|
||||||
|
return fetchJson<Gift[]>("/api/organizador/gift");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createGift(payload: { name: string }) {
|
||||||
|
return fetchJson<Gift>("/api/organizador/gift", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
19
packages/admin/src/modules/guests/api.ts
Normal file
19
packages/admin/src/modules/guests/api.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { fetchJson } from "../../lib/api";
|
||||||
|
|
||||||
|
export type Guest = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
email?: string;
|
||||||
|
rsvp?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function listGuests() {
|
||||||
|
return fetchJson<Guest[]>("/api/organizador/guest");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createGuest(payload: { name: string; email?: string }) {
|
||||||
|
return fetchJson<Guest>("/api/organizador/guest", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
24
packages/admin/src/modules/todos/api.ts
Normal file
24
packages/admin/src/modules/todos/api.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { fetchJson } from "../../lib/api";
|
||||||
|
|
||||||
|
export type Todo = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
completed: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function listTodos() {
|
||||||
|
return fetchJson<Todo[]>("/api/organizador/todo");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createTodo(payload: { title: string }) {
|
||||||
|
return fetchJson<Todo>("/api/organizador/todo", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function completeTodo(id: string) {
|
||||||
|
return fetchJson<Todo>(`/api/organizador/todo/${id}/complete`, {
|
||||||
|
method: "PATCH",
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,8 +1,25 @@
|
|||||||
|
import { Card } from "../ui/Card";
|
||||||
|
|
||||||
export function DashboardPage() {
|
export function DashboardPage() {
|
||||||
return (
|
return (
|
||||||
<div className="p-6">
|
<div className="space-y-6">
|
||||||
<h1 className="text-2xl font-semibold mb-4">Dashboard</h1>
|
<div className="grid gap-6 md:grid-cols-3">
|
||||||
<p className="text-sm text-slate-600 dark:text-slate-300">Select a section from the sidebar to manage guests, gifts, or todos.</p>
|
<Card title="Guests" subtitle="Total invited">
|
||||||
|
<p className="text-3xl font-semibold">—</p>
|
||||||
|
</Card>
|
||||||
|
<Card title="Gifts" subtitle="Gift ideas">
|
||||||
|
<p className="text-3xl font-semibold">—</p>
|
||||||
|
</Card>
|
||||||
|
<Card title="Todos" subtitle="Pending tasks">
|
||||||
|
<p className="text-3xl font-semibold">—</p>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card title="Quick links">
|
||||||
|
<p className="text-sm text-slate-600 dark:text-slate-300">
|
||||||
|
Use the sidebar to navigate, or start by creating a new guest, gift, or todo.
|
||||||
|
</p>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { fetchJson } from "../lib/api";
|
import { createGift, listGifts, type Gift } from "../modules/gifts/api";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { Card } from "../ui/Card";
|
||||||
|
import { Input } from "../ui/Input";
|
||||||
|
|
||||||
export function GiftsPage() {
|
export function GiftsPage() {
|
||||||
const [gifts, setGifts] = useState<any[]>([]);
|
const [gifts, setGifts] = useState<Gift[]>([]);
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
try {
|
try {
|
||||||
const data = await fetchJson<any[]>("/api/gift");
|
const data = await listGifts();
|
||||||
setGifts(data);
|
setGifts(data);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -23,10 +26,7 @@ export function GiftsPage() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
await fetchJson("/api/gift", {
|
await createGift({ name });
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ name }),
|
|
||||||
});
|
|
||||||
setName("");
|
setName("");
|
||||||
load();
|
load();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -35,41 +35,40 @@ export function GiftsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6">
|
<div className="space-y-6">
|
||||||
<h1 className="text-2xl font-semibold mb-4">Gifts</h1>
|
{error ? <div className="rounded-lg bg-red-50 p-4 text-sm text-red-700 dark:bg-red-950/30 dark:text-red-200">{error}</div> : null}
|
||||||
{error ? <div className="mb-4 text-sm text-red-600">{error}</div> : null}
|
|
||||||
<form onSubmit={handleCreate} className="mb-6 flex flex-col gap-3 max-w-md">
|
<Card title="Gifts" subtitle="Manage gift ideas and assignments">
|
||||||
<input
|
<form onSubmit={handleCreate} className="grid gap-3 md:grid-cols-3">
|
||||||
value={name}
|
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Gift name" required />
|
||||||
onChange={(e) => setName(e.target.value)}
|
<div className="md:col-span-3">
|
||||||
placeholder="Gift name"
|
<Button type="submit" className="w-full">
|
||||||
className="rounded border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<button className="w-full rounded bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-500">
|
|
||||||
Add gift
|
Add gift
|
||||||
</button>
|
</Button>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
<div className="overflow-x-auto">
|
|
||||||
|
<div className="mt-6 overflow-x-auto">
|
||||||
<table className="w-full border-collapse text-sm">
|
<table className="w-full border-collapse text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
|
<tr className="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||||
<th className="px-3 py-2">Name</th>
|
<th className="px-4 py-2">Name</th>
|
||||||
<th className="px-3 py-2">Status</th>
|
<th className="px-4 py-2">Status</th>
|
||||||
<th className="px-3 py-2">Owner</th>
|
<th className="px-4 py-2">Owner</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{gifts.map((gift) => (
|
{gifts.map((gift) => (
|
||||||
<tr key={gift.id} className="border-t border-slate-200 dark:border-slate-800">
|
<tr key={gift.id} className="border-t border-slate-200 dark:border-slate-800">
|
||||||
<td className="px-3 py-2">{gift.name}</td>
|
<td className="px-4 py-2">{gift.name}</td>
|
||||||
<td className="px-3 py-2">{gift.status}</td>
|
<td className="px-4 py-2">{gift.status}</td>
|
||||||
<td className="px-3 py-2">{gift.ownerId || "—"}</td>
|
<td className="px-4 py-2">{gift.ownerId || "—"}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,18 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { fetchJson } from "../lib/api";
|
import { createGuest, listGuests, type Guest } from "../modules/guests/api";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { Card } from "../ui/Card";
|
||||||
|
import { Input } from "../ui/Input";
|
||||||
|
|
||||||
export function GuestsPage() {
|
export function GuestsPage() {
|
||||||
const [guests, setGuests] = useState<any[]>([]);
|
const [guests, setGuests] = useState<Guest[]>([]);
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
try {
|
try {
|
||||||
const data = await fetchJson<any[]>('/api/guest');
|
const data = await listGuests();
|
||||||
setGuests(data);
|
setGuests(data);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -24,12 +27,9 @@ export function GuestsPage() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
await fetchJson('/api/guest', {
|
await createGuest({ name, email });
|
||||||
method: 'POST',
|
setName("");
|
||||||
body: JSON.stringify({ name, email }),
|
setEmail("");
|
||||||
});
|
|
||||||
setName('');
|
|
||||||
setEmail('');
|
|
||||||
load();
|
load();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -37,47 +37,39 @@ export function GuestsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6">
|
<div className="space-y-6">
|
||||||
<h1 className="text-2xl font-semibold mb-4">Guests</h1>
|
{error ? <div className="rounded-lg bg-red-50 p-4 text-sm text-red-700 dark:bg-red-950/30 dark:text-red-200">{error}</div> : null}
|
||||||
{error ? <div className="mb-4 text-sm text-red-600">{error}</div> : null}
|
|
||||||
<form onSubmit={handleCreate} className="mb-6 flex flex-col gap-3 max-w-md">
|
<Card title="Guests" subtitle="Manage guest list and RSVPs">
|
||||||
<input
|
<form onSubmit={handleCreate} className="grid gap-3 md:grid-cols-3">
|
||||||
value={name}
|
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" required />
|
||||||
onChange={(e) => setName(e.target.value)}
|
<Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email (optional)" />
|
||||||
placeholder="Name"
|
<Button type="submit" className="md:col-span-3">
|
||||||
className="rounded border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
placeholder="Email (optional)"
|
|
||||||
className="rounded border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"
|
|
||||||
/>
|
|
||||||
<button className="w-full rounded bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-500">
|
|
||||||
Add guest
|
Add guest
|
||||||
</button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
<div className="overflow-x-auto">
|
|
||||||
|
<div className="mt-6 overflow-x-auto">
|
||||||
<table className="w-full border-collapse text-sm">
|
<table className="w-full border-collapse text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
|
<tr className="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||||
<th className="px-3 py-2">Name</th>
|
<th className="px-4 py-2">Name</th>
|
||||||
<th className="px-3 py-2">Email</th>
|
<th className="px-4 py-2">Email</th>
|
||||||
<th className="px-3 py-2">RSVP</th>
|
<th className="px-4 py-2">RSVP</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{guests.map((guest) => (
|
{guests.map((guest) => (
|
||||||
<tr key={guest.id} className="border-t border-slate-200 dark:border-slate-800">
|
<tr key={guest.id} className="border-t border-slate-200 dark:border-slate-800">
|
||||||
<td className="px-3 py-2">{guest.name}</td>
|
<td className="px-4 py-2">{guest.name}</td>
|
||||||
<td className="px-3 py-2">{guest.email ?? "—"}</td>
|
<td className="px-4 py-2">{guest.email ?? "—"}</td>
|
||||||
<td className="px-3 py-2">{guest.rsvp ? "Yes" : "No"}</td>
|
<td className="px-4 py-2">{guest.rsvp ? "Yes" : "No"}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { fetchJson } from "../lib/api";
|
import { login } from "../modules/auth/api";
|
||||||
import { setToken } from "../lib/auth";
|
import { setToken } from "../lib/auth";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { Card } from "../ui/Card";
|
||||||
|
import { Input } from "../ui/Input";
|
||||||
|
|
||||||
export function LoginPage() {
|
export function LoginPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -13,10 +16,7 @@ export function LoginPage() {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const result = await fetchJson<{ token: string }>("/api/auth/login", {
|
const result = await login(email, password);
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ email, password }),
|
|
||||||
});
|
|
||||||
setToken(result.token);
|
setToken(result.token);
|
||||||
navigate("/");
|
navigate("/");
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -25,41 +25,26 @@ export function LoginPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-900">
|
<div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-950">
|
||||||
<div className="w-full max-w-md rounded-xl border border-slate-200 bg-white p-8 shadow-sm dark:border-slate-800 dark:bg-slate-950">
|
<Card className="w-full max-w-md">
|
||||||
<h1 className="text-2xl font-semibold mb-6">Login</h1>
|
<h1 className="text-2xl font-semibold mb-6">Sign in</h1>
|
||||||
{error ? <div className="mb-4 text-sm text-red-600">{error}</div> : null}
|
{error ? <div className="mb-4 text-sm text-red-600">{error}</div> : null}
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-sm font-medium text-slate-700 dark:text-slate-200">Email</span>
|
<span className="text-sm font-medium text-slate-700 dark:text-slate-200">Email</span>
|
||||||
<input
|
<Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||||
type="email"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
className="mt-1 block w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-sm font-medium text-slate-700 dark:text-slate-200">Password</span>
|
<span className="text-sm font-medium text-slate-700 dark:text-slate-200">Password</span>
|
||||||
<input
|
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
|
||||||
type="password"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
className="mt-1 block w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<button
|
<Button type="submit" className="w-full">
|
||||||
type="submit"
|
|
||||||
className="w-full rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-500"
|
|
||||||
>
|
|
||||||
Sign in
|
Sign in
|
||||||
</button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { fetchJson } from "../lib/api";
|
import { createTodo, completeTodo, listTodos, type Todo } from "../modules/todos/api";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { Card } from "../ui/Card";
|
||||||
|
import { Input } from "../ui/Input";
|
||||||
|
|
||||||
export function TodosPage() {
|
export function TodosPage() {
|
||||||
const [todos, setTodos] = useState<any[]>([]);
|
const [todos, setTodos] = useState<Todo[]>([]);
|
||||||
const [title, setTitle] = useState("");
|
const [title, setTitle] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const load = async () => {
|
const load = async () => {
|
||||||
try {
|
try {
|
||||||
const data = await fetchJson<any[]>("/api/todo");
|
const data = await listTodos();
|
||||||
setTodos(data);
|
setTodos(data);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -23,10 +26,7 @@ export function TodosPage() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
await fetchJson("/api/todo", {
|
await createTodo({ title });
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ title }),
|
|
||||||
});
|
|
||||||
setTitle("");
|
setTitle("");
|
||||||
load();
|
load();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -36,7 +36,7 @@ export function TodosPage() {
|
|||||||
|
|
||||||
const markComplete = async (id: string) => {
|
const markComplete = async (id: string) => {
|
||||||
try {
|
try {
|
||||||
await fetchJson(`/api/todo/${id}/complete`, { method: "PATCH" });
|
await completeTodo(id);
|
||||||
load();
|
load();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -44,43 +44,38 @@ export function TodosPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6">
|
<div className="space-y-6">
|
||||||
<h1 className="text-2xl font-semibold mb-4">Todos</h1>
|
{error ? <div className="rounded-lg bg-red-50 p-4 text-sm text-red-700 dark:bg-red-950/30 dark:text-red-200">{error}</div> : null}
|
||||||
{error ? <div className="mb-4 text-sm text-red-600">{error}</div> : null}
|
|
||||||
<form onSubmit={handleCreate} className="mb-6 flex flex-col gap-3 max-w-md">
|
<Card title="Todos" subtitle="Keep track of tasks and due dates">
|
||||||
<input
|
<form onSubmit={handleCreate} className="grid gap-3 md:grid-cols-3">
|
||||||
value={title}
|
<Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="To-do title" required />
|
||||||
onChange={(e) => setTitle(e.target.value)}
|
<div className="md:col-span-3">
|
||||||
placeholder="To-do title"
|
<Button type="submit" className="w-full">
|
||||||
className="rounded border border-slate-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<button className="w-full rounded bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-500">
|
|
||||||
Add todo
|
Add todo
|
||||||
</button>
|
</Button>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
<div className="overflow-x-auto">
|
|
||||||
|
<div className="mt-6 overflow-x-auto">
|
||||||
<table className="w-full border-collapse text-sm">
|
<table className="w-full border-collapse text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
|
<tr className="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
|
||||||
<th className="px-3 py-2">Title</th>
|
<th className="px-4 py-2">Title</th>
|
||||||
<th className="px-3 py-2">Completed</th>
|
<th className="px-4 py-2">Completed</th>
|
||||||
<th className="px-3 py-2">Actions</th>
|
<th className="px-4 py-2">Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{todos.map((todo) => (
|
{todos.map((todo) => (
|
||||||
<tr key={todo.id} className="border-t border-slate-200 dark:border-slate-800">
|
<tr key={todo.id} className="border-t border-slate-200 dark:border-slate-800">
|
||||||
<td className="px-3 py-2">{todo.title}</td>
|
<td className="px-4 py-2">{todo.title}</td>
|
||||||
<td className="px-3 py-2">{todo.completed ? "Yes" : "No"}</td>
|
<td className="px-4 py-2">{todo.completed ? "Yes" : "No"}</td>
|
||||||
<td className="px-3 py-2">
|
<td className="px-4 py-2">
|
||||||
{!todo.completed ? (
|
{!todo.completed ? (
|
||||||
<button
|
<Button variant="secondary" size="sm" onClick={() => markComplete(todo.id)}>
|
||||||
className="rounded bg-green-600 px-3 py-1 text-xs font-semibold text-white hover:bg-green-500"
|
|
||||||
onClick={() => markComplete(todo.id)}
|
|
||||||
>
|
|
||||||
Complete
|
Complete
|
||||||
</button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
"—"
|
"—"
|
||||||
)}
|
)}
|
||||||
@@ -90,6 +85,7 @@ export function TodosPage() {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
40
packages/admin/src/ui/Button.tsx
Normal file
40
packages/admin/src/ui/Button.tsx
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import type { ButtonHTMLAttributes } from "react";
|
||||||
|
|
||||||
|
type ButtonVariant = "primary" | "secondary" | "ghost";
|
||||||
|
|
||||||
|
type ButtonSize = "sm" | "md" | "lg";
|
||||||
|
|
||||||
|
const variantClasses: Record<ButtonVariant, string> = {
|
||||||
|
primary:
|
||||||
|
"bg-indigo-600 text-white hover:bg-indigo-500 focus-visible:ring-indigo-500",
|
||||||
|
secondary:
|
||||||
|
"bg-slate-200 text-slate-900 hover:bg-slate-300 focus-visible:ring-slate-400 dark:bg-slate-800 dark:text-slate-100 dark:hover:bg-slate-700",
|
||||||
|
ghost:
|
||||||
|
"bg-transparent text-slate-700 hover:bg-slate-100 focus-visible:ring-slate-400 dark:text-slate-200 dark:hover:bg-slate-800",
|
||||||
|
};
|
||||||
|
|
||||||
|
const sizeClasses: Record<ButtonSize, string> = {
|
||||||
|
sm: "px-3 py-1.5 text-sm",
|
||||||
|
md: "px-4 py-2 text-sm",
|
||||||
|
lg: "px-5 py-3 text-base",
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||||
|
variant?: ButtonVariant;
|
||||||
|
size?: ButtonSize;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function Button({
|
||||||
|
variant = "primary",
|
||||||
|
size = "md",
|
||||||
|
className = "",
|
||||||
|
...props
|
||||||
|
}: ButtonProps) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`inline-flex items-center justify-center gap-2 rounded-lg font-semibold shadow-sm transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-slate-950 ${variantClasses[variant]} ${sizeClasses[size]} ${className}`}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
25
packages/admin/src/ui/Card.tsx
Normal file
25
packages/admin/src/ui/Card.tsx
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
export function Card({
|
||||||
|
title,
|
||||||
|
subtitle,
|
||||||
|
children,
|
||||||
|
className = "",
|
||||||
|
}: {
|
||||||
|
title?: string;
|
||||||
|
subtitle?: string;
|
||||||
|
children: ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<section className={`rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-800 dark:bg-slate-950 ${className}`}>
|
||||||
|
{title ? (
|
||||||
|
<header className="mb-4">
|
||||||
|
<h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">{title}</h2>
|
||||||
|
{subtitle ? <p className="text-sm text-slate-600 dark:text-slate-400">{subtitle}</p> : null}
|
||||||
|
</header>
|
||||||
|
) : null}
|
||||||
|
{children}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
10
packages/admin/src/ui/Input.tsx
Normal file
10
packages/admin/src/ui/Input.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import type { InputHTMLAttributes } from "react";
|
||||||
|
|
||||||
|
export function Input({ className = "", ...props }: InputHTMLAttributes<HTMLInputElement>) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
className={`w-full rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm shadow-sm transition focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100 ${className}`}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
23
packages/admin/src/ui/PageShell.tsx
Normal file
23
packages/admin/src/ui/PageShell.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { Sidebar } from "../components/Sidebar";
|
||||||
|
import { Topbar } from "./Topbar";
|
||||||
|
|
||||||
|
export function PageShell({
|
||||||
|
children,
|
||||||
|
title,
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
title?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100">
|
||||||
|
<div className="flex min-h-screen">
|
||||||
|
<Sidebar />
|
||||||
|
<div className="flex flex-1 flex-col">
|
||||||
|
<Topbar title={title} />
|
||||||
|
<main className="flex-1 overflow-auto p-6">{children}</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
51
packages/admin/src/ui/Topbar.tsx
Normal file
51
packages/admin/src/ui/Topbar.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import { Moon, Sun, LogOut } from "lucide-react";
|
||||||
|
import { useDarkMode } from "../hooks/useDarkMode";
|
||||||
|
import { logout } from "../lib/auth";
|
||||||
|
import { Button } from "./Button";
|
||||||
|
|
||||||
|
const menuItems = [
|
||||||
|
{ label: "Dashboard", to: "/" },
|
||||||
|
{ label: "Guests", to: "/guests" },
|
||||||
|
{ label: "Gifts", to: "/gifts" },
|
||||||
|
{ label: "Todos", to: "/todos" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function Topbar({ title = "Dashboard" }: { title?: string }) {
|
||||||
|
const { dark, toggle } = useDarkMode();
|
||||||
|
|
||||||
|
const currentLabel = useMemo(() => {
|
||||||
|
const match = menuItems.find((item) => item.label === title);
|
||||||
|
return match ? match.label : title;
|
||||||
|
}, [title]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="flex items-center justify-between border-b border-slate-200 bg-white px-6 py-4 shadow-sm dark:border-slate-800 dark:bg-slate-950">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-slate-600 dark:text-slate-300">{currentLabel}</p>
|
||||||
|
<h1 className="text-2xl font-semibold text-slate-900 dark:text-slate-100">{title}</h1>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="secondary" size="sm" onClick={toggle}>
|
||||||
|
{dark ? (
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Sun className="h-4 w-4" />
|
||||||
|
Light
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Moon className="h-4 w-4" />
|
||||||
|
Dark
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="sm" onClick={logout}>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<LogOut className="h-4 w-4" />
|
||||||
|
Logout
|
||||||
|
</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
const { PostgreSqlDriver } = require('@mikro-orm/postgresql');
|
|
||||||
const { Migrator } = require('@mikro-orm/migrations');
|
|
||||||
|
|
||||||
/** @type {import('@mikro-orm/core').MikroORMOptions} */
|
|
||||||
module.exports = {
|
|
||||||
driver: PostgreSqlDriver,
|
|
||||||
host: process.env.DB_HOST || 'localhost',
|
|
||||||
port: Number(process.env.DB_PORT) || 5432,
|
|
||||||
user: process.env.DB_USER || 'postgres',
|
|
||||||
password: process.env.DB_PASSWORD || 'postgres',
|
|
||||||
dbName: process.env.DB_NAME || 'planner',
|
|
||||||
autoLoadEntities: true,
|
|
||||||
entities: ['./dist/**/*.entity.js'],
|
|
||||||
extensions: [Migrator],
|
|
||||||
migrations: {
|
|
||||||
path: './dist/migrations',
|
|
||||||
transactional: true,
|
|
||||||
emit: 'js',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@planner/legacy",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"private": true,
|
|
||||||
"scripts": {
|
|
||||||
"start": "ts-node -r tsconfig-paths/register src/main.ts",
|
|
||||||
"start:dev": "npx nodemon --watch src --ext ts --exec \"npm run build && node dist/main.js\"",
|
|
||||||
"build": "tsc -p tsconfig.build.json",
|
|
||||||
"migration:generate": "mikro-orm migration:create",
|
|
||||||
"migration:run": "mikro-orm migration:up",
|
|
||||||
"migration:down": "mikro-orm migration:down"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@mikro-orm/core": "^7.0.3",
|
|
||||||
"@mikro-orm/decorators": "^7.0.3",
|
|
||||||
"@mikro-orm/migrations": "^7.0.3",
|
|
||||||
"@mikro-orm/nestjs": "^7.0.1",
|
|
||||||
"@mikro-orm/postgresql": "^7.0.3",
|
|
||||||
"@nestjs/common": "^11.1.17",
|
|
||||||
"@nestjs/core": "^11.1.17",
|
|
||||||
"@nestjs/event-emitter": "^3.0.1",
|
|
||||||
"@nestjs/platform-express": "^11.1.17",
|
|
||||||
"@nestjs/serve-static": "^5.0.4",
|
|
||||||
"bcryptjs": "^3.0.3",
|
|
||||||
"express": "^5.2.1",
|
|
||||||
"jsonwebtoken": "^9.0.3",
|
|
||||||
"pg": "^8.20.0",
|
|
||||||
"reflect-metadata": "^0.1.13",
|
|
||||||
"rxjs": "^7.8.0",
|
|
||||||
"uuid": "^13.0.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@mikro-orm/cli": "^7.0.3",
|
|
||||||
"@swc-node/register": "^1.11.1",
|
|
||||||
"@swc/core": "^1.15.18",
|
|
||||||
"@types/express": "^4.17.0",
|
|
||||||
"@types/jsonwebtoken": "^9.0.0",
|
|
||||||
"@types/node": "^20.0.0",
|
|
||||||
"nodemon": "^2.0.0",
|
|
||||||
"ts-node": "^10.0.0",
|
|
||||||
"tsconfig-paths": "^4.0.0",
|
|
||||||
"typescript": "^5.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,448 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>Admin Panel</title>
|
|
||||||
<style>
|
|
||||||
body {
|
|
||||||
font-family: system-ui, sans-serif;
|
|
||||||
padding: 2rem;
|
|
||||||
max-width: 900px;
|
|
||||||
margin: 0 auto;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
.module {
|
|
||||||
border: 1px solid #ccc;
|
|
||||||
padding: 1rem;
|
|
||||||
border-radius: 10px;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
.badge {
|
|
||||||
display: inline-block;
|
|
||||||
padding: 0.2rem 0.6rem;
|
|
||||||
background: #e5e7eb;
|
|
||||||
border-radius: 9999px;
|
|
||||||
font-size: 0.8rem;
|
|
||||||
color: #111827;
|
|
||||||
}
|
|
||||||
.field {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
.field input {
|
|
||||||
padding: 0.5rem;
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
border-radius: 6px;
|
|
||||||
}
|
|
||||||
button {
|
|
||||||
padding: 0.5rem 0.75rem;
|
|
||||||
border: 1px solid #ccc;
|
|
||||||
border-radius: 6px;
|
|
||||||
background: #f7f7f8;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
button:disabled {
|
|
||||||
opacity: 0.5;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
.error {
|
|
||||||
color: #b91c1c;
|
|
||||||
margin-top: 0.5rem;
|
|
||||||
}
|
|
||||||
.success {
|
|
||||||
color: #047857;
|
|
||||||
margin-top: 0.5rem;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>Admin Panel</h1>
|
|
||||||
<p>Interfaz de administración (Vue 3 + JWT).</p>
|
|
||||||
|
|
||||||
<div id="app" style="display: flex; gap: 1rem;">
|
|
||||||
<div v-if="!token" class="module" style="flex: 1;">
|
|
||||||
<h2>Iniciar sesión</h2>
|
|
||||||
<div class="field">
|
|
||||||
<label>Email</label>
|
|
||||||
<input v-model="login.email" type="email" placeholder="admin@local" />
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<label>Contraseña</label>
|
|
||||||
<input v-model="login.password" type="password" placeholder="••••••" />
|
|
||||||
</div>
|
|
||||||
<button :disabled="loading" @click="loginUser">Iniciar sesión</button>
|
|
||||||
<div :class="{ error: loginError, success: loginSuccess }">{{ loginMessage }}</div>
|
|
||||||
|
|
||||||
<hr />
|
|
||||||
|
|
||||||
<h2>Registrar usuario</h2>
|
|
||||||
<div class="field">
|
|
||||||
<label>Nombre</label>
|
|
||||||
<input v-model="register.name" placeholder="Nombre (opcional)" />
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<label>Email</label>
|
|
||||||
<input v-model="register.email" type="email" placeholder="admin@local" />
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<label>Contraseña</label>
|
|
||||||
<input v-model="register.password" type="password" placeholder="••••••" />
|
|
||||||
</div>
|
|
||||||
<button :disabled="loading" @click="registerUser">Registrar</button>
|
|
||||||
<div :class="{ error: registerError, success: registerSuccess }">{{ registerMessage }}</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-else style="flex: 1; display: flex; gap: 1rem;">
|
|
||||||
<div style="width: 240px;">
|
|
||||||
<div class="module">
|
|
||||||
<div style="display:flex; align-items:center; justify-content:space-between;">
|
|
||||||
<div>
|
|
||||||
<div><strong>{{ user?.name || user?.email }}</strong></div>
|
|
||||||
<div style="font-size:0.85rem; color:#555;">Tenant: unificado</div>
|
|
||||||
</div>
|
|
||||||
<button @click="logout">Salir</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="module">
|
|
||||||
<h3>Módulos</h3>
|
|
||||||
<div v-for="mod in modules" :key="mod.key" style="margin-bottom:0.5rem;">
|
|
||||||
<button
|
|
||||||
:style="{
|
|
||||||
width: '100%',
|
|
||||||
textAlign: 'left',
|
|
||||||
padding: '0.5rem',
|
|
||||||
border: selectedModule === mod.key ? '1px solid #333' : '1px solid #ccc',
|
|
||||||
background: selectedModule === mod.key ? '#f0f0f0' : '#fff',
|
|
||||||
}"
|
|
||||||
@click="selectModule(mod.key)">
|
|
||||||
{{ mod.name }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="module" v-if="selectedModule">
|
|
||||||
<h3>Acciones</h3>
|
|
||||||
<div v-for="action in actions" :key="action.key" style="margin-bottom:0.4rem;">
|
|
||||||
<button style="width: 100%; text-align: left;" @click="action.handler()">{{ action.label }}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style="flex: 1;">
|
|
||||||
<div class="module">
|
|
||||||
<div style="display:flex; justify-content:space-between; align-items:center;">
|
|
||||||
<div>
|
|
||||||
<label>
|
|
||||||
Tenant ID:
|
|
||||||
<input v-model="tenantId" style="margin-left:0.5rem;" />
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div style="color:#555;">{{ status }}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="module">
|
|
||||||
<h2 v-if="selectedModule">Administrar: {{ selectedModule }}</h2>
|
|
||||||
<div v-html="moduleHtml"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
|
|
||||||
<script>
|
|
||||||
const { createApp, reactive, ref, computed } = Vue;
|
|
||||||
|
|
||||||
createApp({
|
|
||||||
setup() {
|
|
||||||
const apiRoot = '/api/admin';
|
|
||||||
const authRoot = '/api/auth';
|
|
||||||
const tokenKey = 'planner_admin_token';
|
|
||||||
|
|
||||||
const token = ref(localStorage.getItem(tokenKey) || '');
|
|
||||||
const user = ref(null);
|
|
||||||
const tenantId = ref('default'); // kept for compatibility (subdomain / future use)
|
|
||||||
const status = ref('');
|
|
||||||
const modules = ref([]);
|
|
||||||
const selectedModule = ref('');
|
|
||||||
const moduleHtml = ref('');
|
|
||||||
const loading = ref(false);
|
|
||||||
|
|
||||||
const login = reactive({ email: '', password: '' });
|
|
||||||
const register = reactive({ name: '', email: '', password: '' });
|
|
||||||
|
|
||||||
const loginMessage = ref('');
|
|
||||||
const loginError = ref(false);
|
|
||||||
const loginSuccess = ref(false);
|
|
||||||
|
|
||||||
const registerMessage = ref('');
|
|
||||||
const registerError = ref(false);
|
|
||||||
const registerSuccess = ref(false);
|
|
||||||
|
|
||||||
const setStatus = (msg) => (status.value = msg);
|
|
||||||
const setToken = (t) => {
|
|
||||||
token.value = t;
|
|
||||||
if (t) localStorage.setItem(tokenKey, t);
|
|
||||||
else localStorage.removeItem(tokenKey);
|
|
||||||
};
|
|
||||||
|
|
||||||
const api = async (path, options = {}) => {
|
|
||||||
setStatus('Consultando ' + path + '...');
|
|
||||||
const headers = options.headers || {};
|
|
||||||
if (token.value) headers.Authorization = `Bearer ${token.value}`;
|
|
||||||
const res = await fetch(`${apiRoot}${path}`, {
|
|
||||||
...options,
|
|
||||||
headers,
|
|
||||||
});
|
|
||||||
const data = await res.json().catch(() => null);
|
|
||||||
if (!res.ok) {
|
|
||||||
const err = data?.message || res.statusText;
|
|
||||||
setStatus(`Error ${res.status}`);
|
|
||||||
throw new Error(err);
|
|
||||||
}
|
|
||||||
setStatus('OK');
|
|
||||||
setTimeout(() => setStatus(''), 1500);
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const logout = () => {
|
|
||||||
setToken('');
|
|
||||||
user.value = null;
|
|
||||||
selectedModule.value = '';
|
|
||||||
moduleHtml.value = '';
|
|
||||||
};
|
|
||||||
|
|
||||||
const loginUser = async () => {
|
|
||||||
loginMessage.value = '';
|
|
||||||
loginError.value = false;
|
|
||||||
loginSuccess.value = false;
|
|
||||||
loading.value = true;
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${authRoot}/login`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({
|
|
||||||
email: login.email,
|
|
||||||
password: login.password,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok || !data.token) {
|
|
||||||
loginMessage.value = data.message || 'Credenciales inválidas';
|
|
||||||
loginError.value = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setToken(data.token);
|
|
||||||
user.value = { email: login.email, name: data.name };
|
|
||||||
loginMessage.value = 'Sesión iniciada correctamente';
|
|
||||||
loginSuccess.value = true;
|
|
||||||
await loadModules();
|
|
||||||
} catch (err) {
|
|
||||||
loginMessage.value = err.message || err;
|
|
||||||
loginError.value = true;
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const registerUser = async () => {
|
|
||||||
registerMessage.value = '';
|
|
||||||
registerError.value = false;
|
|
||||||
registerSuccess.value = false;
|
|
||||||
loading.value = true;
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${authRoot}/register`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({
|
|
||||||
name: register.name,
|
|
||||||
email: register.email,
|
|
||||||
password: register.password,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok) {
|
|
||||||
registerMessage.value = data.message || 'Error al registrar';
|
|
||||||
registerError.value = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
registerMessage.value = 'Registrado. Inicia sesión.';
|
|
||||||
registerSuccess.value = true;
|
|
||||||
} catch (err) {
|
|
||||||
registerMessage.value = err.message || err;
|
|
||||||
registerError.value = true;
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatJson = (value) => `<pre style="white-space: pre-wrap; word-break: break-word;">${JSON.stringify(value, null, 2)}</pre>`;
|
|
||||||
|
|
||||||
const showResult = (value) => {
|
|
||||||
moduleHtml.value = formatJson(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const confirmPrompt = (message, defaultValue = '') => {
|
|
||||||
const result = prompt(message, defaultValue);
|
|
||||||
return result === null ? null : result.trim();
|
|
||||||
};
|
|
||||||
|
|
||||||
const listGuests = async () => {
|
|
||||||
const guests = await api('/guest');
|
|
||||||
showResult(guests);
|
|
||||||
};
|
|
||||||
|
|
||||||
const createGuest = async () => {
|
|
||||||
const name = confirmPrompt('Nombre');
|
|
||||||
if (!name) return;
|
|
||||||
const email = confirmPrompt('Email');
|
|
||||||
const phone = confirmPrompt('Teléfono');
|
|
||||||
const guest = await api('/guest', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ name, email, phone }),
|
|
||||||
});
|
|
||||||
showResult(guest);
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateGuestRsvp = async () => {
|
|
||||||
const id = confirmPrompt('ID del invitado');
|
|
||||||
if (!id) return;
|
|
||||||
const rsvp = confirmPrompt('RSVP (true/false)', 'true');
|
|
||||||
const updated = await api(`/guest/${id}/rsvp`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ rsvp: rsvp === 'true' }),
|
|
||||||
});
|
|
||||||
showResult(updated);
|
|
||||||
};
|
|
||||||
|
|
||||||
const listTodos = async () => {
|
|
||||||
const todos = await api('/todo');
|
|
||||||
showResult(todos);
|
|
||||||
};
|
|
||||||
|
|
||||||
const createTodo = async () => {
|
|
||||||
const title = confirmPrompt('Título');
|
|
||||||
if (!title) return;
|
|
||||||
const description = confirmPrompt('Descripción');
|
|
||||||
const todo = await api('/todo', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ title, description }),
|
|
||||||
});
|
|
||||||
showResult(todo);
|
|
||||||
};
|
|
||||||
|
|
||||||
const completeTodo = async () => {
|
|
||||||
const id = confirmPrompt('ID del To-do');
|
|
||||||
if (!id) return;
|
|
||||||
const completed = await api(`/todo/${id}/complete`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
});
|
|
||||||
showResult(completed);
|
|
||||||
};
|
|
||||||
|
|
||||||
const listGifts = async () => {
|
|
||||||
const gifts = await api('/gift');
|
|
||||||
showResult(gifts);
|
|
||||||
};
|
|
||||||
|
|
||||||
const createGift = async () => {
|
|
||||||
const name = confirmPrompt('Nombre del regalo');
|
|
||||||
if (!name) return;
|
|
||||||
const description = confirmPrompt('Descripción');
|
|
||||||
const price = confirmPrompt('Precio');
|
|
||||||
const gift = await api('/gift', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ name, description, price: Number(price) || 0 }),
|
|
||||||
});
|
|
||||||
showResult(gift);
|
|
||||||
};
|
|
||||||
|
|
||||||
const contributeGift = async () => {
|
|
||||||
const id = confirmPrompt('ID del regalo');
|
|
||||||
if (!id) return;
|
|
||||||
const name = confirmPrompt('Nombre del contribuyente');
|
|
||||||
const amount = confirmPrompt('Monto');
|
|
||||||
const contribution = await api(`/gift/${id}/contribution`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ contributorName: name, amount: Number(amount) || 0 }),
|
|
||||||
});
|
|
||||||
showResult(contribution);
|
|
||||||
};
|
|
||||||
|
|
||||||
const actions = computed(() => {
|
|
||||||
const map = {
|
|
||||||
guest: [
|
|
||||||
{ key: 'list', label: 'Listar invitados', handler: listGuests },
|
|
||||||
{ key: 'create', label: 'Crear invitado', handler: createGuest },
|
|
||||||
{ key: 'rsvp', label: 'Actualizar RSVP', handler: updateGuestRsvp },
|
|
||||||
],
|
|
||||||
todo: [
|
|
||||||
{ key: 'list', label: 'Listar To-dos', handler: listTodos },
|
|
||||||
{ key: 'create', label: 'Crear To-do', handler: createTodo },
|
|
||||||
{ key: 'complete', label: 'Completar To-do', handler: completeTodo },
|
|
||||||
],
|
|
||||||
gift: [
|
|
||||||
{ key: 'list', label: 'Listar regalos', handler: listGifts },
|
|
||||||
{ key: 'create', label: 'Crear regalo', handler: createGift },
|
|
||||||
{ key: 'contribute', label: 'Agregar contribución', handler: contributeGift },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
return map[selectedModule.value] || [];
|
|
||||||
});
|
|
||||||
|
|
||||||
const loadModules = async () => {
|
|
||||||
if (!token.value) return;
|
|
||||||
try {
|
|
||||||
modules.value = await api('/modules');
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const selectModule = (key) => {
|
|
||||||
selectedModule.value = key;
|
|
||||||
moduleHtml.value = `<p>Seleccionado <strong>${key}</strong>. Usa las acciones en el menú.</p>`;
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
token,
|
|
||||||
user,
|
|
||||||
tenantId,
|
|
||||||
status,
|
|
||||||
modules,
|
|
||||||
selectedModule,
|
|
||||||
moduleHtml,
|
|
||||||
actions,
|
|
||||||
login,
|
|
||||||
register,
|
|
||||||
loginMessage,
|
|
||||||
loginError,
|
|
||||||
loginSuccess,
|
|
||||||
registerMessage,
|
|
||||||
registerError,
|
|
||||||
registerSuccess,
|
|
||||||
loading,
|
|
||||||
loginUser,
|
|
||||||
registerUser,
|
|
||||||
logout,
|
|
||||||
loadModules,
|
|
||||||
selectModule,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
}).mount('#app');
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
|
|
||||||
import { GiftService } from '../gift/services/gift.service';
|
|
||||||
import { GuestService } from '../guest/services/guest.service';
|
|
||||||
import { TodoService } from '../todo/services/todo.service';
|
|
||||||
import { ModuleRegistryService } from '../core/services/module-registry.service';
|
|
||||||
|
|
||||||
@Controller('admin')
|
|
||||||
export class AdminController {
|
|
||||||
constructor(
|
|
||||||
private readonly moduleRegistry: ModuleRegistryService,
|
|
||||||
private readonly guestService: GuestService,
|
|
||||||
private readonly giftService: GiftService,
|
|
||||||
private readonly todoService: TodoService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@Get('modules')
|
|
||||||
getModules() {
|
|
||||||
return this.moduleRegistry.getModules();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Guests
|
|
||||||
@Get('guest')
|
|
||||||
listGuests() {
|
|
||||||
return this.guestService.listGuests();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('guest')
|
|
||||||
createGuest(@Body() body: any) {
|
|
||||||
return this.guestService.createGuest(body as any);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch('guest/:id/rsvp')
|
|
||||||
updateGuestRsvp(@Param('id') id: string, @Body() body: any) {
|
|
||||||
return this.guestService.updateRsvp(id, body as any);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Todos
|
|
||||||
@Get('todo')
|
|
||||||
listTodos() {
|
|
||||||
return this.todoService.listTodos();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('todo')
|
|
||||||
createTodo(@Body() body: Record<string, any>) {
|
|
||||||
return this.todoService.createTodo(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch('todo/:id/complete')
|
|
||||||
completeTodo(@Param('id') id: string) {
|
|
||||||
return this.todoService.markComplete(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gifts
|
|
||||||
@Get('gift')
|
|
||||||
listGifts() {
|
|
||||||
return this.giftService.listGifts();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('gift')
|
|
||||||
createGift(@Body() body: any) {
|
|
||||||
return this.giftService.createGift(body as any);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('gift/:id')
|
|
||||||
getGift(@Param('id') id: string) {
|
|
||||||
return this.giftService.getGiftById(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('gift/:id/contribution')
|
|
||||||
createContribution(@Param('id') id: string, @Body() body: any) {
|
|
||||||
return this.giftService.createContribution({
|
|
||||||
...(body as any),
|
|
||||||
giftId: id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('gift/:id/contributions')
|
|
||||||
listContributions(@Param('id') id: string) {
|
|
||||||
return this.giftService.listContributions(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { CoreModule } from '../core/core.module';
|
|
||||||
import { GiftModule } from '../gift/gift.module';
|
|
||||||
import { GuestModule } from '../guest/guest.module';
|
|
||||||
import { TodoModule } from '../todo/todo.module';
|
|
||||||
import { AdminController } from './admin.controller';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [CoreModule, GiftModule, GuestModule, TodoModule],
|
|
||||||
controllers: [AdminController],
|
|
||||||
})
|
|
||||||
export class AdminModule {}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { ServeStaticModule } from '@nestjs/serve-static';
|
|
||||||
import { join } from 'path';
|
|
||||||
import { CoreModule } from './core/core.module';
|
|
||||||
import { GiftModule } from './gift/gift.module';
|
|
||||||
import { GuestModule } from './guest/guest.module';
|
|
||||||
import { TodoModule } from './todo/todo.module';
|
|
||||||
import { AdminModule } from './admin/admin.module';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
ServeStaticModule.forRoot({
|
|
||||||
rootPath: join(__dirname, '..', 'public'),
|
|
||||||
serveRoot: '/admin',
|
|
||||||
exclude: ['/admin/modules'],
|
|
||||||
serveStaticOptions: {
|
|
||||||
index: 'admin.html',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
CoreModule,
|
|
||||||
GiftModule,
|
|
||||||
GuestModule,
|
|
||||||
TodoModule,
|
|
||||||
AdminModule,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class AppModule {}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { Body, Controller, Post } from '@nestjs/common';
|
|
||||||
import { AuthService } from '../services/auth.service';
|
|
||||||
import { UserService } from '../services/user.service';
|
|
||||||
|
|
||||||
@Controller('auth')
|
|
||||||
export class AuthController {
|
|
||||||
constructor(
|
|
||||||
private readonly authService: AuthService,
|
|
||||||
private readonly userService: UserService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@Post('register')
|
|
||||||
async register(
|
|
||||||
@Body()
|
|
||||||
body: {
|
|
||||||
name?: string;
|
|
||||||
email: string;
|
|
||||||
password: string;
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
const tenantId = process.env.DEFAULT_TENANT_ID || 'default';
|
|
||||||
const user = await this.userService.createUser(tenantId, body.email, body.password, body.name);
|
|
||||||
return { id: user.id, email: user.email, name: user.name };
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('login')
|
|
||||||
async login(@Body() body: { email: string; password: string }) {
|
|
||||||
const tenantId = process.env.DEFAULT_TENANT_ID || 'default';
|
|
||||||
const user = await this.userService.validateUser(tenantId, body.email, body.password);
|
|
||||||
if (!user) {
|
|
||||||
return { message: 'Invalid credentials' };
|
|
||||||
}
|
|
||||||
const token = this.authService.sign({ sub: user.id, name: user.name, tenantId });
|
|
||||||
return { token };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
||||||
import { AuthService } from './services/auth.service';
|
|
||||||
import { TokenService } from './services/token.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AuthGuard implements CanActivate {
|
|
||||||
constructor(
|
|
||||||
private readonly authService: AuthService,
|
|
||||||
private readonly tokenService: TokenService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
canActivate(context: ExecutionContext): boolean {
|
|
||||||
const request = context.switchToHttp().getRequest();
|
|
||||||
|
|
||||||
// Allow the admin UI endpoints to be accessed without authentication.
|
|
||||||
// The UI is served from /admin and calls /api/admin/modules.
|
|
||||||
if (request.method === 'GET' && request.url?.startsWith('/api/admin')) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allow auth endpoints (login/register) without a token.
|
|
||||||
if (request.method === 'POST' && request.url?.startsWith('/api/auth/')) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const authHeader = request.headers['authorization'] || '';
|
|
||||||
const token = Array.isArray(authHeader) ? authHeader[0] : authHeader;
|
|
||||||
if (!token) {
|
|
||||||
throw new UnauthorizedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
const raw = token.replace(/^Bearer\s+/i, '');
|
|
||||||
|
|
||||||
// Try JWT first, then fallback to simple token-based auth.
|
|
||||||
const payload = this.authService.verify(raw);
|
|
||||||
if (payload) {
|
|
||||||
request.user = payload;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const validToken = this.tokenService.validate(raw);
|
|
||||||
if (validToken) {
|
|
||||||
request.user = { token: raw, name: validToken.name };
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new UnauthorizedException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
|
||||||
import { AuthService } from './services/auth.service';
|
|
||||||
import { TokenService } from './services/token.service';
|
|
||||||
import { UserService } from './services/user.service';
|
|
||||||
import { AuthGuard } from './auth.guard';
|
|
||||||
import { UserSchema } from './entities/user.entity';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [MikroOrmModule.forFeature([UserSchema])],
|
|
||||||
providers: [AuthService, TokenService, UserService, AuthGuard],
|
|
||||||
exports: [AuthService, TokenService, UserService, AuthGuard],
|
|
||||||
})
|
|
||||||
export class AuthModule {}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
|
||||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
|
||||||
import { AuthModule } from './auth.module';
|
|
||||||
import { ModuleLinkerService } from './services/module-linker.service';
|
|
||||||
import { NotificationService } from './services/notification.service';
|
|
||||||
import { NotificationRuleService } from './services/notification-rule.service';
|
|
||||||
import { ModuleRegistryService } from './services/module-registry.service';
|
|
||||||
import { AuthController } from './api/auth.controller';
|
|
||||||
import { NotificationRuleSchema } from './entities/notification-rule.entity';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
EventEmitterModule.forRoot(),
|
|
||||||
MikroOrmModule.forRoot({
|
|
||||||
driver: (require('@mikro-orm/postgresql').PostgreSqlDriver) as any,
|
|
||||||
host: process.env.DB_HOST || 'localhost',
|
|
||||||
port: Number(process.env.DB_PORT) || 5432,
|
|
||||||
user: process.env.DB_USER || 'postgres',
|
|
||||||
password: process.env.DB_PASSWORD || 'postgres',
|
|
||||||
dbName: process.env.DB_NAME || 'planner',
|
|
||||||
autoLoadEntities: true,
|
|
||||||
migrations: {
|
|
||||||
path: 'dist/migrations',
|
|
||||||
transactional: true,
|
|
||||||
emit: 'js',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
AuthModule,
|
|
||||||
MikroOrmModule.forFeature([NotificationRuleSchema]),
|
|
||||||
],
|
|
||||||
providers: [
|
|
||||||
ModuleLinkerService,
|
|
||||||
NotificationService,
|
|
||||||
NotificationRuleService,
|
|
||||||
ModuleRegistryService,
|
|
||||||
],
|
|
||||||
controllers: [AuthController],
|
|
||||||
exports: [
|
|
||||||
EventEmitterModule,
|
|
||||||
AuthModule,
|
|
||||||
ModuleLinkerService,
|
|
||||||
NotificationService,
|
|
||||||
NotificationRuleService,
|
|
||||||
ModuleRegistryService,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class CoreModule {}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
|
||||||
import { PostgreSqlDriver } from '@mikro-orm/postgresql';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
MikroOrmModule.forRoot({
|
|
||||||
driver: PostgreSqlDriver as any,
|
|
||||||
host: process.env.DB_HOST || 'localhost',
|
|
||||||
port: Number(process.env.DB_PORT) || 5432,
|
|
||||||
user: process.env.DB_USER || 'postgres',
|
|
||||||
password: process.env.DB_PASSWORD || 'postgres',
|
|
||||||
dbName: process.env.DB_NAME || 'planner',
|
|
||||||
autoLoadEntities: true,
|
|
||||||
entities: ['./dist/**/*.entity.js'],
|
|
||||||
entitiesTs: ['./src/**/*.entity.ts'],
|
|
||||||
migrations: {
|
|
||||||
path: 'dist/migrations',
|
|
||||||
transactional: true,
|
|
||||||
emit: 'js',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
exports: [MikroOrmModule],
|
|
||||||
})
|
|
||||||
export class DatabaseModule {}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { v4 as uuidv4 } from 'uuid';
|
|
||||||
|
|
||||||
export abstract class BaseEntity {
|
|
||||||
id: string = uuidv4();
|
|
||||||
tenantId!: string;
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
createdAt: Date = new Date();
|
|
||||||
updatedAt: Date = new Date();
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import { EntitySchema } from '@mikro-orm/core';
|
|
||||||
import { BaseEntity } from './base.entity';
|
|
||||||
|
|
||||||
export class NotificationRule extends BaseEntity {
|
|
||||||
module!: string; // e.g. 'guest', 'gift', 'todo'
|
|
||||||
|
|
||||||
event!: string; // e.g. 'guest.invited', 'todo.completed'
|
|
||||||
|
|
||||||
channels!: Array<'email' | 'whatsapp' | 'sms' | 'custom'>;
|
|
||||||
|
|
||||||
conditions?: Record<string, any>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const NotificationRuleSchema = new EntitySchema<NotificationRule>({
|
|
||||||
class: NotificationRule,
|
|
||||||
tableName: 'notification_rules',
|
|
||||||
properties: {
|
|
||||||
id: { primary: true, type: 'uuid', defaultRaw: 'uuid_generate_v4()' },
|
|
||||||
tenantId: { type: 'string' },
|
|
||||||
metadata: { type: 'json', nullable: true },
|
|
||||||
createdAt: { type: 'date', defaultRaw: 'now()' },
|
|
||||||
updatedAt: { type: 'date', defaultRaw: 'now()' },
|
|
||||||
|
|
||||||
module: { type: 'string' },
|
|
||||||
event: { type: 'string' },
|
|
||||||
channels: { type: 'json' },
|
|
||||||
conditions: { type: 'json', nullable: true },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
import { EntitySchema } from '@mikro-orm/core';
|
|
||||||
|
|
||||||
export class AuthToken {
|
|
||||||
id!: string;
|
|
||||||
tenantId!: string;
|
|
||||||
token!: string;
|
|
||||||
name?: string;
|
|
||||||
expiresAt?: Date;
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
createdAt!: Date;
|
|
||||||
updatedAt!: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const AuthTokenSchema = new EntitySchema<AuthToken>({
|
|
||||||
class: AuthToken,
|
|
||||||
tableName: 'auth_tokens',
|
|
||||||
properties: {
|
|
||||||
id: {
|
|
||||||
primary: true,
|
|
||||||
type: 'uuid',
|
|
||||||
default: 'uuid_generate_v4()',
|
|
||||||
},
|
|
||||||
tenantId: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: false,
|
|
||||||
},
|
|
||||||
token: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: false,
|
|
||||||
},
|
|
||||||
name: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
expiresAt: {
|
|
||||||
type: 'date',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
type: 'json',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
createdAt: {
|
|
||||||
type: 'date',
|
|
||||||
nullable: false,
|
|
||||||
defaultRaw: 'now()',
|
|
||||||
},
|
|
||||||
updatedAt: {
|
|
||||||
type: 'date',
|
|
||||||
nullable: false,
|
|
||||||
defaultRaw: 'now()',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import { EntitySchema } from '@mikro-orm/core';
|
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
|
||||||
import { BaseEntity } from './base.entity';
|
|
||||||
|
|
||||||
export class User extends BaseEntity {
|
|
||||||
email!: string;
|
|
||||||
name?: string;
|
|
||||||
passwordHash!: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const UserSchema = new EntitySchema<User>({
|
|
||||||
class: User,
|
|
||||||
tableName: 'users',
|
|
||||||
properties: {
|
|
||||||
id: {
|
|
||||||
type: 'uuid',
|
|
||||||
primary: true,
|
|
||||||
default: uuidv4(),
|
|
||||||
},
|
|
||||||
tenantId: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
type: 'json',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
createdAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
updatedAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
email: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: false,
|
|
||||||
},
|
|
||||||
name: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
passwordHash: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import * as jwt from 'jsonwebtoken';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AuthService {
|
|
||||||
private readonly jwtSecret: jwt.Secret = process.env.JWT_SECRET || 'default_secret';
|
|
||||||
|
|
||||||
sign(payload: Record<string, any>, expiresIn = '1d'): string {
|
|
||||||
return jwt.sign(payload, this.jwtSecret, { expiresIn } as jwt.SignOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
verify(token: string): Record<string, any> | null {
|
|
||||||
try {
|
|
||||||
const decoded = jwt.verify(token, this.jwtSecret) as jwt.JwtPayload | string;
|
|
||||||
return typeof decoded === 'string' ? { sub: decoded } : (decoded as Record<string, any>);
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class ModuleLinkerService {
|
|
||||||
/**
|
|
||||||
* Hydrates data from multiple modules by IDs for frontend consumption.
|
|
||||||
* @param links Array of objects with moduleName and id
|
|
||||||
*/
|
|
||||||
async hydrate(links: Array<{ moduleName: string; id: string }>): Promise<any[]> {
|
|
||||||
// Implement hydration logic here, e.g. fetch from APIs or repositories
|
|
||||||
// ...existing code...
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
|
|
||||||
export type AdminModuleInfo = {
|
|
||||||
key: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
routePrefix?: string;
|
|
||||||
version?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class ModuleRegistryService {
|
|
||||||
private modules: AdminModuleInfo[] = [];
|
|
||||||
|
|
||||||
registerModule(info: AdminModuleInfo) {
|
|
||||||
if (!this.modules.find((m) => m.key === info.key)) {
|
|
||||||
this.modules.push(info);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getModules(): AdminModuleInfo[] {
|
|
||||||
return [...this.modules];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
export interface NotificationProvider {
|
|
||||||
send(options: { to: string; subject: string; body: string; metadata?: any }): Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type NotificationChannel = 'email' | 'whatsapp' | 'sms' | 'custom';
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { MikroORM } from '@mikro-orm/core';
|
|
||||||
import { NotificationRule } from '../entities/notification-rule.entity';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class NotificationRuleService {
|
|
||||||
constructor(private readonly orm: MikroORM) {}
|
|
||||||
|
|
||||||
private get em() {
|
|
||||||
return this.orm.em.fork();
|
|
||||||
}
|
|
||||||
|
|
||||||
async getRulesForEvent(tenantId: string, module: string, event: string): Promise<NotificationRule[]> {
|
|
||||||
return this.em.find(NotificationRule, { tenantId, module, event });
|
|
||||||
}
|
|
||||||
|
|
||||||
async createRule(tenantId: string, rule: Partial<NotificationRule>): Promise<NotificationRule> {
|
|
||||||
const entity = this.em.create(NotificationRule, {
|
|
||||||
tenantId,
|
|
||||||
...rule,
|
|
||||||
} as any);
|
|
||||||
this.em.persist(entity);
|
|
||||||
await this.em.flush();
|
|
||||||
return entity;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { NotificationProvider, NotificationChannel } from './notification-provider.interface';
|
|
||||||
import { EmailProvider } from './providers/email.provider';
|
|
||||||
import { WhatsappProvider } from './providers/whatsapp.provider';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class NotificationService {
|
|
||||||
private providers: Record<NotificationChannel, NotificationProvider> = {} as any;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
// Registramos proveedores por defecto (puede reemplazarse desde el código de inicialización)
|
|
||||||
this.registerProvider('email', new EmailProvider());
|
|
||||||
this.registerProvider('whatsapp', new WhatsappProvider());
|
|
||||||
}
|
|
||||||
|
|
||||||
registerProvider(channel: NotificationChannel, provider: NotificationProvider) {
|
|
||||||
this.providers[channel] = provider;
|
|
||||||
}
|
|
||||||
|
|
||||||
async send(
|
|
||||||
channel: NotificationChannel,
|
|
||||||
to: string,
|
|
||||||
subject: string,
|
|
||||||
body: string,
|
|
||||||
metadata?: any,
|
|
||||||
) {
|
|
||||||
const provider = this.providers[channel];
|
|
||||||
if (!provider) {
|
|
||||||
throw new Error(`No provider registered for channel ${channel}`);
|
|
||||||
}
|
|
||||||
await provider.send({ to, subject, body, metadata });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { NotificationProvider } from '../notification-provider.interface';
|
|
||||||
|
|
||||||
export class EmailProvider implements NotificationProvider {
|
|
||||||
async send(options: { to: string; subject: string; body: string; metadata?: any }): Promise<void> {
|
|
||||||
// Implementación concreta que use un servicio como Resend, Mailgun o similar.
|
|
||||||
// ...existing code...
|
|
||||||
console.log('[EmailProvider] Sending email to', options.to);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { NotificationProvider } from '../notification-provider.interface';
|
|
||||||
|
|
||||||
export class WhatsappProvider implements NotificationProvider {
|
|
||||||
async send(options: { to: string; subject: string; body: string; metadata?: any }): Promise<void> {
|
|
||||||
// Implementación concreta que use un servicio de WhatsApp Business API o similar.
|
|
||||||
// ...existing code...
|
|
||||||
console.log('[WhatsappProvider] Sending message to', options.to);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
|
||||||
import { AuthToken } from '../entities/token.entity';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class TokenService {
|
|
||||||
// En una implementación real esto debería usar el repositorio de MikroORM.
|
|
||||||
private tokens: AuthToken[] = [];
|
|
||||||
|
|
||||||
createToken(name?: string, expiresInHours?: number): AuthToken {
|
|
||||||
const token = new AuthToken();
|
|
||||||
token.token = uuidv4();
|
|
||||||
token.name = name;
|
|
||||||
if (expiresInHours) {
|
|
||||||
token.expiresAt = new Date(Date.now() + expiresInHours * 60 * 60 * 1000);
|
|
||||||
}
|
|
||||||
this.tokens.push(token);
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
validate(tokenString: string): AuthToken | null {
|
|
||||||
const token = this.tokens.find((t) => t.token === tokenString);
|
|
||||||
if (!token) return null;
|
|
||||||
if (token.expiresAt && token.expiresAt < new Date()) return null;
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { EntityRepository } from '@mikro-orm/core';
|
|
||||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
|
||||||
import * as bcrypt from 'bcryptjs';
|
|
||||||
import { User } from '../entities/user.entity';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class UserService {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(User)
|
|
||||||
private readonly userRepository: EntityRepository<User>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async createUser(tenantId: string, email: string, password: string, name?: string) {
|
|
||||||
const existing = await this.userRepository.findOne({ tenantId, email });
|
|
||||||
if (existing) {
|
|
||||||
throw new Error('User already exists');
|
|
||||||
}
|
|
||||||
const user = new User();
|
|
||||||
user.tenantId = tenantId;
|
|
||||||
user.email = email;
|
|
||||||
user.name = name;
|
|
||||||
user.passwordHash = await bcrypt.hash(password, 10);
|
|
||||||
await this.userRepository.persistAndFlush(user);
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateUser(tenantId: string, email: string, password: string) {
|
|
||||||
const user = await this.userRepository.findOne({ tenantId, email });
|
|
||||||
if (!user) return null;
|
|
||||||
const isValid = await bcrypt.compare(password, user.passwordHash);
|
|
||||||
return isValid ? user : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { Logger } from '@nestjs/common';
|
|
||||||
|
|
||||||
export abstract class BaseWorkflow {
|
|
||||||
protected readonly logger = new Logger(this.constructor.name);
|
|
||||||
|
|
||||||
abstract execute(...args: any[]): Promise<any>;
|
|
||||||
|
|
||||||
protected logExecution(message: string, context?: any) {
|
|
||||||
this.logger.log(`[WORKFLOW] ${message}`);
|
|
||||||
if (context) {
|
|
||||||
this.logger.debug(context);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
export class CreateContributionDto {
|
|
||||||
giftId!: string;
|
|
||||||
contributorName!: string;
|
|
||||||
contributorEmail?: string;
|
|
||||||
amount!: number;
|
|
||||||
type?: 'individual' | 'group';
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
export class CreateGiftDto {
|
|
||||||
name!: string;
|
|
||||||
description?: string;
|
|
||||||
imageUrl?: string;
|
|
||||||
price?: number;
|
|
||||||
experience?: boolean;
|
|
||||||
ownerId?: string;
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
import { Controller, Get, Post, Body, Param, Headers, Req } from '@nestjs/common';
|
|
||||||
import { Request } from 'express';
|
|
||||||
import { GiftService } from '../services/gift.service';
|
|
||||||
import { CreateGiftDto } from './dto/create-gift.dto';
|
|
||||||
import { CreateContributionDto } from './dto/create-contribution.dto';
|
|
||||||
|
|
||||||
@Controller('gift')
|
|
||||||
export class GiftController {
|
|
||||||
constructor(private readonly giftService: GiftService) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
async createGift(
|
|
||||||
@Req() req: Request,
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Body() dto: CreateGiftDto,
|
|
||||||
) {
|
|
||||||
const ownerId = (req as any).user?.id;
|
|
||||||
return this.giftService.createGift(tenantId, { ...dto, ownerId });
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
async listGifts(@Headers('x-tenant-id') tenantId: string) {
|
|
||||||
return this.giftService.listGifts(tenantId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post('contribution')
|
|
||||||
async contribute(
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Body() dto: CreateContributionDto,
|
|
||||||
) {
|
|
||||||
return this.giftService.createContribution(tenantId, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':id')
|
|
||||||
async getGift(
|
|
||||||
@Req() req: Request,
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Param('id') id: string,
|
|
||||||
) {
|
|
||||||
const requesterId = (req as any).user?.id;
|
|
||||||
return this.giftService.getGiftById(tenantId, id, requesterId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':id/contributions')
|
|
||||||
async listContributions(
|
|
||||||
@Req() req: Request,
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Param('id') id: string,
|
|
||||||
) {
|
|
||||||
const requesterId = (req as any).user?.id;
|
|
||||||
return this.giftService.listContributions(tenantId, id, requesterId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
import { EntitySchema } from '@mikro-orm/core';
|
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
|
||||||
import { BaseEntity } from '../../core/entities/base.entity';
|
|
||||||
|
|
||||||
export class Gift extends BaseEntity {
|
|
||||||
name!: string;
|
|
||||||
description?: string;
|
|
||||||
imageUrl?: string;
|
|
||||||
price?: number;
|
|
||||||
experience?: boolean;
|
|
||||||
status: string = 'pending';
|
|
||||||
ownerId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const GiftSchema = new EntitySchema<Gift>({
|
|
||||||
class: Gift,
|
|
||||||
tableName: 'gifts',
|
|
||||||
properties: {
|
|
||||||
id: {
|
|
||||||
type: 'uuid',
|
|
||||||
primary: true,
|
|
||||||
default: uuidv4(),
|
|
||||||
},
|
|
||||||
tenantId: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
type: 'json',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
createdAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
updatedAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
name: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
description: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
imageUrl: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
price: {
|
|
||||||
type: 'float',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
experience: {
|
|
||||||
type: 'boolean',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
status: {
|
|
||||||
type: 'string',
|
|
||||||
default: 'pending',
|
|
||||||
},
|
|
||||||
ownerId: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
export class GiftContribution extends BaseEntity {
|
|
||||||
giftId!: string;
|
|
||||||
contributorName!: string;
|
|
||||||
contributorEmail?: string;
|
|
||||||
amount!: number;
|
|
||||||
type: string = 'individual';
|
|
||||||
status: string = 'pending';
|
|
||||||
}
|
|
||||||
|
|
||||||
export const GiftContributionSchema = new EntitySchema<GiftContribution>({
|
|
||||||
class: GiftContribution,
|
|
||||||
tableName: 'gift_contributions',
|
|
||||||
properties: {
|
|
||||||
id: {
|
|
||||||
type: 'uuid',
|
|
||||||
primary: true,
|
|
||||||
default: uuidv4(),
|
|
||||||
},
|
|
||||||
tenantId: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
type: 'json',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
createdAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
updatedAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
giftId: {
|
|
||||||
type: 'uuid',
|
|
||||||
},
|
|
||||||
contributorName: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
contributorEmail: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
amount: {
|
|
||||||
type: 'float',
|
|
||||||
},
|
|
||||||
type: {
|
|
||||||
type: 'string',
|
|
||||||
default: 'individual',
|
|
||||||
},
|
|
||||||
status: {
|
|
||||||
type: 'string',
|
|
||||||
default: 'pending',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
|
||||||
import { CoreModule } from '../core/core.module';
|
|
||||||
import { GiftService } from './services/gift.service';
|
|
||||||
import { GiftController } from './api/gift.controller';
|
|
||||||
import { GiftSubscriber } from './subscribers/gift.subscriber';
|
|
||||||
import { GiftSchema, GiftContributionSchema } from './entities/gift.entity';
|
|
||||||
import { GiftModuleRegistration } from './gift.registration';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
CoreModule,
|
|
||||||
MikroOrmModule.forFeature({ entities: [GiftSchema, GiftContributionSchema] }),
|
|
||||||
],
|
|
||||||
providers: [GiftService, GiftSubscriber, GiftModuleRegistration],
|
|
||||||
controllers: [GiftController],
|
|
||||||
exports: [GiftService],
|
|
||||||
})
|
|
||||||
export class GiftModule {}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
|
||||||
import { ModuleRegistryService } from '../core/services/module-registry.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GiftModuleRegistration implements OnModuleInit {
|
|
||||||
constructor(private readonly moduleRegistry: ModuleRegistryService) {}
|
|
||||||
|
|
||||||
onModuleInit() {
|
|
||||||
this.moduleRegistry.registerModule({
|
|
||||||
key: 'gift',
|
|
||||||
name: 'Regalos',
|
|
||||||
description: 'Gestión de lista de regalos, aportes individuales y grupales.',
|
|
||||||
routePrefix: '/gift',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { MikroORM } from '@mikro-orm/core';
|
|
||||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
||||||
import { Gift, GiftContribution } from '../entities/gift.entity';
|
|
||||||
import { CreateGiftDto } from '../api/dto/create-gift.dto';
|
|
||||||
import { CreateContributionDto } from '../api/dto/create-contribution.dto';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GiftService {
|
|
||||||
constructor(
|
|
||||||
private readonly orm: MikroORM,
|
|
||||||
private readonly eventEmitter: EventEmitter2,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
private get em() {
|
|
||||||
return this.orm.em.fork();
|
|
||||||
}
|
|
||||||
|
|
||||||
private getTenantId(): string {
|
|
||||||
// Tenant is now fixed; multi-tenant handled by reverse proxy (subdomains)
|
|
||||||
return process.env.DEFAULT_TENANT_ID || 'default';
|
|
||||||
}
|
|
||||||
|
|
||||||
async createGift(dto: CreateGiftDto): Promise<Gift> {
|
|
||||||
const gift = this.em.create(Gift, {
|
|
||||||
tenantId: this.getTenantId(),
|
|
||||||
...dto,
|
|
||||||
} as any);
|
|
||||||
this.em.persist(gift);
|
|
||||||
await this.em.flush();
|
|
||||||
this.eventEmitter.emit('gift.created', { gift });
|
|
||||||
return gift;
|
|
||||||
}
|
|
||||||
|
|
||||||
async createContribution(dto: CreateContributionDto): Promise<GiftContribution> {
|
|
||||||
const contribution = this.em.create(GiftContribution, {
|
|
||||||
tenantId: this.getTenantId(),
|
|
||||||
...dto,
|
|
||||||
} as any);
|
|
||||||
this.em.persist(contribution);
|
|
||||||
await this.em.flush();
|
|
||||||
this.eventEmitter.emit('gift.contribution', { contribution });
|
|
||||||
return contribution;
|
|
||||||
}
|
|
||||||
|
|
||||||
async listGifts(): Promise<Gift[]> {
|
|
||||||
return this.em.find(Gift, { tenantId: this.getTenantId() });
|
|
||||||
}
|
|
||||||
|
|
||||||
async getGiftById(
|
|
||||||
id: string,
|
|
||||||
requesterId?: string,
|
|
||||||
): Promise<Gift | null> {
|
|
||||||
const gift = await this.em.findOne(Gift, { tenantId: this.getTenantId(), id });
|
|
||||||
if (!gift) return null;
|
|
||||||
if (requesterId && gift.ownerId && gift.ownerId !== requesterId) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return gift;
|
|
||||||
}
|
|
||||||
|
|
||||||
async listContributions(
|
|
||||||
giftId: string,
|
|
||||||
requesterId?: string,
|
|
||||||
): Promise<GiftContribution[]> {
|
|
||||||
const gift = await this.getGiftById(giftId, requesterId);
|
|
||||||
if (!gift) return [];
|
|
||||||
return this.em.find(GiftContribution, { tenantId: this.getTenantId(), giftId });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
import { OnEvent } from '@nestjs/event-emitter';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { NotificationService } from '../../core/services/notification.service';
|
|
||||||
import { NotificationRuleService } from '../../core/services/notification-rule.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GiftSubscriber {
|
|
||||||
constructor(
|
|
||||||
private readonly notificationService: NotificationService,
|
|
||||||
private readonly notificationRuleService: NotificationRuleService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@OnEvent('gift.created')
|
|
||||||
async handleGiftCreated(payload: any) {
|
|
||||||
const { gift } = payload;
|
|
||||||
const rules = await this.notificationRuleService.getRulesForEvent(gift.tenantId, 'gift', 'gift.created');
|
|
||||||
for (const rule of rules) {
|
|
||||||
for (const channel of rule.channels) {
|
|
||||||
await this.notificationService.send(
|
|
||||||
channel,
|
|
||||||
gift.metadata?.notifyTo || '',
|
|
||||||
'Nuevo regalo creado',
|
|
||||||
`Se ha creado el regalo: ${gift.name}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OnEvent('gift.contribution')
|
|
||||||
async handleGiftContribution(payload: any) {
|
|
||||||
const { contribution } = payload;
|
|
||||||
const rules = await this.notificationRuleService.getRulesForEvent(contribution.tenantId, 'gift', 'gift.contribution');
|
|
||||||
for (const rule of rules) {
|
|
||||||
for (const channel of rule.channels) {
|
|
||||||
await this.notificationService.send(
|
|
||||||
channel,
|
|
||||||
contribution.metadata?.notifyTo || '',
|
|
||||||
'Nuevo aporte a regalo',
|
|
||||||
`Se ha registrado un aporte de ${contribution.amount} al regalo (${contribution.giftId}).`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { BaseWorkflow } from '../../core/workflows/base-workflow';
|
|
||||||
|
|
||||||
export class GiftWorkflow extends BaseWorkflow {
|
|
||||||
async execute(...args: any[]): Promise<any> {
|
|
||||||
this.logExecution('Ejecutando workflow de regalo', args);
|
|
||||||
// Lógica de workflow para regalos
|
|
||||||
// ...existing code...
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
export class CreateGuestDto {
|
|
||||||
name!: string;
|
|
||||||
email?: string;
|
|
||||||
phone?: string;
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
export class UpdateRsvpDto {
|
|
||||||
rsvp!: boolean;
|
|
||||||
tableId?: string;
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { Controller, Get, Post, Body, Param, Headers, Patch } from '@nestjs/common';
|
|
||||||
import { GuestService } from '../services/guest.service';
|
|
||||||
import { CreateGuestDto } from './dto/create-guest.dto';
|
|
||||||
import { UpdateRsvpDto } from './dto/update-rsvp.dto';
|
|
||||||
|
|
||||||
@Controller('guest')
|
|
||||||
export class GuestController {
|
|
||||||
constructor(private readonly guestService: GuestService) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
async createGuest(
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Body() dto: CreateGuestDto,
|
|
||||||
) {
|
|
||||||
return this.guestService.createGuest(tenantId, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
async listGuests(@Headers('x-tenant-id') tenantId: string) {
|
|
||||||
return this.guestService.listGuests(tenantId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':id/rsvp')
|
|
||||||
async updateRsvp(
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Param('id') id: string,
|
|
||||||
@Body() dto: UpdateRsvpDto,
|
|
||||||
) {
|
|
||||||
return this.guestService.updateRsvp(tenantId, id, dto);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
import { EntitySchema } from '@mikro-orm/core';
|
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
|
||||||
import { BaseEntity } from '../../core/entities/base.entity';
|
|
||||||
|
|
||||||
export class Guest extends BaseEntity {
|
|
||||||
name!: string;
|
|
||||||
email?: string;
|
|
||||||
phone?: string;
|
|
||||||
rsvp: boolean = false;
|
|
||||||
tableId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const GuestSchema = new EntitySchema<Guest>({
|
|
||||||
class: Guest,
|
|
||||||
tableName: 'guests',
|
|
||||||
properties: {
|
|
||||||
id: {
|
|
||||||
type: 'uuid',
|
|
||||||
primary: true,
|
|
||||||
default: uuidv4(),
|
|
||||||
},
|
|
||||||
tenantId: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
type: 'json',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
createdAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
updatedAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
name: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
email: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
phone: {
|
|
||||||
type: 'string',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
rsvp: {
|
|
||||||
type: 'boolean',
|
|
||||||
default: false,
|
|
||||||
},
|
|
||||||
tableId: {
|
|
||||||
type: 'uuid',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
export class GuestNotificationPreference extends BaseEntity {
|
|
||||||
guestId!: string;
|
|
||||||
email: boolean = true;
|
|
||||||
whatsapp: boolean = false;
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const GuestNotificationPreferenceSchema = new EntitySchema<GuestNotificationPreference>({
|
|
||||||
class: GuestNotificationPreference,
|
|
||||||
tableName: 'guest_notification_preferences',
|
|
||||||
properties: {
|
|
||||||
id: {
|
|
||||||
type: 'uuid',
|
|
||||||
primary: true,
|
|
||||||
default: uuidv4(),
|
|
||||||
},
|
|
||||||
tenantId: {
|
|
||||||
type: 'string',
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
type: 'json',
|
|
||||||
nullable: true,
|
|
||||||
},
|
|
||||||
createdAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
updatedAt: {
|
|
||||||
type: 'date',
|
|
||||||
default: new Date(),
|
|
||||||
},
|
|
||||||
guestId: {
|
|
||||||
type: 'uuid',
|
|
||||||
},
|
|
||||||
email: {
|
|
||||||
type: 'boolean',
|
|
||||||
default: true,
|
|
||||||
},
|
|
||||||
whatsapp: {
|
|
||||||
type: 'boolean',
|
|
||||||
default: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
|
||||||
import { CoreModule } from '../core/core.module';
|
|
||||||
import { GuestService } from './services/guest.service';
|
|
||||||
import { GuestController } from './api/guest.controller';
|
|
||||||
import { GuestSubscriber } from './subscribers/guest.subscriber';
|
|
||||||
import { GuestSchema, GuestNotificationPreferenceSchema } from './entities/guest.entity';
|
|
||||||
import { GuestModuleRegistration } from './guest.registration';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
CoreModule,
|
|
||||||
MikroOrmModule.forFeature({
|
|
||||||
entities: [GuestSchema, GuestNotificationPreferenceSchema],
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
providers: [GuestService, GuestSubscriber, GuestModuleRegistration],
|
|
||||||
controllers: [GuestController],
|
|
||||||
exports: [GuestService],
|
|
||||||
})
|
|
||||||
export class GuestModule {}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
|
||||||
import { ModuleRegistryService } from '../core/services/module-registry.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GuestModuleRegistration implements OnModuleInit {
|
|
||||||
constructor(private readonly moduleRegistry: ModuleRegistryService) {}
|
|
||||||
|
|
||||||
onModuleInit() {
|
|
||||||
this.moduleRegistry.registerModule({
|
|
||||||
key: 'guest',
|
|
||||||
name: 'Invitados',
|
|
||||||
description: 'Gestión de invitados, RSVP y asignación de mesas.',
|
|
||||||
routePrefix: '/guest',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { MikroORM } from '@mikro-orm/core';
|
|
||||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
||||||
import { Guest } from '../entities/guest.entity';
|
|
||||||
import { CreateGuestDto } from '../api/dto/create-guest.dto';
|
|
||||||
import { UpdateRsvpDto } from '../api/dto/update-rsvp.dto';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GuestService {
|
|
||||||
constructor(
|
|
||||||
private readonly orm: MikroORM,
|
|
||||||
private readonly eventEmitter: EventEmitter2,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
private get em() {
|
|
||||||
return this.orm.em.fork();
|
|
||||||
}
|
|
||||||
|
|
||||||
private getTenantId(): string {
|
|
||||||
// Tenant is now fixed; multi-tenant will be handled by routing (subdomains) later.
|
|
||||||
return process.env.DEFAULT_TENANT_ID || 'default';
|
|
||||||
}
|
|
||||||
|
|
||||||
async createGuest(dto: CreateGuestDto): Promise<Guest> {
|
|
||||||
const guest = this.em.create(Guest, {
|
|
||||||
tenantId: this.getTenantId(),
|
|
||||||
...dto,
|
|
||||||
} as any);
|
|
||||||
this.em.persist(guest);
|
|
||||||
await this.em.flush();
|
|
||||||
this.eventEmitter.emit('guest.invited', { guest });
|
|
||||||
return guest;
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateRsvp(guestId: string, dto: UpdateRsvpDto): Promise<Guest | null> {
|
|
||||||
const guest = await this.em.findOne(Guest, { tenantId: this.getTenantId(), id: guestId });
|
|
||||||
if (!guest) return null;
|
|
||||||
guest.rsvp = dto.rsvp;
|
|
||||||
if (dto.tableId) {
|
|
||||||
guest.tableId = dto.tableId;
|
|
||||||
}
|
|
||||||
this.em.persist(guest);
|
|
||||||
await this.em.flush();
|
|
||||||
this.eventEmitter.emit('guest.rsvp', { guest });
|
|
||||||
return guest;
|
|
||||||
}
|
|
||||||
|
|
||||||
async listGuests(): Promise<Guest[]> {
|
|
||||||
return this.em.find(Guest, { tenantId: this.getTenantId() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
import { OnEvent } from '@nestjs/event-emitter';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { NotificationService } from '../../core/services/notification.service';
|
|
||||||
import { NotificationRuleService } from '../../core/services/notification-rule.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GuestSubscriber {
|
|
||||||
constructor(
|
|
||||||
private readonly notificationService: NotificationService,
|
|
||||||
private readonly notificationRuleService: NotificationRuleService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@OnEvent('guest.invited')
|
|
||||||
async handleGuestInvited(payload: any) {
|
|
||||||
const { guest } = payload;
|
|
||||||
const rules = await this.notificationRuleService.getRulesForEvent(guest.tenantId, 'guest', 'guest.invited');
|
|
||||||
for (const rule of rules) {
|
|
||||||
for (const channel of rule.channels) {
|
|
||||||
await this.notificationService.send(
|
|
||||||
channel,
|
|
||||||
guest.email || guest.phone || '',
|
|
||||||
'Has sido invitado',
|
|
||||||
`Hola ${guest.name}, has sido invitado al evento.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OnEvent('guest.rsvp')
|
|
||||||
async handleGuestRsvp(payload: any) {
|
|
||||||
const { guest } = payload;
|
|
||||||
const rules = await this.notificationRuleService.getRulesForEvent(guest.tenantId, 'guest', 'guest.rsvp');
|
|
||||||
for (const rule of rules) {
|
|
||||||
for (const channel of rule.channels) {
|
|
||||||
await this.notificationService.send(
|
|
||||||
channel,
|
|
||||||
guest.email || guest.phone || '',
|
|
||||||
'RSVP actualizado',
|
|
||||||
`Hola ${guest.name}, tu RSVP ha sido actualizado.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { BaseWorkflow } from '../../core/workflows/base-workflow';
|
|
||||||
|
|
||||||
export class GuestWorkflow extends BaseWorkflow {
|
|
||||||
async execute(...args: any[]): Promise<any> {
|
|
||||||
this.logExecution('Ejecutando workflow de invitados', args);
|
|
||||||
// Implementar lógica de workflow para invitados
|
|
||||||
// ...existing code...
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import 'reflect-metadata';
|
|
||||||
import { NestFactory } from '@nestjs/core';
|
|
||||||
import { AppModule } from './app.module';
|
|
||||||
import { AuthGuard } from './core/auth.guard';
|
|
||||||
|
|
||||||
async function bootstrap() {
|
|
||||||
const app = await NestFactory.create(AppModule);
|
|
||||||
app.setGlobalPrefix('api');
|
|
||||||
app.useGlobalGuards(app.get(AuthGuard));
|
|
||||||
await app.listen(process.env.PORT ? Number(process.env.PORT) : 3000);
|
|
||||||
console.log(`Application is running on: ${await app.getUrl()}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
bootstrap();
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import { Controller, Get, Post, Body, Param, Headers, Patch } from '@nestjs/common';
|
|
||||||
import { TodoService } from '../services/todo.service';
|
|
||||||
|
|
||||||
@Controller('todo')
|
|
||||||
export class TodoController {
|
|
||||||
constructor(private readonly todoService: TodoService) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
async createTodo(
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Body() dto: any,
|
|
||||||
) {
|
|
||||||
return this.todoService.createTodo(tenantId, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
async listTodos(@Headers('x-tenant-id') tenantId: string) {
|
|
||||||
return this.todoService.listTodos(tenantId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':id/complete')
|
|
||||||
async completeTodo(
|
|
||||||
@Headers('x-tenant-id') tenantId: string,
|
|
||||||
@Param('id') id: string,
|
|
||||||
) {
|
|
||||||
return this.todoService.markComplete(tenantId, id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { EntitySchema } from '@mikro-orm/core';
|
|
||||||
import { BaseEntity } from '../../core/entities/base.entity';
|
|
||||||
|
|
||||||
export class TodoItem extends BaseEntity {
|
|
||||||
title!: string;
|
|
||||||
description?: string;
|
|
||||||
completed: boolean = false;
|
|
||||||
dueDate?: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const TodoItemSchema = new EntitySchema<TodoItem>({
|
|
||||||
class: TodoItem,
|
|
||||||
tableName: 'todo_items',
|
|
||||||
properties: {
|
|
||||||
id: { type: 'uuid', primary: true },
|
|
||||||
tenantId: { type: 'string' },
|
|
||||||
metadata: { type: 'json', nullable: true },
|
|
||||||
createdAt: { type: 'date', defaultRaw: 'now()' },
|
|
||||||
updatedAt: { type: 'date', defaultRaw: 'now()' },
|
|
||||||
|
|
||||||
title: { type: 'string' },
|
|
||||||
description: { type: 'text', nullable: true },
|
|
||||||
completed: { type: 'boolean', default: false },
|
|
||||||
dueDate: { type: 'date', nullable: true },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { MikroORM } from '@mikro-orm/core';
|
|
||||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
||||||
import { TodoItem } from '../entities/todo.entity';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class TodoService {
|
|
||||||
constructor(
|
|
||||||
private readonly orm: MikroORM,
|
|
||||||
private readonly eventEmitter: EventEmitter2,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
private get em() {
|
|
||||||
return this.orm.em.fork();
|
|
||||||
}
|
|
||||||
|
|
||||||
private getTenantId(): string {
|
|
||||||
// Tenant is now fixed; multi-tenant handled by reverse proxy (subdomains)
|
|
||||||
return process.env.DEFAULT_TENANT_ID || 'default';
|
|
||||||
}
|
|
||||||
|
|
||||||
async createTodo(dto: Partial<TodoItem>): Promise<TodoItem> {
|
|
||||||
const todo = this.em.create(TodoItem, {
|
|
||||||
tenantId: this.getTenantId(),
|
|
||||||
...dto,
|
|
||||||
} as any);
|
|
||||||
this.em.persist(todo);
|
|
||||||
await this.em.flush();
|
|
||||||
this.eventEmitter.emit('todo.created', { todo });
|
|
||||||
return todo;
|
|
||||||
}
|
|
||||||
|
|
||||||
async listTodos(): Promise<TodoItem[]> {
|
|
||||||
return this.em.find(TodoItem, { tenantId: this.getTenantId() });
|
|
||||||
}
|
|
||||||
|
|
||||||
async markComplete(id: string): Promise<TodoItem | null> {
|
|
||||||
const todo = await this.em.findOne(TodoItem, { tenantId: this.getTenantId(), id });
|
|
||||||
if (!todo) return null;
|
|
||||||
todo.completed = true;
|
|
||||||
this.em.persist(todo);
|
|
||||||
await this.em.flush();
|
|
||||||
this.eventEmitter.emit('todo.completed', { todo });
|
|
||||||
return todo;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
import { OnEvent } from '@nestjs/event-emitter';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { NotificationService } from '../../core/services/notification.service';
|
|
||||||
import { NotificationRuleService } from '../../core/services/notification-rule.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class TodoSubscriber {
|
|
||||||
constructor(
|
|
||||||
private readonly notificationService: NotificationService,
|
|
||||||
private readonly notificationRuleService: NotificationRuleService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@OnEvent('todo.created')
|
|
||||||
async handleTodoCreated(payload: any) {
|
|
||||||
const { todo } = payload;
|
|
||||||
const rules = await this.notificationRuleService.getRulesForEvent(todo.tenantId, 'todo', 'todo.created');
|
|
||||||
for (const rule of rules) {
|
|
||||||
for (const channel of rule.channels) {
|
|
||||||
await this.notificationService.send(
|
|
||||||
channel,
|
|
||||||
todo.metadata?.notifyTo || '',
|
|
||||||
'Nueva tarea creada',
|
|
||||||
`Se creó la tarea: ${todo.title}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OnEvent('todo.completed')
|
|
||||||
async handleTodoCompleted(payload: any) {
|
|
||||||
const { todo } = payload;
|
|
||||||
const rules = await this.notificationRuleService.getRulesForEvent(todo.tenantId, 'todo', 'todo.completed');
|
|
||||||
for (const rule of rules) {
|
|
||||||
for (const channel of rule.channels) {
|
|
||||||
await this.notificationService.send(
|
|
||||||
channel,
|
|
||||||
todo.metadata?.notifyTo || '',
|
|
||||||
'Tarea completada',
|
|
||||||
`La tarea "${todo.title}" se ha marcado como completada.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
|
||||||
import { CoreModule } from '../core/core.module';
|
|
||||||
import { TodoService } from './services/todo.service';
|
|
||||||
import { TodoController } from './api/todo.controller';
|
|
||||||
import { TodoSubscriber } from './subscribers/todo.subscriber';
|
|
||||||
import { TodoItemSchema } from './entities/todo.entity';
|
|
||||||
import { TodoModuleRegistration } from './todo.registration';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [CoreModule, MikroOrmModule.forFeature({ entities: [TodoItemSchema] })],
|
|
||||||
providers: [TodoService, TodoSubscriber, TodoModuleRegistration],
|
|
||||||
controllers: [TodoController],
|
|
||||||
exports: [TodoService],
|
|
||||||
})
|
|
||||||
export class TodoModule {}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
|
||||||
import { ModuleRegistryService } from '../core/services/module-registry.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class TodoModuleRegistration implements OnModuleInit {
|
|
||||||
constructor(private readonly moduleRegistry: ModuleRegistryService) {}
|
|
||||||
|
|
||||||
onModuleInit() {
|
|
||||||
this.moduleRegistry.registerModule({
|
|
||||||
key: 'todo',
|
|
||||||
name: 'To-do',
|
|
||||||
description: 'Lista de pendientes para la organización del matrimonio.',
|
|
||||||
routePrefix: '/todo',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { BaseWorkflow } from '../../core/workflows/base-workflow';
|
|
||||||
|
|
||||||
export class TodoWorkflow extends BaseWorkflow {
|
|
||||||
async execute(...args: any[]): Promise<any> {
|
|
||||||
this.logExecution('Ejecutando workflow de tareas', args);
|
|
||||||
// Implementar lógica de workflow para tareas
|
|
||||||
// ...existing code...
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "./tsconfig.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"declaration": true,
|
|
||||||
"declarationMap": true,
|
|
||||||
"sourceMap": false,
|
|
||||||
"outDir": "dist"
|
|
||||||
},
|
|
||||||
"exclude": ["node_modules", "test", "dist", "**/*.spec.ts"]
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "./tsconfig.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"noEmit": true,
|
|
||||||
"allowImportingTsExtensions": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"module": "commonjs",
|
|
||||||
"target": "es2020",
|
|
||||||
"lib": ["es2020"],
|
|
||||||
"declaration": true,
|
|
||||||
"sourceMap": true,
|
|
||||||
"outDir": "dist",
|
|
||||||
"rootDir": "src",
|
|
||||||
"strict": true,
|
|
||||||
"moduleResolution": "node",
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"experimentalDecorators": true,
|
|
||||||
"emitDecoratorMetadata": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"noImplicitAny": false,
|
|
||||||
"resolveJsonModule": true,
|
|
||||||
"types": ["node"]
|
|
||||||
},
|
|
||||||
"include": ["src/**/*.ts"],
|
|
||||||
"exclude": ["node_modules", "dist"]
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
const base = path.resolve(__dirname, '../src/modules');
|
|
||||||
const mods = ['gifts', 'guests', 'todos'];
|
|
||||||
for (const mod of mods) {
|
|
||||||
const folder = path.join(base, mod, 'model');
|
|
||||||
if (fs.existsSync(folder)) {
|
|
||||||
try {
|
|
||||||
fs.rmSync(folder, { recursive: true, force: true });
|
|
||||||
console.log(`Removed folder ${folder}`);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn(`Could not remove ${folder}:`, err.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
|
||||||
|
|
||||||
const base = path.resolve(__dirname, '../src/modules');
|
|
||||||
const mapping = {
|
|
||||||
guests: 'guest.model.ts',
|
|
||||||
gifts: 'gift.model.ts',
|
|
||||||
todos: 'todo.model.ts',
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const mod of Object.keys(mapping)) {
|
|
||||||
const modDir = path.join(base, mod);
|
|
||||||
const modelDir = path.join(modDir, 'model');
|
|
||||||
const src = path.join(modelDir, mapping[mod]);
|
|
||||||
const dst = path.join(modDir, 'model.ts');
|
|
||||||
|
|
||||||
if (fs.existsSync(src)) {
|
|
||||||
console.log(`Moving ${src} -> ${dst}`);
|
|
||||||
fs.renameSync(src, dst);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fs.existsSync(modelDir)) {
|
|
||||||
try {
|
|
||||||
const files = fs.readdirSync(modelDir);
|
|
||||||
if (files.length === 0) {
|
|
||||||
console.log(`Removing empty directory ${modelDir}`);
|
|
||||||
fs.rmdirSync(modelDir);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.warn(`Failed to clean model directory ${modelDir}:`, e.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const loginSchema = z.object({
|
|
||||||
email: z.string().email(),
|
|
||||||
password: z.string().min(6),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type LoginDto = z.infer<typeof loginSchema>;
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const registerSchema = z.object({
|
|
||||||
email: z.string().email(),
|
|
||||||
password: z.string().min(6),
|
|
||||||
name: z.string().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type RegisterDto = z.infer<typeof registerSchema>;
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const createContributionSchema = z.object({
|
|
||||||
giftId: z.string().uuid(),
|
|
||||||
contributorName: z.string().min(1),
|
|
||||||
contributorEmail: z.string().email().optional(),
|
|
||||||
amount: z.number().min(0),
|
|
||||||
type: z.enum(["individual", "group"]).optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type CreateContributionDto = z.infer<typeof createContributionSchema>;
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const createGiftSchema = z.object({
|
|
||||||
name: z.string().min(1),
|
|
||||||
description: z.string().optional(),
|
|
||||||
imageUrl: z.string().optional(),
|
|
||||||
price: z.number().optional(),
|
|
||||||
experience: z.boolean().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type CreateGiftDto = z.infer<typeof createGiftSchema>;
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import { Router } from "express";
|
|
||||||
import { GiftService } from "../../modules/gifts/service";
|
|
||||||
import { validateBody } from "../../core/middleware/validate";
|
|
||||||
import { createGiftSchema, createContributionSchema } from "../../modules/gifts/types";
|
|
||||||
import { requireAuth } from "../../core/middleware/auth";
|
|
||||||
|
|
||||||
const service = new GiftService();
|
|
||||||
|
|
||||||
export function registerGiftRoutes(router: Router) {
|
|
||||||
const r = Router();
|
|
||||||
|
|
||||||
// Protected routes
|
|
||||||
r.use(requireAuth);
|
|
||||||
|
|
||||||
r.post("/gift", validateBody(createGiftSchema), async (req, res) => {
|
|
||||||
const ownerId = (req as any).user?.id;
|
|
||||||
const gift = await service.createGift({ ...req.body, ownerId });
|
|
||||||
res.json(gift);
|
|
||||||
});
|
|
||||||
|
|
||||||
r.get("/gift", async (_req, res) => {
|
|
||||||
const gifts = await service.listGifts();
|
|
||||||
res.json(gifts);
|
|
||||||
});
|
|
||||||
|
|
||||||
r.get("/gift/:id", async (req, res) => {
|
|
||||||
const requesterId = (req as any).user?.id;
|
|
||||||
const gift = await service.getGiftById(req.params.id, requesterId);
|
|
||||||
if (!gift) {
|
|
||||||
return res.status(404).json({ error: "Gift not found" });
|
|
||||||
}
|
|
||||||
res.json(gift);
|
|
||||||
});
|
|
||||||
|
|
||||||
r.post(
|
|
||||||
"/gift/contribution",
|
|
||||||
validateBody(createContributionSchema),
|
|
||||||
async (req, res) => {
|
|
||||||
const contribution = await service.createContribution(req.body);
|
|
||||||
res.json(contribution);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
r.get("/gift/:id/contributions", async (req, res) => {
|
|
||||||
const requesterId = (req as any).user?.id;
|
|
||||||
const contributions = await service.listContributions(req.params.id, requesterId);
|
|
||||||
res.json(contributions);
|
|
||||||
});
|
|
||||||
|
|
||||||
router.use(r);
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const createGuestSchema = z.object({
|
|
||||||
name: z.string().min(1),
|
|
||||||
email: z.string().email().optional(),
|
|
||||||
phone: z.string().optional(),
|
|
||||||
rsvp: z.boolean().optional(),
|
|
||||||
tableId: z.string().uuid().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type CreateGuestDto = z.infer<typeof createGuestSchema>;
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const updateRsvpSchema = z.object({
|
|
||||||
rsvp: z.boolean(),
|
|
||||||
tableId: z.string().uuid().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type UpdateRsvpDto = z.infer<typeof updateRsvpSchema>;
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import { Router } from "express";
|
|
||||||
import { GuestService } from "../../modules/guests/service";
|
|
||||||
import { validateBody } from "../../core/middleware/validate";
|
|
||||||
import { createGuestSchema, updateRsvpSchema } from "../../modules/guests/types";
|
|
||||||
|
|
||||||
const service = new GuestService();
|
|
||||||
|
|
||||||
export function registerGuestRoutes(router: Router) {
|
|
||||||
const r = Router();
|
|
||||||
|
|
||||||
r.post("/guest", validateBody(createGuestSchema), async (req, res) => {
|
|
||||||
const guest = await service.createGuest(req.body);
|
|
||||||
res.json(guest);
|
|
||||||
});
|
|
||||||
|
|
||||||
r.get("/guest", async (_req, res) => {
|
|
||||||
const guests = await service.listGuests();
|
|
||||||
res.json(guests);
|
|
||||||
});
|
|
||||||
|
|
||||||
r.patch(
|
|
||||||
"/guest/:id/rsvp",
|
|
||||||
validateBody(updateRsvpSchema),
|
|
||||||
async (req, res) => {
|
|
||||||
const updated = await service.updateRsvp(req.params.id, req.body);
|
|
||||||
if (!updated) {
|
|
||||||
return res.status(404).json({ error: "Guest not found" });
|
|
||||||
}
|
|
||||||
res.json(updated);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
router.use(r);
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { Express } from "express";
|
|
||||||
|
|
||||||
export function registerHealthRoutes(app: Express) {
|
|
||||||
app.get("/api/health", (_req, res) => {
|
|
||||||
res.json({ ok: true, timestamp: new Date().toISOString() });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,15 @@
|
|||||||
import type { Express } from "express";
|
import type { Express } from "express";
|
||||||
import { registerHealthRoutes } from "./health/health.routes";
|
|
||||||
import { registerAdminRoutes } from "./admin/routes";
|
import { registerAdminRoutes } from "./admin/routes";
|
||||||
import { registerAuthRoutes } from "./auth/routes";
|
|
||||||
import { registerOrganizadorRoutes } from "./organizador/routes";
|
import { registerOrganizadorRoutes } from "./organizador/routes";
|
||||||
import { registerInvitadosRoutes } from "./invitados/routes";
|
import { registerInvitadosRoutes } from "./invitados/routes";
|
||||||
|
import { registerAuthRoutes } from "./organizador/auth/routes";
|
||||||
import { requireRole, requireInvitadoAccess } from "./middleware";
|
import { requireRole, requireInvitadoAccess } from "./middleware";
|
||||||
|
|
||||||
export function registerApiRoutes(app: Express) {
|
export function registerApiRoutes(app: Express) {
|
||||||
// shared middleware could be added here (logging, tenant resolution, etc.)
|
// shared middleware could be added here (logging, tenant resolution, etc.)
|
||||||
|
|
||||||
registerHealthRoutes(app);
|
// Public auth endpoints for organizer/admin users
|
||||||
|
app.use("/api/organizador/auth", registerAuthRoutes());
|
||||||
// Auth routes (register / login) are global and shared by all clients.
|
|
||||||
app.use("/api/auth", registerAuthRoutes());
|
|
||||||
|
|
||||||
// Admin-only routes
|
// Admin-only routes
|
||||||
app.use("/api/admin", requireRole("admin"), registerAdminRoutes());
|
app.use("/api/admin", requireRole("admin"), registerAdminRoutes());
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { AuthService } from "../../modules/auth/auth.service";
|
import { AuthService } from "../../../modules/auth/auth.service";
|
||||||
import { UserService } from "../../modules/auth/user.service";
|
import { UserService } from "../../../modules/auth/user.service";
|
||||||
import { validateBody } from "../../core/middleware/validate";
|
import { validateBody } from "../../../core/middleware/validate";
|
||||||
import { loginSchema, registerSchema } from "../../modules/auth/types";
|
import { loginSchema, registerSchema } from "../../../modules/auth/types";
|
||||||
|
|
||||||
const authService = new AuthService();
|
const authService = new AuthService();
|
||||||
const userService = new UserService();
|
const userService = new UserService();
|
||||||
7
packages/server/src/api/organizador/health/routes.ts
Normal file
7
packages/server/src/api/organizador/health/routes.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import type { Router } from "express";
|
||||||
|
|
||||||
|
export function registerHealthRoutes(router: Router) {
|
||||||
|
router.get("/health", (_req, res) => {
|
||||||
|
res.json({ ok: true, timestamp: new Date().toISOString() });
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { Router } from "express";
|
|||||||
import { requireRole } from "../middleware";
|
import { requireRole } from "../middleware";
|
||||||
import { registerGuestRoutes } from "./guests/routes";
|
import { registerGuestRoutes } from "./guests/routes";
|
||||||
import { registerGiftRoutes } from "./gifts/routes";
|
import { registerGiftRoutes } from "./gifts/routes";
|
||||||
|
import { registerHealthRoutes } from "./health/routes";
|
||||||
import { registerTodoRoutes } from "./todos/routes";
|
import { registerTodoRoutes } from "./todos/routes";
|
||||||
|
|
||||||
export function registerOrganizadorRoutes() {
|
export function registerOrganizadorRoutes() {
|
||||||
@@ -10,6 +11,7 @@ export function registerOrganizadorRoutes() {
|
|||||||
// Organizador routes are for organizers (and admins).
|
// Organizador routes are for organizers (and admins).
|
||||||
// Authentication and role enforcement is handled in api/index.ts.
|
// Authentication and role enforcement is handled in api/index.ts.
|
||||||
|
|
||||||
|
registerHealthRoutes(router);
|
||||||
registerGuestRoutes(router, requireRole("admin", "organizer"));
|
registerGuestRoutes(router, requireRole("admin", "organizer"));
|
||||||
registerGiftRoutes(router, requireRole("admin", "organizer"));
|
registerGiftRoutes(router, requireRole("admin", "organizer"));
|
||||||
registerTodoRoutes(router, requireRole("admin", "organizer"));
|
registerTodoRoutes(router, requireRole("admin", "organizer"));
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const createTodoSchema = z.object({
|
|
||||||
title: z.string().min(1),
|
|
||||||
description: z.string().optional(),
|
|
||||||
dueDate: z.string().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type CreateTodoDto = z.infer<typeof createTodoSchema>;
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { Router } from "express";
|
|
||||||
import { TodoService } from "../../modules/todos/service";
|
|
||||||
import { validateBody } from "../../core/middleware/validate";
|
|
||||||
import { createTodoSchema } from "../../modules/todos/types";
|
|
||||||
import { requireAuth } from "../../core/middleware/auth";
|
|
||||||
|
|
||||||
const service = new TodoService();
|
|
||||||
|
|
||||||
export function registerTodoRoutes(router: Router) {
|
|
||||||
const r = Router();
|
|
||||||
|
|
||||||
r.use(requireAuth);
|
|
||||||
|
|
||||||
r.post("/todo", validateBody(createTodoSchema), async (req, res) => {
|
|
||||||
const todo = await service.createTodo(req.body);
|
|
||||||
res.json(todo);
|
|
||||||
});
|
|
||||||
|
|
||||||
r.get("/todo", async (_req, res) => {
|
|
||||||
const todos = await service.listTodos();
|
|
||||||
res.json(todos);
|
|
||||||
});
|
|
||||||
|
|
||||||
r.patch("/todo/:id/complete", async (req, res) => {
|
|
||||||
const updated = await service.markComplete(req.params.id);
|
|
||||||
if (!updated) {
|
|
||||||
return res.status(404).json({ error: "Todo not found" });
|
|
||||||
}
|
|
||||||
res.json(updated);
|
|
||||||
});
|
|
||||||
|
|
||||||
router.use(r);
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user