Initial backend commit

This commit is contained in:
anandham 2026-03-18 21:11:12 +05:30
commit 2a92f387e0
51 changed files with 12201 additions and 0 deletions

56
.gitignore vendored Normal file
View File

@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

98
README.md Normal file
View File

@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

35
eslint.config.mjs Normal file
View File

@ -0,0 +1,35 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
);

8
nest-cli.json Normal file
View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

10803
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

80
package.json Normal file
View File

@ -0,0 +1,80 @@
{
"name": "backend",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^11.0.1",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.6",
"@nestjs/typeorm": "^11.0.0",
"bcrypt": "^6.0.0",
"nodemailer": "^8.0.2",
"pg": "^8.20.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"swagger-ui-express": "^5.0.1",
"typeorm": "^0.3.28"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/bcrypt": "^6.0.0",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@types/nodemailer": "^7.0.11",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

12
src/app.controller.ts Normal file
View File

@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

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

@ -0,0 +1,32 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { StudentModule } from './student/student.module';
import { CourseModule } from './course/course.module';
import { StudentCourseModule } from './student-course/student-course.module';
import { EntityNotesModule } from './entity-notes/entity-notes.module';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'root',
database: 'training_db',
autoLoadEntities: true,
synchronize: false,
}),
StudentModule,
CourseModule,
StudentCourseModule,
EntityNotesModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

8
src/app.service.ts Normal file
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
describe('AuthController', () => {
let controller: AuthController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
}).compile();
controller = module.get<AuthController>(AuthController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,35 @@
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './login.dto';
import { RegisterDto } from './register.dto';
import { ForgotPasswordDto } from './forgot-password.dto';
import { ResetPasswordDto } from './reset-password.dto';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Post('register')
register(@Body() body: RegisterDto) {
return this.authService.register(body);
}
@Post('login')
login(@Body() body: LoginDto) {
return this.authService.login(body);
}
@Post('forgot-password')
forgotPassword(@Body() body: ForgotPasswordDto) {
return this.authService.forgotPassword(body);
}
@Post('reset-password')
resetPassword(@Body() body: ResetPasswordDto) {
return this.authService.resetPassword(body);
}
}

12
src/auth/auth.module.ts Normal file
View File

@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { Student } from '../student/student.entity';
@Module({
imports: [TypeOrmModule.forFeature([Student])],
providers: [AuthService],
controllers: [AuthController],
})
export class AuthModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

127
src/auth/auth.service.ts Normal file
View File

@ -0,0 +1,127 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Student } from '../student/student.entity';
import * as bcrypt from 'bcrypt';
import * as nodemailer from 'nodemailer';
import { NotFoundException, UnauthorizedException } from '@nestjs/common';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(Student)
private studentRepository: Repository<Student>,
) {}
// REGISTER PASSWORD
async register(data: any) {
const student = await this.studentRepository.findOne({
where: { EmailAddress: data.email }
});
if (!student) {
throw new NotFoundException('Email not found');
}
if (data.password !== data.confirmPassword) {
throw new Error('Passwords do not match');
}
const hashedPassword = await bcrypt.hash(data.password, 10);
student.Password = hashedPassword;
student.StudentStatus = 'Active'; // ⭐ IMPORTANT LINE
student.LastUpdatedDate = new Date();
student.LastUpdatedBy = 'System';
await this.studentRepository.save(student);
return {
message: 'Registration successful'
};
}
// LOGIN
async login(data: any) {
const student = await this.studentRepository.findOne({
where: { EmailAddress: data.email }
});
if (!student) {
throw new NotFoundException("Email not found");
}
const match = await bcrypt.compare(data.password, student.Password);
if (!match) {
throw new UnauthorizedException("Invalid password");
}
return {
message: "Login successful",
studentId: student.StudentID,
name: student.Name
};
}
// FORGOT PASSWORD (SEND RESET LINK)
async forgotPassword(data: any) {
const student = await this.studentRepository.findOne({
where: { EmailAddress: data.email }
});
if (!student) {
return { message: "Email not found" };
}
const resetLink = `http://localhost:3000/reset-password?email=${data.email}`;
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '2003nithi@gmail.com',
pass: 'qgxu ufou sycd iyjm'
}
});
await transporter.sendMail({
from: 'yourgmail@gmail.com',
to: data.email,
subject: 'Password Reset Link',
text: `Click the link to reset your password: ${resetLink}`
});
return {
message: "Password reset link sent to your email"
};
}
// RESET PASSWORD
async resetPassword(data: any) {
const student = await this.studentRepository.findOne({
where: { EmailAddress: data.email }
});
if (!student) {
return { message: "Invalid email address" };
}
const bcrypt=require('bcrypt');
const hashedPassword = await bcrypt.hash(data.newPassword, 10);
student.Password = hashedPassword;
await this.studentRepository.save(student);
return {
message: "Password reset successfully"
};
}
}

View File

@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
export class ForgotPasswordDto {
@ApiProperty()
email: string;
}

11
src/auth/login.dto.ts Normal file
View File

@ -0,0 +1,11 @@
import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
@ApiProperty()
email: string;
@ApiProperty()
password: string;
}

14
src/auth/register.dto.ts Normal file
View File

@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
export class RegisterDto {
@ApiProperty()
email: string;
@ApiProperty()
password: string;
@ApiProperty()
confirmPassword: string;
}

View File

@ -0,0 +1,11 @@
import { ApiProperty } from '@nestjs/swagger';
export class ResetPasswordDto {
@ApiProperty()
email: string;
@ApiProperty()
newPassword: string;
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CourseController } from './course.controller';
describe('CourseController', () => {
let controller: CourseController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [CourseController],
}).compile();
controller = module.get<CourseController>(CourseController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,14 @@
import { Controller, Get } from '@nestjs/common';
import { CourseService } from './course.service';
@Controller('courses')
export class CourseController {
constructor(private courseService: CourseService) {}
@Get()
async getCourses() {
return this.courseService.getAvailableCourses();
}
}

View File

@ -0,0 +1,41 @@
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('course')
export class Course {
@PrimaryGeneratedColumn({ name: 'courseid' })
CourseID: number;
@Column({ name: 'name' })
Name: string;
@Column({ name: 'startdate' })
StartDate: Date;
@Column({ name: 'enddate' })
EndDate: Date;
@Column({ name: 'trainingmode' })
TrainingMode: string;
@Column({ name: 'rate' })
Rate: number;
@Column({ name: 'noteid', nullable: true })
NoteID: number;
@Column({ name: 'tutorid', nullable: true })
TutorID: number;
@Column({ name: 'createddate' })
CreatedDate: Date;
@Column({ name: 'createdby' })
CreatedBy: string;
@Column({ name: 'lastupdatedby', nullable: true })
LastUpdatedBy: string;
@Column({ name: 'lastupdateddate', nullable: true })
LastUpdatedDate: Date;
}

View File

@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Course } from './course.entity';
import { CourseController } from './course.controller';
import { CourseService } from './course.service';
@Module({
imports: [TypeOrmModule.forFeature([Course])],
controllers: [CourseController],
providers: [CourseService],
})
export class CourseModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CourseService } from './course.service';
describe('CourseService', () => {
let service: CourseService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CourseService],
}).compile();
service = module.get<CourseService>(CourseService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Course } from './course.entity';
@Injectable()
export class CourseService {
constructor(
@InjectRepository(Course)
private courseRepository: Repository<Course>,
) {}
async getAvailableCourses() {
return this.courseRepository.query(
`SELECT * FROM get_available_courses()`
);
}
}

View File

@ -0,0 +1,26 @@
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('entitynotes')
export class EntityNotes {
@PrimaryGeneratedColumn({ name: 'noteid' })
NoteID: number;
@Column({ name: 'entitytype' })
EntityType: string;
@Column({ name: 'notes' })
Notes: string;
@Column({ name: 'createddate' })
CreatedDate: Date;
@Column({ name: 'createdby' })
CreatedBy: string;
@Column({ name: 'inactivateddate', nullable: true })
InactivatedDate: Date;
@Column({ name: 'inactivatedby', nullable: true })
InactivatedBy: string;
}

View File

@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { EntityNotes } from './entity-notes.entity';
@Module({
imports: [TypeOrmModule.forFeature([EntityNotes])],
})
export class EntityNotesModule {}

24
src/main.ts Normal file
View File

@ -0,0 +1,24 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Online Training Registration System')
.setDescription('API documentation for Training Registration Backend')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();

View File

@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
export class AcceptTermsDto {
@ApiProperty()
studentId: number;
}

View File

@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
export class EstimateFeesDto {
@ApiProperty()
studentId: number;
}

View File

@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
export class PaymentDto {
@ApiProperty()
studentId: number;
}

View File

@ -0,0 +1,11 @@
import { ApiProperty } from '@nestjs/swagger';
export class SelectCourseDto {
@ApiProperty()
studentId: number;
@ApiProperty({ type: [Number] })
courseIds: number[];
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { StudentCourseController } from './student-course.controller';
describe('StudentCourseController', () => {
let controller: StudentCourseController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [StudentCourseController],
}).compile();
controller = module.get<StudentCourseController>(StudentCourseController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,45 @@
import { Controller, Post, Body } from '@nestjs/common';
import { StudentCourseService } from './student-course.service';
import { SelectCourseDto } from './select-course.dto';
import { EstimateFeesDto } from './estimate-fees.dto';
import { PaymentDto } from './payment.dto';
import { SubmitApplicationDto } from './submit-application.dto';
import { AcceptTermsDto } from './accept-terms.dto';
@Controller('student-course')
export class StudentCourseController {
constructor(private readonly studentCourseService: StudentCourseService) {}
// SELECT COURSES
@Post('select-courses')
selectCourses(@Body() body: SelectCourseDto) {
return this.studentCourseService.selectCourses(body);
}
// ESTIMATE FEES
@Post('estimate-fees')
estimateFees(@Body() body: EstimateFeesDto) {
return this.studentCourseService.estimateFees(body);
}
// SUBMIT APPLICATION
@Post('submit-application')
submitApplication(@Body() body: SubmitApplicationDto) {
return this.studentCourseService.submitApplication(body);
}
// ACCEPT TERMS
@Post('accept-terms')
acceptTerms(@Body() body: AcceptTermsDto) {
return this.studentCourseService.acceptTerms(body);
}
// PAYMENT
@Post('payment')
payment(@Body() body: PaymentDto) {
return this.studentCourseService.makePayment(body);
}
}

View File

@ -0,0 +1,35 @@
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('studentcourse')
export class StudentCourse {
@PrimaryGeneratedColumn({ name: 'studentcourseid' })
StudentCourseID: number;
@Column({ name: 'studentid' })
StudentID: number;
@Column({ name: 'courseid' })
CourseID: number;
@Column({ name: 'paymentstatus' })
PaymentStatus: string;
@Column({ name: 'paiddate', nullable: true })
PaidDate: Date;
@Column({ name: 'noteid', nullable: true })
NoteID: number;
@Column({ name: 'createddate' })
CreatedDate: Date;
@Column({ name: 'createdby' })
CreatedBy: string;
@Column({ name: 'lastupdatedby', nullable: true })
LastUpdatedBy: string;
@Column({ name: 'lastupdateddate', nullable: true })
LastUpdatedDate: Date;
}

View File

@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { StudentCourse } from './student-course.entity';
import { EntityNotes } from '../entity-notes/entity-notes.entity';
import { StudentCourseService } from './student-course.service';
import { StudentCourseController } from './student-course.controller';
@Module({
imports: [TypeOrmModule.forFeature([StudentCourse, EntityNotes])],
providers: [StudentCourseService],
controllers: [StudentCourseController],
})
export class StudentCourseModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { StudentCourseService } from './student-course.service';
describe('StudentCourseService', () => {
let service: StudentCourseService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [StudentCourseService],
}).compile();
service = module.get<StudentCourseService>(StudentCourseService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,182 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { StudentCourse } from './student-course.entity';
import { EntityNotes } from '../entity-notes/entity-notes.entity';
@Injectable()
export class StudentCourseService {
constructor(
@InjectRepository(StudentCourse)
private studentCourseRepository: Repository<StudentCourse>,
@InjectRepository(EntityNotes)
private entityNotesRepository: Repository<EntityNotes>,
) {}
// SELECT COURSES
async selectCourses(data: any) {
const note = this.entityNotesRepository.create({
EntityType: 'StudentCourse',
Notes: 'Student selected courses',
CreatedDate: new Date(),
CreatedBy: 'System'
});
const savedNote = await this.entityNotesRepository.save(note);
const noteId = savedNote.NoteID;
// save selected courses
for (const courseId of data.courseIds) {
const studentCourse = this.studentCourseRepository.create({
StudentID: data.studentId,
CourseID: courseId,
PaymentStatus: 'Pending',
NoteID: noteId,
CreatedDate: new Date(),
CreatedBy: 'System'
});
await this.studentCourseRepository.save(studentCourse);
}
// fetch selected courses
const courses = await this.studentCourseRepository.query(
`
SELECT courseid, name, rate
FROM course
WHERE courseid = ANY($1)
`,
[data.courseIds]
);
let total = 0;
for (const course of courses) {
total += Number(course.rate);
}
return {
message: "Courses saved successfully",
selectedCourses: courses,
totalFees: total
};
}
// ESTIMATE FEES
async estimateFees(data: any) {
const courses = await this.studentCourseRepository.query(
`
SELECT c.courseid, c.name, c.rate
FROM studentcourse sc
JOIN course c ON sc.courseid = c.courseid
WHERE sc.studentid = $1
`,
[data.studentId]
);
let total = 0;
for (const course of courses) {
total += Number(course.rate);
}
return {
selectedCourses: courses,
totalFees: total
};
}
// SUBMIT APPLICATION
async submitApplication(data: any) {
const courses = await this.studentCourseRepository.query(
`
SELECT courseid
FROM studentcourse
WHERE studentid = $1
`,
[data.studentId]
);
if (courses.length === 0) {
return {
message: "No courses selected"
};
}
return {
message: "Application submitted successfully",
nextStep: "terms-and-agreement"
};
}
// ACCEPT TERMS
async acceptTerms(data: any) {
const courses = await this.studentCourseRepository.query(
`
SELECT studentcourseid
FROM studentcourse
WHERE studentid = $1
`,
[data.studentId]
);
if (courses.length === 0) {
return {
message: "No courses selected"
};
}
return {
message: "Terms accepted successfully",
nextStep: "payment"
};
}
// PAYMENT
async makePayment(data: any) {
const courses = await this.studentCourseRepository.query(
`
SELECT studentcourseid
FROM studentcourse
WHERE studentid = $1
`,
[data.studentId]
);
if (courses.length === 0) {
return {
message: "No courses found for payment"
};
}
await this.studentCourseRepository.query(
`
UPDATE studentcourse
SET paymentstatus = 'Paid',
paiddate = NOW(),
lastupdatedby = 'System',
lastupdateddate = NOW()
WHERE studentid = $1
`,
[data.studentId]
);
return {
message: "Payment successful",
paymentStatus: "Paid"
};
}
}

View File

@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
export class SubmitApplicationDto {
@ApiProperty()
studentId: number;
}

View File

@ -0,0 +1,17 @@
import { ApiProperty } from '@nestjs/swagger';
export class CreateStudentDto {
@ApiProperty()
name: string;
@ApiProperty()
email: string;
@ApiProperty()
phone: string;
@ApiProperty()
notes: string;
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { StudentController } from './student.controller';
describe('StudentController', () => {
let controller: StudentController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [StudentController],
}).compile();
controller = module.get<StudentController>(StudentController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,15 @@
import { Body, Controller, Post } from '@nestjs/common';
import { StudentService } from './student.service';
import { CreateStudentDto } from './create-student.dto';
@Controller('students')
export class StudentController {
constructor(private readonly studentService: StudentService) {}
@Post('new-user')
createNewUser(@Body() body: CreateStudentDto) {
return this.studentService.createNewUser(body);
}
}

View File

@ -0,0 +1,38 @@
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('student')
export class Student {
@PrimaryGeneratedColumn({ name: 'studentid' })
StudentID: number;
@Column({ name: 'name' })
Name: string;
@Column({ name: 'emailaddress' })
EmailAddress: string;
@Column({ name: 'phoneno' })
PhoneNo: string;
@Column({ name: 'password', nullable: true })
Password: string;
@Column({ name: 'studentstatus' })
StudentStatus: string;
@Column({ name: 'noteid', nullable: true })
NoteID: number;
@Column({ name: 'createddate' })
CreatedDate: Date;
@Column({ name: 'createdby' })
CreatedBy: string;
@Column({ name: 'lastupdatedby', nullable: true })
LastUpdatedBy: string;
@Column({ name: 'lastupdateddate', nullable: true })
LastUpdatedDate: Date;
}

View File

@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Student } from './student.entity';
import { EntityNotes } from '../entity-notes/entity-notes.entity';
import { StudentController } from './student.controller';
import { StudentService } from './student.service';
@Module({
imports: [TypeOrmModule.forFeature([Student, EntityNotes])],
controllers: [StudentController],
providers: [StudentService],
})
export class StudentModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { StudentService } from './student.service';
describe('StudentService', () => {
let service: StudentService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [StudentService],
}).compile();
service = module.get<StudentService>(StudentService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,66 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Student } from './student.entity';
import { EntityNotes } from '../entity-notes/entity-notes.entity';
@Injectable()
export class StudentService {
constructor(
@InjectRepository(Student)
private studentRepository: Repository<Student>,
@InjectRepository(EntityNotes)
private entityNotesRepository: Repository<EntityNotes>,
) {}
// NEW USER SIGNUP
async createNewUser(data: any) {
let noteId: number | null = null;
// Save notes if user entered notes
if (data.notes) {
const note = this.entityNotesRepository.create({
EntityType: 'Student',
Notes: data.notes,
CreatedDate: new Date(),
CreatedBy: 'System'
});
const savedNote = await this.entityNotesRepository.save(note);
noteId = savedNote.NoteID;
}
// Insert student
const student = this.studentRepository.create({
Name: data.name,
EmailAddress: data.email,
PhoneNo: data.phone,
StudentStatus: 'Pending',
NoteID: noteId ?? undefined,
CreatedDate: new Date(),
CreatedBy: 'System'
} as Student);
await this.studentRepository.save(student);
return {
message: "Student created successfully"
};
}
// GET ALL STUDENTS
async getAllStudents() {
return await this.studentRepository.find();
}
}

25
test/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

9
test/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

25
tsconfig.json Normal file
View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}