Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { InventoryModule } from './inventory/inventory.module';
import { DiscountModule } from './discount/discount.module';
import { PaymentModule } from './payments/payment.module';
import { OrderModule } from './order/order.module';
import { NotificationModule } from './notification/notification.module';

@Module({
imports: [
Expand Down Expand Up @@ -57,6 +58,7 @@ import { OrderModule } from './order/order.module';
DiscountModule,
PaymentModule,
OrderModule,
NotificationModule,
],
controllers: [AppController],
providers: [AppService],
Expand Down
1 change: 1 addition & 0 deletions src/database/database.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
password: configService.get('POSTGRES_PASSWORD'),
database: configService.get('POSTGRES_NAME'),
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
subscribers: [__dirname + '/../**/*.subscriber{.ts,.js}'],
synchronize: false,
ssl: configService.get<boolean>('POSTGRES_SSL', false),
}),
Expand Down
51 changes: 51 additions & 0 deletions src/notification/controllers/notification.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {
Controller,
Get,
Post,
Param,
UseGuards,
Req,
HttpCode,
HttpStatus,
ParseUUIDPipe,
} from '@nestjs/common';
import { NotificationService } from '../services/notification.service';
import { AuthGuard, CustomRequest } from 'src/auth/auth.guard';
import { ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { UserRole } from 'src/user/entities/user.entity';

@Controller('notification')
export class NotificationController {
constructor(private readonly notificationService: NotificationService) {}

@Get()
@UseGuards(AuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'List notifications' })
@ApiResponse({
status: HttpStatus.OK,
description: 'Notification list',
})
async getNotifications(@Req() req: CustomRequest) {
if (req.user.role === UserRole.ADMIN) {
return await this.notificationService.getAllNotifications();
} else {
return await this.notificationService.getUserNotifications(req.user.id);
}
}
@Post(':orderId/read')
@UseGuards(AuthGuard)
@ApiBearerAuth()
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Mark notification as read' })
@ApiResponse({
status: HttpStatus.OK,
description: 'Notification marked as read',
})
async markAsRead(
@Param('orderId', ParseUUIDPipe) orderId: string,
@Req() req: CustomRequest,
): Promise<void> {
await this.notificationService.markAsReadAsCustomer(orderId, req.user.id);
}
}
32 changes: 32 additions & 0 deletions src/notification/dto/notification.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { ApiProperty } from '@nestjs/swagger';
import {
IsBoolean,
IsOptional,
IsString,
IsUUID,
IsNotEmpty,
} from 'class-validator';

export class NotificationDTO {
@ApiProperty({ description: 'Notification message' })
@IsNotEmpty()
@IsString()
message: string;

@ApiProperty({
description: 'Indicates if the notification has been read',
default: false,
})
@IsNotEmpty()
@IsBoolean()
isRead: boolean;

@ApiProperty({
description: 'Identifier of the order associated with the notification',
required: false,
nullable: true,
})
@IsOptional()
@IsUUID()
orderId?: string;
}
16 changes: 16 additions & 0 deletions src/notification/entities/notification.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Entity, Column, ManyToOne, JoinColumn } from 'typeorm';
import { BaseModel } from 'src/utils/entity';
import { Order } from 'src/order/entities/order.entity';

@Entity()
export class Notification extends BaseModel {
@ManyToOne(() => Order, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'order_id' })
order: Order;

@Column({ type: 'text' })
message: string;

@Column({ name: 'is_read', type: 'boolean', default: false })
isRead: boolean;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateNotificationMigration1744646198491
implements MigrationInterface
{
name = 'CreateNotificationMigration1744646198491';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "notification" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "deleted_at" TIMESTAMP, "message" text NOT NULL, "is_read" boolean NOT NULL DEFAULT false, "order_id" uuid, CONSTRAINT "PK_705b6c7cdf9b2c2ff7ac7872cb7" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "notification" ADD CONSTRAINT "FK_3ea5cd8a1de9cbf90c86dd0582c" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "notification" DROP CONSTRAINT "FK_3ea5cd8a1de9cbf90c86dd0582c"`,
);
await queryRunner.query(`DROP TABLE "notification"`);
}
}
14 changes: 14 additions & 0 deletions src/notification/notification.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Notification } from './entities/notification.entity';
import { NotificationController } from '../notification/controllers/notification.controller';
import { NotificationService } from '../notification/services/notification.service';
import { NotificationSubscriber } from '../notification/subscribers/notification.subscriber';
import { AuthModule } from 'src/auth/auth.module';

@Module({
imports: [TypeOrmModule.forFeature([Notification]), AuthModule],
controllers: [NotificationController],
providers: [NotificationService, NotificationSubscriber],
})
export class NotificationModule {}
36 changes: 36 additions & 0 deletions src/notification/services/notification.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Injectable, ForbiddenException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Notification } from '../entities/notification.entity';

@Injectable()
export class NotificationService {
constructor(
@InjectRepository(Notification)
private readonly notificationRepository: Repository<Notification>,
) {}

async getAllNotifications() {
return await this.notificationRepository.find({ relations: ['order'] });
}
async getUserNotifications(userId: string) {
return await this.notificationRepository
.createQueryBuilder('notification')
.innerJoinAndSelect('notification.order', 'order')
.where('order.user.id = :userId', { userId })
.orderBy('notification.createdAt', 'DESC')
.getMany();
}

async markAsReadAsCustomer(orderId: string, userId: string): Promise<void> {
const notification = await this.notificationRepository.findOne({
where: { order: { id: orderId, user: { id: userId } } },
relations: ['order'],
});
if (!notification) {
throw new ForbiddenException('Notification not found or no access');
}
notification.isRead = true;
await this.notificationRepository.save(notification);
}
}
42 changes: 42 additions & 0 deletions src/notification/subscribers/notification.subscriber.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
EntitySubscriberInterface,
EventSubscriber,
UpdateEvent,
} from 'typeorm';
import { Order } from 'src/order/entities/order.entity';
import { Notification } from '../entities/notification.entity';

@EventSubscriber()
export class NotificationSubscriber
implements EntitySubscriberInterface<Order>
{
listenTo() {
return Order;
}

async afterUpdate(event: UpdateEvent<Order>) {
const updatedOrder = event.entity as Order | undefined;
console.log('Updated Order:', updatedOrder);
if (!updatedOrder) return;

const message = `The order ${updatedOrder.id} has been updated to ${updatedOrder.status}`;
const notificationRepository = event.manager.getRepository(Notification);

let notification = await notificationRepository.findOne({
where: { order: { id: updatedOrder.id } },
});

if (notification) {
notification.message = message;
notification.isRead = false;
} else {
notification = notificationRepository.create({
order: { id: updatedOrder.id } as Order,
message,
isRead: false,
});
}

await notificationRepository.save(notification);
}
}
9 changes: 4 additions & 5 deletions src/order/order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,13 @@ export class OrderService {
}
return order;
}

async update(id: string, status: OrderStatus) {
const result = await this.orderRepository.update(id, { status });
if (result.affected === 0) {
const order = await this.findOne(id);
if (!order) {
throw new BadRequestException('Order not found');
}
const order = await this.findOne(id);
return order;
order.status = status;
return await this.orderRepository.save(order);
Comment thread
andres15alvarez marked this conversation as resolved.
}

async findAllOD(
Expand Down
Loading