Django React Logistics Portal Expert
Expert system for working with a logistics management portal built with Django REST Framework backend and React/TypeScript frontend. Specializes in dual-database architecture, JWT authentication, multi-step forms, and SQL Server WMS integration.
Architecture Overview
This skill provides deep understanding of a logistics portal with:
**Backend**: Django REST Framework with ViewSet-based APIs, JWT authentication, Swagger/ReDoc documentation**Frontend**: React/TypeScript with Material UI, Axios-based API clients, context-based state management**Dual Database Strategy**: - PostgreSQL for application data (orders, users, configuration)
- SQL Server (FootPrint WMS) for real-time inventory and operational data
**Integration Pattern**: Each database serves a specific purpose with minimal cross-migrationStep-by-Step Instructions
1. Understanding the Codebase Structure
When working with this project:
**Backend Structure**:
Examine `/server/` directory for Django appsReview Django apps: `common`, `enterprise`, `inventory`, `logistics`, `materials`, `orders`, `reports`, `users`Check `/reports/sql/` for raw SQL queries organized by category (inventory, materials, orders)Review database configurations in Django settings**Frontend Structure**:
Examine `/client/src/` for React componentsReview feature-based organization: `components/`, `hooks/`, `utils/`, `services/api/`Check `services/api/secureApi.ts` for protected endpointsReview `services/api/authApi.ts` for authentication logic**Key Integration Points**:
Authentication flow: JWT tokens stored in cookies with automatic 19-minute refreshAPI structure: Core endpoints under `/api/`, auth under `/api/auth/`, admin at `/admin/`Database access pattern: Django ORM for PostgreSQL, raw SQL for SQL Server WMS2. Working with the Dual-Database Architecture
When implementing features involving inventory or reports:
**PostgreSQL (Application Database)**:
Use Django ORM for CRUD operations on orders, users, configurationStandard model definitions in each Django appMigrations managed via `python manage.py migrate`**SQL Server (WMS Database)**:
Connect via pyodbc for direct SQL queriesStore SQL queries in `/reports/sql/` organized by categoryUse SQLReportManager for parameterized SQL executionAccess real-time inventory, material data, and operational reportsNever modify WMS data directly—read-only access**Cross-Database Patterns**:
Materials: Display from SQL Server, store selected items in PostgreSQLAuto-create missing materials in PostgreSQL when found in WMSUse SQL Server for inventory availability checkingUse PostgreSQL for order management and application state3. Implementing New Features
When adding functionality:
**Backend Development**:
```bash
cd server
python manage.py startapp [app_name] # If creating new app
python manage.py makemigrations
python manage.py migrate
python manage.py test [app_name]
```
**Frontend Development**:
```bash
cd client
npm start # Development server
npx tsc --noEmit # Type checking
npx eslint src/**/*.{ts,tsx} # Linting
npm run build # Production build
```
**Code Style Requirements**:
**All code must be in English**: variables, functions, classes, components, comments, documentationTypeScript: Strict type checking, explicit interfaces for API responsesReact: Functional components with hooks, avoid class componentsImports: Group external/internal, alphabetical orderNaming: PascalCase for components, camelCase for functions/variablesDjango: Follow PEP 8, snake_case for methodsError handling: try/catch in async functions, descriptive messages4. Working with Key Feature Sections
**Dashboard Section**:
Components: `Dashboard.tsx`, `OrdersSection.tsx`, `OrdersTable.tsx`, `DashboardFilters.tsx`Features: Order management, type filtering (Outbound/Inbound), search, status visualizationData flow: Loads orders/statuses on render, local state for filters, DashboardUtils for filtering**Create Order Section** (Multi-Step Wizard):
Container: `MultiStepCreateOrder.tsx` orchestrates flowStep 1 (Order Details): `OrderDetailsForm.tsx` with sub-forms for basic info, logistics, delivery, additional infoStep 2 (Material Selection): `MaterialSelectionStep.tsx` with cascading search (Material → Lot → License Plate)Step 3 (Review): `OrderSummary.tsx` with section-based previewState management: `formReducer.ts` with centralized reducer patternCustom hooks: `useReferenceData`, `useInventoriesAndMaterials`, `useMaterialSelection`, `useContactForm`Validation: Field-level and step-level via `OrderValidation.ts`Cross-database: Materials from SQL Server WMS, orders stored in PostgreSQL**Reports Section**:
Components: `Reports.tsx`, `ReportSelector.tsx`, `ReportTable.tsx`, `DownloadMenu.tsx`Data source: SQL Server WMS via raw SQL queriesExport formats: CSV, Excel (styled), PDF (professional layout)Backend utilities: `export_utils.py` with `generate_csv()`, `generate_excel()`, `generate_pdf()`Custom hooks: `useReportsData`, `useTableControls`, `useTableScroll`, `useDownloadMenu`5. API Integration Patterns
**Authentication**:
JWT tokens stored in cookies with httpOnly flagAutomatic refresh every 19 minutes via `authApi.ts`Protected routes use `secureApi.ts` with credential handlingLogout clears tokens and redirects to login**Protected Endpoints**:
```typescript
// Use secureApi for authenticated requests
import secureApi from '@/services/api/secureApi';
const response = await secureApi.get('/api/endpoint/');
```
**Error Handling**:
```typescript
try {
const response = await secureApi.post('/api/endpoint/', data);
// Handle success
} catch (error) {
// Display user-friendly error via Snackbar
console.error('Operation failed:', error);
}
```
6. Database Query Patterns
**Django ORM (PostgreSQL)**:
```python
Standard CRUD operations
from orders.models import Order
orders = Order.objects.filter(status='active').select_related('project')
```
**Raw SQL (SQL Server WMS)**:
```python
Store queries in /reports/sql/ directory
Use SQLReportManager for execution
from reports.sql_manager import SQLReportManager
manager = SQLReportManager()
results = manager.execute_query('inventory/by_project.sql', {'project_id': 123})
```
7. Testing Strategy
**Backend Tests**:
```bash
cd server
python manage.py test [app_name.tests.test_file]
python manage.py test # Run all tests
```
**Frontend Tests**:
```bash
cd client
npm test # Run test suite
npm test -- --coverage # With coverage report
```
8. Common Development Workflows
**Adding a New API Endpoint**:
1. Create/update Django ViewSet in appropriate app
2. Register route in app's `urls.py`
3. Create TypeScript interface for response type
4. Add API client method in `services/api/secureApi.ts`
5. Create React hook for data fetching if needed
6. Update Swagger documentation
**Adding a New Report**:
1. Create SQL query file in `/reports/sql/[category]/`
2. Register report definition in Django
3. Add export endpoint if needed
4. Update `ReportSelector.tsx` options
5. Test with real WMS data
**Creating a New Multi-Step Form**:
1. Create container component with step navigation
2. Implement `formReducer` for state management
3. Create step components with validation
4. Add custom hooks for data fetching
5. Implement API integration for form submission
6. Add error handling and user feedback
Constraints
**Language**: All code must be written in English (variables, functions, comments, documentation)**Database Access**: Never directly modify SQL Server WMS data—read-only access only**Authentication**: All protected routes must use JWT authentication with cookie storage**Error Handling**: Always provide user-friendly error messages, log details server-side**Type Safety**: Maintain strict TypeScript checking, explicit interfaces for all API responses**State Management**: Use React Context for app-wide state, local state for component-specific data**SQL Queries**: Store all SQL queries in `/reports/sql/` directory, use parameterized queries**Component Size**: Keep components small and reusable, extract logic into custom hooksExamples
Example 1: Adding a New Dashboard Filter
```typescript
// In DashboardFilters.tsx
interface FilterState {
searchTerm: string;
orderType: 'outbound' | 'inbound' | 'all';
dateRange: { start: Date; end: Date };
}
const [filters, setFilters] = useState<FilterState>({
searchTerm: '',
orderType: 'all',
dateRange: { start: new Date(), end: new Date() }
});
// Apply filters using DashboardUtils
const filteredOrders = DashboardUtils.filterOrders(orders, filters);
```
Example 2: Creating a New SQL Report
```sql
-- /reports/sql/inventory/by_warehouse.sql
SELECT
warehouse_code,
material_code,
SUM(quantity) as total_quantity,
COUNT(DISTINCT license_plate) as license_plate_count
FROM inventory
WHERE warehouse_code = %(warehouse_code)s
AND status = 'available'
GROUP BY warehouse_code, material_code
ORDER BY total_quantity DESC
```
Example 3: Multi-Step Form with Cross-Database Integration
```typescript
// In useMaterialSelection.ts
const handleMaterialSelect = async (materialCode: string) => {
// Fetch from SQL Server WMS
const inventory = await fetchInventory(materialCode);
// Check if material exists in PostgreSQL
let material = await secureApi.get(`/api/materials/${materialCode}/`);
if (!material) {
// Auto-create in PostgreSQL if found in WMS
material = await secureApi.post('/api/materials/', {
code: materialCode,
description: inventory.description,
// ... other fields from WMS
});
}
// Add to order with PostgreSQL material ID
dispatch({ type: 'ADD_MATERIAL', payload: { material, quantity } });
};
```
Important Notes
This system manages enterprise logistics with real-time WMS integrationThe dual-database approach separates application state from operational dataMaterial selection involves complex cascading filters and real-time inventory validationAll authentication uses JWT with automatic refresh to maintain sessionsReports pull live data from SQL Server WMS for accurate operational insightsThe multi-step order creation process ensures data integrity across both databases