πŸš€ B2B E-Commerce Platform

Enterprise-Grade Wholesale Distribution Management System

A comprehensive full-stack solution handling complex business workflows including multi-tier user management, dynamic pricing, order processing, financial tracking, and automated notifications.

React 18 Redux Toolkit Material-UI PHP MySQL JWT Auth REST API Cron Jobs

πŸ“Š Project Overview

Built from scratch as a full-stack developer, this platform revolutionizes B2B wholesale operations

30+
React Components
40+
API Endpoints
20+
Automated Cron Jobs
3
User Roles (RBAC)
πŸ‘₯

Multi-Tier User System

Sophisticated role-based access control with Superadmin, Admin, and Buyer roles. Dynamic user connections and granular permissions.

πŸ’°

Dynamic Pricing Engine

Real-time price calculations with buyer-specific discounts (rabat), automated price change tracking and notifications.

πŸ“¦

Order Management

Complete order lifecycle from creation to fulfillment with status tracking, modifications, and professional PDF/Excel exports.

πŸ””

Notification System

Dual-channel notifications (email + in-app) with smart routing, rate limiting, and automatic synchronization.

πŸ“Š

Financial Tracking

Real-time invoice management, balance monitoring, and automated ERP synchronization with daily reports.

🎨

Modern UI/UX

Material-UI based interface with responsive design, smooth animations, and optimized performance for large datasets.

πŸ—οΈ System Architecture

Modern, scalable architecture built with best practices and performance in mind

🎨 Frontend Layer

React-based SPA with Redux Toolkit for state management and RTK Query for API caching

React 18.2 Redux Toolkit RTK Query Material-UI v5 React Router v6 React Hook Form i18next React PDF ExcelJS

βš™οΈ Backend Layer

PHP REST API with JWT authentication and role-based access control

PHP 7.4+ Firebase JWT PDO RESTful API Resend API Cron Jobs

πŸ’Ύ Data Layer

MySQL database with optimized queries, proper indexing, and automated synchronization

MySQL Prepared Statements Transactions Indexes Foreign Keys

✨ Key Features & Implementation

Comprehensive feature set covering every aspect of B2B operations

πŸ” Authentication & Security

Secure JWT-based authentication with role-based access control, password reset functionality, and session management.

Login Page
  • JWT token-based authentication with automatic expiration
  • Role-based access control (Superadmin, Admin, Buyer)
  • Secure password hashing with bcrypt
  • Protected routes with automatic redirect
  • Email-based password reset with secure tokens
// JWT Authentication Implementation
const getAuthToken = () => localStorage.getItem('jwtToken');

export const mainApi = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: BASE_API_URL,
    prepareHeaders: (headers) => {
      const token = getAuthToken();
      if (token) {
        headers.set('authorization', `Bearer ${token}`);
      }
      return headers;
    }
  })
});

πŸ”‘ Password Reset Flow

Complete password reset workflow with email verification, secure token generation, and automatic admin notifications.

Password Reset
  • Email-based password reset with secure JWT tokens
  • Automatic admin notification when buyer requests reset
  • Token expiration and validation (1-hour validity)
  • Professional email templates with company branding
  • Platform notifications created for admins

πŸ“¦ Product Catalog & Navigation

Hierarchical product organization (Family β†’ Line β†’ Group β†’ Product) with advanced search, filtering, and real-time price calculations.

Product Catalog Product Detail
  • 4-level hierarchical product taxonomy
  • Real-time search with debouncing (300ms delay)
  • Buyer-specific pricing with automatic discount calculation
  • Virtualized rendering for 1000+ products (React-window)
  • Lazy loading of product images
  • Animated side panel for product details
// Optimized Product Query with Buyer-Specific Pricing
SELECT 
  p.id, p.naziv, p.cena,
  (p.cena * (1 - COALESCE(r.rabat, 0) / 100)) AS final_price,
  p.stanje, p.jm, g.naziv AS group_name
FROM Proizvodi p
LEFT JOIN cene_kupci_rabat r 
  ON p.grupa_id = r.grupa_id 
  AND r.kupac_id = :buyer_id
WHERE p.grupa_id = :group_id
ORDER BY p.naziv

πŸ›’ Order Management System

Complete order lifecycle management with creation, modification, status tracking, and professional exports.

Order Creation Orders Table
  • Multi-item order creation with real-time total calculation
  • Order status tracking with customizable statuses
  • Post-creation order modifications (quantities, items)
  • Optimistic UI updates with rollback on error
  • Transaction-based order creation for data integrity
  • Automatic notifications to admins on new orders

πŸ“„ Professional Document Generation

Client-side PDF and Excel generation with custom styling, company branding, and complex layouts.

PDF Export Excel Export
  • @react-pdf/renderer for client-side PDF generation
  • ExcelJS for complex spreadsheet creation
  • Custom fonts (Roboto) for Serbian Cyrillic support
  • Professional layouts for orders, invoices, price lists
  • Company branding and logos
  • Multi-sheet workbooks with formulas
  • Customizable font sizes and colors
// PDF Generation with React-PDF
import { Document, Page, Text, View } from '@react-pdf/renderer';

const PDFDocument = ({ orderData }) => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.header}>
        <Text style={styles.title}>PorudΕΎbina #{orderData.id}</Text>
      </View>
      <View style={styles.table}>
        {orderData.items.map(item => (
          <View style={styles.row} key={item.id}>
            <Text>{item.name}</Text>
            <Text>{item.quantity} x {item.price}</Text>
          </View>
        ))}
      </View>
    </Page>
  </Document>
);

πŸ”” Real-Time Notification System

Comprehensive dual-channel notification system with email and in-app notifications, smart routing, and automatic synchronization.

Notifications Notification Center
  • Email notifications via Resend API with rate limiting (10 emails/second)
  • In-app notifications with 30-second polling
  • Smart routing: different logic for buyers vs admins
  • Notification types: price changes, orders, profile updates, password resets
  • Automatic cleanup of old read notifications (7 days)
  • Synchronization between email and platform notifications
  • Automated price change detection with daily cron job
  • New feature: Customizable notification preferences for buyers
// Notification Polling Implementation
const { data: countData } = useGetNotificationCountQuery(
  undefined,
  {
    pollingInterval: 30000 // Poll every 30 seconds
  }
);

// Backend: Automated Price Change Detection (track_price_changes.php)
// - Runs daily via cron at 5 AM
// - Compares current vs previous prices
// - Creates notifications for affected buyers
// - Filters by buyer's product group access
// - Sends emails with retry logic and rate limiting
// New feature: Buyer notification preferences stored in database
// - Buyers can opt-in/out of specific notification types
// - Notification preferences synced with platform notifications

πŸ’° Financial State & Invoice Tracking

Real-time financial tracking with automated ERP synchronization, invoice management, and balance monitoring.

  • Daily synchronization from remote ERP database (sync_financial_state.php)
  • Real-time balance and credit limit monitoring
  • Complete invoice history with details
  • Payment method and status tracking
  • Excel export for financial reports
  • Error handling and daily summary emails to admins
  • Transaction-based updates for data consistency

πŸ“Š Price List Management

Dynamic price list generation with buyer-specific discounts, PDF/Excel exports, and automated price change tracking.

  • Real-time price calculation with buyer rabat (discount)
  • PDF generation with custom styling and company logo
  • Excel export with editable spreadsheets and formulas
  • Image upload for price list headers
  • Historical price tracking
  • Automated price change detection and notifications

βš™οΈ Admin Dashboard & Management

Comprehensive admin dashboard for user management, product CRUD operations, image uploads, and document management.

User Management Product Management Image Upload
  • User management with dynamic admin-buyer connections
  • Email validation supporting multiple semicolon-separated addresses
  • Unicode-aware address validation (Serbian Cyrillic/Latin)
  • Product CRUD operations with bulk updates
  • Image upload with drag-drop, compression (Compressor.js), and cropping
  • Document management (PDF/Excel per product group)
  • Autocomplete with virtualization for large datasets
  • Tab-based interface for organized dashboard sections
// Image Compression & Upload
import Compressor from 'compressorjs';

const compressImage = (file) => {
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      quality: 0.6,
      maxWidth: 1920,
      maxHeight: 1080,
      success: (compressedFile) => resolve(compressedFile),
      error: (err) => reject(err)
    });
  });
};

// Typically reduces file size by 70%

βš›οΈ Frontend Excellence

Modern React architecture with performance optimizations and best practices

State Management Strategy

  • Redux Toolkit - Centralized state management with slices
  • RTK Query - Automatic API caching and invalidation
  • Context API - Component-level state (SideDetails, Products, Dashboard, Notifications)
  • Optimistic Updates - Immediate UI feedback with rollback on error
  • Tag-Based Invalidation - Smart cache management (Orders, Invoices, Notifications, etc.)

πŸš€ Performance Optimizations

  • React-window - Virtualized lists for 1000+ products
  • Debouncing - 300ms delay on search inputs
  • Lazy Loading - Code splitting with React.lazy
  • Memoization - useMemo/useCallback for expensive computations
  • Image Optimization - Compressor.js reduces sizes by 70%
  • Pagination - Server-side pagination for large datasets

🎨 Component Architecture

  • Functional Components - 100% hooks-based
  • Custom Hooks - Reusable logic extraction
  • Compound Components - Flexible component composition
  • Render Props - Component logic sharing
  • HOCs - Cross-cutting concerns (auth, error boundaries)
  • Feature-Based Organization - Scalable folder structure

πŸ“ Form Handling

  • React Hook Form - Performant form management
  • Custom Validation - Email, address, Unicode support
  • Real-Time Errors - Instant feedback on input
  • Multi-Step Forms - Order creation wizard
  • Form State Persistence - Draft saving
  • Material-UI Integration - Controlled components

🎯 Code Quality

  • Consistent Patterns - Standardized component structure
  • Error Boundaries - Graceful error handling
  • PropTypes/JSDoc - Type documentation
  • ESLint - Code quality enforcement
  • Separation of Concerns - Logic/UI separation
  • DRY Principle - Reusable utilities and components

Code Sample: RTK Query with Optimistic Updates

// Optimistic UI Update with Rollback
const [updateOrder] = useUpdateOrderMutation();

const handleStatusChange = async (orderId, newStatus) => {
  // Optimistically update UI immediately
  const patchResult = dispatch(
    mainApi.util.updateQueryData('getOrders', undefined, (draft) => {
      const order = draft.find(o => o.id === orderId);
      if (order) {
        order.status = newStatus;
      }
    })
  );

  try {
    // Make actual API call
    await updateOrder({ id: orderId, status: newStatus }).unwrap();
  } catch (error) {
    // Rollback on error
    patchResult.undo();
    showErrorNotification('Failed to update order');
  }
};

Code Sample: Custom Hook for Debounced Search

// Custom hook for debounced search
const useDebounce = (value, delay = 300) => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
};

// Usage in SearchBar component
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearch = useDebounce(searchTerm, 300);

// Only triggers API call after 300ms of no typing
useEffect(() => {
  if (debouncedSearch) {
    fetchProducts(debouncedSearch);
  }
}, [debouncedSearch]);

βš™οΈ Backend Excellence

Robust PHP REST API with security, optimization, and automation

API Design Principles

  • RESTful Architecture - Standard HTTP methods and status codes
  • JWT Authentication - Stateless token-based auth with Firebase JWT
  • Role-Based Access Control - Granular permissions per endpoint
  • Consistent Response Format - Standardized JSON structure
  • Error Handling - Descriptive error messages with proper codes
  • Input Validation - Server-side validation for all inputs

πŸ”’ Security Measures

  • SQL Injection Prevention - PDO prepared statements
  • XSS Protection - Input sanitization and output escaping
  • CSRF Protection - Token validation
  • Password Hashing - bcrypt with salt
  • .htaccess Protection - Directory access restrictions
  • JWT Expiration - Automatic token invalidation

πŸ’Ύ Database Optimization

  • Proper Indexing - Foreign keys and composite indexes
  • Query Optimization - Efficient JOINs and subqueries
  • Transactions - ACID compliance for critical operations
  • Connection Pooling - Reusable database connections
  • Prepared Statements - Query plan caching
  • Normalized Schema - 3NF database design

πŸ€– Cron Job Automation

  • Data Synchronization - Daily ERP sync (buyers, products, financial)
  • Price Change Detection - Automated tracking and notifications
  • Email Sending - Rate-limited batch processing (10/sec)
  • Database Cleanup - Old notification removal (7 days)
  • Health Monitoring - Daily summary emails to admins
  • Error Recovery - Retry logic with exponential backoff

πŸ“§ Email Integration

  • Resend API - Modern email service integration
  • Rate Limiting - 10 emails per second max
  • Template System - Reusable email templates
  • Retry Logic - Failed email retry with status tracking
  • Notification Sync - Email + platform notification creation
  • User Preferences - Opt-in/opt-out per notification type

Code Sample: Secure API Endpoint Structure

// Typical API endpoint structure (get_orders.php)
require_once '../includes/db.php';
require_once '../includes/validation.php';

// 1. Verify JWT token
$token = getBearerToken();
$decoded = verifyJWT($token);

if (!$decoded) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// 2. Check role-based permissions
$role = $decoded->role;
if (!in_array($role, ['admin', 'superadmin'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

// 3. Validate and sanitize inputs
$buyer_id = filter_input(INPUT_GET, 'buyer_id', FILTER_SANITIZE_STRING);

// 4. Execute query with prepared statement
$stmt = $conn->prepare("
    SELECT o.*, u.company_name 
    FROM orders o
    JOIN users u ON o.buyer_id = u.buyer_id
    WHERE o.buyer_id = :buyer_id
    ORDER BY o.created_at DESC
");
$stmt->bindParam(':buyer_id', $buyer_id, PDO::PARAM_STR);
$stmt->execute();

// 5. Return standardized JSON response
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
http_response_code(200);
echo json_encode($orders);

Code Sample: Automated Price Change Detection

// track_price_changes.php - Runs daily at 5 AM via cron

// 1. Detect price changes by comparing current vs previous prices
$sql = "
    SELECT 
        p.id, p.naziv, p.grupa_id, g.naziv as group_name,
        p.cena as current_price,
        pp.cena as previous_price
    FROM Proizvodi p
    JOIN Grupe g ON p.grupa_id = g.id
    LEFT JOIN Proizvodi_previous pp ON p.id = pp.id
    WHERE p.cena != pp.cena OR pp.cena IS NULL
";

// 2. For each changed product, find affected buyers
foreach ($changed_products as $product) {
    // Get buyers with rabat for this product group
    $buyers = getBuyersForGroup($product['grupa_id']);
    
    foreach ($buyers as $buyer) {
        // 3. Create email notification entry
        createPriceChangeNotification($buyer, $product);
    }
}

// 4. Email sending handled by separate cron (send_price_change_email_resend.php)
// - Runs every 3 minutes between 5-12 AM
// - Rate limited to 10 emails/second
// - Creates platform notifications after successful email send
// - Retry logic for failed emails

🎯 Impact & Technical Achievements

Measurable results and technical excellence

πŸ“ˆ Scale & Complexity

  • 30+ React components with complex state management
  • 40+ REST API endpoints with role-based access
  • 20+ automated cron jobs for data synchronization
  • 4-level product hierarchy with 1000+ products
  • Multi-tier user system (3 roles, dynamic connections)
  • Dual-channel notification system (email + in-app)

⚑ Performance Metrics

  • 70% image size reduction with Compressor.js
  • 300ms debounce on search (reduced API calls by 80%)
  • Virtualized lists handle 1000+ items smoothly
  • Optimistic updates provide instant UI feedback
  • RTK Query caching reduces redundant API calls
  • Server-side pagination for large datasets

πŸ” Security & Reliability

  • Zero SQL injection vulnerabilities (PDO prepared statements)
  • JWT authentication with automatic expiration
  • Transaction-based operations for data integrity
  • Error handling with retry logic
  • Daily health monitoring and summary emails
  • .htaccess protection for sensitive directories

πŸš€ Modern Tech Stack

  • React 18 with hooks and functional components
  • Redux Toolkit with RTK Query for state/caching
  • Material-UI v5 with custom theming
  • PHP 7.4+ with modern practices
  • MySQL with optimized queries and indexes
  • Integration with external APIs (Resend, ERP)

πŸ† Key Technical Highlights

  • Full-Stack Ownership - Built entire platform from scratch (frontend + backend + database)
  • Complex Business Logic - Dynamic pricing, multi-tier permissions, automated workflows
  • Real-Time Features - Notifications with polling, optimistic updates, live calculations
  • Enterprise Integration - ERP synchronization, email automation, document generation
  • Production-Ready - Error handling, security, monitoring, automated testing
  • Scalable Architecture - Modular design, reusable components, efficient queries
  • Modern Best Practices - Clean code, DRY principle, separation of concerns