Initial commit - Event Planner application

This commit is contained in:
mberlin
2026-03-18 14:55:56 -03:00
commit 86d779eb4d
7548 changed files with 1006324 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { ModuleRegistryService } from '../core/services/module-registry.service';
@Controller('admin')
export class AdminController {
constructor(private readonly moduleRegistry: ModuleRegistryService) {}
@Get('modules')
getModules() {
return this.moduleRegistry.getModules();
}
}

13
src/admin/admin.module.ts Normal file
View File

@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { CoreModule } from '../core/core.module';
import { AdminController } from './admin.controller';
import { ModuleRegistryService } from '../core/services/module-registry.service';
@Module({
imports: [CoreModule, MikroOrmModule.forFeature([])],
controllers: [AdminController],
providers: [ModuleRegistryService],
exports: [ModuleRegistryService],
})
export class AdminModule {}

23
src/app.module.ts Normal file
View File

@@ -0,0 +1,23 @@
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',
}),
CoreModule,
GiftModule,
GuestModule,
TodoModule,
AdminModule,
],
})
export class AppModule {}

View File

@@ -0,0 +1,12 @@
import { Controller, Post, Body } from '@nestjs/common';
import { TokenService } from '../services/token.service';
@Controller('auth')
export class AuthController {
constructor(private readonly tokenService: TokenService) {}
@Post('token')
createToken(@Body() body: { name?: string; expiresInHours?: number }) {
return this.tokenService.createToken(body.name, body.expiresInHours);
}
}

24
src/core/auth.guard.ts Normal file
View File

@@ -0,0 +1,24 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './services/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const authHeader = request.headers['authorization'] || '';
const token = Array.isArray(authHeader) ? authHeader[0] : authHeader;
if (!token) {
throw new UnauthorizedException();
}
const payload = this.authService.verify(token.replace(/^Bearer\s+/i, ''));
if (!payload) {
throw new UnauthorizedException();
}
request.user = payload;
return true;
}
}

10
src/core/auth.module.ts Normal file
View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { AuthService } from './services/auth.service';
import { TokenService } from './services/token.service';
import { AuthGuard } from './auth.guard';
@Module({
providers: [AuthService, TokenService, AuthGuard],
exports: [AuthService, TokenService, AuthGuard],
})
export class AuthModule {}

48
src/core/core.module.ts Normal file
View 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: false,
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 {}

View 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 {}

View 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();
}

View File

@@ -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 },
},
});

View 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()',
},
},
});

View 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;
}
}
}

View 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 [];
}
}

View 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];
}
}

View File

@@ -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';

View File

@@ -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;
}
}

View 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 });
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View 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;
}
}

View 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);
}
}
}

View File

@@ -0,0 +1,8 @@
export class CreateContributionDto {
giftId!: string;
contributorName!: string;
contributorEmail?: string;
amount!: number;
type?: 'individual' | 'group';
metadata?: Record<string, any>;
}

View File

@@ -0,0 +1,9 @@
export class CreateGiftDto {
name!: string;
description?: string;
imageUrl?: string;
price?: number;
experience?: boolean;
ownerId?: string;
metadata?: Record<string, any>;
}

View 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);
}
}

View 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
src/gift/gift.module.ts Normal file
View 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 {}

View 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',
});
}
}

View File

@@ -0,0 +1,67 @@
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();
}
async createGift(tenantId: string, dto: CreateGiftDto): Promise<Gift> {
const gift = this.em.create(Gift, {
tenantId,
...dto,
} as any);
this.em.persist(gift);
await this.em.flush();
this.eventEmitter.emit('gift.created', { gift });
return gift;
}
async createContribution(tenantId: string, dto: CreateContributionDto): Promise<GiftContribution> {
const contribution = this.em.create(GiftContribution, {
tenantId,
...dto,
} as any);
this.em.persist(contribution);
await this.em.flush();
this.eventEmitter.emit('gift.contribution', { contribution });
return contribution;
}
async listGifts(tenantId: string): Promise<Gift[]> {
return this.em.find(Gift, { tenantId });
}
async getGiftById(
tenantId: string,
id: string,
requesterId?: string,
): Promise<Gift | null> {
const gift = await this.em.findOne(Gift, { tenantId, id });
if (!gift) return null;
if (requesterId && gift.ownerId && gift.ownerId !== requesterId) {
return null;
}
return gift;
}
async listContributions(
tenantId: string,
giftId: string,
requesterId?: string,
): Promise<GiftContribution[]> {
const gift = await this.getGiftById(tenantId, giftId, requesterId);
if (!gift) return [];
return this.em.find(GiftContribution, { tenantId, giftId });
}
}

View 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}).`,
);
}
}
}
}

View 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 {};
}
}

View File

@@ -0,0 +1,6 @@
export class CreateGuestDto {
name!: string;
email?: string;
phone?: string;
metadata?: Record<string, any>;
}

View File

@@ -0,0 +1,4 @@
export class UpdateRsvpDto {
rsvp!: boolean;
tableId?: string;
}

View 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);
}
}

View 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
src/guest/guest.module.ts Normal file
View 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 {}

View 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',
});
}
}

View File

@@ -0,0 +1,46 @@
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();
}
async createGuest(tenantId: string, dto: CreateGuestDto): Promise<Guest> {
const guest = this.em.create(Guest, {
tenantId,
...dto,
} as any);
this.em.persist(guest);
await this.em.flush();
this.eventEmitter.emit('guest.invited', { guest });
return guest;
}
async updateRsvp(tenantId: string, guestId: string, dto: UpdateRsvpDto): Promise<Guest | null> {
const guest = await this.em.findOne(Guest, { tenantId, 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(tenantId: string): Promise<Guest[]> {
return this.em.find(Guest, { tenantId });
}
}

View 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.`,
);
}
}
}
}

View 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
src/main.ts Normal file
View 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();

View 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);
}
}

View 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 },
},
});

View File

@@ -0,0 +1,41 @@
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();
}
async createTodo(tenantId: string, dto: Partial<TodoItem>): Promise<TodoItem> {
const todo = this.em.create(TodoItem, {
tenantId,
...dto,
} as any);
this.em.persist(todo);
await this.em.flush();
this.eventEmitter.emit('todo.created', { todo });
return todo;
}
async listTodos(tenantId: string): Promise<TodoItem[]> {
return this.em.find(TodoItem, { tenantId });
}
async markComplete(tenantId: string, id: string): Promise<TodoItem | null> {
const todo = await this.em.findOne(TodoItem, { tenantId, id });
if (!todo) return null;
todo.completed = true;
this.em.persist(todo);
await this.em.flush();
this.eventEmitter.emit('todo.completed', { todo });
return todo;
}
}

View 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
src/todo/todo.module.ts Normal file
View 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 {}

View 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',
});
}
}

View 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 {};
}
}