Restructure backend into modular API layers with admin/organizador/invitados routes, add role-based middleware, flatten module models, and update build scripts
This commit is contained in:
20
packages/legacy/mikro-orm.config.js
Normal file
20
packages/legacy/mikro-orm.config.js
Normal file
@@ -0,0 +1,20 @@
|
||||
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',
|
||||
},
|
||||
};
|
||||
44
packages/legacy/package.json
Normal file
44
packages/legacy/package.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
448
packages/legacy/public/admin.html
Normal file
448
packages/legacy/public/admin.html
Normal file
@@ -0,0 +1,448 @@
|
||||
<!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>
|
||||
81
packages/legacy/src/admin/admin.controller.ts
Normal file
81
packages/legacy/src/admin/admin.controller.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
12
packages/legacy/src/admin/admin.module.ts
Normal file
12
packages/legacy/src/admin/admin.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
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 {}
|
||||
27
packages/legacy/src/app.module.ts
Normal file
27
packages/legacy/src/app.module.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
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 {}
|
||||
36
packages/legacy/src/core/api/auth.controller.ts
Normal file
36
packages/legacy/src/core/api/auth.controller.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
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 };
|
||||
}
|
||||
}
|
||||
49
packages/legacy/src/core/auth.guard.ts
Normal file
49
packages/legacy/src/core/auth.guard.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
14
packages/legacy/src/core/auth.module.ts
Normal file
14
packages/legacy/src/core/auth.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
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 {}
|
||||
48
packages/legacy/src/core/core.module.ts
Normal file
48
packages/legacy/src/core/core.module.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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 {}
|
||||
26
packages/legacy/src/core/database.module.ts
Normal file
26
packages/legacy/src/core/database.module.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
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 {}
|
||||
9
packages/legacy/src/core/entities/base.entity.ts
Normal file
9
packages/legacy/src/core/entities/base.entity.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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 },
|
||||
},
|
||||
});
|
||||
54
packages/legacy/src/core/entities/token.entity.ts
Normal file
54
packages/legacy/src/core/entities/token.entity.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
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()',
|
||||
},
|
||||
},
|
||||
});
|
||||
48
packages/legacy/src/core/entities/user.entity.ts
Normal file
48
packages/legacy/src/core/entities/user.entity.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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,
|
||||
},
|
||||
},
|
||||
});
|
||||
20
packages/legacy/src/core/services/auth.service.ts
Normal file
20
packages/legacy/src/core/services/auth.service.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
14
packages/legacy/src/core/services/module-linker.service.ts
Normal file
14
packages/legacy/src/core/services/module-linker.service.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
24
packages/legacy/src/core/services/module-registry.service.ts
Normal file
24
packages/legacy/src/core/services/module-registry.service.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
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];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export interface NotificationProvider {
|
||||
send(options: { to: string; subject: string; body: string; metadata?: any }): Promise<void>;
|
||||
}
|
||||
|
||||
export type NotificationChannel = 'email' | 'whatsapp' | 'sms' | 'custom';
|
||||
@@ -0,0 +1,26 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
33
packages/legacy/src/core/services/notification.service.ts
Normal file
33
packages/legacy/src/core/services/notification.service.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
27
packages/legacy/src/core/services/token.service.ts
Normal file
27
packages/legacy/src/core/services/token.service.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
34
packages/legacy/src/core/services/user.service.ts
Normal file
34
packages/legacy/src/core/services/user.service.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
14
packages/legacy/src/core/workflows/base-workflow.ts
Normal file
14
packages/legacy/src/core/workflows/base-workflow.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export class CreateContributionDto {
|
||||
giftId!: string;
|
||||
contributorName!: string;
|
||||
contributorEmail?: string;
|
||||
amount!: number;
|
||||
type?: 'individual' | 'group';
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
9
packages/legacy/src/gift/api/dto/create-gift.dto.ts
Normal file
9
packages/legacy/src/gift/api/dto/create-gift.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export class CreateGiftDto {
|
||||
name!: string;
|
||||
description?: string;
|
||||
imageUrl?: string;
|
||||
price?: number;
|
||||
experience?: boolean;
|
||||
ownerId?: string;
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
53
packages/legacy/src/gift/api/gift.controller.ts
Normal file
53
packages/legacy/src/gift/api/gift.controller.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
124
packages/legacy/src/gift/entities/gift.entity.ts
Normal file
124
packages/legacy/src/gift/entities/gift.entity.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
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',
|
||||
},
|
||||
},
|
||||
});
|
||||
19
packages/legacy/src/gift/gift.module.ts
Normal file
19
packages/legacy/src/gift/gift.module.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
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 {}
|
||||
16
packages/legacy/src/gift/gift.registration.ts
Normal file
16
packages/legacy/src/gift/gift.registration.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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',
|
||||
});
|
||||
}
|
||||
}
|
||||
70
packages/legacy/src/gift/services/gift.service.ts
Normal file
70
packages/legacy/src/gift/services/gift.service.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
44
packages/legacy/src/gift/subscribers/gift.subscriber.ts
Normal file
44
packages/legacy/src/gift/subscribers/gift.subscriber.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
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}).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
10
packages/legacy/src/gift/workflows/gift.workflow.ts
Normal file
10
packages/legacy/src/gift/workflows/gift.workflow.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
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 {};
|
||||
}
|
||||
}
|
||||
6
packages/legacy/src/guest/api/dto/create-guest.dto.ts
Normal file
6
packages/legacy/src/guest/api/dto/create-guest.dto.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export class CreateGuestDto {
|
||||
name!: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
4
packages/legacy/src/guest/api/dto/update-rsvp.dto.ts
Normal file
4
packages/legacy/src/guest/api/dto/update-rsvp.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export class UpdateRsvpDto {
|
||||
rsvp!: boolean;
|
||||
tableId?: string;
|
||||
}
|
||||
31
packages/legacy/src/guest/api/guest.controller.ts
Normal file
31
packages/legacy/src/guest/api/guest.controller.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
102
packages/legacy/src/guest/entities/guest.entity.ts
Normal file
102
packages/legacy/src/guest/entities/guest.entity.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
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,
|
||||
},
|
||||
},
|
||||
});
|
||||
21
packages/legacy/src/guest/guest.module.ts
Normal file
21
packages/legacy/src/guest/guest.module.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
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 {}
|
||||
16
packages/legacy/src/guest/guest.registration.ts
Normal file
16
packages/legacy/src/guest/guest.registration.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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',
|
||||
});
|
||||
}
|
||||
}
|
||||
51
packages/legacy/src/guest/services/guest.service.ts
Normal file
51
packages/legacy/src/guest/services/guest.service.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
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() });
|
||||
}
|
||||
}
|
||||
44
packages/legacy/src/guest/subscribers/guest.subscriber.ts
Normal file
44
packages/legacy/src/guest/subscribers/guest.subscriber.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
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.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
10
packages/legacy/src/guest/workflows/guest.workflow.ts
Normal file
10
packages/legacy/src/guest/workflows/guest.workflow.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
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 {};
|
||||
}
|
||||
}
|
||||
14
packages/legacy/src/main.ts
Normal file
14
packages/legacy/src/main.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
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();
|
||||
28
packages/legacy/src/todo/api/todo.controller.ts
Normal file
28
packages/legacy/src/todo/api/todo.controller.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
26
packages/legacy/src/todo/entities/todo.entity.ts
Normal file
26
packages/legacy/src/todo/entities/todo.entity.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
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 },
|
||||
},
|
||||
});
|
||||
46
packages/legacy/src/todo/services/todo.service.ts
Normal file
46
packages/legacy/src/todo/services/todo.service.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
44
packages/legacy/src/todo/subscribers/todo.subscriber.ts
Normal file
44
packages/legacy/src/todo/subscribers/todo.subscriber.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
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.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
16
packages/legacy/src/todo/todo.module.ts
Normal file
16
packages/legacy/src/todo/todo.module.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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 {}
|
||||
16
packages/legacy/src/todo/todo.registration.ts
Normal file
16
packages/legacy/src/todo/todo.registration.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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',
|
||||
});
|
||||
}
|
||||
}
|
||||
10
packages/legacy/src/todo/workflows/todo.workflow.ts
Normal file
10
packages/legacy/src/todo/workflows/todo.workflow.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
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 {};
|
||||
}
|
||||
}
|
||||
10
packages/legacy/tsconfig.build.json
Normal file
10
packages/legacy/tsconfig.build.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": false,
|
||||
"outDir": "dist"
|
||||
},
|
||||
"exclude": ["node_modules", "test", "dist", "**/*.spec.ts"]
|
||||
}
|
||||
7
packages/legacy/tsconfig.dev.json
Normal file
7
packages/legacy/tsconfig.dev.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true
|
||||
}
|
||||
}
|
||||
22
packages/legacy/tsconfig.json
Normal file
22
packages/legacy/tsconfig.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"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"]
|
||||
}
|
||||
Reference in New Issue
Block a user