Skip to content

Quy trình phát triển phần mềm với one-toolkit (SDLC thực tế)

Tổng quan workflow

one-toolkit áp dụng SDLC chuẩn với 5 phases chính:

Requirements → Design → Planning → Implementation → Testing

Mỗi phase có:

  • Mục tiêu rõ ràng: Làm gì
  • Ràng buộc: AI được phép/không được phép làm gì
  • Output cụ thể: Deliverable là gì
  • Validation: Làm sao biết phase xong

Phase 1: Requirements Analysis

Mục tiêu

Hiểu rõ vấn đề cần giải quyết trước khi nghĩ về giải pháp.

AI được phép làm gì

Được phép:

  • Hỏi câu hỏi làm rõ về feature
  • Viết problem statement
  • Tạo user stories theo format chuẩn
  • Định nghĩa success criteria (measurable)
  • Liệt kê constraints và assumptions
  • Identify edge cases và open questions

Ví dụ output tốt:

markdown
## Problem Statement
Users cannot track their daily expenses, leading to poor budget management.
Currently, they use spreadsheets which are error-prone and time-consuming.

## User Stories
- As a user, I want to add expenses quickly so that I don't forget them
- As a user, I want to categorize expenses so that I can see spending patterns
- As a user, I want to set monthly budgets so that I can control spending
- As a user, I want to see reports so that I can analyze my finances

## Success Criteria
- User can add expense in < 10 seconds
- Categories are customizable
- Budget alerts work in real-time
- Reports show data for last 12 months
- Mobile-friendly interface

## Constraints
- Must work offline (sync when online)
- Must support multiple currencies
- Data must be encrypted at rest
- Must comply with GDPR

## Edge Cases
- What if user adds expense without internet?
- What if expense is in foreign currency?
- What if user exceeds budget?

AI KHÔNG được phép làm gì

Không được phép:

  • Viết code
  • Chọn technology stack (React vs Vue, SQL vs NoSQL)
  • Thiết kế database schema
  • Đề xuất architecture
  • Estimate effort

Ví dụ output SAI:

markdown
## Requirements
User needs expense tracking.

## Solution
We'll use React + Node.js + MongoDB.
Database schema:
{
  expense: {
    amount: Number,
    category: String
  }
}

Sai vì: Đã nhảy sang design và implementation, chưa làm rõ requirements.

Output mong đợi

File: docs/agent/requirements/feature-{name}.md

Nội dung:

  • ✅ Problem statement rõ ràng
  • ✅ 5-10 user stories chi tiết
  • ✅ Success criteria có thể đo được
  • ✅ Constraints và assumptions
  • ✅ Edge cases và open questions

Validation

Phase này xong khi:

  • [ ] Stakeholders đồng ý với problem statement
  • [ ] User stories cover tất cả use cases chính
  • [ ] Success criteria có thể test được
  • [ ] Không còn open questions quan trọng

Command để dùng

/new-requirement          # Bắt đầu requirements
/review-requirements      # Review requirements doc

Phase 2: System Design

Mục tiêu

Thiết kế giải pháp kỹ thuật để đáp ứng requirements.

AI được phép làm gì

Được phép:

  • Đề xuất system architecture
  • Thiết kế database schema
  • Define API endpoints
  • Vẽ architecture diagrams (Mermaid)
  • Chọn technology stack (với rationale)
  • Document design decisions và trade-offs
  • Identify integration points
  • Define non-functional requirements (performance, security)

Ví dụ output tốt:

markdown
## Architecture Overview

```mermaid
graph TD
    Client[Mobile App] -->|HTTPS| API[API Gateway]
    API --> Auth[Auth Service]
    API --> Expense[Expense Service]
    Expense --> Cache[(Redis Cache)]
    Expense --> DB[(PostgreSQL)]
    Expense --> Queue[Message Queue]
    Queue --> Sync[Sync Service]

Data Models

typescript
interface Expense {
  id: string;
  userId: string;
  amount: number;
  currency: string;
  category: string;
  date: Date;
  description?: string;
  syncStatus: 'pending' | 'synced';
  createdAt: Date;
  updatedAt: Date;
}

interface Category {
  id: string;
  userId: string;
  name: string;
  color: string;
  icon: string;
}

interface Budget {
  id: string;
  userId: string;
  categoryId: string;
  amount: number;
  period: 'monthly' | 'yearly';
  startDate: Date;
}

API Design

Endpoints

  • POST /api/expenses - Create expense
  • GET /api/expenses - List expenses (with filters)
  • PUT /api/expenses/:id - Update expense
  • DELETE /api/expenses/:id - Delete expense
  • GET /api/expenses/stats - Get statistics

Request/Response

json
POST /api/expenses
{
  "amount": 50.00,
  "currency": "USD",
  "category": "food",
  "date": "2024-01-15",
  "description": "Lunch"
}

Response 201:
{
  "id": "exp_123",
  "amount": 50.00,
  "currency": "USD",
  "category": "food",
  "date": "2024-01-15",
  "syncStatus": "synced"
}

Design Decisions

Why PostgreSQL over MongoDB?

  • Need ACID transactions for financial data
  • Complex queries for reports
  • Strong consistency required

Why Redis cache?

  • Frequently accessed data (categories, budgets)
  • Reduce DB load
  • Fast response times

Why message queue for sync?

  • Handle offline mode
  • Retry failed syncs
  • Decouple services

Non-Functional Requirements

  • Response time: < 200ms for API calls
  • Offline support: 30 days of local data
  • Encryption: AES-256 for data at rest
  • Availability: 99.9% uptime

### AI KHÔNG được phép làm gì

❌ **Không được phép**:
- Viết implementation code
- Break down thành tasks chi tiết
- Viết tests
- Estimate effort cho từng task

❌ **Ví dụ output SAI**:

```markdown
## Design
Use React for frontend.

## Implementation
```typescript
// expense.service.ts
export class ExpenseService {
  async create(data) {
    // implementation code here
  }
}

Tasks:

  • [ ] Setup React project (2 hours)
  • [ ] Create ExpenseService (3 hours)

→ **Sai vì**: Đã nhảy sang implementation và planning.

### Output mong đợi

**File**: `docs/agent/design/feature-{name}.md`

**Nội dung**:
- ✅ Architecture diagram (Mermaid)
- ✅ Data models với types đầy đủ
- ✅ API design với request/response examples
- ✅ Design decisions với rationale
- ✅ Non-functional requirements
- ✅ Integration points
- ✅ Security considerations

### Validation

Phase này xong khi:
- [ ] Architecture hợp lý và scalable
- [ ] Data models cover tất cả requirements
- [ ] API design RESTful và consistent
- [ ] Design decisions được justify
- [ ] Tech lead approve design

### Command để dùng

/review-design # Review và update design doc


---

## Phase 3: Planning

### Mục tiêu

Chia nhỏ công việc thành tasks có thể thực thi.

### AI được phép làm gì

✅ **Được phép**:
- Break down design thành tasks cụ thể
- Identify dependencies giữa tasks
- Suggest implementation order
- Estimate effort (rough)
- Group tasks thành milestones
- Identify risks và mitigation strategies
- Tạo task list với checkboxes

✅ **Ví dụ output tốt**:

```markdown
## Task Breakdown

### Milestone 1: Foundation (Est: 1 day)
- [ ] Setup project structure
- [ ] Configure database (PostgreSQL)
- [ ] Setup Redis cache
- [ ] Create database migrations
- [ ] Setup authentication middleware

### Milestone 2: Core Expense API (Est: 2 days)
- [ ] Create Expense model
- [ ] Implement POST /api/expenses
- [ ] Implement GET /api/expenses (with pagination)
- [ ] Implement PUT /api/expenses/:id
- [ ] Implement DELETE /api/expenses/:id
- [ ] Add input validation
- [ ] Add error handling

### Milestone 3: Categories & Budgets (Est: 1.5 days)
- [ ] Create Category model
- [ ] Implement category CRUD endpoints
- [ ] Create Budget model
- [ ] Implement budget CRUD endpoints
- [ ] Add budget alert logic

### Milestone 4: Offline Sync (Est: 2 days)
- [ ] Setup message queue (RabbitMQ)
- [ ] Implement sync service
- [ ] Add conflict resolution logic
- [ ] Handle offline data storage
- [ ] Test sync scenarios

### Milestone 5: Reports & Analytics (Est: 1 day)
- [ ] Implement GET /api/expenses/stats
- [ ] Add date range filters
- [ ] Add category grouping
- [ ] Optimize queries for performance

### Milestone 6: Testing (Est: 1.5 days)
- [ ] Unit tests for models
- [ ] Unit tests for services
- [ ] Integration tests for API endpoints
- [ ] E2E tests for critical flows
- [ ] Load testing

## Dependencies

```mermaid
graph TD
    A[Foundation] --> B[Core Expense API]
    A --> C[Categories & Budgets]
    B --> D[Offline Sync]
    C --> D
    B --> E[Reports]
    C --> E
    D --> F[Testing]
    E --> F

Implementation Order

  1. Foundation (must be first)
  2. Core Expense API (depends on Foundation)
  3. Categories & Budgets (parallel with Expense API)
  4. Offline Sync (depends on Expense API + Categories)
  5. Reports (depends on Expense API + Categories)
  6. Testing (after all features)

Effort Estimates

MilestoneTasksEffortPriority
Foundation51 dayP0
Core Expense API72 daysP0
Categories & Budgets61.5 daysP0
Offline Sync52 daysP1
Reports41 dayP1
Testing61.5 daysP0
Total339 days

Risks & Mitigation

RiskImpactProbabilityMitigation
Offline sync conflictsHighMediumImplement last-write-wins + user notification
Performance issues with large datasetsHighLowAdd pagination, caching, indexes
Currency conversion complexityMediumHighUse third-party API (exchangeratesapi.io)
Database migration failuresHighLowTest migrations in staging first

### AI KHÔNG được phép làm gì

❌ **Không được phép**:
- Implement tasks
- Viết code
- Thay đổi design
- Skip tasks

❌ **Ví dụ output SAI**:

```markdown
## Tasks
- [ ] Build the app
- [ ] Test it
- [ ] Deploy

## Code
```typescript
// Starting implementation...

Sai vì: Tasks quá vague, và đã bắt đầu code.

Output mong đợi

File: docs/agent/planning/feature-{name}.md

Nội dung:

  • ✅ Task breakdown chi tiết với checkboxes
  • ✅ Dependencies rõ ràng
  • ✅ Implementation order hợp lý
  • ✅ Effort estimates
  • ✅ Risk analysis

Validation

Phase này xong khi:

  • [ ] Tasks đủ chi tiết để implement
  • [ ] Dependencies được identify
  • [ ] Estimates hợp lý
  • [ ] Team đồng ý với plan

Command để dùng

/update-planning          # Update planning doc

Phase 4: Implementation

Mục tiêu

Viết code theo plan đã định.

AI được phép làm gì

Được phép:

  • Implement tasks theo thứ tự trong plan
  • Viết code theo design doc
  • Add error handling
  • Add logging
  • Refactor code (trong phạm vi task)
  • Update implementation notes
  • Ask questions nếu design không rõ

Ví dụ output tốt:

typescript
// src/models/expense.model.ts
// Implemented according to design doc

import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm';

@Entity('expenses')
export class Expense {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  userId: string;

  @Column('decimal', { precision: 10, scale: 2 })
  amount: number;

  @Column({ length: 3 })
  currency: string;

  @Column()
  category: string;

  @Column('date')
  date: Date;

  @Column({ nullable: true })
  description?: string;

  @Column({
    type: 'enum',
    enum: ['pending', 'synced'],
    default: 'pending'
  })
  syncStatus: 'pending' | 'synced';

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

Implementation notes được ghi vào docs/agent/implementation/feature-{name}.md:

markdown
## Implementation Notes

### Task: Create Expense model
- Used TypeORM decorators as per project standard
- Added decimal type for amount (precision 10, scale 2)
- Currency stored as ISO 4217 code (3 chars)
- syncStatus enum for offline sync tracking

### Patterns Used
- Repository pattern for data access
- DTO pattern for API validation
- Service layer for business logic

### Error Handling
- ValidationError for invalid input
- NotFoundError for missing resources
- SyncError for offline sync failures

### Integration Points
- ExpenseService → ExpenseRepository → Database
- ExpenseService → CacheService → Redis
- ExpenseService → QueueService → RabbitMQ

AI KHÔNG được phép làm gì

Không được phép:

  • Thay đổi design tùy tiện
  • Skip tasks trong plan
  • Implement features không có trong requirements
  • Ignore error handling
  • Skip logging

Ví dụ output SAI:

typescript
// Thay đổi design không thông báo
export class Expense {
  // Design doc nói dùng PostgreSQL, nhưng code dùng MongoDB
  @prop()
  amount: number;
}

// Implement feature không có trong requirements
async sendEmailNotification() {
  // Feature này không có trong requirements
}

// Skip error handling
async create(data) {
  return await this.repo.save(data); // No try-catch, no validation
}

Sai vì: Không follow design, thêm feature không cần, thiếu error handling.

Output mong đợi

Code:

  • ✅ Clean, readable code
  • ✅ Follow design doc
  • ✅ Proper error handling
  • ✅ Logging at key points
  • ✅ Comments cho complex logic

File: docs/agent/implementation/feature-{name}.md

  • ✅ Implementation notes
  • ✅ Patterns used
  • ✅ Integration points
  • ✅ Decisions made during implementation

Validation

Phase này xong khi:

  • [ ] Tất cả tasks trong plan được implement
  • [ ] Code follow design doc
  • [ ] Error handling đầy đủ
  • [ ] Code review pass

Command để dùng

/execute-plan             # Execute tasks từ planning doc
/check-implementation     # Verify implementation vs design

Phase 5: Testing

Mục tiêu

Verify implementation đáp ứng requirements.

AI được phép làm gì

Được phép:

  • Viết unit tests
  • Viết integration tests
  • Viết E2E tests
  • Generate test cases từ requirements
  • Test edge cases
  • Measure coverage
  • Suggest missing tests

Ví dụ output tốt:

typescript
// src/__tests__/expense.service.test.ts

describe('ExpenseService', () => {
  describe('create', () => {
    it('should create expense with valid data', async () => {
      const data = {
        userId: 'user_123',
        amount: 50.00,
        currency: 'USD',
        category: 'food',
        date: new Date('2024-01-15')
      };

      const result = await service.create(data);

      expect(result.id).toBeDefined();
      expect(result.amount).toBe(50.00);
      expect(result.syncStatus).toBe('pending');
    });

    it('should throw ValidationError for negative amount', async () => {
      const data = {
        userId: 'user_123',
        amount: -50.00, // Invalid
        currency: 'USD',
        category: 'food',
        date: new Date()
      };

      await expect(service.create(data)).rejects.toThrow(ValidationError);
    });

    it('should throw ValidationError for invalid currency', async () => {
      const data = {
        userId: 'user_123',
        amount: 50.00,
        currency: 'INVALID', // Not ISO 4217
        category: 'food',
        date: new Date()
      };

      await expect(service.create(data)).rejects.toThrow(ValidationError);
    });

    it('should handle offline mode correctly', async () => {
      // Simulate offline
      mockNetworkService.isOnline.mockReturnValue(false);

      const result = await service.create(validData);

      expect(result.syncStatus).toBe('pending');
      expect(mockQueueService.enqueue).toHaveBeenCalledWith('sync', result);
    });
  });
});

Test documentation trong docs/agent/testing/feature-{name}.md:

markdown
## Test Strategy

### Unit Tests
- All models
- All services
- All validators
- Target: 90% coverage

### Integration Tests
- API endpoints
- Database operations
- Cache operations
- Message queue operations
- Target: 80% coverage

### E2E Tests
- Complete user flows
- Offline sync scenarios
- Error scenarios

## Test Cases (from Requirements)

| Requirement | Test Case | Status |
|-------------|-----------|--------|
| User can add expense in < 10s | Test API response time | ✅ Pass |
| Categories are customizable | Test category CRUD | ✅ Pass |
| Budget alerts work real-time | Test budget threshold | ✅ Pass |
| Reports show 12 months data | Test date range filter | ✅ Pass |
| Offline mode works | Test offline sync | ✅ Pass |

## Coverage Report
File% Stmts% Branch% Funcs% Lines
expense.model.ts100100100100
expense.service.ts95.590.210095.8
expense.controller.ts92.385.710092.1
-------------------------------------------------------------
Total94.288.610094.5

## Missing Coverage
- Error handling in sync service (line 45-48)
- Edge case: concurrent updates (race condition)

## Manual Testing Checklist
- [ ] Test on iOS
- [ ] Test on Android
- [ ] Test offline → online transition
- [ ] Test with slow network
- [ ] Test with 10,000+ expenses

AI KHÔNG được phép làm gì

Không được phép:

  • Skip tests
  • Viết tests không cover requirements
  • Fake test results
  • Test implementation details thay vì behavior

Ví dụ output SAI:

typescript
// Test implementation detail, không test behavior
it('should call repository.save', async () => {
  await service.create(data);
  expect(mockRepo.save).toHaveBeenCalled(); // Testing implementation
});

// Test không có assertion
it('should create expense', async () => {
  await service.create(data);
  // No expect()
});

// Fake coverage
// Coverage: 100% (but many tests are empty)

Sai vì: Tests không meaningful, không verify requirements.

Output mong đợi

Test code:

  • ✅ Unit tests cho tất cả logic
  • ✅ Integration tests cho API
  • ✅ E2E tests cho critical flows
  • ✅ Coverage > 90%

File: docs/agent/testing/feature-{name}.md

  • ✅ Test strategy
  • ✅ Test cases map to requirements
  • ✅ Coverage report
  • ✅ Manual testing checklist

Validation

Phase này xong khi:

  • [ ] All tests pass
  • [ ] Coverage target met
  • [ ] All requirements have tests
  • [ ] Manual testing done

Command để dùng

/writing-test             # Generate tests

Phase 6: Review & Refactor (Bonus Phase)

Mặc dù không phải phase chính thức, nhưng đây là bước quan trọng.

Mục tiêu

Đảm bảo code quality trước khi merge.

AI được phép làm gì

Được phép:

  • Review code against design doc
  • Identify code smells
  • Suggest refactoring
  • Check for security issues
  • Verify error handling
  • Check performance issues

Command để dùng

/code-review              # Comprehensive code review

Tổng kết workflow

Start

/new-requirement → Requirements Phase → /review-requirements

Design Phase → /review-design

Planning Phase → /update-planning

Implementation Phase → /execute-plan → /check-implementation

Testing Phase → /writing-test

Review Phase → /code-review

Done (or loop back if issues found)

Key principles:

  1. Không nhảy phase: Phải hoàn thành phase hiện tại trước khi chuyển
  2. Output của phase trước là input của phase sau: Design dựa trên Requirements, Planning dựa trên Design
  3. Mỗi phase có deliverable cụ thể: Không phase nào "chỉ nói suông"
  4. AI bị ràng buộc bởi rules: Không được làm việc ngoài scope của phase

Lợi ích:

  • Code có chất lượng cao
  • Documentation đầy đủ
  • Dễ maintain và scale
  • Team collaboration tốt hơn
  • Ít technical debt

Tiếp theo: Xem ví dụ thực tế chi tiết → Xem phần tiếp theo.

Internal documentation for iNET Portal