Monday, 20 July 2026

AI-Based Smart Retail Inventory Monitoring System

Yes. Below is the same complete Smart Retail Inventory Monitoring project converted into a PHP-based project structure, with the web dashboard, APIs, database, AI logic, n8n integration, Telegram alerts, Google Sheets integration, ThingSpeak integration, and documentation pages. Important: ESP32 firmware must remain .ino/Arduino C++ code because ESP32 cannot execute PHP. PHP is used for the web server, APIs, database, AI logic, cloud integration, and dashboard. 1. Complete PHP Project Structure smart-retail-inventory/ │ ├── index.php ├── dashboard.php ├── products.php ├── alerts.php ├── predictions.php ├── settings.php │ ├── config/ │ ├── database.php │ ├── config.php │ └── api_keys.php │ ├── api/ │ ├── esp32_data.php │ ├── inventory.php │ ├── products.php │ ├── alerts.php │ ├── prediction.php │ ├── telegram.php │ ├── thingspeak.php │ └── google_sheets.php │ ├── ai/ │ ├── inventory_ai.php │ ├── consumption_prediction.php │ └── reorder_prediction.php │ ├── includes/ │ ├── header.php │ ├── footer.php │ ├── navbar.php │ └── functions.php │ ├── assets/ │ ├── css/ │ │ └── style.css │ └── js/ │ └── dashboard.js │ ├── database/ │ └── smart_retail.sql │ ├── n8n/ │ └── inventory_workflow.json │ ├── documentation/ │ ├── project_description.php │ ├── components.php │ ├── circuit.php │ ├── flowchart.php │ ├── installation.php │ └── future_enhancements.php │ └── esp32/ └── smart_retail_inventory.ino 2. config/database.php connect_error) { die( "Database connection failed: " . $conn->connect_error ); } $conn->set_charset("utf8mb4"); ?> 3. config/config.php 4. config/api_keys.php "YOUR_N8N_SECRET_KEY", "esp32" => "YOUR_ESP32_SECRET_KEY", "telegram" => "YOUR_TELEGRAM_BOT_TOKEN", "thingspeak" => "YOUR_THINGSPEAK_WRITE_API_KEY" ]; ?> 5. Database SQL File database/smart_retail.sql CREATE DATABASE IF NOT EXISTS smart_retail; USE smart_retail; CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100) NOT NULL UNIQUE, product_name VARCHAR(200) NOT NULL, rfid_uid VARCHAR(100), category VARCHAR(100), unit_weight FLOAT DEFAULT 0, minimum_stock INT DEFAULT 10, reorder_level INT DEFAULT 10, supplier_name VARCHAR(200), supplier_contact VARCHAR(100), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE inventory ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), quantity INT DEFAULT 0, weight FLOAT DEFAULT 0, temperature FLOAT DEFAULT 0, humidity FLOAT DEFAULT 0, daily_consumption FLOAT DEFAULT 0, predicted_consumption FLOAT DEFAULT 0, days_remaining FLOAT DEFAULT 0, stock_status VARCHAR(50), risk_level VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (product_id) REFERENCES products(product_id) ); CREATE TABLE inventory_history ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), quantity INT, weight FLOAT, temperature FLOAT, humidity FLOAT, recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE alerts ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), alert_type VARCHAR(100), message TEXT, severity VARCHAR(50), sent_to_telegram BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE predictions ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), average_daily_consumption FLOAT, predicted_consumption FLOAT, estimated_days_remaining FLOAT, recommended_reorder_quantity INT, risk_level VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); 6. includes/header.php <?= SITE_NAME ?> 7. includes/navbar.php 8. includes/footer.php

AI Smart Retail Inventory Monitoring System

ESP32 + AI Agent + n8n + Telegram + Google Sheets + ThingSpeak

9. includes/functions.php 10. Main Dashboard index.php query( "SELECT i.*, p.product_name, p.category FROM inventory i LEFT JOIN products p ON i.product_id = p.product_id ORDER BY i.id DESC" ); $total_products = $conn->query( "SELECT COUNT(*) AS total FROM products" )->fetch_assoc()["total"]; $low_stock = $conn->query( "SELECT COUNT(*) AS total FROM inventory WHERE stock_status = 'LOW_STOCK'" )->fetch_assoc()["total"]; $out_of_stock = $conn->query( "SELECT COUNT(*) AS total FROM inventory WHERE stock_status = 'OUT_OF_STOCK'" )->fetch_assoc()["total"]; ?> AI Smart Retail Dashboard

AI Smart Retail Inventory Dashboard

Total Products

Low Stock Products

Out of Stock

AI Agent

ONLINE

fetch_assoc() ) { ?>
Product ID Product Name Quantity Weight Temperature Humidity Daily Consumption Days Remaining Status Risk
11. ESP32 Data API api/esp32_data.php This PHP file receives data from ESP32. false, "message" => "Invalid JSON data" ]); exit; } $product_id = $data["product_id"] ?? ""; $quantity = intval( $data["quantity"] ?? 0 ); $weight = floatval( $data["weight"] ?? 0 ); $temperature = floatval( $data["temperature"] ?? 0 ); $humidity = floatval( $data["humidity"] ?? 0 ); $product_query = $conn->prepare( "SELECT minimum_stock FROM products WHERE product_id = ?" ); $product_query->bind_param( "s", $product_id ); $product_query->execute(); $product_result = $product_query->get_result(); if ( $product_result->num_rows == 0 ) { echo json_encode([ "success" => false, "message" => "Product not found" ]); exit; } $product = $product_result->fetch_assoc(); $minimum_stock = $product["minimum_stock"]; $status = calculateStockStatus( $quantity, $minimum_stock ); $risk = calculateRiskLevel( $quantity, $minimum_stock ); $insert = $conn->prepare( "INSERT INTO inventory ( product_id, quantity, weight, temperature, humidity, stock_status, risk_level ) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $insert->bind_param( "isddsss", $product_id, $quantity, $weight, $temperature, $humidity, $status, $risk ); $insert->execute(); $history = $conn->prepare( "INSERT INTO inventory_history ( product_id, quantity, weight, temperature, humidity ) VALUES (?, ?, ?, ?, ?)" ); $history->bind_param( "isddd", $product_id, $quantity, $weight, $temperature, $humidity ); $history->execute(); echo json_encode([ "success" => true, "product_id" => $product_id, "quantity" => $quantity, "stock_status" => $status, "risk_level" => $risk ]); ?> 12. Product Registration products.php prepare( "INSERT INTO products ( product_id, product_name, rfid_uid, category, unit_weight, minimum_stock, supplier_name ) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $stmt->bind_param( "ssssdis", $product_id, $product_name, $rfid_uid, $category, $unit_weight, $minimum_stock, $supplier_name ); $stmt->execute(); } ?> Product Management

Add Retail Product








13. AI Inventory Logic ai/inventory_ai.php prepare( "SELECT quantity, daily_consumption FROM inventory WHERE product_id = ? ORDER BY id DESC LIMIT 1" ); $query->bind_param( "s", $product_id ); $query->execute(); $result = $query->get_result(); $data = $result->fetch_assoc(); if (!$data) { echo json_encode([ "success" => false, "message" => "No inventory data" ]); exit; } $quantity = $data["quantity"]; $daily_consumption = $data["daily_consumption"]; $days_remaining = calculateDaysRemaining( $quantity, $daily_consumption ); if ($days_remaining <= 1) { $risk = "CRITICAL"; } elseif ($days_remaining <= 3) { $risk = "HIGH"; } elseif ($days_remaining <= 7) { $risk = "MEDIUM"; } else { $risk = "LOW"; } echo json_encode([ "product_id" => $product_id, "current_stock" => $quantity, "daily_consumption" => $daily_consumption, "estimated_days_remaining" => $days_remaining, "risk_level" => $risk ]); ?> 14. Consumption Prediction ai/consumption_prediction.php prepare( "SELECT quantity, recorded_at FROM inventory_history WHERE product_id = ? ORDER BY recorded_at ASC" ); $query->bind_param( "s", $product_id ); $query->execute(); $result = $query->get_result(); $records = []; while ( $row = $result->fetch_assoc() ) { $records[] = $row; } if ( count($records) < 2 ) { echo json_encode([ "success" => false, "message" => "Insufficient historical data" ]); exit; } $consumption_values = []; for ( $i = 1; $i < count($records); $i++ ) { $previous = $records[$i - 1]["quantity"]; $current = $records[$i]["quantity"]; $consumption = $previous - $current; if ($consumption > 0) { $consumption_values[] = $consumption; } } if ( count($consumption_values) == 0 ) { $average_consumption = 0; } else { $average_consumption = array_sum( $consumption_values ) / count( $consumption_values ); } echo json_encode([ "product_id" => $product_id, "average_daily_consumption" => round( $average_consumption, 2 ) ]); ?> 15. Reorder Prediction ai/reorder_prediction.php $current_stock, "daily_consumption" => $daily_consumption, "lead_time" => $lead_time, "safety_stock" => $safety_stock, "recommended_reorder_quantity" => $reorder_quantity ]); ?> 16. Telegram Alert PHP File api/telegram.php TELEGRAM_CHAT_ID, "text" => $message ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $data ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); return $response; } $product = $_POST["product"] ?? ""; $quantity = $_POST["quantity"] ?? ""; $status = $_POST["status"] ?? ""; $message = "🚨 SMART RETAIL INVENTORY ALERT 🚨\n\n" . "Product: " . $product . "\n\n" . "Current Stock: " . $quantity . "\n\n" . "Status: " . $status . "\n\n" . "Please check inventory."; $response = sendTelegramMessage( $message ); echo $response; ?> 17. Telegram Voice Notification api/telegram_voice.php TELEGRAM_CHAT_ID, "voice" => new CURLFile( $audio_file, "audio/mpeg", "inventory_alert.mp3" ) ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_fields ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 18. ThingSpeak PHP Integration api/thingspeak.php true, "response" => $response ]); ?> 19. Google Sheets Integration Through n8n PHP sends inventory data to n8n: api/google_sheets.php $_POST["product_id"], "quantity" => $_POST["quantity"], "weight" => $_POST["weight"], "temperature" => $_POST["temperature"], "humidity" => $_POST["humidity"], "stock_status" => $_POST["stock_status"] ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, N8N_WEBHOOK_URL ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) ); curl_setopt( $ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ] ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 20. n8n Workflow JSON n8n/inventory_workflow.json { "name": "AI Smart Retail Inventory Automation", "nodes": [ { "parameters": { "httpMethod": "POST", "path": "inventory" }, "name": "ESP32 PHP Webhook", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [ 200, 300 ] }, { "parameters": { "jsCode": "const data = $json;\nconst quantity = Number(data.quantity || 0);\nconst minimumStock = 10;\nlet status = 'NORMAL';\nif (quantity <= 0) {\n status = 'OUT_OF_STOCK';\n} else if (quantity <= minimumStock) {\n status = 'LOW_STOCK';\n}\nreturn [{json: {...data, stock_status: status, alert_required: status !== 'NORMAL'}}];" }, "name": "AI Inventory Analysis", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 450, 300 ] }, { "parameters": { "conditions": { "boolean": [ { "value1": "={{$json.alert_required}}", "value2": true } ] } }, "name": "Low Stock Decision", "type": "n8n-nodes-base.if", "typeVersion": 2, "position": [ 700, 300 ] }, { "parameters": { "chatId": "YOUR_TELEGRAM_CHAT_ID", "text": "🚨 INVENTORY ALERT 🚨\nProduct: {{$json.product_id}}\nQuantity: {{$json.quantity}}\nStatus: {{$json.stock_status}}" }, "name": "Telegram Alert", "type": "n8n-nodes-base.telegram", "typeVersion": 1, "position": [ 950, 200 ] }, { "parameters": { "operation": "append", "documentId": "YOUR_GOOGLE_SHEET_ID", "sheetName": "Inventory" }, "name": "Google Sheets", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4, "position": [ 950, 400 ] } ], "connections": { "ESP32 PHP Webhook": { "main": [ [ { "node": "AI Inventory Analysis", "type": "main", "index": 0 } ] ] }, "AI Inventory Analysis": { "main": [ [ { "node": "Low Stock Decision", "type": "main", "index": 0 } ] ] }, "Low Stock Decision": { "main": [ [ { "node": "Telegram Alert", "type": "main", "index": 0 } ], [ { "node": "Google Sheets", "type": "main", "index": 0 } ] ] } } } 21. PHP Flowchart Page documentation/flowchart.php

Smart Retail Inventory Flowchart

START
ESP32 Initializes
Connect Wi-Fi
Read RFID Product
Read Weight
Read Temperature
Read Humidity
Send JSON Data
PHP API / n8n Webhook
AI Inventory Analysis
Check Stock Level
LOW STOCK?
Telegram Voice Alert
Google Sheets Update
ThingSpeak Update
PHP Dashboard
22. PHP Project Description Page documentation/project_description.php

AI-Based Smart Retail Inventory Monitoring System

Project Description

This project is an AI-powered IoT inventory monitoring system designed to automatically monitor retail products using ESP32, RFID, load cells, environmental sensors, PHP, MySQL, n8n automation, Telegram notifications, Google Sheets and ThingSpeak.

The ESP32 collects product and inventory data and sends it through Wi-Fi to the PHP API or n8n webhook.

The AI Agent analyzes current stock, historical consumption, stock depletion rate and future inventory requirements.

When the inventory reaches a critical level, the system automatically sends Telegram text and voice notifications.

Inventory information is stored in MySQL and Google Sheets and visualized through a PHP dashboard and ThingSpeak cloud platform.

Main Technologies

  • ESP32
  • RFID
  • Load Cell
  • PHP
  • MySQL
  • n8n
  • AI Agent
  • Telegram
  • Google Sheets
  • ThingSpeak
23. PHP Components Page documentation/components.php

Hardware Components

Component Purpose
ESP32 Main IoT controller
RFID RC522 Product identification
Load Cell Stock weight measurement
HX711 Load cell amplifier
DHT22 Temperature and humidity
OLED Display Local data display
Buzzer Local alert
24. CSS File assets/css/style.css body { font-family: Arial; margin: 0; padding: 20px; background: #f4f4f4; } .navbar { background: #222; padding: 20px; margin-bottom: 30px; } .navbar a { color: white; margin-right: 20px; text-decoration: none; } .dashboard-cards { display: flex; gap: 20px; flex-wrap: wrap; } .card { background: white; padding: 25px; min-width: 200px; border-radius: 10px; box-shadow: 0 0 10px rgba( 0, 0, 0, 0.15 ); } table { width: 100%; border-collapse: collapse; margin-top: 30px; background: white; } th, td { padding: 12px; border: 1px solid #ddd; } th { background: #222; color: white; } input, button { padding: 12px; margin: 8px; } button { cursor: pointer; } .flowchart { text-align: center; font-size: 20px; } .flowchart div { background: white; padding: 20px; margin: 10px auto; max-width: 500px; border-radius: 10px; box-shadow: 0 0 8px rgba( 0, 0, 0, 0.2 ); } 25. ESP32 to PHP API Connection In the ESP32 source code, the endpoint becomes: #define PHP_API_URL \ "https://your-domain.com/smart-retail/api/esp32_data.php" The ESP32 sends: { "product_id": "MILK001", "quantity": 5, "weight": 5200, "temperature": 28.5, "humidity": 61.4 } to: api/esp32_data.php PHP then: Receive JSON ↓ Validate Data ↓ Find Product ↓ Calculate Stock Status ↓ Calculate Risk ↓ Save MySQL Data ↓ Save History ↓ Send Response 26. Final PHP-Based System Architecture ┌──────────────────────────────┐ │ ESP32 │ │ │ │ RFID + Load Cell + DHT22 │ └──────────────┬───────────────┘ │ │ HTTP POST JSON ▼ ┌──────────────────────────────┐ │ PHP API SERVER │ │ │ │ esp32_data.php │ └──────────────┬───────────────┘ │ ▼ ┌──────────────────────────────┐ │ MySQL │ │ │ │ Products │ │ Inventory │ │ History │ │ Alerts │ │ Predictions │ └──────────────┬───────────────┘ │ ▼ ┌──────────────────────────────┐ │ PHP AI LOGIC │ │ │ │ Stock Analysis │ │ Consumption Prediction │ │ Reorder Prediction │ └──────────────┬───────────────┘ │ ┌───────┼────────┐ ▼ ▼ ▼ n8n Telegram ThingSpeak │ │ │ ▼ ▼ ▼ AI Voice Cloud Agent Alerts Dashboard │ ▼ Google Sheets 27. Complete Working Sequence 1. Product enters the retail shelf. 2. RFID identifies the product. 3. Load cell measures the product weight. 4. ESP32 reads environmental conditions. 5. ESP32 sends JSON data to PHP. 6. PHP validates the data. 7. PHP stores data in MySQL. 8. AI logic calculates stock status. 9. AI predicts future consumption. 10. AI estimates remaining stock days. 11. AI calculates reorder quantity. 12. n8n receives inventory data. 13. n8n updates Google Sheets. 14. n8n updates ThingSpeak. 15. Telegram text alert is sent. 16. Voice notification is generated. 17. Telegram voice alert is delivered. 18. PHP dashboard displays current status. 19. Store manager takes action. 28. Important Deployment Configuration For local testing: XAMPP Apache MySQL PHP Project location: C:\xampp\htdocs\smart-retail\ Open: http://localhost/smart-retail/ For Internet access: PHP Hosting MySQL Database HTTPS Domain n8n Cloud or VPS Telegram Bot Google Sheets API ThingSpeak Channel Final Result This PHP version gives you the complete software architecture for: ESP32 + RFID + Load Cell + DHT22 + PHP + MySQL + AI Inventory Prediction + n8n Automation + Telegram Text Alerts + Telegram Voice Notifications + Google Sheets + ThingSpeak + PHP IoT Web Dashboard. The only part that should not be written in PHP is the ESP32 firmware, because the ESP32 requires Arduino C++/C code to directly control sensors and hardware.

No comments:

Post a Comment