From d0cc76a75cf1529c7443682f8f44c3774c2fa57b Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Thu, 12 Feb 2026 12:22:59 +0000 Subject: [PATCH] Enhance supply chain platform with AI security, logistics optimization, and data engineering. - Created supply_chain_platform/security_tools.py for AI-driven anomaly detection and IoT risk assessment. - Updated supply_chain_platform/ai_logistics_engine.py with data engineering pipeline and transport optimizer. - Enhanced supply_chain_platform/incoterms_data.json with detailed trade term information. - Updated supply_chain_platform/supply_chain_main.py (CLI) to include new features. - Redesigned src/SupplyChainPlatform.jsx (Frontend) with new Security and Data Engineering tabs, and improved Incoterms UI. Co-authored-by: GYFX35 <134739293+GYFX35@users.noreply.github.com> --- src/SupplyChainPlatform.jsx | 234 +++++++++++++++++-- supply_chain_platform/ai_logistics_engine.py | 34 +++ supply_chain_platform/incoterms_data.json | 78 ++++++- supply_chain_platform/security_tools.py | 96 ++++++++ supply_chain_platform/supply_chain_main.py | 93 ++++++-- 5 files changed, 485 insertions(+), 50 deletions(-) create mode 100644 supply_chain_platform/security_tools.py diff --git a/src/SupplyChainPlatform.jsx b/src/SupplyChainPlatform.jsx index 7550b50..2874135 100644 --- a/src/SupplyChainPlatform.jsx +++ b/src/SupplyChainPlatform.jsx @@ -63,10 +63,42 @@ function Warehouse() { // --- Main Component --- const INCOTERMS_DATA = { - "EXW": "Ex Works: Buyer takes all risk from seller's door.", - "FOB": "Free On Board: Seller covers costs until goods are on ship.", - "CIF": "Cost, Insurance, and Freight: Seller pays to destination port.", - "DDP": "Delivered Duty Paid: Seller covers all costs including taxes." + "EXW": { + "desc": "Ex Works: Buyer takes all risk from seller's door.", + "risk": "Seller's premises", + "cost": "Seller's premises", + "modes": "Any" + }, + "FCA": { + "desc": "Free Carrier: Seller delivers to carrier at named place.", + "risk": "Delivery to carrier", + "cost": "Delivery to carrier", + "modes": "Any" + }, + "FOB": { + "desc": "Free On Board: Seller covers costs until goods are on ship.", + "risk": "On board vessel", + "cost": "On board vessel", + "modes": "Sea/Inland Waterway" + }, + "CIF": { + "desc": "Cost, Insurance, and Freight: Seller pays to destination port.", + "risk": "On board vessel", + "cost": "Destination port", + "modes": "Sea/Inland Waterway" + }, + "DAP": { + "desc": "Delivered at Place: Seller delivers at named destination.", + "risk": "At destination (ready for unloading)", + "cost": "At destination (ready for unloading)", + "modes": "Any" + }, + "DDP": { + "desc": "Delivered Duty Paid: Seller covers all costs including taxes.", + "risk": "At destination (ready for unloading)", + "cost": "At destination (cleared for import)", + "modes": "Any" + } }; export default function SupplyChainPlatform() { @@ -75,6 +107,8 @@ export default function SupplyChainPlatform() { const [trackingId, setTrackingId] = useState(''); const [aiStatus, setAiStatus] = useState('Idle'); const [blockchainLog, setBlockchainLog] = useState([]); + const [pipelineStep, setPipelineStep] = useState(0); + const [securityScan, setSecurityScan] = useState(null); const logToBlockchain = async (event) => { setAiStatus('Securing data on blockchain...'); @@ -94,14 +128,54 @@ export default function SupplyChainPlatform() { }, 1500); }; + const runDataPipeline = () => { + setPipelineStep(1); + const steps = [ + 'Ingesting IoT Telemetry...', + 'Cleaning Data...', + 'Running AI Transformers...', + 'Loading to Warehouse...' + ]; + let i = 0; + const interval = setInterval(() => { + if (i < steps.length) { + setAiStatus(steps[i]); + setPipelineStep(i + 1); + i++; + } else { + clearInterval(interval); + setAiStatus('Pipeline Complete.'); + logToBlockchain('Data Pipeline Executed'); + } + }, 800); + }; + + const runSecurityScan = () => { + setAiStatus('Scanning for anomalies...'); + setTimeout(() => { + setSecurityScan({ + anomaly: "CRITICAL: Route deviation 22% detected near high-risk zone.", + iotRisk: "MEDIUM: 3 sensors running outdated firmware.", + fraud: "CLEAN: All invoices verified for this shipment." + }); + setAiStatus('Security Scan Complete.'); + logToBlockchain('Security Audit Triggered'); + }, 2000); + }; + return ( -
-

Supply Chain & Digital Twin Platform

+
+
+

Supply Chain & Logistics AI Platform

+ Enhanced Data Engineering & Security Integration +
-
- - - +
+ + + + +
{activeTab === 'twin' && ( @@ -135,17 +209,35 @@ export default function SupplyChainPlatform() { {activeTab === 'incoterms' && (

Incoterms 2020 Navigator

- -
- {selectedTerm}: {INCOTERMS_DATA[selectedTerm]} +
+
    + {Object.keys(INCOTERMS_DATA).map(term => ( +
  • setSelectedTerm(term)} + style={{ + padding: '10px', + cursor: 'pointer', + background: selectedTerm === term ? '#444' : '#333', + marginBottom: '5px', + borderRadius: '4px' + }} + > + {term} - {INCOTERMS_DATA[term].desc.split(':')[0]} +
  • + ))} +
+
+

{selectedTerm} Details

+

{INCOTERMS_DATA[selectedTerm].desc}

+ + + + + + +
Risk Transfer{INCOTERMS_DATA[selectedTerm].risk}
Cost Transfer{INCOTERMS_DATA[selectedTerm].cost}
Transport Modes{INCOTERMS_DATA[selectedTerm].modes}
+
)} @@ -154,14 +246,15 @@ export default function SupplyChainPlatform() {

Logistics Optimizer

+

AI-driven route and delay prediction based on live environmental data.

setTrackingId(e.target.value)} - style={{ padding: '10px', width: '80%', marginBottom: '10px' }} + style={{ padding: '10px', width: '80%', marginBottom: '10px', background: '#333', color: 'white', border: '1px solid #555' }} /> - +

Status: {aiStatus}

@@ -180,9 +273,100 @@ export default function SupplyChainPlatform() {
)} -
- Supply Chain AI Services Software v1.0.0 | Integrated with Digital Twin & Web3 Ledger. + {activeTab === 'security' && ( +
+

AI Security & Risk Analyzer

+
+ + System Status: {aiStatus} +
+ + {securityScan && ( +
+ + + +
+ )} +
+ )} + + {activeTab === 'data' && ( +
+

Data Engineering Pipeline

+

Visualize the flow of telemetry from IoT edge devices to the analytics warehouse.

+
+ = 1} label="IoT Ingestion" /> + = 1} /> + = 2} label="Cleaning" /> + = 2} /> + = 3} label="AI Transform" /> + = 3} /> + = 4} label="Data Warehouse" /> +
+ +
+ )} + +
+ Supply Chain AI Services Software v1.2.0 | Integrated with Digital Twin, Web3 Ledger & AI Security.
); } + +// --- Helper Components --- + +function btnStyle(active) { + return { + padding: '10px 15px', + background: active ? '#444' : '#222', + color: active ? '#00ff00' : 'white', + border: '1px solid #555', + borderRadius: '4px', + cursor: 'pointer', + fontWeight: active ? 'bold' : 'normal' + }; +} + +function SecurityCard({ title, status, desc, color }) { + return ( +
+

{title}

+
Status: {status}
+

{desc}

+
+ ); +} + +function PipelineNode({ active, label }) { + return ( +
+
+ {active ? '✅' : '⚙️'} +
+ {label} +
+ ); +} + +function Arrow({ active }) { + return ( +
+ {active &&
} +
+ ); +} diff --git a/supply_chain_platform/ai_logistics_engine.py b/supply_chain_platform/ai_logistics_engine.py index 5bc00df..e1a952f 100644 --- a/supply_chain_platform/ai_logistics_engine.py +++ b/supply_chain_platform/ai_logistics_engine.py @@ -37,6 +37,40 @@ def analyze_supply_chain_risk(self, inventory_level, demand_forecast): else: return "LOW: Healthy inventory levels." +class DataEngineeringPipe: + """Simulates Data Engineering processes for Supply Chain Analytics.""" + + def simulate_pipeline(self, batch_size=100): + print(f"[*] Ingesting {batch_size} events from IoT Gateway...") + time.sleep(0.5) + print(f"[*] Processing: Normalizing timestamps and cleaning null values...") + time.sleep(0.5) + print(f"[*] Transform: Calculating rolling averages for sensor telemetry...") + time.sleep(0.5) + print(f"[*] Load: Storing results in Data Warehouse and Vector DB...") + return {"status": "SUCCESS", "records_processed": batch_size, "latency_ms": random.randint(100, 500)} + +class TransportOptimizer: + """Advanced Transportation & Route Optimization.""" + + def calculate_multimodal_cost(self, distance, weight, mode='Truck'): + """Calculates cost based on transport mode.""" + rates = { + "Truck": 1.5, # $ per km per ton + "Rail": 0.8, + "Sea": 0.2, + "Air": 5.0 + } + rate = rates.get(mode, 1.5) + cost = distance * (weight / 1000) * rate + carbon_footprint = distance * (weight / 1000) * (rate * 0.1) # Simplified CO2 estimate + + return { + "mode": mode, + "estimated_cost_usd": round(cost, 2), + "carbon_footprint_kg": round(carbon_footprint, 2) + } + if __name__ == "__main__": engine = AILogisticsEngine() print(f"Predicted Delay: {engine.predict_delivery_delay(5000, 'storm')} hours") diff --git a/supply_chain_platform/incoterms_data.json b/supply_chain_platform/incoterms_data.json index 73947da..71fcdcb 100644 --- a/supply_chain_platform/incoterms_data.json +++ b/supply_chain_platform/incoterms_data.json @@ -2,21 +2,89 @@ "EXW": { "name": "Ex Works", "description": "The seller makes the goods available at their premises. The buyer bears all costs and risks of moving the goods to the destination.", - "responsibilities": "Buyer covers all costs and risks from the seller's door." + "responsibilities": "Buyer covers all costs and risks from the seller's door.", + "risk_transfer": "At seller's premises (not loaded)", + "cost_transfer": "At seller's premises (not loaded)", + "transport_modes": "Any" + }, + "FCA": { + "name": "Free Carrier", + "description": "The seller delivers the goods to the carrier or another person nominated by the buyer at the seller's premises or another named place.", + "responsibilities": "Seller is responsible for loading goods onto the buyer's carrier.", + "risk_transfer": "When goods delivered to the carrier at the named place", + "cost_transfer": "When goods delivered to the carrier at the named place", + "transport_modes": "Any" + }, + "FAS": { + "name": "Free Alongside Ship", + "description": "The seller delivers when the goods are placed alongside the vessel nominated by the buyer at the named port of shipment.", + "responsibilities": "Seller covers costs until goods are alongside the ship.", + "risk_transfer": "When goods are placed alongside the ship", + "cost_transfer": "When goods are placed alongside the ship", + "transport_modes": "Sea and Inland Waterway" }, "FOB": { "name": "Free On Board", "description": "The seller delivers the goods on board the vessel nominated by the buyer at the named port of shipment.", - "responsibilities": "Seller covers costs until goods are on the ship. Buyer covers everything after." + "responsibilities": "Seller covers costs until goods are on the ship. Buyer covers everything after.", + "risk_transfer": "When goods are on board the vessel", + "cost_transfer": "When goods are on board the vessel", + "transport_modes": "Sea and Inland Waterway" + }, + "CFR": { + "name": "Cost and Freight", + "description": "The seller delivers the goods on board the vessel and pays the costs and freight to bring the goods to the named port of destination.", + "responsibilities": "Seller pays freight to destination port; Buyer assumes risk once goods are on board.", + "risk_transfer": "When goods are on board the vessel", + "cost_transfer": "At destination port", + "transport_modes": "Sea and Inland Waterway" }, "CIF": { "name": "Cost, Insurance, and Freight", - "description": "The seller delivers the goods on board the vessel and pays the costs and freight to bring the goods to the named port of destination.", - "responsibilities": "Seller covers freight and insurance to the destination port." + "description": "The seller delivers the goods on board the vessel and pays the costs and freight to bring the goods to the named port of destination, including insurance.", + "responsibilities": "Seller covers freight and insurance to the destination port.", + "risk_transfer": "When goods are on board the vessel", + "cost_transfer": "At destination port", + "transport_modes": "Sea and Inland Waterway" + }, + "CPT": { + "name": "Carriage Paid To", + "description": "The seller delivers the goods to the carrier and pays for carriage to the named place of destination.", + "responsibilities": "Seller pays for carriage to destination; Buyer assumes risk once goods are with the first carrier.", + "risk_transfer": "When goods are delivered to the first carrier", + "cost_transfer": "At named place of destination", + "transport_modes": "Any" + }, + "CIP": { + "name": "Carriage and Insurance Paid To", + "description": "The seller delivers the goods to the carrier and pays for carriage and insurance to the named place of destination.", + "responsibilities": "Seller pays for carriage and insurance to destination; Buyer assumes risk once goods are with first carrier.", + "risk_transfer": "When goods are delivered to the first carrier", + "cost_transfer": "At named place of destination", + "transport_modes": "Any" + }, + "DAP": { + "name": "Delivered at Place", + "description": "The seller delivers when the goods are placed at the disposal of the buyer on the arriving means of transport ready for unloading at the named place of destination.", + "responsibilities": "Seller covers all costs/risks until arrival at the named place, except unloading and import clearance.", + "risk_transfer": "At named place of destination (ready for unloading)", + "cost_transfer": "At named place of destination (ready for unloading)", + "transport_modes": "Any" + }, + "DPU": { + "name": "Delivered at Place Unloaded", + "description": "The seller delivers when the goods, once unloaded, are placed at the disposal of the buyer at a named place of destination.", + "responsibilities": "Seller covers all costs/risks including unloading at destination, except import clearance.", + "risk_transfer": "At named place of destination (unloaded)", + "cost_transfer": "At named place of destination (unloaded)", + "transport_modes": "Any" }, "DDP": { "name": "Delivered Duty Paid", "description": "The seller delivers the goods to the buyer, cleared for import and not unloaded from any arriving means of transport at the named place of destination.", - "responsibilities": "Seller covers all costs and risks including import duties and taxes." + "responsibilities": "Seller covers all costs and risks including import duties and taxes.", + "risk_transfer": "At named place of destination (ready for unloading)", + "cost_transfer": "At named place of destination (cleared for import)", + "transport_modes": "Any" } } diff --git a/supply_chain_platform/security_tools.py b/supply_chain_platform/security_tools.py new file mode 100644 index 0000000..fb36128 --- /dev/null +++ b/supply_chain_platform/security_tools.py @@ -0,0 +1,96 @@ +import random +import hashlib +import time + +class SupplyChainSecurityAnalyzer: + """AI-driven security analyzer for Supply Chain and Logistics.""" + + def detect_shipment_anomaly(self, shipment_data): + """ + Detects anomalies in shipment tracking data. + shipment_data: dict with 'current_location', 'expected_route', 'temperature', etc. + """ + anomalies = [] + + # 1. Route Deviation Check + if shipment_data.get('route_deviation', 0) > 15: # > 15% deviation + anomalies.append(f"CRITICAL: Major route deviation detected ({shipment_data['route_deviation']}%).") + + # 2. Environmental Security (e.g., Cold Chain) + temp = shipment_data.get('temperature') + max_temp = shipment_data.get('max_allowed_temp') + if temp and max_temp and temp > max_temp: + anomalies.append(f"WARNING: Temperature excursion detected: {temp}°C (Max: {max_temp}°C).") + + # 3. Unscheduled Stops + if shipment_data.get('unscheduled_stops', 0) > 2: + anomalies.append("SUSPICIOUS: Multiple unscheduled stops in high-risk zone.") + + if not anomalies: + return "SECURE: No anomalies detected in current shipment telemetry." + return " | ".join(anomalies) + + def assess_iot_cyber_risk(self, device_info): + """ + Assesses cybersecurity risk for IoT sensors used in logistics. + device_info: dict with 'firmware_version', 'last_patch_date', 'protocol' + """ + score = 100 + reasons = [] + + # Outdated Firmware + if device_info.get('outdated_firmware', False): + score -= 30 + reasons.append("Outdated firmware version.") + + # Insecure Protocol + if device_info.get('protocol') in ['HTTP', 'Telnet', 'MQTT-Unencrypted']: + score -= 40 + reasons.append(f"Insecure communication protocol: {device_info.get('protocol')}.") + + # Default Credentials (simulated check) + if device_info.get('uses_default_creds', False): + score -= 50 + reasons.append("Device using default administrative credentials.") + + risk_level = "LOW" + if score < 40: risk_level = "CRITICAL" + elif score < 70: risk_level = "MEDIUM" + + return { + "risk_score": max(0, score), + "risk_level": risk_level, + "vulnerabilities": reasons if reasons else ["None detected"] + } + + def verify_invoice_integrity(self, invoice_id, amount, vendor_id): + """ + Simulates AI fraud detection for logistics invoices. + Checks for duplicate billing or anomalous amounts. + """ + # Simulated 'AI' logic + if amount > 50000 and vendor_id == "NEW_VENDOR": + return "FLAGGED: High-value invoice from unverified new vendor. Manual audit required." + + # Simulate check against previous averages + if random.random() < 0.05: # 5% chance of simulating a fraudulent match + return "FLAGGED: Potential duplicate invoice detected (ID match with 2023-X92)." + + return "VERIFIED: Invoice matches historical patterns and vendor profile." + +if __name__ == "__main__": + analyzer = SupplyChainSecurityAnalyzer() + + # Test Shipment Anomaly + print("--- Shipment Security Check ---") + shipment = {"route_deviation": 20, "temperature": -2, "max_allowed_temp": -10} + print(analyzer.detect_shipment_anomaly(shipment)) + + # Test IoT Risk + print("\n--- IoT Cybersecurity Assessment ---") + device = {"protocol": "HTTP", "uses_default_creds": True} + print(analyzer.assess_iot_cyber_risk(device)) + + # Test Invoice Integrity + print("\n--- Logistics Fraud Detection ---") + print(analyzer.verify_invoice_integrity("INV-001", 75000, "NEW_VENDOR")) diff --git a/supply_chain_platform/supply_chain_main.py b/supply_chain_platform/supply_chain_main.py index 82e59e2..2f77060 100644 --- a/supply_chain_platform/supply_chain_main.py +++ b/supply_chain_platform/supply_chain_main.py @@ -1,6 +1,7 @@ import json import os -from ai_logistics_engine import AILogisticsEngine +from ai_logistics_engine import AILogisticsEngine, DataEngineeringPipe, TransportOptimizer +from security_tools import SupplyChainSecurityAnalyzer def load_incoterms(): path = os.path.join(os.path.dirname(__file__), 'incoterms_data.json') @@ -9,15 +10,19 @@ def load_incoterms(): def display_menu(): print("\n=== Supply Chain & Logistics AI Platform ===") - print("1. Incoterms Lookup") - print("2. AI Delivery Delay Predictor") - print("3. Inventory Risk Analysis") - print("4. Exit") + print("1. Incoterms Explorer") + print("2. AI Logistics & Transport Tools") + print("3. Security & Risk Analyzer (AI)") + print("4. Data Engineering Pipeline Simulation") + print("5. Exit") print("============================================") def main(): incoterms = load_incoterms() ai_engine = AILogisticsEngine() + transport = TransportOptimizer() + security = SupplyChainSecurityAnalyzer() + data_eng = DataEngineeringPipe() while True: display_menu() @@ -28,31 +33,79 @@ def main(): term = input("Enter term for details: ").upper() if term in incoterms: data = incoterms[term] - print(f"\n[{data['name']}]") + print(f"\n[{data['name']} - {term}]") print(f"Description: {data['description']}") print(f"Responsibilities: {data['responsibilities']}") + print(f"Risk Transfer: {data.get('risk_transfer', 'N/A')}") + print(f"Cost Transfer: {data.get('cost_transfer', 'N/A')}") + print(f"Transport Modes: {data.get('transport_modes', 'N/A')}") else: print("Term not found.") elif choice == '2': - try: - dist = float(input("Enter route distance (km): ")) - weather = input("Enter weather (clear, rain, storm, snow): ").lower() - delay = ai_engine.predict_delivery_delay(dist, weather) - print(f"\nAI Prediction: Estimated delay of {delay} hours due to {weather} conditions over {dist}km.") - except ValueError: - print("Invalid distance.") + print("\n--- Logistics & Transport AI ---") + print("a. Delivery Delay Predictor") + print("b. Multimodal Transport Cost Estimator") + print("c. Inventory Risk Analysis") + sub_choice = input("Select sub-option: ").lower() + + if sub_choice == 'a': + try: + dist = float(input("Enter route distance (km): ")) + weather = input("Enter weather (clear, rain, storm, snow): ").lower() + delay = ai_engine.predict_delivery_delay(dist, weather) + print(f"\nAI Prediction: Estimated delay of {delay} hours.") + except ValueError: + print("Invalid input.") + elif sub_choice == 'b': + try: + dist = float(input("Distance (km): ")) + weight = float(input("Weight (kg): ")) + mode = input("Mode (Truck, Rail, Sea, Air): ").capitalize() + res = transport.calculate_multimodal_cost(dist, weight, mode) + print(f"\nTransport Analysis: {res}") + except ValueError: + print("Invalid input.") + elif sub_choice == 'c': + try: + inv = float(input("Current Inventory: ")) + demand = float(input("Demand Forecast: ")) + risk = ai_engine.analyze_supply_chain_risk(inv, demand) + print(f"\nAI Risk Assessment: {risk}") + except ValueError: + print("Invalid input.") elif choice == '3': - try: - inv = float(input("Current Inventory Level: ")) - demand = float(input("Forecasted Demand: ")) - risk = ai_engine.analyze_supply_chain_risk(inv, demand) - print(f"\nAI Risk Assessment: {risk}") - except ValueError: - print("Invalid numbers.") + print("\n--- Security & Risk AI ---") + print("a. Shipment Anomaly Detection") + print("b. IoT Device Cyber Risk Assessment") + print("c. Invoice Integrity Check") + sub_choice = input("Select sub-option: ").lower() + + if sub_choice == 'a': + dev = float(input("Route Deviation % (e.g. 10): ")) + temp = float(input("Current Temp: ")) + max_t = float(input("Max Allowed Temp: ")) + res = security.detect_shipment_anomaly({"route_deviation": dev, "temperature": temp, "max_allowed_temp": max_t}) + print(f"\nSecurity Scan: {res}") + elif sub_choice == 'b': + prot = input("IoT Protocol (HTTP, MQTT, etc.): ") + def_c = input("Uses default credentials? (y/n): ").lower() == 'y' + res = security.assess_iot_cyber_risk({"protocol": prot, "uses_default_creds": def_c}) + print(f"\nCyber Risk Report: {res}") + elif sub_choice == 'c': + amt = float(input("Invoice Amount: ")) + vend = input("Vendor ID: ") + res = security.verify_invoice_integrity("ID-1", amt, vend) + print(f"\nFraud Analysis: {res}") elif choice == '4': + print("\n--- Data Engineering Pipeline ---") + batch = int(input("Enter batch size to process: ")) + results = data_eng.simulate_pipeline(batch) + print(f"\nPipeline Execution Complete: {results}") + + elif choice == '5': print("Exiting Supply Chain Platform.") break else: