Files
FE-DEVICE-SGW/CLAUDE.md
2025-11-20 16:21:17 +07:00

10 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

This is a React-based Ship Monitoring System (Hệ thống giám sát tàu cá) built with UmiJS Max framework for Mobifone. The application provides real-time monitoring of fishing vessels with GPS tracking, alarm management, and trip logging capabilities.

Domain: Maritime & Fishing Industry Target Users: Fishing vessel operators and monitoring centers Language: Vietnamese (Primary) with English development comments

Technology Stack

Core Framework

  • UmiJS Max 4.5.0 - Enterprise-level React application framework
  • React 18 - UI library with hooks and functional components
  • TypeScript - Type-safe JavaScript
  • Ant Design 5.x - UI component library with Pro Components
  • TailwindCSS - Utility-first CSS framework

Mapping & Visualization

  • OpenLayers 10.6.1 - Interactive maps and geospatial visualization
  • GeoJSON - Geospatial data format
  • WKT (Well-Known Text) - Geometry representation

State Management

  • UmiJS Model Plugin - Global state management
  • Event Bus Pattern - Custom event-driven communication
  • React Hooks - Local state management

Development Tools

  • Husky + Lint-staged - Git hooks for code quality
  • Prettier - Code formatting
  • ESLint - Code linting
  • pnpm - Package manager

Project Structure

src/
├── app.tsx                 # Global app configuration & layout
├── access.ts              # User permissions & access control
├── constants/             # Application constants & enums
│   ├── index.ts          # Global constants
│   └── enums.ts          # Application enums
├── models/               # Global state models (UmiJS Model plugin)
│   ├── global.ts         # Global state
│   ├── getTrip.ts        # Trip management state
│   └── getSos.ts         # SOS/Alarm state
├── pages/                # Application pages (routes)
│   ├── Auth/            # Authentication page
│   ├── Home/            # Map monitoring page
│   └── Trip/            # Trip management page
├── components/           # Reusable UI components
│   ├── 403/             # Access denied page
│   ├── 404/             # Not found page
│   ├── 500/             # Server error page
│   └── Footer/           # Footer component
├── services/             # API services & controllers
│   ├── controller/      # API endpoint controllers
│   │   ├── AuthController.ts
│   │   ├── DeviceController.ts
│   │   ├── MapController.ts
│   │   ├── TripController.ts
│   │   └── UserController.ts
│   └── service/         # Business logic services
│       └── MapService.ts
├── utils/               # Utility functions
│   ├── eventBus.ts      # Custom event bus
│   ├── localStorageUtils.ts
│   ├── jwtTokenUtils.ts
│   ├── mapUtils.ts
│   ├── geomUtils.ts
│   ├── format.ts
│   └── cacheStore.ts
├── types/               # TypeScript type definitions
│   └── geojson.d.ts
├── assets/              # Static assets (icons, images)
└── .umi-production/     # UmiJS build artifacts (auto-generated)

Key Architectural Patterns

1. Event-Driven Architecture

The application uses a custom Event Bus pattern for decoupled component communication:

// src/utils/eventBus.ts
export const eventBus = new EventBus();

// Components emit events
eventBus.emit('gpsData:update', data);

// Components listen to events
eventBus.on('gpsData:update', handleUpdate);

Key Events:

  • gpsData:update - GPS position updates
  • ship:update - Ship marker updates
  • alarm:update - Alarm status changes
  • trackpoints:update - Track history updates
  • entities:update - Geographic entities updates

2. Real-time Data Flow

GPS API (5s interval) → Event Bus → Multiple Components
                    ↓
            Ship Marker Updates
            Alarm Status Updates
            Track History Updates
            Zone Boundary Updates

3. Controller Pattern

API endpoints are organized in controllers following REST conventions:

// src/services/controller/DeviceController.ts
export async function getGPS(): Promise<API.GPSResponse>
export async function queryAlarms(): Promise<API.AlarmResponse>
export async function queryEntities(): Promise<API.EntityResponse[]>

4. UmiJS Model Pattern

Global state management using UmiJS Models:

// src/models/getTrip.ts
export default function useGetTripModel() {
  const [data, setData] = useState<API.Trip | null>(null);
  const getApi = useCallback(async () => {
    // API call and state update
  }, []);
  return { data, loading, getApi };
}

Development Workflow

Available Scripts

npm run dev      # Start development server
npm run build    # Build for production
npm run format   # Format code with Prettier
npm run setup    # Initial setup

Package Management

  • Primary: pnpm (configured in .umirc.ts)
  • Fallback: npm

Code Quality Tools

  • Prettier: Code formatting (80 char width, single quotes)
  • ESLint: Code linting via UmiJS max lint
  • Husky: Git hooks for pre-commit checks
  • Lint-staged: Staged file processing

Environment Configuration

  • Development: REACT_APP_ENV=dev (localhost:8000)
  • Test: REACT_APP_ENV=test (test server)
  • Production: REACT_APP_ENV=prod (production server)

Key Features & Components

1. Real-time GPS Monitoring (/map)

  • VietNamMap: Interactive OpenLayers map
  • Ship Tracking: Real-time vessel position updates
  • Alarm Management: Visual alert system
  • Zone Boundaries: Geographic restriction zones
  • SOS Functionality: Emergency button

2. Trip Management (/trip)

  • Trip Creation/Update: Fishing trip lifecycle
  • Haul Logging: Fish catch records
  • Crew Management: Team member tracking
  • Cost Tracking: Expense management
  • Alarm Table: Real-time alerts display

3. Authentication System

  • JWT Token Management: Secure authentication
  • Auto-refresh: Token expiration handling
  • Route Protection: Login redirects

4. Dynamic API Configuration

The application supports dynamic API endpoints based on deployment environment:

// Auto-detects device IP and configures API accordingly
const deviceApiUrl = `http://${window.location.hostname}:81`;

Map & Geospatial Features

Map Components

  • VietNamMap: Main map component
  • BaseMap: OpenLayers integration
  • MapManager: Map state and interaction management

Geographic Data

  • GPS Coordinates: WGS84 format
  • GeoJSON: Layer data format
  • WKT: Well-Known Text for geometries
  • Zone Types: Fishing zones, restricted areas

Ship Icons & States

  • Online/Offline: Connection status
  • Fishing/Non-fishing: Activity state
  • Alarm Levels: Warning, alarm, SOS states
  • Custom Icons: Activity-specific markers

API Integration

Base URL Configuration

  • Development: http://192.168.30.103:81
  • Test: https://test-sgw-device.gms.vn
  • Production: https://prod-sgw-device.gms.vn

Key API Endpoints

GPS: /api/sgw/gps
Trips: /api/sgw/trip
Alarms: /api/io/alarms
Entities: /api/io/entities
Ship Info: /api/sgw/shipinfo
SOS: /api/sgw/sos

Request Interceptors

  • Authentication: JWT token injection
  • Error Handling: Global error management
  • Timeout: 20-second timeout

State Management

Global State Models

  1. global.ts - User authentication state
  2. getTrip.ts - Trip management state
  3. getSos.ts - SOS and alarm state

Local State Patterns

  • useState: Local component state
  • useEffect: Side effects and subscriptions
  • useCallback: Function memoization
  • useRef: DOM references and persistent values

Development Guidelines

Code Style

  • TypeScript: Strict typing enabled
  • Component Structure: Functional components with hooks
  • File Naming: PascalCase for components, camelCase for functions
  • Import Organization: Third-party libs → Local imports

Best Practices

  1. Error Boundaries: Implement error boundaries for maps
  2. Performance: Use React.memo for expensive components
  3. Memory Management: Clean up event listeners and intervals
  4. API Calls: Use proper error handling and loading states
  5. Type Safety: Define TypeScript interfaces for all API responses

Testing Approach

  • Component Testing: React Testing Library (if added)
  • Integration Testing: Manual testing with real API endpoints
  • E2E Testing: Browser testing scenarios

Deployment

Build Process

npm run build
# Creates dist/ folder for deployment

Static Deployment

  1. Build application
  2. Copy dist folder to target device
  3. Serve via web server (nginx, apache, etc.)
  4. Ensure backend API runs on port 81

Multi-Device Support

  • Auto-detection: Application detects device IP
  • Dynamic API: Base URL configured automatically
  • CORS: Ensure proper CORS configuration on backend

Troubleshooting

Common Issues

  1. Map Loading: Check OpenLayers dependencies
  2. API Calls: Verify proxy configuration and network access
  3. Event Bus: Ensure proper event listener cleanup
  4. State Management: Check model initialization
  5. Authentication: Verify JWT token expiration

Debug Mode

  • Enable console logging for GPS updates
  • Check network requests in browser dev tools
  • Monitor event bus emissions
  • Verify map coordinate transformations

Contributing

Adding New Features

  1. Create new page in src/pages/
  2. Add route in .umirc.ts
  3. Create API controller in src/services/controller/
  4. Add TypeScript types in src/types/
  5. Update constants in src/constants/

Code Review Checklist

  • TypeScript types defined
  • Error handling implemented
  • Performance considerations
  • Accessibility compliance
  • Code style guidelines followed
  • Testing coverage (if applicable)

Last Updated: 2025-01-20 Maintainers: Mobifone Development Team Version: 1.2.2 - Dynamic API