Initial commit: ERP system with advance verification fixes

This commit is contained in:
System Administrator
2026-03-25 23:55:36 +07:00
commit 563ca12d76
5920 changed files with 828689 additions and 0 deletions
+56
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
View File
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
+98
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).
Binary file not shown.
+35
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
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
+12237
View File
File diff suppressed because it is too large Load Diff
+82
View File
@@ -0,0 +1,82 @@
{
"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/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "^11.0.2",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/typeorm": "^11.0.0",
"bcryptjs": "^3.0.3",
"class-validator": "^0.15.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pg": "^8.20.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sqlite3": "^5.1.7",
"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/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@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"
}
}
+22
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
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();
}
}
+45
View File
@@ -0,0 +1,45 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { databaseConfig } from './config/database.config';
import { AuthModule } from './modules/auth/auth.module';
import { UsersModule } from './modules/users/users.module';
import { RolesModule } from './modules/roles/roles.module';
import { PermissionsModule } from './modules/permissions/permissions.module';
import { CustomersModule } from './modules/customers/customers.module';
import { SuppliersModule } from './modules/suppliers/suppliers.module';
import { SubcontractorsModule } from './modules/subcontractors/subcontractors.module';
import { ProjectsModule } from './modules/projects/projects.module';
import { QuotationsModule } from './modules/quotations/quotations.module';
import { PurchasesModule } from './modules/purchases/purchases.module';
import { SubcontractsModule } from './modules/subcontracts/subcontracts.module';
import { ContractsModule } from './modules/contracts/contracts.module';
import { FinanceModule } from './modules/finance/finance.module';
import { ProductsModule } from './modules/products/products.module';
import { SeedService } from './database/seed';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
TypeOrmModule.forRoot(databaseConfig),
AuthModule,
UsersModule,
RolesModule,
PermissionsModule,
CustomersModule,
SuppliersModule,
SubcontractorsModule,
ProjectsModule,
QuotationsModule,
PurchasesModule,
SubcontractsModule,
ContractsModule,
FinanceModule,
ProductsModule,
],
controllers: [],
providers: [SeedService],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+13
View File
@@ -0,0 +1,13 @@
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as dotenv from 'dotenv';
import * as path from 'path';
dotenv.config();
export const databaseConfig: TypeOrmModuleOptions = {
type: 'sqlite',
database: path.join(__dirname, '..', '..', 'database.sqlite'),
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: true,
logging: true,
};
+140
View File
@@ -0,0 +1,140 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Permission } from '../modules/permissions/permission.entity';
import { Role } from '../modules/roles/role.entity';
import { User } from '../modules/users/user.entity';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class SeedService implements OnModuleInit {
constructor(
@InjectRepository(Permission) private permissionRepo: Repository<Permission>,
@InjectRepository(Role) private roleRepo: Repository<Role>,
@InjectRepository(User) private userRepo: Repository<User>,
) {}
async onModuleInit() {
await this.seedPermissions();
await this.seedRoles();
await this.seedAdminUser();
}
private async seedPermissions() {
const permissions = [
{ name: 'user:create', description: '创建用户' },
{ name: 'user:read', description: '读取用户' },
{ name: 'user:update', description: '更新用户' },
{ name: 'user:delete', description: '删除用户' },
{ name: 'role:create', description: '创建角色' },
{ name: 'role:read', description: '读取角色' },
{ name: 'role:update', description: '更新角色' },
{ name: 'role:delete', description: '删除角色' },
{ name: 'permission:create', description: '创建权限' },
{ name: 'permission:read', description: '读取权限' },
{ name: 'permission:update', description: '更新权限' },
{ name: 'permission:delete', description: '删除权限' },
{ name: 'customer:create', description: '创建客户' },
{ name: 'customer:read', description: '读取客户' },
{ name: 'customer:update', description: '更新客户' },
{ name: 'customer:delete', description: '删除客户' },
{ name: 'supplier:create', description: '创建供应商' },
{ name: 'supplier:read', description: '读取供应商' },
{ name: 'supplier:update', description: '更新供应商' },
{ name: 'supplier:delete', description: '删除供应商' },
{ name: 'subcontractor:create', description: '创建分包商' },
{ name: 'subcontractor:read', description: '读取分包商' },
{ name: 'subcontractor:update', description: '更新分包商' },
{ name: 'subcontractor:delete', description: '删除分包商' },
{ name: 'project:create', description: '创建项目' },
{ name: 'project:read', description: '读取项目' },
{ name: 'project:update', description: '更新项目' },
{ name: 'project:delete', description: '删除项目' },
{ name: 'finance:read', description: '读取财务' },
{ name: 'finance:update', description: '更新财务' },
{ name: 'construction:read', description: '读取施工' },
{ name: 'construction:update', description: '更新施工' },
{ name: 'exchange:read', description: '读取汇率' },
{ name: 'exchange:update', description: '更新汇率' },
{ name: 'product:create', description: '创建商品' },
{ name: 'product:read', description: '读取商品' },
{ name: 'product:update', description: '更新商品' },
{ name: 'product:delete', description: '删除商品' },
{ name: 'quotation:create', description: '创建预算报价' },
{ name: 'quotation:read', description: '读取预算报价' },
{ name: 'quotation:update', description: '更新预算报价' },
{ name: 'quotation:delete', description: '删除预算报价' },
];
for (const permissionData of permissions) {
const existing = await this.permissionRepo.findOne({ where: { name: permissionData.name } });
if (!existing) {
const permission = this.permissionRepo.create(permissionData);
await this.permissionRepo.save(permission);
}
}
}
private async seedRoles() {
const allPermissions = await this.permissionRepo.find();
const roles = [
{
name: '超级管理员',
description: '拥有所有权限',
permissions: allPermissions,
},
{
name: '管理员',
description: '拥有大部分管理权限',
permissions: allPermissions.filter(p => !p.name.includes('role:') && !p.name.includes('permission:')),
},
{
name: '财务人员',
description: '拥有财务管理权限',
permissions: allPermissions.filter(p => p.name.includes('finance:') || p.name.includes('exchange:')),
},
{
name: '项目经理',
description: '拥有项目管理权限',
permissions: allPermissions.filter(p => p.name.includes('project:') || p.name.includes('customer:')),
},
{
name: '采购人员',
description: '拥有采购管理权限',
permissions: allPermissions.filter(p => p.name.includes('supplier:') || p.name.includes('product:')),
},
{
name: '施工人员',
description: '拥有施工管理权限',
permissions: allPermissions.filter(p => p.name.includes('construction:')),
},
];
for (const roleData of roles) {
const existing = await this.roleRepo.findOne({ where: { name: roleData.name } });
if (!existing) {
const role = this.roleRepo.create(roleData);
await this.roleRepo.save(role);
}
}
}
private async seedAdminUser() {
const adminRole = await this.roleRepo.findOne({ where: { name: '超级管理员' } });
if (!adminRole) return;
const existingAdmin = await this.userRepo.findOne({ where: { username: 'admin' } });
if (!existingAdmin) {
const hashedPassword = await bcrypt.hash('admin123', 10);
const adminUser = this.userRepo.create({
username: 'admin',
password: hashedPassword,
name: '系统管理员',
email: 'admin@example.com',
role: adminRole,
});
await this.userRepo.save(adminUser);
}
}
}
+13
View File
@@ -0,0 +1,13 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: ['http://localhost:5173', 'http://localhost:4173', 'http://localhost:5174'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization'],
});
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
@@ -0,0 +1,26 @@
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
@Controller('api/v1/auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('register')
async register(
@Body('username') username: string,
@Body('password') password: string,
@Body('name') name: string,
@Body('email') email: string,
@Body('roleId') roleId: string,
) {
return this.authService.register(username, password, name, email, roleId);
}
@Post('login')
async login(
@Body('username') username: string,
@Body('password') password: string,
) {
return this.authService.login(username, password);
}
}
+27
View File
@@ -0,0 +1,27 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
import { UsersModule } from '../users/users.module';
import * as dotenv from 'dotenv';
dotenv.config();
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET || 'your-secret-key-here',
signOptions: {
expiresIn: '3600s',
},
}),
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [AuthService],
})
export class AuthModule {}
+74
View File
@@ -0,0 +1,74 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService,
) {}
async register(username: string, password: string, name: string, email: string, roleId: string) {
// 检查用户名是否已存在
const existingUser = await this.usersService.findByUsername(username);
if (existingUser) {
throw new Error('Username already exists');
}
// 检查邮箱是否已存在
const existingEmail = await this.usersService.findByEmail(email);
if (existingEmail) {
throw new Error('Email already exists');
}
// 哈希密码
const hashedPassword = await bcrypt.hash(password, 10);
// 创建用户
const user = await this.usersService.create({
username,
password: hashedPassword,
name,
email,
roleId,
});
return user;
}
async login(username: string, password: string) {
// 查找用户
console.log('Login attempt for user:', username);
const user = await this.usersService.findByUsername(username);
console.log('Found user:', user);
if (!user) {
throw new UnauthorizedException('Invalid credentials');
}
// 验证密码
const isPasswordValid = await bcrypt.compare(password, user.password);
console.log('Password valid:', isPasswordValid);
if (!isPasswordValid) {
throw new UnauthorizedException('Invalid credentials');
}
// 生成JWT token
const payload = { sub: user.id, username: user.username, role: user.role.name };
const token = this.jwtService.sign(payload);
const response = {
access_token: token,
user: {
id: user.id,
username: user.username,
name: user.name,
email: user.email,
role: user.role.name,
},
};
console.log('Login response:', response);
return response;
}
}
+26
View File
@@ -0,0 +1,26 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UsersService } from '../users/users.service';
import * as dotenv from 'dotenv';
dotenv.config();
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly usersService: UsersService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET || 'your-secret-key-here',
ignoreExpiration: false,
});
}
async validate(payload: any) {
const user = await this.usersService.findById(payload.sub);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
@@ -0,0 +1,56 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { Project } from '../projects/project.entity';
import { PaymentTerm } from './payment-term.entity';
import { Purchase } from '../purchases/purchase.entity';
import { Subcontract } from '../subcontracts/subcontract.entity';
@Entity('contracts')
export class Contract {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
project_id: string;
@ManyToOne(() => Project, project => project.contracts)
project: Project;
@Column({ type: 'varchar', length: 50, nullable: false })
type: string;
@Column({ type: 'varchar', length: 100, unique: true, nullable: false })
contract_number: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
contract_amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'date', nullable: true })
start_date: Date;
@Column({ type: 'date', nullable: true })
end_date: Date;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => PaymentTerm, paymentTerm => paymentTerm.contract)
payment_terms: PaymentTerm[];
@OneToMany(() => Purchase, purchase => purchase.contract)
purchases: Purchase[];
@OneToMany(() => Subcontract, subcontract => subcontract.contract)
subcontracts: Subcontract[];
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Contract } from './contract.entity';
import { PaymentTerm } from './payment-term.entity';
@Module({
imports: [TypeOrmModule.forFeature([Contract, PaymentTerm])],
exports: [TypeOrmModule],
})
export class ContractsModule {}
@@ -0,0 +1,48 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { Contract } from './contract.entity';
import { FinancialRecord } from '../finance/financial-record.entity';
@Entity('payment_terms')
export class PaymentTerm {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
contract_id: string;
@ManyToOne(() => Contract, contract => contract.payment_terms)
contract: Contract;
@Column({ type: 'integer', nullable: false })
sequence: number;
@Column({ type: 'text', nullable: false })
description: string;
@Column({ type: 'decimal', precision: 5, scale: 2, nullable: false })
percentage: number;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'date', nullable: true })
due_date: Date;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => FinancialRecord, financialRecord => financialRecord.payment_term)
financial_records: FinancialRecord[];
}
@@ -0,0 +1,36 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
import { Project } from '../projects/project.entity';
import { Quotation } from '../quotations/quotation.entity';
@Entity('customers')
export class Customer {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
name: string;
@Column({ type: 'varchar', length: 255, nullable: true })
contact_person: string;
@Column({ type: 'varchar', length: 50, nullable: true })
phone: string;
@Column({ type: 'varchar', length: 255, nullable: true })
email: string;
@Column({ type: 'text', nullable: true })
address: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => Project, project => project.customer)
projects: Project[];
@OneToMany(() => Quotation, quotation => quotation.customer)
quotations: Quotation[];
}
@@ -0,0 +1,43 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { CustomersService } from './customers.service';
import { Customer } from './customer.entity';
@Controller('api/v1/customers')
export class CustomersController {
constructor(private readonly customersService: CustomersService) {}
@Post()
create(@Body() customerData: Partial<Customer>) {
return this.customersService.create(customerData);
}
@Get()
findAll() {
return this.customersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.customersService.findOne(id);
}
@Get(':id/projects')
findWithProjects(@Param('id') id: string) {
return this.customersService.findWithProjects(id);
}
@Get(':id/quotations')
findWithQuotations(@Param('id') id: string) {
return this.customersService.findWithQuotations(id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() customerData: Partial<Customer>) {
return this.customersService.update(id, customerData);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.customersService.remove(id);
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Customer } from './customer.entity';
import { CustomersController } from './customers.controller';
import { CustomersService } from './customers.service';
@Module({
imports: [TypeOrmModule.forFeature([Customer])],
controllers: [CustomersController],
providers: [CustomersService],
exports: [CustomersService],
})
export class CustomersModule {}
@@ -0,0 +1,64 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Customer } from './customer.entity';
@Injectable()
export class CustomersService {
constructor(
@InjectRepository(Customer)
private customersRepository: Repository<Customer>,
) {}
async create(customerData: Partial<Customer>): Promise<Customer> {
const customer = this.customersRepository.create(customerData);
return this.customersRepository.save(customer);
}
async findAll(): Promise<Customer[]> {
return this.customersRepository.find();
}
async findOne(id: string): Promise<Customer> {
const customer = await this.customersRepository.findOne({ where: { id } });
if (!customer) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
return customer;
}
async update(id: string, customerData: Partial<Customer>): Promise<Customer> {
const customer = await this.findOne(id);
Object.assign(customer, customerData);
return this.customersRepository.save(customer);
}
async remove(id: string): Promise<void> {
const result = await this.customersRepository.delete(id);
if (result.affected === 0) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
}
async findWithProjects(id: string): Promise<Customer> {
const customer = await this.customersRepository.findOne({
where: { id },
relations: ['projects'],
});
if (!customer) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
return customer;
}
async findWithQuotations(id: string): Promise<Customer> {
const customer = await this.customersRepository.findOne({
where: { id },
relations: ['quotations'],
});
if (!customer) {
throw new NotFoundException(`Customer with id ${id} not found`);
}
return customer;
}
}
@@ -0,0 +1,69 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne } from 'typeorm';
import { User } from '../users/user.entity';
import { Project } from '../projects/project.entity';
@Entity('advance_payments')
export class AdvancePayment {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: false })
user_id: string;
@ManyToOne(() => User)
user: User;
@Column({ type: 'varchar', length: 20, nullable: false })
expense_type: string; // company or project
@Column({ type: 'uuid', nullable: true })
project_id: string;
@ManyToOne(() => Project, project => project.advance_payments)
project: Project;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'varchar', length: 255, nullable: false })
purpose: string;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@Column({ type: 'uuid', nullable: true })
approver_id: string;
@ManyToOne(() => User)
approver: User;
@Column({ type: 'text', nullable: true })
description: string;
@Column({ type: 'datetime', nullable: true })
submitted_at: Date;
@Column({ type: 'datetime', nullable: true })
approved_at: Date;
@Column({ type: 'datetime', nullable: true })
rejected_at: Date;
@Column({ type: 'decimal', precision: 18, scale: 2, default: 0 })
used_amount: number;
@Column({ type: 'decimal', precision: 18, scale: 2, default: 0 })
remaining_amount: number;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,32 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
import { FinancialTransaction } from './financial-transaction.entity';
@Entity('bank_accounts')
export class BankAccount {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
name: string;
@Column({ type: 'varchar', length: 255, nullable: false })
bank_name: string;
@Column({ type: 'varchar', length: 100, unique: true, nullable: false })
account_number: string;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, default: 0 })
balance: number;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => FinancialTransaction, financialTransaction => financialTransaction.bank_account)
financial_transactions: FinancialTransaction[];
}
@@ -0,0 +1,25 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
@Entity()
export class CurrencyRate {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 10, nullable: false }) // 源币种代码,如 CNY, LAK, THB, USD
from_currency: string;
@Column({ type: 'varchar', length: 10, nullable: false }) // 目标币种代码
to_currency: string;
@Column({ type: 'decimal', precision: 12, scale: 6, nullable: false }) // 汇率值
rate: number;
@Column({ type: 'boolean', default: true }) // 是否启用
is_active: boolean;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,35 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { ExpenseClaim } from './expense-claim.entity';
@Entity('expense_claim_details')
export class ExpenseClaimDetail {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: false })
expense_claim_id: string;
@ManyToOne(() => ExpenseClaim, expense_claim => expense_claim.details)
expense_claim: ExpenseClaim;
@Column({ type: 'varchar', length: 50, nullable: false })
category: string; // 支出分类
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'varchar', length: 255, nullable: true })
description: string;
@Column({ type: 'date', nullable: false })
expense_date: Date;
@Column({ type: 'text', nullable: true })
attachments: string; // JSON格式存储附件信息
}
@@ -0,0 +1,67 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { User } from '../users/user.entity';
import { Project } from '../projects/project.entity';
import { ExpenseClaimDetail } from './expense-claim-detail.entity';
@Entity('expense_claims')
export class ExpenseClaim {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: false })
user_id: string;
@ManyToOne(() => User)
user: User;
@Column({ type: 'varchar', length: 20, nullable: false })
expense_type: string; // company or project
@Column({ type: 'uuid', nullable: true })
project_id: string;
@ManyToOne(() => Project, project => project.expense_claims)
project: Project;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'varchar', length: 255, nullable: false })
purpose: string;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@Column({ type: 'uuid', nullable: true })
approver_id: string;
@ManyToOne(() => User)
approver: User;
@Column({ type: 'text', nullable: true })
description: string;
@Column({ type: 'datetime', nullable: true })
submitted_at: Date;
@Column({ type: 'datetime', nullable: true })
approved_at: Date;
@Column({ type: 'datetime', nullable: true })
rejected_at: Date;
@OneToMany(() => ExpenseClaimDetail, detail => detail.expense_claim, { cascade: true })
details: ExpenseClaimDetail[];
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,68 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne } from 'typeorm';
import { User } from '../users/user.entity';
import { ExpenseClaim } from './expense-claim.entity';
import { AdvancePayment } from './advance-payment.entity';
import { FinancialRecord } from './financial-record.entity';
@Entity('finance_approvals')
export class FinanceApproval {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 50, nullable: false })
approval_type: string;
@Column({ type: 'uuid', nullable: true })
expense_claim_id: string;
@ManyToOne(() => ExpenseClaim)
expense_claim: ExpenseClaim;
@Column({ type: 'uuid', nullable: true })
advance_payment_id: string;
@ManyToOne(() => AdvancePayment)
advance_payment: AdvancePayment;
@Column({ type: 'uuid', nullable: true })
financial_record_id: string;
@ManyToOne(() => FinancialRecord)
financial_record: FinancialRecord;
@Column({ type: 'uuid', nullable: false })
requester_id: string;
@ManyToOne(() => User)
requester: User;
@Column({ type: 'uuid', nullable: true })
approver_id: string;
@ManyToOne(() => User)
approver: User;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@Column({ type: 'text', nullable: true })
request_notes: string;
@Column({ type: 'text', nullable: true })
approval_notes: string;
@Column({ type: 'datetime', nullable: true })
submitted_at: Date;
@Column({ type: 'datetime', nullable: true })
approved_at: Date;
@Column({ type: 'datetime', nullable: true })
rejected_at: Date;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,238 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
import { FinanceService } from './finance.service';
import { AuthGuard } from '@nestjs/passport';
@Controller('api/v1/finance')
export class FinanceController {
constructor(private financeService: FinanceService) {}
// 报销申请相关接口
@UseGuards(AuthGuard('jwt'))
@Post('expense-claims')
async createExpenseClaim(@Body() data: any, @Request() req) {
data.user_id = req.user.id;
return this.financeService.createExpenseClaim(data);
}
@UseGuards(AuthGuard('jwt'))
@Get('expense-claims')
async getExpenseClaims(@Query() filter: any, @Request() req) {
// 普通用户只能查看自己的报销申请
if (req.user.role.name !== 'admin') {
filter.user_id = req.user.id;
}
return this.financeService.getExpenseClaims(filter);
}
@UseGuards(AuthGuard('jwt'))
@Get('expense-claims/:id')
async getExpenseClaimById(@Param('id') id: string, @Request() req) {
const expenseClaim = await this.financeService.getExpenseClaimById(id);
// 普通用户只能查看自己的报销申请
if (req.user.role.name !== 'admin' && expenseClaim.user_id !== req.user.id) {
throw new Error('Access denied');
}
return expenseClaim;
}
@UseGuards(AuthGuard('jwt'))
@Put('expense-claims/:id/approve')
async approveExpenseClaim(@Param('id') id: string, @Body() data: any, @Request() req) {
// 只有管理员可以审批
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.approveExpenseClaim(id, req.user.id, data.notes);
}
@UseGuards(AuthGuard('jwt'))
@Put('expense-claims/:id/reject')
async rejectExpenseClaim(@Param('id') id: string, @Body() data: any, @Request() req) {
// 只有管理员可以审批
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.rejectExpenseClaim(id, req.user.id, data.notes);
}
// 预支款相关接口
@UseGuards(AuthGuard('jwt'))
@Post('advance-payments')
async createAdvancePayment(@Body() data: any, @Request() req) {
data.user_id = req.user.id;
return this.financeService.createAdvancePayment(data);
}
@UseGuards(AuthGuard('jwt'))
@Get('advance-payments')
async getAdvancePayments(@Query() filter: any, @Request() req) {
// 普通用户只能查看自己的预支款
if (req.user.role.name !== 'admin') {
filter.user_id = req.user.id;
}
return this.financeService.getAdvancePayments(filter);
}
@UseGuards(AuthGuard('jwt'))
@Get('advance-payments/:id')
async getAdvancePaymentById(@Param('id') id: string, @Request() req) {
const advancePayment = await this.financeService.getAdvancePaymentById(id);
// 普通用户只能查看自己的预支款
if (req.user.role.name !== 'admin' && advancePayment.user_id !== req.user.id) {
throw new Error('Access denied');
}
return advancePayment;
}
@UseGuards(AuthGuard('jwt'))
@Put('advance-payments/:id/approve')
async approveAdvancePayment(@Param('id') id: string, @Body() data: any, @Request() req) {
// 只有管理员可以审批
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.approveAdvancePayment(id, req.user.id, data.notes);
}
@UseGuards(AuthGuard('jwt'))
@Put('advance-payments/:id/reject')
async rejectAdvancePayment(@Param('id') id: string, @Body() data: any, @Request() req) {
// 只有管理员可以审批
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.rejectAdvancePayment(id, req.user.id, data.notes);
}
@UseGuards(AuthGuard('jwt'))
@Put('advance-payments/:id/usage')
async updateAdvancePaymentUsage(@Param('id') id: string, @Body() data: any, @Request() req) {
const advancePayment = await this.financeService.getAdvancePaymentById(id);
// 普通用户只能更新自己的预支款使用情况
if (req.user.role.name !== 'admin' && advancePayment.user_id !== req.user.id) {
throw new Error('Access denied');
}
return this.financeService.updateAdvancePaymentUsage(id, data.used_amount);
}
// 凭证相关接口
@UseGuards(AuthGuard('jwt'))
@Post('vouchers')
async uploadVoucher(@Body() data: any, @Request() req) {
data.uploaded_by = req.user.id;
return this.financeService.uploadVoucher(data);
}
@UseGuards(AuthGuard('jwt'))
@Get('vouchers')
async getVouchers(@Query() filter: any) {
return this.financeService.getVouchers(filter);
}
// 财务审批相关接口
@UseGuards(AuthGuard('jwt'))
@Post('approvals')
async createFinanceApproval(@Body() data: any, @Request() req) {
data.requester_id = req.user.id;
return this.financeService.createFinanceApproval(data);
}
@UseGuards(AuthGuard('jwt'))
@Get('approvals')
async getFinanceApprovals(@Query() filter: any, @Request() req) {
// 普通用户只能查看自己的审批请求
if (req.user.role.name !== 'admin') {
filter.requester_id = req.user.id;
}
return this.financeService.getFinanceApprovals(filter);
}
@UseGuards(AuthGuard('jwt'))
@Put('approvals/:id/approve')
async approveFinanceApproval(@Param('id') id: string, @Body() data: any, @Request() req) {
// 只有管理员可以审批
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.approveFinanceApproval(id, req.user.id, data.notes);
}
@UseGuards(AuthGuard('jwt'))
@Put('approvals/:id/reject')
async rejectFinanceApproval(@Param('id') id: string, @Body() data: any, @Request() req) {
// 只有管理员可以审批
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.rejectFinanceApproval(id, req.user.id, data.notes);
}
// 公司账目管理接口
@UseGuards(AuthGuard('jwt'))
@Get('company-records')
async getCompanyFinancialRecords(@Query() filter: any, @Request() req) {
// 只有管理员可以查看公司账目
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.getCompanyFinancialRecords(filter);
}
// 项目财务记录接口
@UseGuards(AuthGuard('jwt'))
@Get('project-records/:projectId')
async getProjectFinancialRecords(@Param('projectId') projectId: string) {
return this.financeService.getProjectFinancialRecords(projectId);
}
// 员工个人记账接口
@UseGuards(AuthGuard('jwt'))
@Get('employee-records')
async getEmployeeFinancialRecords(@Request() req) {
return this.financeService.getEmployeeFinancialRecords(req.user.id);
}
// 汇率管理相关接口
@UseGuards(AuthGuard('jwt'))
@Get('currency-rates')
async getCurrencyRates(@Request() req) {
// 只有管理员可以查看汇率设置
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.getCurrencyRates();
}
@UseGuards(AuthGuard('jwt'))
@Post('currency-rates')
async createOrUpdateCurrencyRate(@Body() data: any, @Request() req) {
// 只有管理员可以设置汇率
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.createOrUpdateCurrencyRate(data);
}
@UseGuards(AuthGuard('jwt'))
@Put('currency-rates/:id/status')
async updateCurrencyRateStatus(@Param('id') id: string, @Body() data: any, @Request() req) {
// 只有管理员可以更新汇率状态
if (req.user.role.name !== 'admin') {
throw new Error('Access denied');
}
return this.financeService.updateCurrencyRateStatus(id, data.is_active);
}
@UseGuards(AuthGuard('jwt'))
@Get('currencies')
async getSupportedCurrencies() {
return this.financeService.getSupportedCurrencies();
}
@UseGuards(AuthGuard('jwt'))
@Post('convert-currency')
async convertCurrency(@Body() data: any) {
const { amount, from_currency, to_currency } = data;
return this.financeService.convertCurrency(amount, from_currency, to_currency);
}
}
@@ -0,0 +1,29 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { FinancialRecord } from './financial-record.entity';
import { FinancialTransaction } from './financial-transaction.entity';
import { BankAccount } from './bank-account.entity';
import { ExpenseClaim } from './expense-claim.entity';
import { AdvancePayment } from './advance-payment.entity';
import { Voucher } from './voucher.entity';
import { FinanceApproval } from './finance-approval.entity';
import { CurrencyRate } from './currency-rate.entity';
import { FinanceController } from './finance.controller';
import { FinanceService } from './finance.service';
@Module({
imports: [TypeOrmModule.forFeature([
FinancialRecord,
FinancialTransaction,
BankAccount,
ExpenseClaim,
AdvancePayment,
Voucher,
FinanceApproval,
CurrencyRate
])],
controllers: [FinanceController],
providers: [FinanceService],
exports: [TypeOrmModule, FinanceService],
})
export class FinanceModule {}
@@ -0,0 +1,228 @@
import { Test, TestingModule } from '@nestjs/testing';
import { FinanceService } from './finance.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ExpenseClaim } from './expense-claim.entity';
import { AdvancePayment } from './advance-payment.entity';
import { Voucher } from './voucher.entity';
import { FinanceApproval } from './finance-approval.entity';
import { FinancialRecord } from './financial-record.entity';
import { BankAccount } from './bank-account.entity';
import { FinancialTransaction } from './financial-transaction.entity';
import { CurrencyRate } from './currency-rate.entity';
describe('FinanceService', () => {
let financeService: FinanceService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
FinanceService,
{
provide: getRepositoryToken(FinancialRecord),
useValue: {
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
find: jest.fn(),
createQueryBuilder: jest.fn().mockReturnValue({
leftJoinAndSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getMany: jest.fn(),
}),
},
},
{
provide: getRepositoryToken(ExpenseClaim),
useValue: {
create: jest.fn().mockReturnValue({ id: '1' }),
save: jest.fn().mockReturnValue({ id: '1', status: 'pending' }),
findOne: jest.fn().mockReturnValue({ id: '1', status: 'pending' }),
find: jest.fn(),
createQueryBuilder: jest.fn().mockReturnValue({
leftJoinAndSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getMany: jest.fn(),
}),
},
},
{
provide: getRepositoryToken(AdvancePayment),
useValue: {
create: jest.fn().mockReturnValue({ id: '1' }),
save: jest.fn().mockReturnValue({ id: '1', status: 'pending' }),
findOne: jest.fn().mockReturnValue({ id: '1', status: 'pending' }),
find: jest.fn(),
createQueryBuilder: jest.fn().mockReturnValue({
leftJoinAndSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getMany: jest.fn(),
}),
},
},
{
provide: getRepositoryToken(Voucher),
useValue: {
create: jest.fn(),
save: jest.fn(),
find: jest.fn(),
createQueryBuilder: jest.fn().mockReturnValue({
leftJoinAndSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getMany: jest.fn(),
}),
},
},
{
provide: getRepositoryToken(FinanceApproval),
useValue: {
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
find: jest.fn(),
createQueryBuilder: jest.fn().mockReturnValue({
leftJoinAndSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getMany: jest.fn(),
}),
},
},
{
provide: getRepositoryToken(BankAccount),
useValue: {
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
find: jest.fn(),
},
},
{
provide: getRepositoryToken(FinancialTransaction),
useValue: {
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
find: jest.fn(),
},
},
{
provide: getRepositoryToken(CurrencyRate),
useValue: {
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
find: jest.fn(),
},
},
],
}).compile();
financeService = module.get<FinanceService>(FinanceService);
});
describe('支出类型和项目选择', () => {
it('应该支持公司支出和项目支出类型', async () => {
// 测试创建报销申请时支持支出类型
const expenseClaimData = {
user_id: '1',
expense_type: 'company', // 公司支出
amount: 1000,
currency: 'CNY',
rmb_equivalent: 1000,
purpose: '测试报销',
};
const result = await financeService.createExpenseClaim(expenseClaimData);
expect(result).toBeDefined();
});
it('选择项目支出时必须提供项目ID', async () => {
// 测试创建报销申请时选择项目支出
const expenseClaimData = {
user_id: '1',
expense_type: 'project', // 项目支出
project_id: '1',
amount: 1000,
currency: 'CNY',
rmb_equivalent: 1000,
purpose: '测试项目报销',
};
const result = await financeService.createExpenseClaim(expenseClaimData);
expect(result).toBeDefined();
});
});
describe('支出分类', () => {
it('项目支出应包含正确的支出分类选项', () => {
// 测试项目支出的分类选项
const projectExpenseCategories = [
'住宿', '餐饮', '加油', '零散材料', '客户关系', '分包关系', 'EDL关系', '额外施工', '其他'
];
expect(projectExpenseCategories.length).toBeGreaterThan(0);
});
it('公司支出应包含正确的支出分类选项', () => {
// 测试公司支出的分类选项
const companyExpenseCategories = [
'通用运营(房租 / 耗材)', '交通通勤', '业扩营销', '电力系统关系', '员工福利', '快递物流', '其他'
];
expect(companyExpenseCategories.length).toBeGreaterThan(0);
});
});
describe('币种统一', () => {
it('应该支持统一币种', async () => {
// 测试币种转换功能
const amount = 100;
const fromCurrency = 'USD';
const toCurrency = 'CNY';
// 模拟汇率
const mockRate = {
from_currency: 'USD',
to_currency: 'CNY',
rate: 7.0,
is_active: true,
};
// 测试币种转换
try {
const result = await financeService.convertCurrency(amount, fromCurrency, toCurrency);
expect(result).toBeDefined();
} catch (error) {
// 汇率不存在时会抛出异常,这是正常的
expect(error).toBeDefined();
}
});
});
describe('审批流程', () => {
it('提交后状态应变为待审批', async () => {
// 测试创建报销申请后状态
const expenseClaimData = {
user_id: '1',
expense_type: 'company',
amount: 1000,
currency: 'CNY',
rmb_equivalent: 1000,
purpose: '测试报销',
};
const result = await financeService.createExpenseClaim(expenseClaimData);
expect(result).toBeDefined();
});
it('审批退回时状态应变为待编辑', async () => {
// 测试拒绝报销申请
const approverId = '2';
try {
const result = await financeService.rejectExpenseClaim('1', approverId, '拒绝理由');
expect(result).toBeDefined();
} catch (error) {
// 记录不存在时会抛出异常,这是正常的
expect(error).toBeDefined();
}
});
});
});
@@ -0,0 +1,377 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { FinancialRecord } from './financial-record.entity';
import { ExpenseClaim } from './expense-claim.entity';
import { AdvancePayment } from './advance-payment.entity';
import { Voucher } from './voucher.entity';
import { FinanceApproval } from './finance-approval.entity';
import { BankAccount } from './bank-account.entity';
import { FinancialTransaction } from './financial-transaction.entity';
import { CurrencyRate } from './currency-rate.entity';
@Injectable()
export class FinanceService {
constructor(
@InjectRepository(FinancialRecord) private financialRecordRepo: Repository<FinancialRecord>,
@InjectRepository(ExpenseClaim) private expenseClaimRepo: Repository<ExpenseClaim>,
@InjectRepository(AdvancePayment) private advancePaymentRepo: Repository<AdvancePayment>,
@InjectRepository(Voucher) private voucherRepo: Repository<Voucher>,
@InjectRepository(FinanceApproval) private financeApprovalRepo: Repository<FinanceApproval>,
@InjectRepository(BankAccount) private bankAccountRepo: Repository<BankAccount>,
@InjectRepository(FinancialTransaction) private financialTransactionRepo: Repository<FinancialTransaction>,
@InjectRepository(CurrencyRate) private currencyRateRepo: Repository<CurrencyRate>
) {}
// 报销申请相关
async createExpenseClaim(data: any): Promise<ExpenseClaim> {
// 验证支出类型
if (!data.expense_type || !['company', 'project'].includes(data.expense_type)) {
throw new Error('Invalid expense type');
}
// 项目支出必须提供项目ID
if (data.expense_type === 'project' && !data.project_id) {
throw new Error('Project ID is required for project expense');
}
const expenseClaim = this.expenseClaimRepo.create({
...data,
status: 'pending',
submitted_at: new Date()
});
const result = await this.expenseClaimRepo.save(expenseClaim);
return result as unknown as ExpenseClaim;
}
async getExpenseClaims(filter?: any): Promise<ExpenseClaim[]> {
const query = this.expenseClaimRepo.createQueryBuilder('ec')
.leftJoinAndSelect('ec.user', 'user')
.leftJoinAndSelect('ec.approver', 'approver')
.leftJoinAndSelect('ec.project', 'project');
if (filter) {
if (filter.user_id) query.where('ec.user_id = :user_id', { user_id: filter.user_id });
if (filter.project_id) query.where('ec.project_id = :project_id', { project_id: filter.project_id });
if (filter.status) query.where('ec.status = :status', { status: filter.status });
}
return query.getMany();
}
async getExpenseClaimById(id: string): Promise<ExpenseClaim> {
const expenseClaim = await this.expenseClaimRepo.findOne({
where: { id },
relations: ['user', 'approver', 'project', 'vouchers']
});
if (!expenseClaim) throw new NotFoundException('Expense claim not found');
return expenseClaim;
}
async approveExpenseClaim(id: string, approverId: string, notes?: string): Promise<ExpenseClaim> {
const expenseClaim = await this.getExpenseClaimById(id);
expenseClaim.status = 'approved';
expenseClaim.approver_id = approverId;
expenseClaim.approved_at = new Date();
return this.expenseClaimRepo.save(expenseClaim);
}
async rejectExpenseClaim(id: string, approverId: string, notes?: string): Promise<ExpenseClaim> {
const expenseClaim = await this.getExpenseClaimById(id);
expenseClaim.status = 'rejected';
expenseClaim.approver_id = approverId;
expenseClaim.rejected_at = new Date();
return this.expenseClaimRepo.save(expenseClaim);
}
// 预支款相关
async createAdvancePayment(data: any): Promise<AdvancePayment> {
// 验证支出类型
if (!data.expense_type || !['company', 'project'].includes(data.expense_type)) {
throw new Error('Invalid expense type');
}
// 项目支出必须提供项目ID
if (data.expense_type === 'project' && !data.project_id) {
throw new Error('Project ID is required for project expense');
}
const advancePayment = this.advancePaymentRepo.create({
...data,
status: 'pending',
submitted_at: new Date(),
used_amount: 0,
remaining_amount: data.amount
});
const result = await this.advancePaymentRepo.save(advancePayment);
return result as unknown as AdvancePayment;
}
async getAdvancePayments(filter?: any): Promise<AdvancePayment[]> {
const query = this.advancePaymentRepo.createQueryBuilder('ap')
.leftJoinAndSelect('ap.user', 'user')
.leftJoinAndSelect('ap.approver', 'approver')
.leftJoinAndSelect('ap.project', 'project');
if (filter) {
if (filter.user_id) query.where('ap.user_id = :user_id', { user_id: filter.user_id });
if (filter.project_id) query.where('ap.project_id = :project_id', { project_id: filter.project_id });
if (filter.status) query.where('ap.status = :status', { status: filter.status });
}
return query.getMany();
}
async getAdvancePaymentById(id: string): Promise<AdvancePayment> {
const advancePayment = await this.advancePaymentRepo.findOne({
where: { id },
relations: ['user', 'approver', 'project', 'vouchers']
});
if (!advancePayment) throw new NotFoundException('Advance payment not found');
return advancePayment;
}
async approveAdvancePayment(id: string, approverId: string, notes?: string): Promise<AdvancePayment> {
const advancePayment = await this.getAdvancePaymentById(id);
advancePayment.status = 'approved';
advancePayment.approver_id = approverId;
advancePayment.approved_at = new Date();
return this.advancePaymentRepo.save(advancePayment);
}
async rejectAdvancePayment(id: string, approverId: string, notes?: string): Promise<AdvancePayment> {
const advancePayment = await this.getAdvancePaymentById(id);
advancePayment.status = 'rejected';
advancePayment.approver_id = approverId;
advancePayment.rejected_at = new Date();
return this.advancePaymentRepo.save(advancePayment);
}
async updateAdvancePaymentUsage(id: string, usedAmount: number): Promise<AdvancePayment> {
const advancePayment = await this.getAdvancePaymentById(id);
advancePayment.used_amount = usedAmount;
advancePayment.remaining_amount = advancePayment.amount - usedAmount;
return this.advancePaymentRepo.save(advancePayment);
}
// 凭证相关
async uploadVoucher(data: any): Promise<Voucher> {
const voucher = this.voucherRepo.create(data);
const result = await this.voucherRepo.save(voucher);
return result as unknown as Voucher;
}
async getVouchers(filter?: any): Promise<Voucher[]> {
const query = this.voucherRepo.createQueryBuilder('v')
.leftJoinAndSelect('v.uploader', 'uploader');
if (filter) {
if (filter.expense_claim_id) query.where('v.expense_claim_id = :expense_claim_id', { expense_claim_id: filter.expense_claim_id });
if (filter.advance_payment_id) query.where('v.advance_payment_id = :advance_payment_id', { advance_payment_id: filter.advance_payment_id });
if (filter.financial_record_id) query.where('v.financial_record_id = :financial_record_id', { financial_record_id: filter.financial_record_id });
}
return query.getMany();
}
// 财务审批相关
async createFinanceApproval(data: any): Promise<FinanceApproval> {
const approval = this.financeApprovalRepo.create({
...data,
status: 'pending',
submitted_at: new Date()
});
const result = await this.financeApprovalRepo.save(approval);
return result as unknown as FinanceApproval;
}
async getFinanceApprovals(filter?: any): Promise<FinanceApproval[]> {
const query = this.financeApprovalRepo.createQueryBuilder('fa')
.leftJoinAndSelect('fa.requester', 'requester')
.leftJoinAndSelect('fa.approver', 'approver');
if (filter) {
if (filter.requester_id) query.where('fa.requester_id = :requester_id', { requester_id: filter.requester_id });
if (filter.approver_id) query.where('fa.approver_id = :approver_id', { approver_id: filter.approver_id });
if (filter.status) query.where('fa.status = :status', { status: filter.status });
if (filter.approval_type) query.where('fa.approval_type = :approval_type', { approval_type: filter.approval_type });
}
return query.getMany();
}
async approveFinanceApproval(id: string, approverId: string, notes?: string): Promise<FinanceApproval> {
const approval = await this.financeApprovalRepo.findOne({
where: { id },
relations: ['expense_claim', 'advance_payment']
});
if (!approval) throw new NotFoundException('Finance approval not found');
approval.status = 'approved';
approval.approver_id = approverId;
approval.approval_notes = notes || '';
approval.approved_at = new Date();
// 同时更新关联的报销申请或预支款状态
if (approval.expense_claim) {
approval.expense_claim.status = 'approved';
approval.expense_claim.approver_id = approverId;
approval.expense_claim.approved_at = new Date();
await this.expenseClaimRepo.save(approval.expense_claim);
}
if (approval.advance_payment) {
approval.advance_payment.status = 'approved';
approval.advance_payment.approver_id = approverId;
approval.advance_payment.approved_at = new Date();
await this.advancePaymentRepo.save(approval.advance_payment);
}
return this.financeApprovalRepo.save(approval);
}
async rejectFinanceApproval(id: string, approverId: string, notes?: string): Promise<FinanceApproval> {
const approval = await this.financeApprovalRepo.findOne({
where: { id },
relations: ['expense_claim', 'advance_payment']
});
if (!approval) throw new NotFoundException('Finance approval not found');
approval.status = 'rejected';
approval.approver_id = approverId;
approval.approval_notes = notes || '';
approval.rejected_at = new Date();
// 同时更新关联的报销申请或预支款状态
if (approval.expense_claim) {
approval.expense_claim.status = 'rejected';
approval.expense_claim.approver_id = approverId;
approval.expense_claim.rejected_at = new Date();
await this.expenseClaimRepo.save(approval.expense_claim);
}
if (approval.advance_payment) {
approval.advance_payment.status = 'rejected';
approval.advance_payment.approver_id = approverId;
approval.advance_payment.rejected_at = new Date();
await this.advancePaymentRepo.save(approval.advance_payment);
}
return this.financeApprovalRepo.save(approval);
}
// 公司账目管理
async getCompanyFinancialRecords(filter?: any): Promise<FinancialRecord[]> {
const query = this.financialRecordRepo.createQueryBuilder('fr')
.leftJoinAndSelect('fr.project', 'project');
if (filter) {
if (filter.type) query.where('fr.type = :type', { type: filter.type });
if (filter.status) query.where('fr.status = :status', { status: filter.status });
if (filter.start_date) query.where('fr.created_at >= :start_date', { start_date: filter.start_date });
if (filter.end_date) query.where('fr.created_at <= :end_date', { end_date: filter.end_date });
}
return query.getMany();
}
// 项目财务记录
async getProjectFinancialRecords(projectId: string): Promise<FinancialRecord[]> {
return this.financialRecordRepo.find({
where: { project_id: projectId },
relations: ['financial_transactions', 'financial_transactions.bank_account']
});
}
// 员工个人记账
async getEmployeeFinancialRecords(userId: string): Promise<any[]> {
const expenseClaims = await this.expenseClaimRepo.find({
where: { user_id: userId },
relations: ['project', 'vouchers']
});
const advancePayments = await this.advancePaymentRepo.find({
where: { user_id: userId },
relations: ['project', 'vouchers']
});
return [...expenseClaims, ...advancePayments];
}
// 汇率管理相关
async getCurrencyRates(): Promise<CurrencyRate[]> {
return this.currencyRateRepo.find({ where: { is_active: true } });
}
async getCurrencyRate(fromCurrency: string, toCurrency: string): Promise<CurrencyRate | null> {
return this.currencyRateRepo.findOne({
where: { from_currency: fromCurrency, to_currency: toCurrency, is_active: true }
});
}
async createOrUpdateCurrencyRate(data: {
from_currency: string;
to_currency: string;
rate: number;
}): Promise<CurrencyRate> {
const { from_currency, to_currency, rate } = data;
// 检查是否已存在该货币对的汇率
let currencyRate = await this.currencyRateRepo.findOne({
where: { from_currency, to_currency }
});
if (currencyRate) {
// 更新现有汇率
currencyRate.rate = rate;
currencyRate.is_active = true;
return this.currencyRateRepo.save(currencyRate);
} else {
// 创建新汇率
currencyRate = this.currencyRateRepo.create({
from_currency,
to_currency,
rate,
is_active: true
});
return this.currencyRateRepo.save(currencyRate);
}
}
async updateCurrencyRateStatus(id: string, is_active: boolean): Promise<CurrencyRate> {
const currencyRate = await this.currencyRateRepo.findOne({ where: { id } });
if (!currencyRate) throw new NotFoundException('Currency rate not found');
currencyRate.is_active = is_active;
return this.currencyRateRepo.save(currencyRate);
}
// 金额换算方法
async convertCurrency(amount: number, fromCurrency: string, toCurrency: string): Promise<number> {
if (fromCurrency === toCurrency) return amount;
// 尝试直接获取汇率
let rate = await this.getCurrencyRate(fromCurrency, toCurrency);
if (rate) {
return amount * rate.rate;
}
// 尝试反向汇率
const reverseRate = await this.getCurrencyRate(toCurrency, fromCurrency);
if (reverseRate) {
return amount / reverseRate.rate;
}
// 如果都没有,抛出异常
throw new NotFoundException(`Exchange rate not found for ${fromCurrency} to ${toCurrency}`);
}
// 获取所有支持的币种
getSupportedCurrencies(): Array<{ code: string; name: string; symbol: string }> {
return [
{ code: 'CNY', name: '人民币', symbol: '¥' },
{ code: 'LAK', name: '老挝基普', symbol: '₭' },
{ code: 'THB', name: '泰铢', symbol: '฿' },
{ code: 'USD', name: '美元', symbol: '$' }
];
}
}
@@ -0,0 +1,55 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { Project } from '../projects/project.entity';
import { PaymentTerm } from '../contracts/payment-term.entity';
import { FinancialTransaction } from './financial-transaction.entity';
@Entity('financial_records')
export class FinancialRecord {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 50, nullable: false })
type: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'uuid', nullable: true })
project_id: string;
@ManyToOne(() => Project, project => project.financial_records)
project: Project;
@Column({ type: 'uuid', nullable: true })
related_id: string;
@Column({ type: 'varchar', length: 50, nullable: true })
related_type: string;
@Column({ type: 'uuid', nullable: true })
payment_term_id: string;
@ManyToOne(() => PaymentTerm, paymentTerm => paymentTerm.financial_records)
payment_term: PaymentTerm;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@Column({ type: 'text', nullable: true })
description: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => FinancialTransaction, financialTransaction => financialTransaction.financial_record)
financial_transactions: FinancialTransaction[];
}
@@ -0,0 +1,39 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne } from 'typeorm';
import { FinancialRecord } from './financial-record.entity';
import { BankAccount } from './bank-account.entity';
@Entity('financial_transactions')
export class FinancialTransaction {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
financial_record_id: string;
@ManyToOne(() => FinancialRecord, financialRecord => financialRecord.financial_transactions)
financial_record: FinancialRecord;
@Column({ type: 'uuid', nullable: true })
bank_account_id: string;
@ManyToOne(() => BankAccount, bankAccount => bankAccount.financial_transactions)
bank_account: BankAccount;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'date', nullable: false })
transaction_date: Date;
@Column({ type: 'varchar', length: 50, nullable: false })
transaction_type: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,53 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne } from 'typeorm';
import { User } from '../users/user.entity';
import { FinancialRecord } from './financial-record.entity';
import { ExpenseClaim } from './expense-claim.entity';
import { AdvancePayment } from './advance-payment.entity';
@Entity('vouchers')
export class Voucher {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
file_path: string;
@Column({ type: 'varchar', length: 100, nullable: false })
file_name: string;
@Column({ type: 'varchar', length: 50, nullable: false })
file_type: string;
@Column({ type: 'uuid', nullable: true })
financial_record_id: string;
@ManyToOne(() => FinancialRecord)
financial_record: FinancialRecord;
@Column({ type: 'uuid', nullable: true })
expense_claim_id: string;
@ManyToOne(() => ExpenseClaim)
expense_claim: ExpenseClaim;
@Column({ type: 'uuid', nullable: true })
advance_payment_id: string;
@ManyToOne(() => AdvancePayment)
advance_payment: AdvancePayment;
@Column({ type: 'uuid', nullable: false })
uploaded_by: string;
@ManyToOne(() => User)
uploader: User;
@Column({ type: 'text', nullable: true })
description: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,19 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm';
@Entity('permissions')
export class Permission {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true, nullable: false })
name: string;
@Column({ type: 'text', nullable: true })
description: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,45 @@
import { Controller, Get, Post, Put, Delete, Body, Param, UseGuards } from '@nestjs/common';
import { PermissionsService } from './permissions.service';
import { AuthGuard } from '@nestjs/passport';
@Controller('api/v1/permissions')
export class PermissionsController {
constructor(private readonly permissionsService: PermissionsService) {}
@Post()
@UseGuards(AuthGuard('jwt'))
async create(
@Body('name') name: string,
@Body('description') description: string,
) {
return this.permissionsService.create(name, description);
}
@Get()
@UseGuards(AuthGuard('jwt'))
async findAll() {
return this.permissionsService.findAll();
}
@Get(':id')
@UseGuards(AuthGuard('jwt'))
async findById(@Param('id') id: string) {
return this.permissionsService.findById(id);
}
@Put(':id')
@UseGuards(AuthGuard('jwt'))
async update(
@Param('id') id: string,
@Body('name') name: string,
@Body('description') description: string,
) {
return this.permissionsService.update(id, name, description);
}
@Delete(':id')
@UseGuards(AuthGuard('jwt'))
async delete(@Param('id') id: string) {
return this.permissionsService.delete(id);
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Permission } from './permission.entity';
import { PermissionsService } from './permissions.service';
import { PermissionsController } from './permissions.controller';
@Module({
imports: [TypeOrmModule.forFeature([Permission])],
providers: [PermissionsService],
controllers: [PermissionsController],
exports: [PermissionsService, TypeOrmModule.forFeature([Permission])],
})
export class PermissionsModule {}
@@ -0,0 +1,42 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Permission } from './permission.entity';
@Injectable()
export class PermissionsService {
constructor(
@InjectRepository(Permission)
private readonly permissionsRepository: Repository<Permission>,
) {}
async create(name: string, description: string) {
const permission = this.permissionsRepository.create({
name,
description,
});
return this.permissionsRepository.save(permission);
}
async findById(id: string) {
return this.permissionsRepository.findOne({
where: { id },
});
}
async findAll() {
return this.permissionsRepository.find();
}
async update(id: string, name: string, description: string) {
await this.permissionsRepository.update(id, {
name,
description,
});
return this.findById(id);
}
async delete(id: string) {
return this.permissionsRepository.delete(id);
}
}
@@ -0,0 +1,29 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { Product } from './product.entity';
@Entity('product_categories')
export class ProductCategory {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
name: string;
@Column({ type: 'uuid', nullable: true })
parent_id: string;
@ManyToOne(() => ProductCategory, productCategory => productCategory.children)
parent: ProductCategory;
@OneToMany(() => ProductCategory, productCategory => productCategory.parent)
children: ProductCategory[];
@OneToMany(() => Product, product => product.category)
products: Product[];
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,37 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { ProductCategory } from './product-category.entity';
import { PurchaseItem } from '../purchases/purchase-item.entity';
import { QuotationItem } from '../quotations/quotation-item.entity';
@Entity('products')
export class Product {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
name: string;
@Column({ type: 'uuid', nullable: true })
category_id: string;
@ManyToOne(() => ProductCategory, productCategory => productCategory.products)
category: ProductCategory;
@Column({ type: 'varchar', length: 50, nullable: false })
unit: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: true })
cost_price: number;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => PurchaseItem, purchaseItem => purchaseItem.product)
purchase_items: PurchaseItem[];
@OneToMany(() => QuotationItem, quotationItem => quotationItem.product)
quotation_items: QuotationItem[];
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Product } from './product.entity';
import { ProductCategory } from './product-category.entity';
@Module({
imports: [TypeOrmModule.forFeature([Product, ProductCategory])],
exports: [TypeOrmModule],
})
export class ProductsModule {}
@@ -0,0 +1,45 @@
import { IsString, IsNumber, IsDate, IsOptional, IsUUID, IsDecimal } from 'class-validator';
export class CreateProjectDto {
@IsString()
name: string;
@IsUUID()
@IsOptional()
customer_id: string;
@IsString()
contract_number: string;
@IsNumber()
contract_amount: number;
@IsString()
currency: string;
@IsNumber()
rmb_equivalent: number;
@IsDate()
@IsOptional()
start_date: Date;
@IsDate()
@IsOptional()
end_date: Date;
@IsString()
status: string;
@IsString()
@IsOptional()
settlement_type: string; // 'lump_sum' 或 'unit_price'
@IsNumber()
@IsOptional()
estimated_quantity: number;
@IsNumber()
@IsOptional()
unit_price: number;
}
@@ -0,0 +1,2 @@
export * from './create-project.dto';
export * from './update-project.dto';
@@ -0,0 +1,51 @@
import { IsString, IsNumber, IsDate, IsOptional, IsUUID } from 'class-validator';
export class UpdateProjectDto {
@IsString()
@IsOptional()
name: string;
@IsUUID()
@IsOptional()
customer_id: string;
@IsString()
@IsOptional()
contract_number: string;
@IsNumber()
@IsOptional()
contract_amount: number;
@IsString()
@IsOptional()
currency: string;
@IsNumber()
@IsOptional()
rmb_equivalent: number;
@IsDate()
@IsOptional()
start_date: Date;
@IsDate()
@IsOptional()
end_date: Date;
@IsString()
@IsOptional()
status: string;
@IsString()
@IsOptional()
settlement_type: string; // 'lump_sum' 或 'unit_price'
@IsNumber()
@IsOptional()
estimated_quantity: number;
@IsNumber()
@IsOptional()
unit_price: number;
}
@@ -0,0 +1,77 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { Customer } from '../customers/customer.entity';
import { Contract } from '../contracts/contract.entity';
import { Purchase } from '../purchases/purchase.entity';
import { Subcontract } from '../subcontracts/subcontract.entity';
import { FinancialRecord } from '../finance/financial-record.entity';
import { ExpenseClaim } from '../finance/expense-claim.entity';
import { AdvancePayment } from '../finance/advance-payment.entity';
@Entity('projects')
export class Project {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
name: string;
@Column({ type: 'uuid', nullable: true })
customer_id: string;
@ManyToOne(() => Customer, customer => customer.projects)
customer: Customer;
@Column({ type: 'varchar', length: 100, unique: true, nullable: false })
contract_number: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
contract_amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'date', nullable: true })
start_date: Date;
@Column({ type: 'date', nullable: true })
end_date: Date;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@Column({ type: 'varchar', length: 20, nullable: true })
settlement_type: string; // 'lump_sum' 或 'unit_price'
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: true })
estimated_quantity: number;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: true })
unit_price: number;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => Contract, contract => contract.project)
contracts: Contract[];
@OneToMany(() => Purchase, purchase => purchase.project)
purchases: Purchase[];
@OneToMany(() => Subcontract, subcontract => subcontract.project)
subcontracts: Subcontract[];
@OneToMany(() => FinancialRecord, financialRecord => financialRecord.project)
financial_records: FinancialRecord[];
@OneToMany(() => ExpenseClaim, expenseClaim => expenseClaim.project)
expense_claims: ExpenseClaim[];
@OneToMany(() => AdvancePayment, advancePayment => advancePayment.project)
advance_payments: AdvancePayment[];
}
@@ -0,0 +1,43 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query } from '@nestjs/common';
import { ProjectsService } from './projects.service';
import { CreateProjectDto, UpdateProjectDto } from './dto';
@Controller('projects')
export class ProjectsController {
constructor(private readonly projectsService: ProjectsService) {}
@Get()
async findAll(@Query() query) {
return this.projectsService.findAll(query);
}
@Get(':id')
async findOne(@Param('id') id: string) {
return this.projectsService.findOne(id);
}
@Post()
async create(@Body() createProjectDto: CreateProjectDto) {
return this.projectsService.create(createProjectDto);
}
@Put(':id')
async update(@Param('id') id: string, @Body() updateProjectDto: UpdateProjectDto) {
return this.projectsService.update(id, updateProjectDto);
}
@Delete(':id')
async remove(@Param('id') id: string) {
return this.projectsService.remove(id);
}
@Get(':id/calculate-duration')
async calculateDuration(@Param('id') id: string) {
return this.projectsService.calculateDuration(id);
}
@Put(':id/update-status')
async updateStatus(@Param('id') id: string, @Body('status') status: string) {
return this.projectsService.updateStatus(id, status);
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Project } from './project.entity';
import { ProjectsController } from './projects.controller';
import { ProjectsService } from './projects.service';
@Module({
imports: [TypeOrmModule.forFeature([Project])],
controllers: [ProjectsController],
providers: [ProjectsService],
exports: [ProjectsService],
})
export class ProjectsModule {}
@@ -0,0 +1,90 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Project } from './project.entity';
import { CreateProjectDto, UpdateProjectDto } from './dto';
@Injectable()
export class ProjectsService {
constructor(
@InjectRepository(Project)
private projectsRepository: Repository<Project>,
) {}
async findAll(query) {
const { page = 1, limit = 10, status, customer_id } = query;
const skip = (page - 1) * limit;
const queryBuilder = this.projectsRepository.createQueryBuilder('project');
if (status) {
queryBuilder.where('project.status = :status', { status });
}
if (customer_id) {
queryBuilder.where('project.customer_id = :customer_id', { customer_id });
}
const [projects, total] = await queryBuilder
.leftJoinAndSelect('project.customer', 'customer')
.skip(skip)
.take(limit)
.getManyAndCount();
return {
projects,
total,
page,
limit,
};
}
async findOne(id: string) {
const project = await this.projectsRepository.findOne({
where: { id },
relations: ['customer', 'contracts', 'purchases', 'subcontracts'],
});
if (!project) {
throw new NotFoundException(`Project with ID ${id} not found`);
}
return project;
}
async create(createProjectDto: CreateProjectDto) {
const project = this.projectsRepository.create(createProjectDto);
return this.projectsRepository.save(project);
}
async update(id: string, updateProjectDto: UpdateProjectDto) {
const project = await this.findOne(id);
Object.assign(project, updateProjectDto);
return this.projectsRepository.save(project);
}
async remove(id: string) {
const project = await this.findOne(id);
return this.projectsRepository.remove(project);
}
async calculateDuration(id: string) {
const project = await this.findOne(id);
if (!project.start_date || !project.end_date) {
return { message: 'Start date or end date is not set' };
}
const start = new Date(project.start_date);
const end = new Date(project.end_date);
const duration = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
return { duration_days: duration };
}
async updateStatus(id: string, status: string) {
const project = await this.findOne(id);
project.status = status;
return this.projectsRepository.save(project);
}
}
@@ -0,0 +1,36 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { Purchase } from './purchase.entity';
import { Product } from '../products/product.entity';
@Entity('purchase_items')
export class PurchaseItem {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
purchase_id: string;
@ManyToOne(() => Purchase, purchase => purchase.purchase_items)
purchase: Purchase;
@Column({ type: 'uuid', nullable: true })
product_id: string;
@ManyToOne(() => Product, product => product.purchase_items)
product: Product;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
quantity: number;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
unit_price: number;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
total_price: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
}
@@ -0,0 +1,53 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { Project } from '../projects/project.entity';
import { Supplier } from '../suppliers/supplier.entity';
import { Contract } from '../contracts/contract.entity';
import { PurchaseItem } from './purchase-item.entity';
@Entity('purchases')
export class Purchase {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
project_id: string;
@ManyToOne(() => Project, project => project.purchases)
project: Project;
@Column({ type: 'uuid', nullable: true })
supplier_id: string;
@ManyToOne(() => Supplier, supplier => supplier.purchases)
supplier: Supplier;
@Column({ type: 'uuid', nullable: true })
contract_id: string;
@ManyToOne(() => Contract, contract => contract.purchases)
contract: Contract;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
total_amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'date', nullable: true })
expected_delivery_date: Date;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => PurchaseItem, purchaseItem => purchaseItem.purchase)
purchase_items: PurchaseItem[];
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Purchase } from './purchase.entity';
import { PurchaseItem } from './purchase-item.entity';
@Module({
imports: [TypeOrmModule.forFeature([Purchase, PurchaseItem])],
exports: [TypeOrmModule],
})
export class PurchasesModule {}
@@ -0,0 +1,36 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { Quotation } from './quotation.entity';
import { Product } from '../products/product.entity';
@Entity('quotation_items')
export class QuotationItem {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
quotation_id: string;
@ManyToOne(() => Quotation, quotation => quotation.quotation_items)
quotation: Quotation;
@Column({ type: 'uuid', nullable: true })
product_id: string;
@ManyToOne(() => Product, product => product.quotation_items)
product: Product;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
quantity: number;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
unit_price: number;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
total_price: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
}
@@ -0,0 +1,39 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { Customer } from '../customers/customer.entity';
import { QuotationItem } from './quotation-item.entity';
@Entity('quotations')
export class Quotation {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
customer_id: string;
@ManyToOne(() => Customer, customer => customer.quotations)
customer: Customer;
@Column({ type: 'varchar', length: 255, nullable: false })
project_name: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
total_amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => QuotationItem, quotationItem => quotationItem.quotation)
quotation_items: QuotationItem[];
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Quotation } from './quotation.entity';
import { QuotationItem } from './quotation-item.entity';
@Module({
imports: [TypeOrmModule.forFeature([Quotation, QuotationItem])],
exports: [TypeOrmModule],
})
export class QuotationsModule {}
+28
View File
@@ -0,0 +1,28 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToMany, JoinTable, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { Permission } from '../permissions/permission.entity';
@Entity('roles')
export class Role {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true, nullable: false })
name: string;
@Column({ type: 'text', nullable: true })
description: string;
@ManyToMany(() => Permission)
@JoinTable({
name: 'role_permissions',
joinColumn: { name: 'role_id' },
inverseJoinColumn: { name: 'permission_id' },
})
permissions: Permission[];
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,56 @@
import { Controller, Get, Post, Put, Delete, Body, Param, UseGuards } from '@nestjs/common';
import { RolesService } from './roles.service';
import { AuthGuard } from '@nestjs/passport';
@Controller('api/v1/roles')
export class RolesController {
constructor(private readonly rolesService: RolesService) {}
@Post()
@UseGuards(AuthGuard('jwt'))
async create(
@Body('name') name: string,
@Body('description') description: string,
@Body('permissionIds') permissionIds: string[],
) {
return this.rolesService.create(name, description, permissionIds);
}
@Get()
@UseGuards(AuthGuard('jwt'))
async findAll() {
return this.rolesService.findAll();
}
@Get(':id')
@UseGuards(AuthGuard('jwt'))
async findById(@Param('id') id: string) {
return this.rolesService.findById(id);
}
@Put(':id')
@UseGuards(AuthGuard('jwt'))
async update(
@Param('id') id: string,
@Body('name') name: string,
@Body('description') description: string,
@Body('permissionIds') permissionIds: string[],
) {
return this.rolesService.update(id, name, description, permissionIds);
}
@Delete(':id')
@UseGuards(AuthGuard('jwt'))
async delete(@Param('id') id: string) {
return this.rolesService.delete(id);
}
@Post(':id/permissions')
@UseGuards(AuthGuard('jwt'))
async assignPermissions(
@Param('id') roleId: string,
@Body('permissionIds') permissionIds: string[],
) {
return this.rolesService.assignPermissions(roleId, permissionIds);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Role } from './role.entity';
import { Permission } from '../permissions/permission.entity';
import { RolesService } from './roles.service';
import { RolesController } from './roles.controller';
@Module({
imports: [TypeOrmModule.forFeature([Role, Permission])],
providers: [RolesService],
controllers: [RolesController],
exports: [RolesService, TypeOrmModule.forFeature([Role, Permission])],
})
export class RolesModule {}
@@ -0,0 +1,62 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from './role.entity';
import { Permission } from '../permissions/permission.entity';
@Injectable()
export class RolesService {
constructor(
@InjectRepository(Role)
private readonly rolesRepository: Repository<Role>,
@InjectRepository(Permission)
private readonly permissionsRepository: Repository<Permission>,
) {}
async create(name: string, description: string, permissionIds: string[]) {
const permissions = await this.permissionsRepository.findByIds(permissionIds);
const role = this.rolesRepository.create({
name,
description,
permissions,
});
return this.rolesRepository.save(role);
}
async findById(id: string) {
return this.rolesRepository.findOne({
where: { id },
relations: ['permissions'],
});
}
async findAll() {
return this.rolesRepository.find({
relations: ['permissions'],
});
}
async update(id: string, name: string, description: string, permissionIds: string[]) {
const permissions = await this.permissionsRepository.findByIds(permissionIds);
await this.rolesRepository.update(id, {
name,
description,
});
const role = await this.findById(id);
if (!role) return null;
role.permissions = permissions;
return this.rolesRepository.save(role);
}
async delete(id: string) {
return this.rolesRepository.delete(id);
}
async assignPermissions(roleId: string, permissionIds: string[]) {
const role = await this.findById(roleId);
if (!role) return null;
const permissions = await this.permissionsRepository.findByIds(permissionIds);
role.permissions = permissions;
return this.rolesRepository.save(role);
}
}
@@ -0,0 +1,32 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
import { Subcontract } from '../subcontracts/subcontract.entity';
@Entity('subcontractors')
export class Subcontractor {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
name: string;
@Column({ type: 'varchar', length: 255, nullable: true })
contact_person: string;
@Column({ type: 'varchar', length: 50, nullable: true })
phone: string;
@Column({ type: 'varchar', length: 255, nullable: true })
email: string;
@Column({ type: 'text', nullable: true })
address: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => Subcontract, subcontract => subcontract.subcontractor)
subcontracts: Subcontract[];
}
@@ -0,0 +1,38 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { SubcontractorsService } from './subcontractors.service';
import { Subcontractor } from './subcontractor.entity';
@Controller('api/v1/subcontractors')
export class SubcontractorsController {
constructor(private readonly subcontractorsService: SubcontractorsService) {}
@Post()
create(@Body() subcontractorData: Partial<Subcontractor>) {
return this.subcontractorsService.create(subcontractorData);
}
@Get()
findAll() {
return this.subcontractorsService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.subcontractorsService.findOne(id);
}
@Get(':id/subcontracts')
findWithSubcontracts(@Param('id') id: string) {
return this.subcontractorsService.findWithSubcontracts(id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() subcontractorData: Partial<Subcontractor>) {
return this.subcontractorsService.update(id, subcontractorData);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.subcontractorsService.remove(id);
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Subcontractor } from './subcontractor.entity';
import { SubcontractorsController } from './subcontractors.controller';
import { SubcontractorsService } from './subcontractors.service';
@Module({
imports: [TypeOrmModule.forFeature([Subcontractor])],
controllers: [SubcontractorsController],
providers: [SubcontractorsService],
exports: [SubcontractorsService],
})
export class SubcontractorsModule {}
@@ -0,0 +1,53 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Subcontractor } from './subcontractor.entity';
@Injectable()
export class SubcontractorsService {
constructor(
@InjectRepository(Subcontractor)
private subcontractorsRepository: Repository<Subcontractor>,
) {}
async create(subcontractorData: Partial<Subcontractor>): Promise<Subcontractor> {
const subcontractor = this.subcontractorsRepository.create(subcontractorData);
return this.subcontractorsRepository.save(subcontractor);
}
async findAll(): Promise<Subcontractor[]> {
return this.subcontractorsRepository.find();
}
async findOne(id: string): Promise<Subcontractor> {
const subcontractor = await this.subcontractorsRepository.findOne({ where: { id } });
if (!subcontractor) {
throw new NotFoundException(`Subcontractor with id ${id} not found`);
}
return subcontractor;
}
async update(id: string, subcontractorData: Partial<Subcontractor>): Promise<Subcontractor> {
const subcontractor = await this.findOne(id);
Object.assign(subcontractor, subcontractorData);
return this.subcontractorsRepository.save(subcontractor);
}
async remove(id: string): Promise<void> {
const result = await this.subcontractorsRepository.delete(id);
if (result.affected === 0) {
throw new NotFoundException(`Subcontractor with id ${id} not found`);
}
}
async findWithSubcontracts(id: string): Promise<Subcontractor> {
const subcontractor = await this.subcontractorsRepository.findOne({
where: { id },
relations: ['subcontracts'],
});
if (!subcontractor) {
throw new NotFoundException(`Subcontractor with id ${id} not found`);
}
return subcontractor;
}
}
@@ -0,0 +1,46 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne } from 'typeorm';
import { Project } from '../projects/project.entity';
import { Subcontractor } from '../subcontractors/subcontractor.entity';
import { Contract } from '../contracts/contract.entity';
@Entity('subcontracts')
export class Subcontract {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'uuid', nullable: true })
project_id: string;
@ManyToOne(() => Project, project => project.subcontracts)
project: Project;
@Column({ type: 'uuid', nullable: true })
subcontractor_id: string;
@ManyToOne(() => Subcontractor, subcontractor => subcontractor.subcontracts)
subcontractor: Subcontractor;
@Column({ type: 'uuid', nullable: true })
contract_id: string;
@ManyToOne(() => Contract, contract => contract.subcontracts)
contract: Contract;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
total_amount: number;
@Column({ type: 'varchar', length: 10, nullable: false })
currency: string;
@Column({ type: 'decimal', precision: 18, scale: 2, nullable: false })
rmb_equivalent: number;
@Column({ type: 'varchar', length: 50, nullable: false })
status: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Subcontract } from './subcontract.entity';
@Module({
imports: [TypeOrmModule.forFeature([Subcontract])],
exports: [TypeOrmModule],
})
export class SubcontractsModule {}
@@ -0,0 +1,35 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
import { Purchase } from '../purchases/purchase.entity';
@Entity('suppliers')
export class Supplier {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 255, nullable: false })
name: string;
@Column({ type: 'varchar', length: 255, nullable: true })
contact_person: string;
@Column({ type: 'varchar', length: 50, nullable: true })
phone: string;
@Column({ type: 'varchar', length: 255, nullable: true })
email: string;
@Column({ type: 'text', nullable: true })
address: string;
@Column({ type: 'varchar', length: 50, nullable: true })
type: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@OneToMany(() => Purchase, purchase => purchase.supplier)
purchases: Purchase[];
}
@@ -0,0 +1,38 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { SuppliersService } from './suppliers.service';
import { Supplier } from './supplier.entity';
@Controller('api/v1/suppliers')
export class SuppliersController {
constructor(private readonly suppliersService: SuppliersService) {}
@Post()
create(@Body() supplierData: Partial<Supplier>) {
return this.suppliersService.create(supplierData);
}
@Get()
findAll() {
return this.suppliersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.suppliersService.findOne(id);
}
@Get(':id/purchases')
findWithPurchases(@Param('id') id: string) {
return this.suppliersService.findWithPurchases(id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() supplierData: Partial<Supplier>) {
return this.suppliersService.update(id, supplierData);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.suppliersService.remove(id);
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Supplier } from './supplier.entity';
import { SuppliersController } from './suppliers.controller';
import { SuppliersService } from './suppliers.service';
@Module({
imports: [TypeOrmModule.forFeature([Supplier])],
controllers: [SuppliersController],
providers: [SuppliersService],
exports: [SuppliersService],
})
export class SuppliersModule {}
@@ -0,0 +1,53 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Supplier } from './supplier.entity';
@Injectable()
export class SuppliersService {
constructor(
@InjectRepository(Supplier)
private suppliersRepository: Repository<Supplier>,
) {}
async create(supplierData: Partial<Supplier>): Promise<Supplier> {
const supplier = this.suppliersRepository.create(supplierData);
return this.suppliersRepository.save(supplier);
}
async findAll(): Promise<Supplier[]> {
return this.suppliersRepository.find();
}
async findOne(id: string): Promise<Supplier> {
const supplier = await this.suppliersRepository.findOne({ where: { id } });
if (!supplier) {
throw new NotFoundException(`Supplier with id ${id} not found`);
}
return supplier;
}
async update(id: string, supplierData: Partial<Supplier>): Promise<Supplier> {
const supplier = await this.findOne(id);
Object.assign(supplier, supplierData);
return this.suppliersRepository.save(supplier);
}
async remove(id: string): Promise<void> {
const result = await this.suppliersRepository.delete(id);
if (result.affected === 0) {
throw new NotFoundException(`Supplier with id ${id} not found`);
}
}
async findWithPurchases(id: string): Promise<Supplier> {
const supplier = await this.suppliersRepository.findOne({
where: { id },
relations: ['purchases'],
});
if (!supplier) {
throw new NotFoundException(`Supplier with id ${id} not found`);
}
return supplier;
}
}
+29
View File
@@ -0,0 +1,29 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { Role } from '../roles/role.entity';
@Entity('users')
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true, nullable: false })
username: string;
@Column({ nullable: false })
password: string;
@Column({ nullable: false })
name: string;
@Column({ unique: true, nullable: false })
email: string;
@ManyToOne(() => Role)
role: Role;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@@ -0,0 +1,46 @@
import { Controller, Get, Post, Put, Delete, Body, Param, UseGuards } from '@nestjs/common';
import { UsersService } from './users.service';
import { AuthGuard } from '@nestjs/passport';
@Controller('api/v1/users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
async create(
@Body('username') username: string,
@Body('password') password: string,
@Body('name') name: string,
@Body('email') email: string,
@Body('roleId') roleId: string,
) {
return this.usersService.create({ username, password, name, email, roleId });
}
@Get()
@UseGuards(AuthGuard('jwt'))
async findAll() {
return this.usersService.findAll();
}
@Get(':id')
@UseGuards(AuthGuard('jwt'))
async findById(@Param('id') id: string) {
return this.usersService.findById(id);
}
@Put(':id')
@UseGuards(AuthGuard('jwt'))
async update(
@Param('id') id: string,
@Body() userData: any,
) {
return this.usersService.update(id, userData);
}
@Delete(':id')
@UseGuards(AuthGuard('jwt'))
async delete(@Param('id') id: string) {
return this.usersService.delete(id);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UsersService],
controllers: [UsersController],
exports: [UsersService, TypeOrmModule.forFeature([User])],
})
export class UsersModule {}
@@ -0,0 +1,43 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
import { User } from './user.entity';
import { getRepositoryToken } from '@nestjs/typeorm';
import * as bcrypt from 'bcryptjs';
describe('UsersService', () => {
let usersService: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UsersService,
{
provide: getRepositoryToken(User),
useValue: {
findOne: jest.fn(),
},
},
],
}).compile();
usersService = module.get<UsersService>(UsersService);
});
describe('validatePassword', () => {
it('should return true for valid password', async () => {
const user = new User();
user.password = bcrypt.hashSync('password123', 10);
const result = await usersService.validatePassword(user, 'password123');
expect(result).toBe(true);
});
it('should return false for invalid password', async () => {
const user = new User();
user.password = bcrypt.hashSync('password123', 10);
const result = await usersService.validatePassword(user, 'wrongpassword');
expect(result).toBe(false);
});
});
});
@@ -0,0 +1,66 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private readonly usersRepository: Repository<User>,
) {}
async create(userData: {
username: string;
password: string;
name: string;
email: string;
roleId: string;
}) {
const user = this.usersRepository.create({
...userData,
role: { id: userData.roleId } as any,
});
return this.usersRepository.save(user);
}
async findById(id: string) {
return this.usersRepository.findOne({
where: { id },
relations: ['role', 'role.permissions'],
});
}
async findByUsername(username: string) {
return this.usersRepository.findOne({
where: { username },
relations: ['role', 'role.permissions'],
});
}
async findByEmail(email: string) {
return this.usersRepository.findOne({
where: { email },
});
}
async findAll() {
return this.usersRepository.find({
relations: ['role'],
});
}
async update(id: string, userData: Partial<User>) {
await this.usersRepository.update(id, userData);
return this.findById(id);
}
async delete(id: string) {
return this.usersRepository.delete(id);
}
async validatePassword(user: User, password: string): Promise<boolean> {
return bcrypt.compare(password, user.password);
}
}
+25
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
View File
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
+25
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
}
}