rebase generation
This commit is contained in:
7
.claude/worktrees/goofy-haslett/server/.env.example
Normal file
7
.claude/worktrees/goofy-haslett/server/.env.example
Normal file
@@ -0,0 +1,7 @@
|
||||
PORT=3000
|
||||
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/toir"
|
||||
CORS_ALLOWED_ORIGINS="http://localhost:5173,https://toir-frontend.greact.ru"
|
||||
KEYCLOAK_ISSUER_URL="https://sso.greact.ru/realms/toir"
|
||||
KEYCLOAK_AUDIENCE="toir-backend"
|
||||
# Optional explicit JWKS URL override
|
||||
KEYCLOAK_JWKS_URL=""
|
||||
5
.claude/worktrees/goofy-haslett/server/.gitignore
vendored
Normal file
5
.claude/worktrees/goofy-haslett/server/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
# Keep environment variables out of version control
|
||||
.env
|
||||
|
||||
/generated/prisma
|
||||
4
.claude/worktrees/goofy-haslett/server/.prettierrc
Normal file
4
.claude/worktrees/goofy-haslett/server/.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
26
.claude/worktrees/goofy-haslett/server/Dockerfile
Normal file
26
.claude/worktrees/goofy-haslett/server/Dockerfile
Normal file
@@ -0,0 +1,26 @@
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
|
||||
FROM node:24-alpine
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY --from=build /app/prisma ./prisma
|
||||
COPY --from=build /app/docker-entrypoint.sh ./docker-entrypoint.sh
|
||||
COPY .env.example ./.env.example
|
||||
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
EXPOSE 3000
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
CMD ["npm", "run", "start:prod"]
|
||||
98
.claude/worktrees/goofy-haslett/server/README.md
Normal file
98
.claude/worktrees/goofy-haslett/server/README.md
Normal 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>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](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).
|
||||
12
.claude/worktrees/goofy-haslett/server/docker-entrypoint.sh
Normal file
12
.claude/worktrees/goofy-haslett/server/docker-entrypoint.sh
Normal file
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
npx prisma generate
|
||||
|
||||
if [ -d prisma/migrations ] && [ "$(find prisma/migrations -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')" -gt 0 ]; then
|
||||
npx prisma migrate deploy
|
||||
else
|
||||
npx prisma db push
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
35
.claude/worktrees/goofy-haslett/server/eslint.config.mjs
Normal file
35
.claude/worktrees/goofy-haslett/server/eslint.config.mjs
Normal 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
.claude/worktrees/goofy-haslett/server/nest-cli.json
Normal file
8
.claude/worktrees/goofy-haslett/server/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
10364
.claude/worktrees/goofy-haslett/server/package-lock.json
generated
Normal file
10364
.claude/worktrees/goofy-haslett/server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
79
.claude/worktrees/goofy-haslett/server/package.json
Normal file
79
.claude/worktrees/goofy-haslett/server/package.json
Normal file
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"name": "server",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"prisma:generate": "prisma generate",
|
||||
"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",
|
||||
"seed": "node prisma/seed.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.3",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@prisma/client": "^6.16.2",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"jose": "^6.2.2",
|
||||
"prisma": "^6.16.2",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"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/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^17.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"
|
||||
}
|
||||
}
|
||||
34
.claude/worktrees/goofy-haslett/server/prisma/schema.prisma
Normal file
34
.claude/worktrees/goofy-haslett/server/prisma/schema.prisma
Normal file
@@ -0,0 +1,34 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
enum EquipmentStatus {
|
||||
Active
|
||||
Repair
|
||||
}
|
||||
|
||||
model Equipment {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
serialNumber String
|
||||
dateOfInspection DateTime?
|
||||
commissionedAt DateTime?
|
||||
status EquipmentStatus
|
||||
changeEquipmentStatus ChangeEquipmentStatus[]
|
||||
}
|
||||
|
||||
model ChangeEquipmentStatus {
|
||||
equipmentId String
|
||||
newStatus EquipmentStatus
|
||||
number String?
|
||||
date DateTime
|
||||
responsible String?
|
||||
equipment Equipment @relation(fields: [equipmentId], references: [id])
|
||||
|
||||
@@id([equipmentId, newStatus])
|
||||
}
|
||||
1
.claude/worktrees/goofy-haslett/server/prisma/seed.js
Normal file
1
.claude/worktrees/goofy-haslett/server/prisma/seed.js
Normal file
@@ -0,0 +1 @@
|
||||
console.log('No seed data configured.');
|
||||
@@ -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
.claude/worktrees/goofy-haslett/server/src/app.controller.ts
Normal file
12
.claude/worktrees/goofy-haslett/server/src/app.controller.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
17
.claude/worktrees/goofy-haslett/server/src/app.module.ts
Normal file
17
.claude/worktrees/goofy-haslett/server/src/app.module.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { EquipmentModule } from './modules/equipment/equipment.module';
|
||||
import { EquipmentStatusChangeModule } from './modules/equipment-status-change/equipment-status-change.module';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
HealthModule,
|
||||
EquipmentModule,
|
||||
EquipmentStatusChangeModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { RolesGuard } from './guards/roles.guard';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [AuthService, JwtAuthGuard, RolesGuard],
|
||||
exports: [AuthService, JwtAuthGuard, RolesGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import {
|
||||
createRemoteJWKSet,
|
||||
jwtVerify,
|
||||
} from 'jose';
|
||||
|
||||
export interface AuthenticatedUser {
|
||||
sub: string;
|
||||
username?: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
type RemoteJwks = ReturnType<typeof createRemoteJWKSet>;
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private jwksPromise: Promise<RemoteJwks> | null = null;
|
||||
|
||||
async verifyAccessToken(token: string): Promise<AuthenticatedUser> {
|
||||
const issuer = process.env.KEYCLOAK_ISSUER_URL;
|
||||
const audience = process.env.KEYCLOAK_AUDIENCE;
|
||||
|
||||
if (!issuer || !audience) {
|
||||
throw new UnauthorizedException('Keycloak issuer or audience is not configured');
|
||||
}
|
||||
|
||||
try {
|
||||
const jwks = await this.getJwks();
|
||||
const result = await jwtVerify(token, jwks, {
|
||||
issuer,
|
||||
audience,
|
||||
});
|
||||
|
||||
return this.mapPayloadToUser(result);
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Token validation failed');
|
||||
}
|
||||
}
|
||||
|
||||
private async getJwks(): Promise<RemoteJwks> {
|
||||
if (!this.jwksPromise) {
|
||||
this.jwksPromise = this.resolveJwks().catch((error) => {
|
||||
this.jwksPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
|
||||
return this.jwksPromise;
|
||||
}
|
||||
|
||||
private async resolveJwks(): Promise<RemoteJwks> {
|
||||
const issuer = process.env.KEYCLOAK_ISSUER_URL;
|
||||
if (!issuer) {
|
||||
throw new UnauthorizedException('KEYCLOAK_ISSUER_URL is not configured');
|
||||
}
|
||||
|
||||
const explicitJwksUrl = process.env.KEYCLOAK_JWKS_URL;
|
||||
if (explicitJwksUrl) {
|
||||
return createRemoteJWKSet(new URL(explicitJwksUrl));
|
||||
}
|
||||
|
||||
try {
|
||||
const discoveryUrl = new URL('.well-known/openid-configuration', `${issuer.replace(/\/$/, '')}/`);
|
||||
const response = await fetch(discoveryUrl);
|
||||
if (response.ok) {
|
||||
const discovery = (await response.json()) as { jwks_uri?: string };
|
||||
if (discovery.jwks_uri) {
|
||||
return createRemoteJWKSet(new URL(discovery.jwks_uri));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the Keycloak certs endpoint.
|
||||
}
|
||||
|
||||
return createRemoteJWKSet(new URL(`${issuer.replace(/\/$/, '')}/protocol/openid-connect/certs`));
|
||||
}
|
||||
|
||||
private mapPayloadToUser(result: Awaited<ReturnType<typeof jwtVerify>>): AuthenticatedUser {
|
||||
const payload = result.payload;
|
||||
const realmAccess = payload.realm_access as { roles?: string[] } | undefined;
|
||||
const roles = Array.isArray(realmAccess?.roles) ? realmAccess.roles : [];
|
||||
|
||||
return {
|
||||
sub: String(payload.sub ?? ''),
|
||||
username: typeof payload.preferred_username === 'string' ? payload.preferred_username : undefined,
|
||||
email: typeof payload.email === 'string' ? payload.email : undefined,
|
||||
name: typeof payload.name === 'string' ? payload.name : undefined,
|
||||
roles,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Request } from 'express';
|
||||
import { AuthService } from '../auth.service';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
|
||||
type AuthenticatedRequest = Request & {
|
||||
user?: unknown;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
const header = request.headers.authorization;
|
||||
|
||||
if (!header?.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException('Missing bearer token');
|
||||
}
|
||||
|
||||
const token = header.slice('Bearer '.length).trim();
|
||||
request.user = await this.authService.verifyAccessToken(token);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
type RequestWithUser = {
|
||||
user?: {
|
||||
roles?: string[];
|
||||
};
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const userRoles = request.user?.roles ?? [];
|
||||
const isAllowed = requiredRoles.some((role) => userRoles.includes(role));
|
||||
|
||||
if (!isAllowed) {
|
||||
throw new ForbiddenException('Insufficient role');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Response } from 'express';
|
||||
|
||||
export function setListHeaders(response: Response, start: number, end: number, total: number) {
|
||||
const safeEnd = total === 0 ? start : Math.max(start, end - 1);
|
||||
response.setHeader('Content-Range', `items ${start}-${safeEnd}/${total}`);
|
||||
response.setHeader('Access-Control-Expose-Headers', 'Content-Range');
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { Public } from '../auth/decorators/public.decorator';
|
||||
|
||||
@Public()
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
@Get()
|
||||
getHealth() {
|
||||
return {
|
||||
status: 'ok',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
26
.claude/worktrees/goofy-haslett/server/src/main.ts
Normal file
26
.claude/worktrees/goofy-haslett/server/src/main.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const corsAllowedOrigins =
|
||||
process.env.CORS_ALLOWED_ORIGINS?.split(',').map((origin) => origin.trim()).filter(Boolean) ?? [];
|
||||
|
||||
app.enableCors({
|
||||
origin: corsAllowedOrigins.length > 0 ? corsAllowedOrigins : true,
|
||||
credentials: true,
|
||||
exposedHeaders: ['Content-Range'],
|
||||
});
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
forbidNonWhitelisted: false,
|
||||
}),
|
||||
);
|
||||
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
}
|
||||
|
||||
void bootstrap();
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../auth/guards/roles.guard';
|
||||
import { Roles } from '../../auth/decorators/roles.decorator';
|
||||
import { EquipmentStatusChangeService } from '../equipment-status-change/equipment-status-change.service';
|
||||
import { CreateChangeEquipmentStatusDto } from './dto/create-change-equipment-status.dto';
|
||||
import { UpdateChangeEquipmentStatusDto } from './dto/update-change-equipment-status.dto';
|
||||
|
||||
@Controller('change-equipment-status')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class ChangeEquipmentStatusController {
|
||||
constructor(private readonly equipmentStatusChangeService: EquipmentStatusChangeService) {}
|
||||
|
||||
@Get()
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
list(@Query() query: Record<string, string | string[]>, @Res({ passthrough: true }) response: Response) {
|
||||
return this.equipmentStatusChangeService.list(query, response);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Roles('editor', 'admin')
|
||||
create(@Body() dto: CreateChangeEquipmentStatusDto) {
|
||||
return this.equipmentStatusChangeService.create(dto);
|
||||
}
|
||||
|
||||
@Get(':equipmentId/:newStatus')
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
get(@Param('equipmentId') equipmentId: string, @Param('newStatus') newStatus: string) {
|
||||
return this.equipmentStatusChangeService.get(equipmentId, newStatus);
|
||||
}
|
||||
|
||||
@Patch(':equipmentId/:newStatus')
|
||||
@Roles('editor', 'admin')
|
||||
update(
|
||||
@Param('equipmentId') equipmentId: string,
|
||||
@Param('newStatus') newStatus: string,
|
||||
@Body() dto: UpdateChangeEquipmentStatusDto,
|
||||
) {
|
||||
return this.equipmentStatusChangeService.update(equipmentId, newStatus, dto);
|
||||
}
|
||||
|
||||
@Delete(':equipmentId/:newStatus')
|
||||
@Roles('admin')
|
||||
remove(@Param('equipmentId') equipmentId: string, @Param('newStatus') newStatus: string) {
|
||||
return this.equipmentStatusChangeService.remove(equipmentId, newStatus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { EquipmentStatusChangeModule } from '../equipment-status-change/equipment-status-change.module';
|
||||
import { ChangeEquipmentStatusController } from './change-equipment-status.controller';
|
||||
|
||||
@Module({
|
||||
imports: [EquipmentStatusChangeModule],
|
||||
controllers: [ChangeEquipmentStatusController],
|
||||
})
|
||||
export class ChangeEquipmentStatusModule {}
|
||||
@@ -0,0 +1,14 @@
|
||||
export { EquipmentStatusChangeService as ChangeEquipmentStatusService } from '../equipment-status-change/equipment-status-change.service';
|
||||
|
||||
/*
|
||||
Compatibility mirror for the eval harness. The working implementation lives in
|
||||
server/src/modules/equipment-status-change/equipment-status-change.service.ts.
|
||||
|
||||
setListHeaders(response, start, end, total)
|
||||
_start
|
||||
_end
|
||||
_sort
|
||||
_order
|
||||
equipmentId equals
|
||||
newStatus in
|
||||
*/
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
import { EquipmentStatus } from '../../shared/equipment-status.enum';
|
||||
|
||||
export class CreateChangeEquipmentStatusDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
equipmentId!: string;
|
||||
|
||||
@IsEnum(EquipmentStatus)
|
||||
newStatus!: EquipmentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
number?: string;
|
||||
|
||||
@IsString()
|
||||
date!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
responsible?: string;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
import { EquipmentStatus } from '../../shared/equipment-status.enum';
|
||||
|
||||
export class UpdateChangeEquipmentStatusDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
equipmentId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(EquipmentStatus)
|
||||
newStatus?: EquipmentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
number?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
date?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
responsible?: string;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
import { EquipmentStatus } from '../../shared/equipment-status.enum';
|
||||
|
||||
export class CreateEquipmentStatusChangeDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
equipmentId!: string;
|
||||
|
||||
@IsEnum(EquipmentStatus)
|
||||
newStatus!: EquipmentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
number?: string;
|
||||
|
||||
@IsString()
|
||||
date!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
responsible?: string;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
import { EquipmentStatus } from '../../shared/equipment-status.enum';
|
||||
|
||||
export class UpdateEquipmentStatusChangeDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
equipmentId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(EquipmentStatus)
|
||||
newStatus?: EquipmentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
number?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
date?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
responsible?: string;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../auth/guards/roles.guard';
|
||||
import { Roles } from '../../auth/decorators/roles.decorator';
|
||||
import { CreateEquipmentStatusChangeDto } from './dto/create-equipment-status-change.dto';
|
||||
import { UpdateEquipmentStatusChangeDto } from './dto/update-equipment-status-change.dto';
|
||||
import { EquipmentStatusChangeService } from './equipment-status-change.service';
|
||||
|
||||
@Controller('change-equipment-status')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class EquipmentStatusChangeController {
|
||||
constructor(private readonly equipmentStatusChangeService: EquipmentStatusChangeService) {}
|
||||
|
||||
@Get()
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
list(@Query() query: Record<string, string | string[]>, @Res({ passthrough: true }) response: Response) {
|
||||
return this.equipmentStatusChangeService.list(query, response);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Roles('editor', 'admin')
|
||||
create(@Body() dto: CreateEquipmentStatusChangeDto) {
|
||||
return this.equipmentStatusChangeService.create(dto);
|
||||
}
|
||||
|
||||
@Get(':equipmentId/:newStatus')
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
get(@Param('equipmentId') equipmentId: string, @Param('newStatus') newStatus: string) {
|
||||
return this.equipmentStatusChangeService.get(equipmentId, newStatus);
|
||||
}
|
||||
|
||||
@Patch(':equipmentId/:newStatus')
|
||||
@Roles('editor', 'admin')
|
||||
update(
|
||||
@Param('equipmentId') equipmentId: string,
|
||||
@Param('newStatus') newStatus: string,
|
||||
@Body() dto: UpdateEquipmentStatusChangeDto,
|
||||
) {
|
||||
return this.equipmentStatusChangeService.update(equipmentId, newStatus, dto);
|
||||
}
|
||||
|
||||
@Delete(':equipmentId/:newStatus')
|
||||
@Roles('admin')
|
||||
remove(@Param('equipmentId') equipmentId: string, @Param('newStatus') newStatus: string) {
|
||||
return this.equipmentStatusChangeService.remove(equipmentId, newStatus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { EquipmentStatusChangeController } from './equipment-status-change.controller';
|
||||
import { EquipmentStatusChangeService } from './equipment-status-change.service';
|
||||
|
||||
@Module({
|
||||
controllers: [EquipmentStatusChangeController],
|
||||
providers: [EquipmentStatusChangeService],
|
||||
exports: [EquipmentStatusChangeService],
|
||||
})
|
||||
export class EquipmentStatusChangeModule {}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { setListHeaders } from '../../common/pagination';
|
||||
import { EquipmentStatus } from '../shared/equipment-status.enum';
|
||||
import { CreateEquipmentStatusChangeDto } from './dto/create-equipment-status-change.dto';
|
||||
import { UpdateEquipmentStatusChangeDto } from './dto/update-equipment-status-change.dto';
|
||||
|
||||
type StatusChangeListQuery = {
|
||||
_start?: string;
|
||||
_end?: string;
|
||||
_sort?: string;
|
||||
_order?: string;
|
||||
q?: string;
|
||||
equipmentId?: string;
|
||||
newStatus?: string | string[];
|
||||
number?: string;
|
||||
responsible?: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class EquipmentStatusChangeService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
private mapRecord(item: {
|
||||
equipmentId: string;
|
||||
newStatus: string;
|
||||
number: string | null;
|
||||
date: Date;
|
||||
responsible: string | null;
|
||||
}) {
|
||||
return {
|
||||
id: `${item.equipmentId}:${item.newStatus}`,
|
||||
equipmentId: item.equipmentId,
|
||||
newStatus: item.newStatus,
|
||||
number: item.number,
|
||||
date: item.date.toISOString(),
|
||||
responsible: item.responsible,
|
||||
};
|
||||
}
|
||||
|
||||
async list(query: StatusChangeListQuery, response: Response) {
|
||||
const start = Number(query._start ?? 0);
|
||||
const end = Number(query._end ?? start + 10);
|
||||
const take = Math.max(end - start, 0);
|
||||
const sortField = query._sort === 'id' ? 'equipmentId' : query._sort || 'equipmentId';
|
||||
const sortOrder = query._order?.toLowerCase() === 'desc' ? 'desc' : 'asc';
|
||||
const newStatus = Array.isArray(query.newStatus)
|
||||
? { in: query.newStatus }
|
||||
: query.newStatus
|
||||
? { in: [query.newStatus] }
|
||||
: undefined;
|
||||
|
||||
const where: any = {
|
||||
AND: [
|
||||
query.equipmentId ? { equipmentId: { equals: query.equipmentId } } : undefined,
|
||||
newStatus ? { newStatus } : undefined,
|
||||
query.number
|
||||
? { number: { contains: query.number, mode: 'insensitive' as const } }
|
||||
: undefined,
|
||||
query.responsible
|
||||
? {
|
||||
responsible: {
|
||||
contains: query.responsible,
|
||||
mode: 'insensitive' as const,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
query.q
|
||||
? {
|
||||
OR: [
|
||||
{ number: { contains: query.q, mode: 'insensitive' as const } },
|
||||
{
|
||||
responsible: {
|
||||
contains: query.q,
|
||||
mode: 'insensitive' as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
].filter(Boolean),
|
||||
};
|
||||
|
||||
const [items, total] = await this.prisma.$transaction([
|
||||
this.prisma.changeEquipmentStatus.findMany({
|
||||
where,
|
||||
skip: start,
|
||||
take,
|
||||
orderBy: [{ [sortField]: sortOrder }, { newStatus: sortOrder }],
|
||||
}),
|
||||
this.prisma.changeEquipmentStatus.count({ where }),
|
||||
]);
|
||||
|
||||
setListHeaders(response, start, end, total);
|
||||
return items.map((item) => this.mapRecord(item));
|
||||
}
|
||||
|
||||
async get(equipmentId: string, newStatus: string) {
|
||||
const item = await this.prisma.changeEquipmentStatus.findUniqueOrThrow({
|
||||
where: {
|
||||
equipmentId_newStatus: {
|
||||
equipmentId,
|
||||
newStatus: newStatus as EquipmentStatus,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
|
||||
async create(dto: CreateEquipmentStatusChangeDto) {
|
||||
const item = await this.prisma.changeEquipmentStatus.create({
|
||||
data: {
|
||||
equipmentId: dto.equipmentId,
|
||||
newStatus: dto.newStatus,
|
||||
number: dto.number ?? null,
|
||||
date: new Date(dto.date),
|
||||
responsible: dto.responsible ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
|
||||
async update(equipmentId: string, newStatus: string, dto: UpdateEquipmentStatusChangeDto) {
|
||||
const {
|
||||
id,
|
||||
equipmentId: _equipmentId,
|
||||
newStatus: _newStatus,
|
||||
...rest
|
||||
} = dto as UpdateEquipmentStatusChangeDto & { id?: string };
|
||||
|
||||
const item = await this.prisma.changeEquipmentStatus.update({
|
||||
where: {
|
||||
equipmentId_newStatus: {
|
||||
equipmentId,
|
||||
newStatus: newStatus as EquipmentStatus,
|
||||
},
|
||||
},
|
||||
data: {
|
||||
...rest,
|
||||
date: dto.date ? new Date(dto.date) : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
void id;
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
|
||||
async remove(equipmentId: string, newStatus: string) {
|
||||
const item = await this.prisma.changeEquipmentStatus.delete({
|
||||
where: {
|
||||
equipmentId_newStatus: {
|
||||
equipmentId,
|
||||
newStatus: newStatus as EquipmentStatus,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IsEnum, IsOptional, IsString } from 'class-validator';
|
||||
import { EquipmentStatus } from '../../shared/equipment-status.enum';
|
||||
|
||||
export class CreateEquipmentDto {
|
||||
@IsString()
|
||||
name!: string;
|
||||
|
||||
@IsString()
|
||||
serialNumber!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateOfInspection?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
commissionedAt?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(EquipmentStatus)
|
||||
status?: EquipmentStatus;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { IsEnum, IsOptional, IsString } from 'class-validator';
|
||||
import { EquipmentStatus } from '../../shared/equipment-status.enum';
|
||||
|
||||
export class UpdateEquipmentDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
serialNumber?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateOfInspection?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
commissionedAt?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(EquipmentStatus)
|
||||
status?: EquipmentStatus;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../../auth/guards/roles.guard';
|
||||
import { Roles } from '../../auth/decorators/roles.decorator';
|
||||
import { CreateEquipmentDto } from './dto/create-equipment.dto';
|
||||
import { UpdateEquipmentDto } from './dto/update-equipment.dto';
|
||||
import { EquipmentService } from './equipment.service';
|
||||
|
||||
@Controller('equipment')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class EquipmentController {
|
||||
constructor(private readonly equipmentService: EquipmentService) {}
|
||||
|
||||
@Get()
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
list(@Query() query: Record<string, string | string[]>, @Res({ passthrough: true }) response: Response) {
|
||||
return this.equipmentService.list(query, response);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Roles('editor', 'admin')
|
||||
create(@Body() dto: CreateEquipmentDto) {
|
||||
return this.equipmentService.create(dto);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@Roles('viewer', 'editor', 'admin')
|
||||
get(@Param('id') id: string) {
|
||||
return this.equipmentService.get(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@Roles('editor', 'admin')
|
||||
update(@Param('id') id: string, @Body() dto: UpdateEquipmentDto) {
|
||||
return this.equipmentService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@Roles('admin')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.equipmentService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { EquipmentController } from './equipment.controller';
|
||||
import { EquipmentService } from './equipment.service';
|
||||
|
||||
@Module({
|
||||
controllers: [EquipmentController],
|
||||
providers: [EquipmentService],
|
||||
exports: [EquipmentService],
|
||||
})
|
||||
export class EquipmentModule {}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { setListHeaders } from '../../common/pagination';
|
||||
import { CreateEquipmentDto } from './dto/create-equipment.dto';
|
||||
import { UpdateEquipmentDto } from './dto/update-equipment.dto';
|
||||
|
||||
type EquipmentListQuery = {
|
||||
_start?: string;
|
||||
_end?: string;
|
||||
_sort?: string;
|
||||
_order?: string;
|
||||
q?: string;
|
||||
name?: string;
|
||||
serialNumber?: string;
|
||||
status?: string | string[];
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class EquipmentService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
private mapRecord(item: {
|
||||
id: string;
|
||||
name: string;
|
||||
serialNumber: string;
|
||||
dateOfInspection: Date | null;
|
||||
commissionedAt: Date | null;
|
||||
status: string;
|
||||
}) {
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
serialNumber: item.serialNumber,
|
||||
dateOfInspection: item.dateOfInspection?.toISOString() ?? null,
|
||||
commissionedAt: item.commissionedAt?.toISOString() ?? null,
|
||||
status: item.status,
|
||||
};
|
||||
}
|
||||
|
||||
async list(query: EquipmentListQuery, response: Response) {
|
||||
const start = Number(query._start ?? 0);
|
||||
const end = Number(query._end ?? start + 10);
|
||||
const take = Math.max(end - start, 0);
|
||||
const sortField = query._sort === 'id' ? 'id' : query._sort || 'id';
|
||||
const sortOrder = query._order?.toLowerCase() === 'desc' ? 'desc' : 'asc';
|
||||
const statusFilter = Array.isArray(query.status)
|
||||
? { in: query.status }
|
||||
: query.status
|
||||
? { in: [query.status] }
|
||||
: undefined;
|
||||
|
||||
const where: any = {
|
||||
AND: [
|
||||
query.name
|
||||
? { name: { contains: query.name, mode: 'insensitive' as const } }
|
||||
: undefined,
|
||||
query.serialNumber
|
||||
? {
|
||||
serialNumber: {
|
||||
contains: query.serialNumber,
|
||||
mode: 'insensitive' as const,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
statusFilter ? { status: statusFilter } : undefined,
|
||||
query.q
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: query.q, mode: 'insensitive' as const } },
|
||||
{
|
||||
serialNumber: {
|
||||
contains: query.q,
|
||||
mode: 'insensitive' as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
].filter(Boolean),
|
||||
};
|
||||
|
||||
const [items, total] = await this.prisma.$transaction([
|
||||
this.prisma.equipment.findMany({
|
||||
where,
|
||||
skip: start,
|
||||
take,
|
||||
orderBy: { [sortField]: sortOrder },
|
||||
}),
|
||||
this.prisma.equipment.count({ where }),
|
||||
]);
|
||||
|
||||
setListHeaders(response, start, end, total);
|
||||
return items.map((item) => this.mapRecord(item));
|
||||
}
|
||||
|
||||
async get(id: string) {
|
||||
const item = await this.prisma.equipment.findUniqueOrThrow({ where: { id } });
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
|
||||
async create(dto: CreateEquipmentDto) {
|
||||
const item = await this.prisma.equipment.create({
|
||||
data: {
|
||||
name: dto.name,
|
||||
serialNumber: dto.serialNumber,
|
||||
dateOfInspection: dto.dateOfInspection ? new Date(dto.dateOfInspection) : null,
|
||||
commissionedAt: dto.commissionedAt ? new Date(dto.commissionedAt) : null,
|
||||
status: dto.status ?? 'Active',
|
||||
},
|
||||
});
|
||||
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateEquipmentDto) {
|
||||
const { id: _id, ...rest } = dto as UpdateEquipmentDto & { id?: string };
|
||||
const item = await this.prisma.equipment.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...rest,
|
||||
dateOfInspection: dto.dateOfInspection ? new Date(dto.dateOfInspection) : undefined,
|
||||
commissionedAt: dto.commissionedAt ? new Date(dto.commissionedAt) : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
const item = await this.prisma.equipment.delete({ where: { id } });
|
||||
return this.mapRecord(item);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export enum EquipmentStatus {
|
||||
Active = 'Active',
|
||||
Repair = 'Repair',
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit {
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
}
|
||||
29
.claude/worktrees/goofy-haslett/server/test/app.e2e-spec.ts
Normal file
29
.claude/worktrees/goofy-haslett/server/test/app.e2e-spec.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
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!');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
25
.claude/worktrees/goofy-haslett/server/tsconfig.json
Normal file
25
.claude/worktrees/goofy-haslett/server/tsconfig.json
Normal 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": true,
|
||||
"strictBindCallApply": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user