diff --git a/.env.template b/.env.template index 907bfee5..9688169c 100644 --- a/.env.template +++ b/.env.template @@ -1,5 +1,5 @@ DOMAIN_NAME=demo.yoman.online -MYSQL_HOST=mysql +MYSQL_HOST=database MYSQL_USER=mysql_user MYSQL_PASSWORD=mysql_password MYSQL_DATABASE=mysql_database diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml new file mode 100644 index 00000000..b6ddb87d --- /dev/null +++ b/.github/workflows/copilot-setup-steps.yml @@ -0,0 +1,69 @@ +name: "Copilot Setup Steps" + +# Automatically run the setup steps when they are changed to allow for easy validation, and +# allow manual testing through the repository's "Actions" tab +on: + workflow_dispatch: + push: + paths: + - .github/workflows/copilot-setup-steps.yml + pull_request: + paths: + - .github/workflows/copilot-setup-steps.yml + +jobs: + # The job MUST be called `copilot-setup-steps` or it will not be picked up by Copilot. + copilot-setup-steps: + runs-on: ubuntu-latest + + # Set the permissions to the lowest permissions possible needed for your steps. + # Copilot will be given its own token for its operations. + permissions: + # Clone the repository to install dependencies + contents: read + + # Environment variables to configure development tools + env: + # Skip Chromium download for Puppeteer (firewall restrictions) + PUPPETEER_SKIP_DOWNLOAD: true + PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: true + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + # Initialize git submodules for shared components + submodules: recursive + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + cache: "yarn" + cache-dependency-path: | + server/yarn.lock + client/yarn.lock + + - name: Install server dependencies + working-directory: ./server + run: yarn install --frozen-lockfile + + - name: Install client dependencies + working-directory: ./client + run: yarn install --frozen-lockfile + + # - name: Build server + # working-directory: ./server + # run: yarn build + + # - name: Build client + # working-directory: ./client + # run: yarn build + + # - name: Verify server tests can run + # working-directory: ./server + # run: yarn test --passWithNoTests + + # - name: Verify client tests can run + # working-directory: ./client + # run: yarn test --passWithNoTests diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index ff1fbaa7..46409518 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -3,7 +3,7 @@ name: Run tests on pull request on: pull_request: branches: - - main + - main jobs: prepare: @@ -28,7 +28,6 @@ jobs: server: - 'server/**' - server-tests: name: Run server tests runs-on: ubuntu-latest @@ -49,7 +48,6 @@ jobs: - run: yarn - run: yarn test - run: yarn test:e2e - client-tests: name: Run client tests diff --git a/client/.gitignore b/client/.gitignore index 800f3a80..0c512d8a 100644 --- a/client/.gitignore +++ b/client/.gitignore @@ -22,3 +22,5 @@ npm-debug.log* yarn-debug.log* yarn-error.log* + +.vite-cache/ diff --git a/client/Dockerfile b/client/Dockerfile index 2d268816..aef78e31 100644 --- a/client/Dockerfile +++ b/client/Dockerfile @@ -1,14 +1,14 @@ -FROM node:18-alpine as development +FROM node:18-alpine AS development -RUN apk add git +RUN apk add --no-cache git -WORKDIR /app +ENV NODE_ENV development -# COPY package*.json /app/ -# COPY yarn.lock /app/ +WORKDIR /app +# No need to do this, because external node_modules are mounted +# COPY package*.json yarn.lock ./ # RUN yarn install - # COPY . . CMD ["yarn", "start"] diff --git a/client/jest.config.js b/client/jest.config.js index 2912df92..8ff6fde1 100644 --- a/client/jest.config.js +++ b/client/jest.config.js @@ -1,8 +1,5 @@ +const base = require('./shared/config/jest.base'); module.exports = { - moduleNameMapper: { - "src/(.*)": "/src/$1", - "@shared/(.*)": "/shared/$1" - }, - testEnvironment: 'jsdom', - setupFilesAfterEnv: ['./src/setupTests.js'], + ...base, + setupFilesAfterEnv: ['/src/setupTests.js'], }; \ No newline at end of file diff --git a/client/shared b/client/shared index 9276a7ea..df48787f 160000 --- a/client/shared +++ b/client/shared @@ -1 +1 @@ -Subproject commit 9276a7eaa68f99fd88152dd7c845ae0ecf574899 +Subproject commit df48787f1e635825a262f163dc56f8ac26331234 diff --git a/client/src/App.jsx b/client/src/App.jsx index da2ed391..0dde49d2 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -144,7 +144,7 @@ const App = () => ( - + {isAdmin(permissions) && } {CommonSettingsResources()} {isUploadedFiles(permissions) && } @@ -155,8 +155,6 @@ const App = () => ( - - {isAdmin(permissions) && } {CommonAdminResources({ permissions })} {isLessonSignature(permissions) && <> diff --git a/client/vite.config.js b/client/vite.config.js index 633fcd81..b0f3066d 100644 --- a/client/vite.config.js +++ b/client/vite.config.js @@ -1,38 +1,2 @@ -import { defineConfig } from "vite"; -import react from "@vitejs/plugin-react"; -import path from 'path'; - -export default ({ mode }) => { - return defineConfig({ - envPrefix: 'REACT_APP', - plugins: [react()], - server: { - host: '0.0.0.0', - port: Number(process.env.PORT || 3000), - hmr: { - overlay: true, - clientPort: 3000, - }, - }, - define: { - "process.env.NODE_ENV": `"${mode}"`, - "process.env.REACT_APP_API_URL": `"${process.env.REACT_APP_API_URL ?? ''}"`, - }, - resolve: { - alias: { - '@shared': path.resolve(__dirname, './shared'), - 'src': path.resolve(__dirname, './src') - }, - }, - build: { - rollupOptions: { - onwarn(warning, warn) { - if (warning.code === 'MODULE_LEVEL_DIRECTIVE') { - return - } - warn(warning) - } - } - }, - }) -} +import { createViteConfig } from './shared/config/createViteConfig'; +export default createViteConfig(); diff --git a/docker-compose.override.yml.template b/docker-compose.override.yml.template index 80a77d71..ac2b47db 100644 --- a/docker-compose.override.yml.template +++ b/docker-compose.override.yml.template @@ -1,39 +1,51 @@ version: "3" name: react-admin-nestjs-dev services: - frontend: - container_name: frontend-dev + client: + container_name: ran-client-dev build: target: development environment: PORT: 3000 + REACT_APP_API_URL: http://localhost:3001 ports: - - "3000:3000" # Main Vite dev server port + - "3000:3000" + - "24678:24678" + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3000/"] + interval: 10s + timeout: 5s + start_period: 60s + retries: 3 volumes: - ./client:/app + - ./client/node_modules:/app/node_modules networks: - private-network - backend: - container_name: backend-dev + server: + container_name: ran-server-dev build: target: development + command: sh -c "yarn typeorm:run && yarn start:dev" ports: - - "3001:3000" # Map container port 3000 to host port 3001 + - "3001:3000" volumes: - ./server:/app + - ./server/node_modules:/app/node_modules networks: - private-network - mysql: - container_name: mysql-dev + database: + container_name: ran-database-dev ports: - - "3306:3306" # MySQL port for local access + - "3306:3306" phpmyadmin: - container_name: php-myadmin-dev + container_name: ran-phpmyadmin-dev + profiles: [tools] ports: - - "8080:80" # PhpMyAdmin web interface + - "8080:80" networks: - private-network diff --git a/docker-compose.yml b/docker-compose.yml index 8b7b7665..4b4e82a0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,10 +1,10 @@ version: "3" services: - frontend: - container_name: frontend + client: + container_name: client restart: unless-stopped depends_on: - - backend + - server build: context: ./client target: production @@ -44,8 +44,8 @@ services: window: 120s - backend: - container_name: backend + server: + container_name: server restart: unless-stopped build: context: ./server @@ -64,7 +64,7 @@ services: MAINTENANCE_MODE: $MAINTENANCE_MODE MAINTENANCE_MESSAGE: $MAINTENANCE_MESSAGE depends_on: - - mysql + - database labels: caddy: api.$DOMAIN_NAME caddy.reverse_proxy: "{{upstreams 3000}}" @@ -97,8 +97,8 @@ services: max_attempts: 3 window: 120s - mysql: - container_name: mysql + database: + container_name: database restart: unless-stopped build: context: ./db @@ -119,13 +119,13 @@ services: container_name: php-myadmin restart: unless-stopped depends_on: - - mysql + - database image: phpmyadmin labels: caddy: sql.$DOMAIN_NAME caddy.reverse_proxy: "{{upstreams 80}}" environment: - PMA_HOST: mysql + PMA_HOST: database MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD # ports: # - "80" diff --git a/server/Dockerfile b/server/Dockerfile index 18ddcee4..cf730d02 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -20,8 +20,6 @@ CMD ["yarn", "start:dev"] FROM node:16-alpine AS builder -RUN apk add curl bash - WORKDIR /app COPY package*.json /app/ diff --git a/server/helpers/sync-db-from-data-sql.sh b/server/helpers/sync-db-from-data-sql.sh index df2f13b4..a4d8ec4d 100755 --- a/server/helpers/sync-db-from-data-sql.sh +++ b/server/helpers/sync-db-from-data-sql.sh @@ -8,8 +8,8 @@ set -e echo "🔄 Syncing database from data.sql..." # Check if docker compose is running -if ! docker compose ps mysql | grep -q "Up"; then - echo "❌ Database container is not running. Please start it with: docker compose up -d mysql" +if ! docker compose ps database | grep -q "Up"; then + echo "❌ Database container is not running. Please start it with: docker compose up -d database" exit 1 fi @@ -17,7 +17,7 @@ fi echo "⏳ Waiting for MySQL to be ready..." timeout=30 counter=0 -until docker compose exec mysql mysqladmin ping -h localhost --silent 2>/dev/null; do +until docker compose exec database mysqladmin ping -h localhost --silent 2>/dev/null; do sleep 1 counter=$((counter + 1)) if [ $counter -ge $timeout ]; then @@ -35,15 +35,15 @@ DB_PASSWORD=${MYSQL_PASSWORD:-mysql_password} # Drop and recreate database echo "🗑️ Dropping existing database..." -docker compose exec mysql mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "DROP DATABASE IF EXISTS \`$DB_NAME\`;" +docker compose exec database mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "DROP DATABASE IF EXISTS \`$DB_NAME\`;" echo "📦 Creating fresh database..." -docker compose exec mysql mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "CREATE DATABASE \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" +docker compose exec database mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "CREATE DATABASE \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" # Import data.sql echo "📥 Importing data.sql..." -docker compose exec -T mysql mysql -u"$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < db/data.sql +docker compose exec -T database mysql -u"$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < db/data.sql echo "✅ Database synced successfully!" echo "" -echo "💡 You can now run: docker compose exec backend yarn typeorm:generate src/migrations/migrationMeaningfulName -p --dr" +echo "💡 You can now run: docker compose exec server yarn typeorm:generate src/migrations/migrationMeaningfulName -p --dr" diff --git a/server/jest.config.js b/server/jest.config.js index 74c01139..85ed2082 100644 --- a/server/jest.config.js +++ b/server/jest.config.js @@ -1,29 +1,5 @@ -const { pathsToModuleNameMapper } = require('ts-jest') -const { compilerOptions } = require('./tsconfig') +const { compilerOptions } = require('./tsconfig'); +const makeJestBase = require('./shared/config/jest.base'); module.exports = { - preset: 'ts-jest', - testEnvironment: 'node', - moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths), - modulePaths: [ - '' - ], - maxWorkers: 1, - testRegex: ".*\\.(spec|test)\\.ts$", - transform: { - "^.+\\.(t|j)s$": "ts-jest" - }, - collectCoverageFrom: [ - "**/*.(t|j)s", - "!**/node_modules/**", - "!**/dist/**", - "!**/coverage/**", - "!helpers/**", - "!.eslintrc.js", - "!jest.config.js", - "!**/migrations/**", - "!test/**", - "!**/config/**", - ], - coverageDirectory: "coverage", - coverageReporters: ["json", "lcov", "text", "clover"], -} + ...makeJestBase(compilerOptions), +}; diff --git a/server/package.json b/server/package.json index a71e47d5..ed402d3e 100644 --- a/server/package.json +++ b/server/package.json @@ -19,7 +19,7 @@ "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", - "typeorm:cli": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d shared/config/migration.config.ts", + "typeorm:cli": "ts-node --project tsconfig.json -r tsconfig-paths/register ./node_modules/typeorm/cli -d shared/config/migration.config.ts", "typeorm:cli-js": "typeorm -d dist/shared/config/migration.config.js", "typeorm:cli-no-d": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli", "typeorm:run": "npm run typeorm:cli -- migration:run", @@ -27,7 +27,8 @@ "typeorm:generate": "npm run typeorm:cli -- migration:generate", "typeorm:create": "npm run typeorm:cli-no-d -- migration:create", "typeorm:revert": "npm run typeorm:cli -- migration:revert", - "clean-migrations": "node helpers/clean-migrations" + "clean-migrations": "node helpers/clean-migrations", + "prettier": "prettier --write \"{src,apps,libs,test}/**/*.ts\"" }, "dependencies": { "@dataui/crud": "^5.2.3", @@ -109,4 +110,4 @@ "tsconfig-paths": "^4.2.0", "typescript": "^4.7.4" } -} +} \ No newline at end of file diff --git a/server/shared b/server/shared index 2f339e04..ef761f09 160000 --- a/server/shared +++ b/server/shared @@ -1 +1 @@ -Subproject commit 2f339e04741a7c1f3ab976c1c4a6e352125c1cbe +Subproject commit ef761f09e0798d6eefc337cc3ea27991b92f4268 diff --git a/server/src/__tests__/app.controller.spec.ts b/server/src/__tests__/app.controller.spec.ts deleted file mode 100644 index bcd1e179..00000000 --- a/server/src/__tests__/app.controller.spec.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { AppController } from '../app.controller'; -import { AppService } from '../app.service'; -import { AuthService } from '@shared/auth/auth.service'; -import { Response } from 'express'; -import { UnauthorizedException } from '@nestjs/common'; -import { AuthenticatedRequest } from '@shared/auth/auth.types'; - -describe('AppController', () => { - let appController: AppController; - let authService: AuthService; - - beforeEach(async () => { - const app: TestingModule = await Test.createTestingModule({ - controllers: [AppController], - providers: [ - AppService, - { - provide: AuthService, - useValue: { - getCookieWithJwtToken: jest.fn(user => { - if (user) return 'cookie'; - throw new UnauthorizedException(); - }), - getCookieForImpersonate: jest.fn(user => { - if (user) return 'cookie'; - throw new UnauthorizedException(); - }), - getCookieForLogOut: jest.fn().mockResolvedValue('Authentication=; HttpOnly; Path=/; Max-Age=0; SameSite=true'), - registerUser: jest.fn().mockRejectedValue(new UnauthorizedException()), - getProfile: jest.fn().mockResolvedValue({}), - updateSettings: jest.fn().mockResolvedValue({}), - } - }, - ], - }).compile(); - - appController = app.get(AppController); - authService = app.get(AuthService); - }); - - it('should return hello message with startup timestamp', () => { - expect(appController.getHello()).toMatch(/^Hello World! Server started at /); - }); - - it('should log in a user and return a success message', async () => { - const req = { user: { email: 'test@example.com' } } as unknown as AuthenticatedRequest; - const res = { setHeader: jest.fn(), send: jest.fn() } as unknown as Response; - - await appController.login(req, res); - - expect(authService.getCookieWithJwtToken).toHaveBeenCalledWith(req.user); - expect(res.setHeader).toHaveBeenCalledWith('Set-Cookie', 'cookie'); - expect(res.send).toHaveBeenCalledWith({ success: true }); - }); - - it('should register a user and return a success message', async () => { - const req = { user: { email: 'test@example.com' } } as unknown as AuthenticatedRequest; - const res = { setHeader: jest.fn(), send: jest.fn() } as unknown as Response; - - await appController.register(req, res); - - expect(authService.getCookieWithJwtToken).toHaveBeenCalledWith(req.user); - expect(res.setHeader).toHaveBeenCalledWith('Set-Cookie', 'cookie'); - expect(res.send).toHaveBeenCalledWith({ success: true }); - }); - - it('should throw an UnauthorizedException when login with unauthenticated user', async () => { - const req = { user: null } as unknown as AuthenticatedRequest; - const res = { setHeader: jest.fn(), send: jest.fn() } as unknown as Response; - - await expect(appController.login(req, res)).rejects.toThrow(UnauthorizedException); - }); - - it('should throw an UnauthorizedException with non-admin user impersonation', async () => { - const req = { - user: { permissions: {} }, - body: { userId: 1 } - } as unknown as AuthenticatedRequest; - const res = { setHeader: jest.fn(), send: jest.fn() } as unknown as Response; - - await expect(appController.impersonate(req, res)).rejects.toThrow(UnauthorizedException); - }); - - it('should log out a user and return a success message', async () => { - const responseMock = { - setHeader: jest.fn(), - sendStatus: jest.fn(), - } as unknown as Response; - - await appController.logOut(responseMock); - - expect(responseMock.setHeader).toHaveBeenCalledWith( - 'Set-Cookie', - expect.any(String) - ); - expect(responseMock.sendStatus).toHaveBeenCalledWith(200); - }); - - it('should return the user\'s profile information', async () => { - const req = { - user: { - id: 1, - email: 'test@example.com', - name: 'Test User' - } - } as unknown as AuthenticatedRequest; - const expectedProfile = { id: 1, email: 'test@example.com', name: 'Test User' }; - - const profile = await appController.getProfile(req); - - expect(profile).toEqual(expectedProfile); - }); - - it('should impersonate a user and return a success message', async () => { - const userId = 1; - const responseMock = { - setHeader: jest.fn(), - send: jest.fn(), - } as unknown as Response; - const req = { - body: { userId }, - user: { permissions: { admin: true } } - } as unknown as AuthenticatedRequest; - - await appController.impersonate(req, responseMock); - - expect(authService.getCookieForImpersonate).toHaveBeenCalledWith(userId); - expect(responseMock.setHeader).toHaveBeenCalledWith('Set-Cookie', 'cookie'); - expect(responseMock.send).toHaveBeenCalledWith({ success: true }); - }); - - it('should unimpersonate a user and return a success message', async () => { - const responseMock = { - setHeader: jest.fn(), - sendStatus: jest.fn(), - send: jest.fn(), - } as unknown as Response; - const getCookieForLogOutSpy = jest.spyOn(authService, 'getCookieForLogOut').mockResolvedValue('cookie'); - - await appController.unimpersonate({} as AuthenticatedRequest, responseMock); - - expect(getCookieForLogOutSpy).toHaveBeenCalled(); - expect(responseMock.setHeader).toHaveBeenCalledWith('Set-Cookie', 'cookie'); - expect(responseMock.sendStatus).toHaveBeenCalledWith(200); - }); - - it('should update user settings', async () => { - const req = { user: { id: 1 } } as unknown as AuthenticatedRequest; - const data = { key: 'value' }; - - await appController.updateSettings(req, data); - - expect(authService.updateSettings).toHaveBeenCalledWith(1, data); - }); -}); diff --git a/server/src/__tests__/app.module.spec.ts b/server/src/__tests__/app.module.spec.ts deleted file mode 100644 index 02657096..00000000 --- a/server/src/__tests__/app.module.spec.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { AppModule } from '../app.module'; -import { AppController } from '../app.controller'; -import { AppService } from '../app.service'; -import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler'; -import { APP_GUARD } from '@nestjs/core'; -import { TypeOrmModule } from '@nestjs/typeorm'; -import { RequestContextModule } from 'nestjs-request-context'; -import { LoggerModule } from 'nestjs-pino'; -import { AuthModule } from '@shared/auth/auth.module'; -import { YemotModule } from '@shared/utils/yemot/v2/yemot.module'; -import { MailSendModule } from '@shared/utils/mail/mail-send.module'; -import { EntitiesModule } from '../entities.module'; -import { getPinoConfig } from '@shared/config/pino.config'; -import { JwtModule } from '@nestjs/jwt'; - -// Mock required modules -jest.mock('../entities.module', () => ({ - EntitiesModule: class { - static imports = []; - } -})); - -jest.mock('@shared/config/pino.config', () => ({ - getPinoConfig: jest.fn().mockImplementation((isDev) => ({ - pinoHttp: { level: isDev ? 'debug' : 'info' } - })) -})); - -// Mock JWT configuration -jest.mock('@shared/auth/constants', () => ({ - jwtConstants: { - secret: 'test-secret', - maxAge: '60s' - } -})); - -// Other external configurations -jest.mock('@shared/config/pino.config', () => ({ - getPinoConfig: jest.fn().mockReturnValue({ - pinoHttp: { level: 'silent' } - }) -})); - -jest.mock('@shared/config/typeorm.config', () => ({ - typeOrmModuleConfig: { - type: 'sqlite', - database: ':memory:', - synchronize: true, - logging: false - } -})); - -describe('AppModule', () => { - let module: TestingModule; - - beforeEach(async () => { - const moduleRef = await Test.createTestingModule({ - imports: [ - AppModule - ], - }) - .overrideProvider('JWT_SECRET') - .useValue('test-secret') - .compile(); - - module = moduleRef; - }); - - it('should be defined', () => { - expect(module).toBeDefined(); - }); - - it('should have AppController', () => { - const controller = module.get(AppController); - expect(controller).toBeDefined(); - }); - - it('should have AppService', () => { - const service = module.get(AppService); - expect(service).toBeDefined(); - }); - - it('should configure ThrottlerModule with correct options', () => { - const throttlerModule = Reflect.getMetadata('imports', AppModule); - const throttlerConfig = throttlerModule.find( - (imp: any) => imp && imp.module === ThrottlerModule - ); - expect(throttlerConfig).toBeDefined(); - expect(throttlerConfig.module).toBe(ThrottlerModule); - }); - - it('should register ThrottlerGuard as APP_GUARD', () => { - const providers = Reflect.getMetadata('providers', AppModule); - const guardProvider = providers.find( - (provider: any) => provider.provide === APP_GUARD - ); - expect(guardProvider).toBeDefined(); - expect(guardProvider.useClass).toBe(ThrottlerGuard); - }); - - it('should configure TypeOrmModule', () => { - const imports = Reflect.getMetadata('imports', AppModule); - const typeOrmConfig = imports.find( - (imp: any) => imp && imp.module === TypeOrmModule - ); - expect(typeOrmConfig).toBeDefined(); - expect(typeOrmConfig.module).toBe(TypeOrmModule); - }); - - it('should import RequestContextModule', () => { - const imports = Reflect.getMetadata('imports', AppModule); - expect(imports.includes(RequestContextModule)).toBe(true); - }); - - it('should configure LoggerModule with Pino', () => { - const imports = Reflect.getMetadata('imports', AppModule); - const loggerConfig = imports.find( - (imp: any) => imp && imp.module === LoggerModule - ); - expect(loggerConfig).toBeDefined(); - expect(loggerConfig.module).toBe(LoggerModule); - expect(getPinoConfig).toHaveBeenCalled(); - }); - - it('should import MailSendModule', () => { - const imports = Reflect.getMetadata('imports', AppModule); - expect(imports.includes(MailSendModule)).toBe(true); - }); - - it('should import EntitiesModule', () => { - const imports = Reflect.getMetadata('imports', AppModule); - expect(imports.includes(EntitiesModule)).toBe(true); - }); - - it('should import AuthModule', () => { - const imports = Reflect.getMetadata('imports', AppModule); - const authModuleImport = imports.find( - (imp: any) => imp && imp.module === AuthModule - ); - expect(authModuleImport).toBeDefined(); - }); - - it('should configure YemotModule with chain', () => { - const imports = Reflect.getMetadata('imports', AppModule); - const yemotConfig = imports.find( - (imp: any) => imp && imp.module === YemotModule - ); - expect(yemotConfig).toBeDefined(); - expect(yemotConfig.module).toBe(YemotModule); - }); - - describe('Environment configuration', () => { - const previousEnv = process.env.NODE_ENV; - - beforeEach(() => { - jest.clearAllMocks(); - }); - - afterEach(() => { - process.env.NODE_ENV = previousEnv; - }); - - it('should configure Pino logger for development environment', async () => { - process.env.NODE_ENV = 'development'; - - const moduleRef = await Test.createTestingModule({ - imports: [LoggerModule.forRoot(getPinoConfig(true))] - }).compile(); - - const loggerModule = moduleRef.get(LoggerModule); - expect(getPinoConfig).toHaveBeenCalledWith(true); - expect(loggerModule).toBeDefined(); - }); - - it('should configure Pino logger for production environment', async () => { - process.env.NODE_ENV = 'production'; - - const moduleRef = await Test.createTestingModule({ - imports: [LoggerModule.forRoot(getPinoConfig(false))] - }).compile(); - - const loggerModule = moduleRef.get(LoggerModule); - expect(getPinoConfig).toHaveBeenCalledWith(false); - expect(loggerModule).toBeDefined(); - }); - }); -}); \ No newline at end of file diff --git a/server/src/__tests__/app.service.spec.ts b/server/src/__tests__/app.service.spec.ts deleted file mode 100644 index 1a5b3094..00000000 --- a/server/src/__tests__/app.service.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { AppService } from '../app.service'; - -describe('AppService', () => { - let service: AppService; - - beforeEach(async () => { - const module: TestingModule = await Test.createTestingModule({ - providers: [AppService], - }).compile(); - - service = module.get(AppService); - }); - - it('should be defined', () => { - expect(service).toBeDefined(); - }); - - describe('getHello', () => { - it('should return hello message with startup timestamp', () => { - expect(service.getHello()).toMatch(/^Hello World! Server started at /); - }); - }); -}); \ No newline at end of file diff --git a/server/src/app.controller.ts b/server/src/app.controller.ts deleted file mode 100644 index 5c7810d4..00000000 --- a/server/src/app.controller.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { Controller, Get, HttpCode, UnauthorizedException, Post, Request, Res, UseGuards, Body } from '@nestjs/common'; -import { AppService } from 'src/app.service'; -import { AuthService } from '@shared/auth/auth.service'; -import { JwtAuthGuard } from '@shared/auth/jwt-auth.guard'; -import { LocalAuthGuard } from '@shared/auth/local-auth.guard'; -import { Response } from 'express'; -import { LocalRegisterAuthGuard } from '@shared/auth/local-register-auth.guard'; -import { getUserIdFromUser } from '@shared/auth/auth.util'; -import { isAdmin } from '@shared/utils/permissionsUtil'; -import { AuthenticatedRequest } from '@shared/auth/auth.types'; -import { SkipMaintenance } from '@shared/decorators/skip-maintenance.decorator'; - -@Controller() -export class AppController { - constructor( - private readonly appService: AppService, - private authService: AuthService) { } - - @UseGuards(LocalAuthGuard) - @Post('auth/login') - @HttpCode(200) - async login(@Request() req: AuthenticatedRequest, @Res() response: Response) { - const cookie = await this.authService.getCookieWithJwtToken(req.user); - response.setHeader('Set-Cookie', cookie); - return response.send({ success: true }); - } - - @UseGuards(LocalRegisterAuthGuard) - @Post('auth/register') - @HttpCode(200) - async register(@Request() req: AuthenticatedRequest, @Res() response: Response) { - const cookie = await this.authService.getCookieWithJwtToken(req.user); - response.setHeader('Set-Cookie', cookie); - return response.send({ success: true }); - } - - @Post('auth/logout') - async logOut(@Res() response: Response) { - const cookie = await this.authService.getCookieForLogOut(); - response.setHeader('Set-Cookie', cookie); - return response.sendStatus(200); - } - - @UseGuards(JwtAuthGuard) - @Get('profile') - async getProfile(@Request() req: AuthenticatedRequest) { - const userId = getUserIdFromUser(req.user, true); - if (!userId) { - return req.user; - } - const user = await this.authService.getProfile(userId); - return Object.assign({}, req.user, user); - } - - @UseGuards(JwtAuthGuard) - @Post('auth/impersonate') - async impersonate(@Request() req: AuthenticatedRequest, @Res() response: Response) { - if (!isAdmin(req.user) || !req.body.userId) { - console.log('impersonate non authorized') - throw new UnauthorizedException(); - } - const cookie = await this.authService.getCookieForImpersonate(req.body.userId); - response.setHeader('Set-Cookie', cookie); - return response.send({ success: true }); - } - - @UseGuards(JwtAuthGuard) - @Post('auth/unimpersonate') - async unimpersonate(@Request() req: Express.AuthenticatedRequest, @Res() response: Response) { - const cookie = await this.authService.getCookieForLogOut(req.user); - response.setHeader('Set-Cookie', cookie); - return response.sendStatus(200); - } - - @UseGuards(JwtAuthGuard) - @Post('settings') - async updateSettings(@Request() req: AuthenticatedRequest, @Body() data: any) { - const userId = getUserIdFromUser(req.user); - return this.authService.updateSettings(userId, data); - } - - @Get() - getHello(): string { - return this.appService.getHello(); - } - - @SkipMaintenance() - @Get('health') - @HttpCode(200) - healthCheck() { - return { status: 'ok', timestamp: new Date().toISOString() }; - } -} diff --git a/server/src/app.module.ts b/server/src/app.module.ts index 93354ed5..285c3612 100644 --- a/server/src/app.module.ts +++ b/server/src/app.module.ts @@ -1,42 +1,11 @@ -import { Module } from '@nestjs/common'; -import { APP_GUARD } from '@nestjs/core'; -import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler'; -import { AppController } from 'src/app.controller'; -import { AppService } from 'src/app.service'; -import { TypeOrmModule } from '@nestjs/typeorm'; -import { RequestContextModule } from 'nestjs-request-context'; -import { LoggerModule } from 'nestjs-pino'; -import { typeOrmModuleConfig } from '@shared/config/typeorm.config'; -import { AuthModule } from '@shared/auth/auth.module'; -import { YemotModule } from '@shared/utils/yemot/v2/yemot.module'; -import { YemotHandlerService } from './yemot-handler.service'; -import { MailSendModule } from '@shared/utils/mail/mail-send.module'; +import { BaseNraAppModule } from '@shared/app/base-app.module'; import { EntitiesModule } from './entities.module'; -import { getPinoConfig } from '@shared/config/pino.config'; import { UserInitModule } from './user-init.module'; -import { UserInitializationService } from './user-initialization.service'; +import { YemotHandlerService } from './yemot-handler.service'; -@Module({ - imports: [ - RequestContextModule, - LoggerModule.forRoot(getPinoConfig(process.env.NODE_ENV === 'development')), - ThrottlerModule.forRoot({ ttl: 5, limit: 200 }), - TypeOrmModule.forRoot(typeOrmModuleConfig), - MailSendModule, - EntitiesModule, - AuthModule.forRootAsync({ - imports: [UserInitModule], - userInitServiceType: UserInitializationService, - }), - YemotModule.register(YemotHandlerService), - ], - controllers: [AppController], - providers: [ - AppService, - { - provide: APP_GUARD, - useClass: ThrottlerGuard - } - ], -}) -export class AppModule { } +export const AppModule = BaseNraAppModule.forRoot({ + entitiesModule: EntitiesModule, + yemotHandlerService: YemotHandlerService, + userInitModule: UserInitModule, + throttlerLimit: 200, +}); diff --git a/server/src/app.service.ts b/server/src/app.service.ts deleted file mode 100644 index 7a60d033..00000000 --- a/server/src/app.service.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Injectable } from '@nestjs/common'; - -const serverStartTime = new Date(); - -@Injectable() -export class AppService { - getHello(): string { - return `Hello World! Server started at ${serverStartTime.toISOString()}`; - } -} diff --git a/server/src/entities.module.ts b/server/src/entities.module.ts index 6c15a6bc..ce419e5c 100644 --- a/server/src/entities.module.ts +++ b/server/src/entities.module.ts @@ -1,7 +1,6 @@ import { Module } from "@nestjs/common"; import { BaseEntityModule } from '@shared/base-entity/base-entity.module'; -// TODO: move all shared configs to shared folder -import userConfig from '@shared/entities/configs/user.config'; +import { createSharedEntitiesImports } from '@shared/entities/createSharedEntitiesImports'; import attReportConfig from './entity-modules/att-report.config'; import gradeConfig from './entity-modules/grade.config'; import klassConfig from './entity-modules/klass.config'; @@ -11,23 +10,16 @@ import lessonConfig from './entity-modules/lesson.config'; import studentKlassConfig from './entity-modules/student-klass.config'; import studentConfig from './entity-modules/student.config'; import teacherConfig from './entity-modules/teacher.config'; -import textConfig from '@shared/entities/configs/text.config'; import studentKlassReportConfig from './entity-modules/student-klass-report.config'; import { StudentBaseKlass } from './db/view-entities/StudentBaseKlass.entity'; import { createAuditLogConfig } from '@shared/entities/configs/audit-log.config'; -import { YemotCall } from '@shared/entities/YemotCall.entity'; -import { TextByUser } from '@shared/view-entities/TextByUser.entity'; -import mailAddressConfig from '@shared/utils/mail/mail-address.config'; -import { RecievedMail } from '@shared/entities/RecievedMail.entity'; -import { Image } from "@shared/entities/Image.entity"; -import pageConfig from '@shared/entities/configs/page.config'; +import { registerEntityNameMap } from '@shared/entities/configs/import-file.config'; import { ReportMonth } from './db/entities/ReportMonth.entity'; import teacherReportStatusConfig from './entity-modules/teacher-report-status.config'; import studentPercentReportConfig from './entity-modules/student-percent-report.config'; import { AttReportAndGrade } from "./db/view-entities/AttReportAndGrade.entity"; import { StudentGlobalReport } from "./db/view-entities/StudentGlobalReport.entity"; import studentByYearConfig from "./entity-modules/student-by-year.config"; -import paymentTrackConfig from "@shared/entities/configs/payment-track.config"; import teacherSalaryReportConfig from "./entity-modules/teacher-salary-report.config"; import attReportWithReportMonthConfig from "./entity-modules/att-report-with-report-month.config"; import { KnownAbsenceWithReportMonth } from "./db/view-entities/KnownAbsenceWithReportMonth.entity"; @@ -37,17 +29,16 @@ import teacherGradeReportStatusConfig from "./entity-modules/teacher-grade-repor import { GradeEffectByUser } from "src/db/view-entities/GradeEffectByUser.entity"; import { AbsCountEffectByUser } from "src/db/view-entities/AbsCountEffectByUser.entity"; import { LessonKlassName } from "./db/view-entities/LessonKlassName.entity"; -import importFileConfig from "@shared/entities/configs/import-file.config"; import { StudentSpeciality } from "./db/view-entities/StudentSpeciality.entity"; import { AttendanceName } from "./db/entities/AttendanceName.entity"; import reportGroupConfig from "./entity-modules/report-group.config"; import reportGroupSessionConfig from "./entity-modules/report-group-session.config"; -import transportationConfig from './entity-modules/transportation.config'; +import transportationConfig from './entity-modules/transportation.config'; import absenceTypeConfig from "./entity-modules/absenceType.config"; import uploadedFileConfig from "@shared/entities/configs/uploaded-file.config"; import { Student } from "./db/entities/Student.entity"; import { Teacher } from "./db/entities/Teacher.entity"; -import { registerEntityNameMap } from '@shared/entities/configs/import-file.config'; +import userConfig from "@shared/entities/configs/user.config"; registerEntityNameMap({ att_report: 'נוכחות', @@ -64,7 +55,7 @@ registerEntityNameMap({ @Module({ imports: [ - BaseEntityModule.register(userConfig), + ...createSharedEntitiesImports(userConfig), BaseEntityModule.register(attReportConfig), BaseEntityModule.register(attReportWithReportMonthConfig), BaseEntityModule.register(gradeConfig), @@ -75,28 +66,19 @@ registerEntityNameMap({ BaseEntityModule.register(studentKlassConfig), BaseEntityModule.register(studentConfig), BaseEntityModule.register(teacherConfig), - BaseEntityModule.register(textConfig), BaseEntityModule.register(studentKlassReportConfig), BaseEntityModule.register({ entity: StudentBaseKlass }), BaseEntityModule.register({ entity: StudentSpeciality }), BaseEntityModule.register(createAuditLogConfig({ student: Student, teacher: Teacher })), - BaseEntityModule.register(importFileConfig), BaseEntityModule.register(reportGroupConfig), BaseEntityModule.register(reportGroupSessionConfig), - BaseEntityModule.register({ entity: YemotCall }), - BaseEntityModule.register(mailAddressConfig), - BaseEntityModule.register({ entity: RecievedMail }), - BaseEntityModule.register(pageConfig), BaseEntityModule.register({ entity: ReportMonth }), BaseEntityModule.register(teacherReportStatusConfig), BaseEntityModule.register(teacherGradeReportStatusConfig), - BaseEntityModule.register({ entity: TextByUser }), BaseEntityModule.register(studentPercentReportConfig), BaseEntityModule.register({ entity: AttReportAndGrade }), BaseEntityModule.register({ entity: StudentGlobalReport }), - BaseEntityModule.register({ entity: Image }), BaseEntityModule.register(studentByYearConfig), - BaseEntityModule.register(paymentTrackConfig), BaseEntityModule.register(teacherSalaryReportConfig), BaseEntityModule.register({ entity: KnownAbsenceWithReportMonth }), BaseEntityModule.register({ entity: GradeName }), diff --git a/server/src/main.ts b/server/src/main.ts index 83ab4e24..58e00613 100644 --- a/server/src/main.ts +++ b/server/src/main.ts @@ -1,19 +1,9 @@ import '@shared/config/crud.config'; -import { NestFactory } from '@nestjs/core'; import { AppModule } from 'src/app.module'; -import { setupApplication, setupYemotRouter } from '@shared/utils/bootstrap.util'; +import { bootstrapNraApplication } from '@shared/utils/bootstrap.util'; -async function bootstrap() { - const app = await NestFactory.create(AppModule); - - setupApplication(app, { - swaggerTitle: 'react-admin-nestjs', - swaggerDescription: 'Demo website description', - swaggerTag: 'demo', - }); - - setupYemotRouter(app); - - await app.listen(3000); -} -bootstrap(); +bootstrapNraApplication(AppModule, { + swaggerTitle: 'react-admin-nestjs', + swaggerDescription: 'Demo website description', + swaggerTag: 'demo', +}); diff --git a/server/src/user-init.module.ts b/server/src/user-init.module.ts index 56bc125a..426be10e 100644 --- a/server/src/user-init.module.ts +++ b/server/src/user-init.module.ts @@ -1,5 +1,6 @@ import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; +import { USER_INITIALIZATION_SERVICE } from '@shared/auth/user-initialization.interface'; import { UserInitializationService } from './user-initialization.service'; import { ReportMonth } from './db/entities/ReportMonth.entity'; @@ -7,7 +8,10 @@ import { ReportMonth } from './db/entities/ReportMonth.entity'; imports: [ TypeOrmModule.forFeature([ReportMonth]), ], - providers: [UserInitializationService], - exports: [UserInitializationService], + providers: [ + UserInitializationService, + { provide: USER_INITIALIZATION_SERVICE, useExisting: UserInitializationService }, + ], + exports: [UserInitializationService, USER_INITIALIZATION_SERVICE], }) export class UserInitModule { } \ No newline at end of file diff --git a/server/test/app.e2e-spec.ts b/server/test/app.e2e-spec.ts index 715c07bc..b342c5f5 100644 --- a/server/test/app.e2e-spec.ts +++ b/server/test/app.e2e-spec.ts @@ -1,38 +1,4 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { INestApplication } from '@nestjs/common'; -import * as request from 'supertest'; import { AppModule } from 'src/app.module'; -import { DataSource } from 'typeorm'; +import { createSharedAppE2eTests } from '@shared/utils/testing/e2e/app-e2e.shared'; -describe('AppController (e2e)', () => { - let app: INestApplication; - let dataSource: DataSource; - - beforeEach(async () => { - const moduleFixture: TestingModule = await Test.createTestingModule({ - imports: [AppModule], - }).compile(); - - app = moduleFixture.createNestApplication(); - await app.init(); - - dataSource = moduleFixture.get(DataSource); - }); - - afterEach(async () => { - await app.close(); - }); - - it('/ (GET)', () => { - return request(app.getHttpServer()) - .get('/') - .expect(200) - .expect(/^Hello World! Server started at /); - }); - - it('should use SQLite in-memory database for E2E tests', () => { - expect(dataSource).toBeDefined(); - expect(dataSource.options.type).toBe('sqlite'); - expect((dataSource.options as any).database).toBe(':memory:'); - }); -}); +createSharedAppE2eTests(AppModule); diff --git a/server/test/jest-e2e.json b/server/test/jest-e2e.json index 915e569a..18c9331a 100644 --- a/server/test/jest-e2e.json +++ b/server/test/jest-e2e.json @@ -1,15 +1,28 @@ { - "moduleFileExtensions": ["js", "json", "ts", "tsx", "jsx"], - "rootDir": "..", + "moduleFileExtensions": [ + "js", + "json", + "ts", + "tsx", + "jsx" + ], + "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", "transform": { "^.+\\.(t|j)sx?$": "ts-jest" }, "forceExit": true, + "detectOpenHandles": true, + "maxWorkers": 1, "moduleNameMapper": { - "^src/(.*)$": "/src/$1", - "^@shared/(.*)$": "/shared/$1" + "^src/(.*)$": "/../src/$1", + "^@shared/(.*)$": "/../shared/$1" }, - "setupFiles": ["/test/setup-e2e.ts"] -} + "modulePaths": [ + "/../" + ], + "setupFilesAfterEnv": [ + "/setup-tests.ts" + ] +} \ No newline at end of file diff --git a/server/test/setup-tests.ts b/server/test/setup-tests.ts new file mode 100644 index 00000000..262f4d2a --- /dev/null +++ b/server/test/setup-tests.ts @@ -0,0 +1,12 @@ +// Global test setup for e2e tests +jest.setTimeout(10000); + +process.env.NODE_ENV = 'test'; +process.env.JWT_SECRET = 'test-secret-key-for-e2e-tests'; +process.env.JWT_EXPIRES_IN = '1h'; + +process.on('unhandledRejection', (reason) => { + console.warn('Unhandled promise rejection:', reason); +}); + +process.setMaxListeners(20);