Developer Guide & Best Practices
Comprehensive guide for developers working on the Compliance Scorecard project, including coding standards, best practices, and common patterns.
Coding Standards
PHP/Laravel Standards
React/JavaScript Standards
/**
* Policy Management Component
* Handles CRUD operations for client policies
*/
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchPolicies } from 'features/company/policiesActions';
const PolicyManagement = ({ clientId }) => {
const dispatch = useDispatch();
const { policies, loading, error } = useSelector(state => state.policies);
useEffect(() => {
if (clientId) {
dispatch(fetchPolicies({ clientId }));
}
}, [dispatch, clientId]);
// Component implementation
return (
// JSX here
);
};
Code Style Guidelines
- PHP: Follow PSR-12 coding standards
- JavaScript: Use ESLint with React recommended rules
- Naming: Use descriptive, self-documenting names
- Functions: Keep functions small and focused (single responsibility)
- Comments: Explain why, not what
Laravel Best Practices
Service Layer Pattern
documents()->create([
'content' => $this->generateContent($policy),
'status' => 'published',
'published_by' => $user->id,
]);
$this->notifyStakeholders($policy, $user);
return $document;
});
}
}
Resource Collections
$this->id,
'title' => $this->title,
'status' => $this->status,
'category' => new CategoryResource($this->whenLoaded('category')),
'documents' => PolicyDocumentResource::collection(
$this->whenLoaded('documents')
),
'created_at' => $this->created_at?->toISOString(),
];
}
}
Laravel Best Practices (polygon-be)
- Use service classes for complex business logic
- Implement proper validation with Form Requests
- Use database transactions for data consistency
- Implement proper error handling with custom exceptions
- Follow file header convention:
// File: path/to/file.php
- Use Eloquent relationships efficiently
- Implement caching for expensive operations
- Use queues for background processing
- Follow RESTful API design principles
- Use logging format:
Log::info("FILENAME.php LINE " . __LINE__ . " Message", $context)
React & Redux Patterns
Custom Hooks Pattern
// Custom hook for policy management
const usePolicyManager = (clientId) => {
const dispatch = useDispatch();
const { policies, loading, error } = useSelector(state => state.policies);
const fetchPolicies = useCallback(() => {
if (clientId) {
dispatch(fetchPoliciesAction({ clientId }));
}
}, [dispatch, clientId]);
const createPolicy = useCallback((policyData) => {
return dispatch(createPolicyAction({ clientId, ...policyData }));
}, [dispatch, clientId]);
return {
policies,
loading,
error,
fetchPolicies,
createPolicy,
};
};
Component Composition
// Composable components with proper prop types
const PolicyCard = ({ policy, onEdit, onDelete }) => (
{policy.title}
{policy.description}
onEdit(policy)} color="info" size="small">
Edit
onDelete(policy)} color="error" size="small">
Delete
);
PolicyCard.propTypes = {
policy: PropTypes.object.isRequired,
onEdit: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
};
React Best Practices (polygon-fe)
- Use functional components with hooks
- Implement proper error boundaries
- Use React.memo for performance optimization
- Follow the rules of hooks
- Use Material-UI components consistently
- Implement proper loading and error states
- Use custom hooks for reusable logic
- Keep components small and focused
- Use PropTypes or TypeScript for type checking
- Follow Redux Toolkit patterns for state management
Security Guidelines
Critical Security Practices
Backend Security
- Always validate and sanitize user input
- Use parameterized queries (Eloquent handles this)
- Implement proper authentication middleware
- Never expose sensitive data in API responses
- Use HTTPS in production
- Implement rate limiting
Frontend Security
- Sanitize data before rendering (use DOMPurify)
- Store tokens securely (not in localStorage for sensitive data)
- Implement CSP headers
- Validate all user inputs
- Use secure HTTP-only cookies when possible
- Implement proper error handling
Example: Secure API Call Pattern
// Secure API call with proper error handling
const createPolicy = async (policyData) => {
try {
// Validate input before sending
const validatedData = validatePolicyData(policyData);
const response = await axios.post('/api/v3/policies', validatedData, {
headers: {
'Authorization': `Bearer ${getToken()}`,
'Content-Type': 'application/json',
}
});
return response.data;
} catch (error) {
// Don't expose sensitive error information
if (error.response?.status === 401) {
redirectToLogin();
}
throw new Error('Failed to create policy');
}
};
Git Workflow
Branch Strategy
# Feature development workflow
git checkout dev
git pull origin dev
git checkout -b feature/PG3-1234-add-policy-approval
# Make your changes
git add .
git commit -m "feat: add policy approval workflow
- Implement approval state machine
- Add reviewer assignment logic
- Update UI for approval actions
Closes PG3-1234"
# Push and create PR
git push origin feature/PG3-1234-add-policy-approval
Commit Message Format
type(scope): description
- Detailed change 1
- Detailed change 2
Closes TICKET-123
Types: feat, fix, docs, style, refactor, test, chore
Branch Naming Convention
| Type | Format | Example |
|---|---|---|
| Feature | feature/PG3-####-description |
feature/PG3-1536-add-milestone-field |
| Bug Fix | bugfix/PG3-####-description |
bugfix/PG3-1540-fix-policy-approval |
| Hotfix | hotfix/description |
hotfix/security-patch-auth |
Testing Across Technologies
Backend Testing (PHPUnit)
public function test_policy_creation(): void
{
$company = Company::factory()->create();
$policyData = [
'name' => 'Test Policy',
'type' => 'privacy',
'content' => 'Policy content'
];
$service = new PolicyManagementService();
$policy = $service->createPolicy($company, $policyData);
$this->assertInstanceOf(Policy::class, $policy);
$this->assertEquals('Test Policy', $policy->name);
$this->assertDatabaseHas('policies', [
'name' => 'Test Policy',
'company_id' => $company->id
]);
}
Frontend Testing (Jest)
import { render, screen, fireEvent } from '@testing-library/react';
import { Provider } from 'react-redux';
import { store } from 'features/storeConfig/store';
import PolicyManagement from './PolicyManagement';
test('renders policy management component', () => {
render(
);
expect(screen.getByText('Policy Management')).toBeInTheDocument();
expect(screen.getByText('Create Policy')).toBeInTheDocument();
});
Python Testing
import unittest
from dns_scanner import scan_domain
class TestDnsScanner(unittest.TestCase):
def test_scan_domain_returns_valid_structure(self):
result = scan_domain('example.com')
self.assertIn('status', result)
self.assertIn('domain', result)
self.assertIn('results', result)
self.assertIn(result['status'], ['pass', 'fail'])
Testing Strategy
Backend Testing (PHPUnit)
create();
$client = Client::factory()->create(['company_id' => $user->company_id]);
$response = $this->actingAs($user)
->postJson("/api/v3/clients/{$client->id}/policies", [
'title' => 'Test Policy',
'category_id' => Category::factory()->create()->id,
'description' => 'Test description',
]);
$response->assertStatus(201)
->assertJsonStructure(['data' => ['id', 'title', 'status']]);
$this->assertDatabaseHas('policies', [
'title' => 'Test Policy',
'client_id' => $client->id,
]);
}
}
Frontend Testing (Jest)
// Component test example
import { render, screen, fireEvent } from '@testing-library/react';
import { Provider } from 'react-redux';
import { store } from 'features/storeConfig/store';
import PolicyCard from './PolicyCard';
const mockPolicy = {
id: '123',
title: 'Test Policy',
description: 'Test description',
status: 'draft'
};
test('renders policy card with correct information', () => {
render(
);
expect(screen.getByText('Test Policy')).toBeInTheDocument();
expect(screen.getByText('Test description')).toBeInTheDocument();
});
Testing Guidelines
- Backend: Write feature tests for API endpoints, unit tests for services
- Frontend: Test user interactions and component rendering
- Integration: Test external API integrations with mocked responses
- E2E: Test critical user workflows end-to-end
- Coverage: Aim for 80%+ code coverage on critical paths
Common Development Tasks
Adding New Functionality
- Review existing similar implementations
- Create appropriate tests first (TDD approach)
- Implement following established patterns
- Add comprehensive logging with our format
- Update documentation
- Run tests and ensure they pass
Debugging Issues
- Check application logs in
storage/logs/ - Use structured logging with context
- Add temporary debug logging if needed
- Use Laravel's built-in debugging tools
- Test fixes thoroughly across BE/FE
Before Submitting Changes
- ☐ All tests pass (backend and frontend)
- ☐ Code follows our established standards
- ☐ Documentation is updated
- ☐ Logging is comprehensive and follows format
- ☐ Error handling is implemented properly
- ☐ Performance impact is considered
- ☐ Security implications are reviewed
- ☐ Multi-language integration works correctly
Performance Optimization
Backend Optimization
- Database: Use proper indexes, avoid N+1 queries
- Caching: Implement Redis caching for expensive operations
- Queues: Use background jobs for heavy processing
- Pagination: Implement cursor-based pagination for large datasets
- Optimization: Use
php artisan optimizein production
Frontend Optimization
- Code Splitting: Use React.lazy for route-based splitting
- Memoization: Use React.memo and useMemo appropriately
- Virtual Scrolling: For large data tables (already implemented)
- Image Optimization: Use proper image formats and lazy loading
- Bundle Analysis: Regular bundle size monitoring
Performance Monitoring
// Example: Performance monitoring in React
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
function sendToAnalytics(metric) {
// Send to your analytics service
console.log(metric);
}
// Monitor Core Web Vitals
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);
Debugging Tips
Backend Debugging
- Use
Log::debug()for detailed tracing - Check
storage/logs/laravel.log - Use
dd()ordump()for quick debugging - Enable Laravel Debugbar in development
- Use Clockwork for API debugging
- Monitor database queries with Laravel Telescope
Frontend Debugging
- Use Redux DevTools for state inspection
- Console.log with structured data
- React Developer Tools for component trees
- Network tab for API call inspection
- Use React Error Boundaries
- Material-UI theme debugging tools
Python Debugging
- Use Python logging with structured output
- Check scanner log files in
scanners/ - Use
pdbfor interactive debugging - Print JSON output for Laravel integration
- Test scanners independently
- Handle exceptions gracefully
Application Monitoring
Backend Monitoring
// Performance monitoring in Laravel
use Illuminate\Support\Facades\Log;
class PolicyService
{
public function createPolicy(Company $company, array $data): Policy
{
$startTime = microtime(true);
try {
// Service logic here
$policy = $this->performPolicyCreation($company, $data);
$executionTime = microtime(true) - $startTime;
Log::info("PolicyService.php LINE " . __LINE__ . " Policy creation completed", [
'execution_time' => $executionTime,
'policy_id' => $policy->id,
'company_id' => $company->id
]);
return $policy;
} catch (\Throwable $e) {
$executionTime = microtime(true) - $startTime;
Log::error("PolicyService.php LINE " . __LINE__ . " Policy creation failed", [
'execution_time' => $executionTime,
'error' => $e->getMessage(),
'company_id' => $company->id
]);
throw $e;
}
}
}
Frontend Monitoring
// Performance monitoring in React
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
function sendToAnalytics(metric) {
// Send to your analytics service
console.log('Performance metric:', metric);
// Example: Send to backend for logging
fetch('/api/v3/metrics', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${getToken()}`
},
body: JSON.stringify({
name: metric.name,
value: metric.value,
delta: metric.delta,
id: metric.id,
url: window.location.href
})
});
}
// Monitor Core Web Vitals
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);
Common Issues & Solutions
Problem: Users getting logged out unexpectedly or token refresh failing.
Solution:
// Check Auth0 configuration
1. Verify REACT_APP_AUTH0_AUDIENCE is set correctly
2. Check token expiration settings in Auth0 dashboard
3. Implement proper error handling for token refresh
4. Use Auth0's silent authentication for seamless renewal
Problem: Slow database queries, especially on large datasets.
Solutions:
- Add database indexes on frequently queried columns
- Use eager loading to prevent N+1 queries
- Implement database query caching
- Use
php artisan db:monitorto identify slow queries
Problem: State not updating correctly or unnecessary re-renders.
Solutions:
- Use Redux DevTools to debug state changes
- Implement proper selectors to prevent unnecessary renders
- Use React.memo for expensive components
- Check for state mutations (Redux Toolkit helps prevent this)
Problem: CORS errors when calling external APIs or backend endpoints.
Solutions:
// Laravel config/cors.php
'allowed_origins' => ['http://localhost:3000', 'https://yourdomain.com'],
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],
'supports_credentials' => true,
- Verify CORS configuration in Laravel
- Check if credentials are being sent with requests
- Ensure API endpoints are properly defined
Problem: Communication issues between PHP, Python, and JavaScript components.
Solutions:
- Ensure consistent JSON data structures across languages
- Validate Python script output before processing in PHP
- Use proper error handling in shell_exec calls
- Check Python script permissions and dependencies
- Monitor log files for each language component
Key Points to Remember
Critical Reminders
- This is a compliance management application - accuracy is critical
- Performance matters as the system handles large datasets
- Proper logging is essential for debugging production issues
- Security and compliance data is sensitive - handle with care
- The application integrates multiple technologies - maintain consistency
- Queue jobs handle background processing - implement proper error recovery
- Follow established patterns across both BE and FE projects
- When in doubt, refer to existing implementations
Architecture Overview
Remember: The Compliance Scorecard consists of:
- polygon-be: Laravel API backend with policy management, assessments, and compliance features
- polygon-fe: React frontend with Material-UI, Redux state management, and comprehensive user interface
- Integration Layer: Auth0 authentication, Stripe payments, and various third-party services
- Data Processing: Background jobs, caching, and performance optimization
Comments & TODOs Found in Codebase
Based on my review of the codebase, here are the key areas that need attention:
Backend TODOs
User.php (Line 102-103)
Priority: High - Fix user ID tracking in model events
Commented Code Sections
Important Code Comments
Authentication Logic
Database Relationships
Recommended Action Items
Cleanup Tasks
Enhancement Opportunities
Security Reviews