File "bulk_upload_processor.php"
Full path: /home2/santhos2/public_html/bharath-coe.firstmatrix.in.net/api/bulk_upload_processor.php
File size: 8.53 KiB (8737 bytes)
MIME-type: text/x-php
Charset: utf-8
<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
class BulkUploadProcessor {
private $pdo;
private $errors = [];
private $successCount = 0;
private $errorCount = 0;
private $duplicateCount = 0;
private $processedRecords = [];
public function __construct($pdo) {
$this->pdo = $pdo;
}
/**
* Process bulk upload from Excel file
*/
public function processBulkUpload($filePath) {
try {
// Load the spreadsheet
$spreadsheet = IOFactory::load($filePath);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
// Skip header row (row 1), start from row 2
$startRow = 2;
for ($row = $startRow; $row <= $highestRow; $row++) {
$rowData = $worksheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, null, true, false)[0];
// Skip empty rows
if (empty(array_filter($rowData))) {
continue;
}
$record = $this->parseRecord($rowData, $row);
$this->validateAndSaveRecord($record, $row);
}
return $this->generateResponse();
} catch (Exception $e) {
return [
'status' => 'error',
'message' => 'Upload processing failed: ' . $e->getMessage()
];
}
}
/**
* Parse Excel row data into record array
*/
private function parseRecord($rowData, $rowNumber) {
return [
'project_title' => trim($rowData[0] ?? ''),
'student_name' => trim($rowData[1] ?? ''),
'email' => trim($rowData[2] ?? ''),
'address' => trim($rowData[3] ?? ''),
'phone' => trim($rowData[4] ?? ''),
'department' => trim($rowData[5] ?? ''),
'year' => trim($rowData[6] ?? ''),
'project_description' => trim($rowData[7] ?? ''),
'status' => trim($rowData[8] ?? ''),
'row_number' => $rowNumber
];
}
/**
* Validate and save individual record
*/
private function validateAndSaveRecord($record, $rowNumber) {
$errors = $this->validateRecord($record);
if (empty($errors)) {
// No validation errors, attempt to save
try {
$this->saveRecord($record);
$this->successCount++;
$this->processedRecords[] = array_merge($record, [
'upload_status' => 'success',
'error_message' => null
]);
} catch (Exception $e) {
$this->errorCount++;
$errorMsg = $e->getMessage();
if (strpos($errorMsg, 'Duplicate entry') !== false) {
$this->duplicateCount++;
$errorMsg = 'Email address already exists';
}
$this->processedRecords[] = array_merge($record, [
'upload_status' => 'error',
'error_message' => $errorMsg
]);
}
} else {
// Validation errors found
$this->errorCount++;
$this->processedRecords[] = array_merge($record, [
'upload_status' => 'error',
'error_message' => implode('; ', $errors)
]);
}
}
/**
* Validate record data
*/
private function validateRecord($record) {
$errors = [];
// Required field validations
if (empty($record['project_title'])) {
$errors[] = 'Project title is required';
}
if (empty($record['student_name'])) {
$errors[] = 'Student name is required';
}
if (empty($record['email'])) {
$errors[] = 'Email is required';
} elseif (!filter_var($record['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email format';
}
if (empty($record['address'])) {
$errors[] = 'Address is required';
}
// Optional field validations
if (!empty($record['phone']) && !preg_match('/^[0-9+\-\s()]+$/', $record['phone'])) {
$errors[] = 'Invalid phone number format';
}
if (!empty($record['status']) && !in_array(strtolower($record['status']), ['active', 'inactive', 'pending'])) {
$errors[] = 'Status must be active, inactive, or pending';
}
return $errors;
}
/**
* Save record to database
*/
private function saveRecord($record) {
// Set default values
$record['status'] = !empty($record['status']) ? strtolower($record['status']) : 'pending';
$stmt = $this->pdo->prepare("
INSERT INTO sample_projects
(project_title, student_name, email, address, phone, department, year, project_description, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$record['project_title'],
$record['student_name'],
$record['email'],
$record['address'],
$record['phone'] ?: null,
$record['department'] ?: null,
$record['year'] ?: null,
$record['project_description'] ?: null,
$record['status']
]);
// Get the inserted ID
$record['id'] = $this->pdo->lastInsertId();
}
/**
* Generate response with results
*/
private function generateResponse() {
// Separate successful and failed records
$successfulRecords = array_filter($this->processedRecords, function($record) {
return $record['upload_status'] === 'success';
});
$failedRecords = array_filter($this->processedRecords, function($record) {
return $record['upload_status'] === 'error';
});
return [
'status' => 'success',
'message' => "Processed {$this->successCount + $this->errorCount} records. " .
"Successful: {$this->successCount}, Failed: {$this->errorCount}",
'data' => [
'total_processed' => count($this->processedRecords),
'successful_uploads' => $this->successCount,
'failed_uploads' => $this->errorCount,
'duplicate_records' => $this->duplicateCount,
'successful_records' => array_values($successfulRecords),
'failed_records' => array_values($failedRecords),
'all_records' => $this->processedRecords
]
];
}
}
// Handle API requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
if ($action === 'bulk_upload_projects') {
if (!isset($_FILES['excel_file']) || $_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {
header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => 'No file uploaded or upload error']);
exit;
}
$tempFile = $_FILES['excel_file']['tmp_name'];
$fileName = $_FILES['excel_file']['name'];
$fileSize = $_FILES['excel_file']['size'];
// Validate file
$allowedExtensions = ['xlsx', 'xls'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!in_array($fileExtension, $allowedExtensions)) {
header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => 'Invalid file type. Only .xlsx and .xls files are allowed']);
exit;
}
if ($fileSize > 10 * 1024 * 1024) { // 10MB limit
header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => 'File size exceeds 10MB limit']);
exit;
}
// Process the upload
$processor = new BulkUploadProcessor($pdo);
$result = $processor->processBulkUpload($tempFile);
header('Content-Type: application/json');
echo json_encode($result);
} else {
header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
}
?>