Implementation Plan: API Tính Toán DRC + Tính Lương
Mục tiêu: Migrate logic tính toán DRC và Tính lương từ React Native frontend (rubber-app) sang NestJS backend (rubber-bff).
Tổng Quan Kiến Trúc
rubber-bff/src/
├── drc/ # Module DRC (Quality Control)
│ ├── drc.module.ts
│ ├── drc.controller.ts
│ ├── drc.service.ts
│ └── dto/
│ ├── create-drc-evaluation.dto.ts
│ ├── update-drc-evaluation.dto.ts
│ └── drc-analytics-query.dto.ts
│
├── salary/ # Module Tính Lương
│ ├── salary.module.ts
│ ├── salary.controller.ts
│ ├── salary.service.ts
│ ├── salary-calculator.service.ts
│ └── dto/
│ ├── calculate-salary.dto.ts
│ ├── create-salary-calculation.dto.ts
│ ├── salary-settings.dto.ts
│ └── salary-advance.dto.ts
│
└── app.module.ts # Register new modules
Nguồn Code Frontend Cần Migrate
| File Frontend | Responsibility |
|---|---|
features/salary-calculation/services/salary-auto-calculator.ts | Core salary engine (298 lines) |
features/salary-calculation/services/salary-service.ts | Salary CRUD (233 lines) |
features/salary-calculation/services/salary-settings-service.ts | Settings singleton (53 lines) |
features/salary-calculation/services/salary-advance-service.ts | Advances CRUD (42 lines) |
features/salary-calculation/types/index.ts | All salary types (83 lines) |
features/quality-control/services/quality-control-service.directus.ts | DRC CRUD (321 lines) |
features/warehouse/hooks/use-warehouse-analytics.ts | DRC analytics (443 lines) |
features/latex-prices-management/services/latex-price-service.ts | Price lookup (75 lines) |
Directus Collections Used
| Collection | Purpose |
|---|---|
drc_evaluation | DRC evaluation records |
latex_production | Worker production records |
latex_prices | Price configuration per latex type |
salary_calculation | Salary records |
salary_details | Salary breakdown by latex type |
salary_settings | Insurance/CDP rate config (singleton) |
salary_advances | Salary advance payments |
inventory_input_items | Warehouse intake (drc_percent, wet_quantity) |
workers | Worker records (insurance_salary) |
production_teams | Team records |
tapping_plots | Tapping plot records |
Phase 1: DRC Module
1.1 API Endpoints
GET /api/drc/evaluations List all DRC evaluations
GET /api/drc/evaluations/:id Get single evaluation
POST /api/drc/evaluations Create evaluation
PATCH /api/drc/evaluations/:id Update evaluation
DELETE /api/drc/evaluations/:id Delete evaluation
GET /api/drc/evaluations/plot/:plotId Filter by tapping_plot
GET /api/drc/analytics Weighted DRC analytics
?startDate=2026-01-01&endDate=2026-09-30&ytdStartDate=2026-01-01
GET /api/drc/analytics/dashboard Simple avg DRC for dashboard
?month=9&year=2026
1.2 Files to Create
src/drc/drc.module.ts
import { Module } from '@nestjs/common';
import { DrcController } from './drc.controller';
import { DrcService } from './drc.service';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [AuthModule],
controllers: [DrcController],
providers: [DrcService],
exports: [DrcService],
})
export class DrcModule {}
src/drc/drc.controller.ts
import { Controller, Get, Post, Patch, Delete, Param, Query, Body, Res, Req } from '@nestjs/common';
import { Request, Response } from 'express';
import { DrcService } from './drc.service';
@Controller('api/drc')
export class DrcController {
constructor(private readonly drcService: DrcService) {}
@Get('evaluations')
async getEvaluations(@Query() query, @Res() response: Response) {
// filter: plotId, startDate, endDate
// Returns: DrcEvaluation[]
}
@Get('evaluations/plot/:plotId')
async getEvaluationsByPlot(@Param('plotId') plotId: string, @Res() response: Response) {
// Returns: DrcEvaluation[]
}
@Get('evaluations/:id')
async getEvaluationById(@Param('id') id: string, @Res() response: Response) {
// Returns: DrcEvaluation
}
@Post('evaluations')
async createEvaluation(@Body() body, @Res() response: Response) {
// Body: { evaluation_date, drc_content, tapping_plot_id }
// Returns: DrcEvaluation
}
@Patch('evaluations/:id')
async updateEvaluation(@Param('id') id: string, @Body() body, @Res() response: Response) {
// Returns: DrcEvaluation
}
@Delete('evaluations/:id')
async deleteEvaluation(@Param('id') id: string, @Res() response: Response) {
// Returns: { status: 'success' }
}
@Get('analytics')
async getAnalytics(@Query() query, @Res() response: Response) {
// Query: { startDate, endDate, ytdStartDate? }
// Returns: { averageDrc, ytdAverageDrc, teamStats[] }
}
@Get('analytics/dashboard')
async getDashboardAnalytics(@Query() query, @Res() response: Response) {
// Query: { month, year }
// Returns: { avgDrc, recordCount }
}
}
src/drc/drc.service.ts
Core logic:
import { Injectable, Logger } from '@nestjs/common';
import { UpstreamTokenService } from '../auth/upstream-token.service';
@Injectable()
export class DrcService {
private readonly logger = new Logger(DrcService.name);
constructor(private readonly upstreamTokens: UpstreamTokenService) {}
// --- CRUD --- //
async getEvaluations(filters?: { plotId?: string; startDate?: string; endDate?: string })
async getEvaluationById(id: string)
async createEvaluation(data: { evaluation_date: string; drc_content: number; tapping_plot_id: number })
async updateEvaluation(id: string, data: Partial<{ evaluation_date: string; drc_content: number; tapping_plot_id: number }>)
async deleteEvaluation(id: string)
async getEvaluationsByPlotId(plotId: string)
// --- Analytics --- //
async getWeightedAnalytics(startDate: string, endDate: string, ytdStartDate?: string)
// Formula from frontend use-warehouse-analytics.ts:
// avgDrc = sum(wetQty * drcPercent) / sum(wetQty)
// Per-team: teamAvgDrc = teamWeightedSum / teamTotalWet
// Source: inventory_input_items collection
async getDashboardAnalytics(month: number, year: number)
// Formula from frontend general-report-screen.tsx:
// avgDrc = sum(drc_content) / count(records)
// Source: drc_evaluation collection
}
Key Calculation Logic to Migrate:
-
Weighted DRC (from
use-warehouse-analytics.ts:106-180):For each inventory_input_item:wetQty = wet_quantitydrc = drc_percentweightedDrcSum += wetQty * drctotalWet += wetQtyaverageDrc = weightedDrcSum / totalWet -
Simple Average DRC (from
general-report-screen.tsx:75-77):avgDrc = sum(drc_content) / count(drc_evaluation records in month)
1.3 DTOs
// dto/create-drc-evaluation.dto.ts
export class CreateDrcEvaluationDto {
evaluation_date: string; // YYYY-MM-DD
drc_content: number; // 0-100, validate range
tapping_plot_id: number; // FK to tapping_plots
}
// dto/update-drc-evaluation.dto.ts
export class UpdateDrcEvaluationDto {
evaluation_date?: string;
drc_content?: number;
tapping_plot_id?: number;
}
// dto/drc-analytics-query.dto.ts
export class DrcAnalyticsQueryDto {
startDate: string;
endDate: string;
ytdStartDate?: string;
}
// dto/drc-dashboard-query.dto.ts
export class DrcDashboardQueryDto {
month: number; // 1-12
year: number;
}
1.4 Known Issues to Fix During Migration
| # | Issue | Fix |
|---|---|---|
| 1 | No DRC range validation (accepts negative, >100) | Add validation: 0 <= drc_content <= 100 |
| 2 | Two disconnected DRC systems (drc_evaluation vs inventory drc_percent) | Keep separate, document clearly |
| 3 | Dashboard simple avg vs weighted avg give different numbers | Provide both endpoints, let frontend choose |
Phase 2: Salary Module
2.1 API Endpoints
# Salary Calculations
GET /api/salary/calculations List salary records
GET /api/salary/calculations/:id Get with details
POST /api/salary/calculations Create salary record
PATCH /api/salary/calculations/:id Update salary record
DELETE /api/salary/calculations/:id Delete salary record
POST /api/salary/calculations/with-details Create with salary_details
# Auto Calculation Engine
POST /api/salary/calculate Calculate salary for worker
Body: { workerId, month, year }
Returns: AutoCalculationResult
POST /api/salary/calculate-team-review Bulk calculate for team
Body: { teamId, month?, year }
Returns: WorkerSalaryReview[]
# Settings
GET /api/salary/settings Get salary settings
PATCH /api/salary/settings Update settings
# Advances
GET /api/salary/advances List advances
?workerId=1&month=9&year=2026
POST /api/salary/advances Create advance
2.2 Files to Create
src/salary/salary.module.ts
import { Module } from '@nestjs/common';
import { SalaryController } from './salary.controller';
import { SalaryService } from './salary.service';
import { SalaryCalculatorService } from './salary-calculator.service';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [AuthModule],
controllers: [SalaryController],
providers: [SalaryService, SalaryCalculatorService],
exports: [SalaryService, SalaryCalculatorService],
})
export class SalaryModule {}
src/salary/salary.controller.ts
import { Controller, Get, Post, Patch, Delete, Param, Query, Body, Res } from '@nestjs/common';
import { Response } from 'express';
import { SalaryService } from './salary.service';
import { SalaryCalculatorService } from './salary-calculator.service';
@Controller('api/salary')
export class SalaryController {
constructor(
private readonly salaryService: SalaryService,
private readonly calculatorService: SalaryCalculatorService,
) {}
// --- CRUD --- //
@Get('calculations')
async getCalculations(@Query() query, @Res() response: Response) {
// Query: { year?, workerId?, teamId? }
}
@Get('calculations/:id')
async getCalculationById(@Param('id') id: string, @Res() response: Response) {
// Returns: SalaryCalculationWithDetails
}
@Post('calculations')
async createCalculation(@Body() body, @Res() response: Response) {}
@Post('calculations/with-details')
async createWithDetails(@Body() body, @Res() response: Response) {
// Body: { salary: {...}, details: [...] }
}
@Patch('calculations/:id')
async updateCalculation(@Param('id') id: string, @Body() body, @Res() response: Response) {}
@Delete('calculations/:id')
async deleteCalculation(@Param('id') id: string, @Res() response: Response) {}
// --- Auto Calculation Engine --- //
@Post('calculate')
async calculateForWorker(@Body() body, @Res() response: Response) {
// Body: { workerId: string, month: number, year: number }
// Returns: AutoCalculationResult
}
@Post('calculate-team-review')
async calculateTeamReview(@Body() body, @Res() response: Response) {
// Body: { teamId: string, month?: number, year: number }
// Returns: WorkerSalaryReview[]
}
// --- Settings --- //
@Get('settings')
async getSettings(@Res() response: Response) {}
@Patch('settings')
async updateSettings(@Body() body, @Res() response: Response) {}
// --- Advances --- //
@Get('advances')
async getAdvances(@Query() query, @Res() response: Response) {
// Query: { workerId, month, year }
}
@Post('advances')
async createAdvance(@Body() body, @Res() response: Response) {}
}
src/salary/salary.service.ts
CRUD operations for Directus:
import { Injectable, Logger } from '@nestjs/common';
import { UpstreamTokenService } from '../auth/upstream-token.service';
@Injectable()
export class SalaryService {
constructor(private readonly upstreamTokens: UpstreamTokenService) {}
// --- Salary Calculation CRUD --- //
async getCalculations(filters?: { year?: number; workerId?: number; teamId?: number })
async getCalculationById(id: string)
async createCalculation(data)
async createWithDetails(salaryData, detailsData[])
async updateCalculation(id: string, data)
async deleteCalculation(id: string)
// --- Settings --- //
async getSettings()
// Default: { bhxh_rate: 8, bhyt_rate: 1.5, bhtn_rate: 1, cdp_rate: 1 }
async saveSettings(settings)
// --- Advances --- //
async getAdvancesForWorker(workerId: number, month: number, year: number)
async createAdvance(data)
}
src/salary/salary-calculator.service.ts
CORE ENGINE — migrate from salary-auto-calculator.ts:
import { Injectable, Logger } from '@nestjs/common';
import { UpstreamTokenService } from '../auth/upstream-token.service';
import { SalaryService } from './salary.service';
@Injectable()
export class SalaryCalculatorService {
private readonly logger = new Logger(SalaryCalculatorService.name);
constructor(
private readonly upstreamTokens: UpstreamTokenService,
private readonly salaryService: SalaryService,
) {}
async calculateForWorker(workerId: number, month: number, year: number) {
// STEP 1: Fetch all data in parallel
const [settings, worker, advances, productions, allPrices] = await Promise.all([
this.salaryService.getSettings(),
this.getWorker(workerId),
this.getAdvances(workerId, month, year),
this.getProductions(workerId, month, year),
this.getLatexPrices(),
]);
// STEP 2: Calculate product details with dynamic prices
const details = this.calculateProductDetails(productions, allPrices);
// STEP 3: Aggregate by latex type
const summary = this.aggregateByLatexType(productions);
// STEP 4: Gross salary
const gross_salary = details.reduce((sum, d) => sum + d.amount, 0);
// STEP 5: Insurance deductions (based on insurance_salary, NOT gross)
const insuranceBase = worker.insurance_salary || 0;
const bhxh_amount = Math.round(insuranceBase * (settings.bhxh_rate / 100));
const bh_yt_amount = Math.round(insuranceBase * (settings.bhyt_rate / 100));
const bh_tn_amount = Math.round(insuranceBase * (settings.bhtn_rate / 100));
// STEP 5.1: CDP = (gross - insurance) * cdp_rate
const cdp_amount = Math.round(
(gross_salary - bhxh_amount - bh_yt_amount - bh_tn_amount) * (settings.cdp_rate / 100)
);
// STEP 6: Advances total
const advance_amount = advances.reduce((sum, a) => sum + a.amount, 0);
// STEP 7: Net salary
const net_salary = gross_salary - bhxh_amount - bh_yt_amount - bh_tn_amount - cdp_amount - advance_amount;
return {
totalSalary: net_salary,
gross_salary, bhxh_amount, bh_yt_amount, bh_tn_amount,
cdp_amount, advance_amount, net_salary,
details, summary,
};
}
async calculateTeamReview(teamId: number, month: number | null, year: number) {
// Bulk calculate for all workers in a team
// Same logic as calculateForWorker but for entire team
// Returns: { workerId, full_name, worker_code, accumulatedSalary, details, summary }[]
}
// --- Private helpers --- //
private calculateProductDetails(productions: any[], allPrices: any[]) {
// Group by latex_type + priceId + priceVal
// Priority: applied_price on record -> lookup latex_prices by date
// amount = quantity_kg * price_per_kg
}
private aggregateByLatexType(productions: any[]) {
// Returns { fresh: number, coagulated: number, secondary: number }
}
private async getWorker(workerId: number) { /* Directus: /items/workers/:id */ }
private async getAdvances(workerId: number, month: number, year: number) { /* /items/salary_advances */ }
private async getProductions(workerId: number, month: number, year: number) { /* /items/latex_production */ }
private async getLatexPrices() { /* /items/latex_prices */ }
}
2.3 DTOs
// dto/calculate-salary.dto.ts
export class CalculateSalaryDto {
workerId: number; // required
month: number; // 1-12
year: number; // e.g. 2026
}
// dto/calculate-team-review.dto.ts
export class CalculateTeamReviewDto {
teamId: number;
month?: number; // null = whole year
year: number;
}
// dto/create-salary-calculation.dto.ts
export class CreateSalaryCalculationDto {
month: number;
year: number;
worker_id: number;
production_team_id?: number;
gross_salary: number;
bhxh_amount?: number;
bh_yt_amount?: number;
bh_tn_amount?: number;
cdp_amount?: number;
advance_amount?: number;
net_salary: number;
}
// dto/salary-settings.dto.ts
export class SalarySettingsDto {
bhxh_rate?: number; // default 8
bhyt_rate?: number; // default 1.5
bhtn_rate?: number; // default 1
cdp_rate?: number; // default 1
}
// dto/salary-advance.dto.ts
export class SalaryAdvanceDto {
worker_id: number;
amount: number;
advance_date: string; // YYYY-MM-DD
note?: string;
status?: 'pending' | 'approved' | 'deducted';
}
2.4 Salary Calculation Formulas (Reference)
From salary-auto-calculator.ts:
GROSS = sum(quantity_kg * price_per_kg) for all production records
- price priority: applied_price on record -> latex_prices effective date lookup
BHXH = insurance_salary * 8%
BHYT = insurance_salary * 1.5%
BHTN = insurance_salary * 1%
CDP = (GROSS - BHXH - BHYT - BHTN) * 1%
NET = GROSS - BHXH - BHYT - BHTN - CDP - ADVANCES
2.5 Known Issues to Fix During Migration
| # | Issue | Source | Fix |
|---|---|---|---|
| 1 | salary-form shows "Cong doan (0.5%)" but default is 1% | salary-form.tsx:178 | Fix label in frontend |
| 2 | total_salary = net_salary (alias, confusing) | salary-service.ts | Use consistent naming |
| 3 | calculateTeamReview only computes gross, not net | salary-auto-calculator.ts:282 | Add net calculation in BFF |
| 4 | insurance_salary = 0 means no deductions except CDP | salary-auto-calculator.ts:41 | Document behavior |
| 5 | No role-based permission for salary CRUD | salary-service.ts | Add auth guard to BFF endpoints |
Phase 3: Integration & Migration
3.1 Register Modules in app.module.ts
// src/app.module.ts
import { DrcModule } from './drc/drc.module';
import { SalaryModule } from './salary/salary.module';
@Module({
imports: [
ConfigModule.forRoot(),
AuthModule,
HttpProxyModule.register(),
RideNDineModule,
OnboardingModule,
DrcModule, // NEW
SalaryModule, // NEW
],
})
export class AppModule {}
3.2 Frontend Migration Strategy
Step 1: Update Frontend Service Layer
- Replace Directus SDK calls with BFF API calls
features/salary-calculation/services/salary-auto-calculator.ts-> callPOST /api/salary/calculatefeatures/salary-calculation/services/salary-service.ts-> callGET/POST/PATCH/DELETE /api/salary/calculationsfeatures/quality-control/services/quality-control-service.directus.ts-> call/api/drc/evaluations
Step 2: Remove Directus Dependency from Frontend
- Frontend no longer talks to Directus directly for DRC/salary
- All data flows through BFF (server-side auth injection)
- Frontend only calls BFF REST API
Step 3: Update Hooks
use-auto-salary-calculation.ts-> fetch from BFF endpointuse-warehouse-analytics.ts-> fetch from BFF analytics endpoint
3.3 Data Flow After Migration
Frontend (React Native)
|
| HTTP REST
v
rubber-bff (NestJS)
|
| UpstreamTokenService.directusRequest()
v
Directus (rubberapi.appmkt.vn)
|
| REST API
v
Database
3.4 Environment Variables
No new env vars needed. BFF already has:
DIRECTUS_URL- Directus API base URLDIRECTUS_EMAIL/DIRECTUS_PASSWORD- Admin credentials for server-side auth
Implementation Order
| Step | Task | Estimated Lines | Dependencies |
|---|---|---|---|
| 1 | Create src/drc/dto/ (3 files) | ~40 | None |
| 2 | Create src/drc/drc.service.ts | ~180 | UpstreamTokenService |
| 3 | Create src/drc/drc.controller.ts | ~100 | DrcService |
| 4 | Create src/drc/drc.module.ts | ~12 | DrcController, DrcService |
| 5 | Create src/salary/dto/ (5 files) | ~80 | None |
| 6 | Create src/salary/salary.service.ts | ~150 | UpstreamTokenService |
| 7 | Create src/salary/salary-calculator.service.ts | ~250 | SalaryService, UpstreamTokenService |
| 8 | Create src/salary/salary.controller.ts | ~120 | SalaryService, SalaryCalculatorService |
| 9 | Create src/salary/salary.module.ts | ~15 | All salary files |
| 10 | Update src/app.module.ts | ~5 | DrcModule, SalaryModule |
| 11 | Update frontend services to call BFF | ~200 | All BFF endpoints ready |
Total new code: ~1,150 lines in BFF
Testing Checklist
-
npm run buildpasses - All DRC endpoints return correct data from Directus
- DRC weighted analytics matches frontend calculation
- DRC dashboard analytics matches frontend calculation
- Salary auto-calculation produces same result as frontend
- Team review calculation produces same result as frontend
- Insurance deductions calculated correctly (base on insurance_salary)
- CDP calculated on (gross - insurance)
- Net salary = gross - all deductions - advances
- Dynamic price lookup works (applied_price priority, then latex_prices fallback)
- Settings singleton read/write works
- Advances CRUD works
- Frontend successfully calls BFF endpoints instead of Directus