Key Changes: - Fixed CSV transformation to create 16 separate files (one per ISO code) - Each CSV has all input rows with Language/Country replaced - Handles Excel Sep=, prefix correctly - Parses date format "24 Mar 2025 00:00" from sample CSV - Skip OMG API for testing (use business unit "TESTING") - Upload all 16 CSVs to Box folder - Show list of all files in preview - Download preview functionality PHP Compatibility: - Downgraded nesbot/carbon to ^2.0 (supports PHP 7.1+) - Downgraded league/csv to 9.8.0 (supports PHP 7.4+) - Now compatible with PHP 7.4-8.0 servers Preview Enhancements: - Shows all 16 filenames with ISO codes - Preview table shows first file as sample - Summary shows file count and total rows Testing: - Added sample CSV: Project_1601654_mediaBookings.csv - OMG API lookup commented out (ready to enable later) - Using "TESTING" as business unit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
193 lines
6.5 KiB
PHP
193 lines
6.5 KiB
PHP
<?php
|
|
/**
|
|
* Upload CSV to Box
|
|
* Uploads the processed CSV file to Box after user approval
|
|
*/
|
|
|
|
error_reporting(E_ALL);
|
|
ini_set('display_errors', 1);
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
try {
|
|
// Load dependencies
|
|
require_once __DIR__ . '/vendor/autoload.php';
|
|
require_once __DIR__ . '/AuthMiddleware.php';
|
|
require_once __DIR__ . '/BoxService.php';
|
|
require_once __DIR__ . '/EmailService.php';
|
|
|
|
// Authenticate
|
|
$auth = new AuthMiddleware();
|
|
$user = $auth->requireAuth();
|
|
|
|
// Check if processed data exists in session
|
|
session_start();
|
|
|
|
if (!isset($_SESSION['processed_csv'])) {
|
|
echo json_encode([
|
|
'success' => false,
|
|
'stage' => 'session',
|
|
'error' => 'No processed data found',
|
|
'details' => 'Session expired or CSV not processed',
|
|
'action' => 'Please upload and process the CSV again'
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
$processedData = $_SESSION['processed_csv'];
|
|
$csvFiles = $processedData['files'];
|
|
$campaignNumber = $processedData['campaignNumber'];
|
|
$businessUnit = $processedData['businessUnit'];
|
|
$fileCount = $processedData['fileCount'];
|
|
|
|
// Load config
|
|
$appConfig = require __DIR__ . '/config.php';
|
|
$outputFolderId = $appConfig['global_to_local']['output_box_folder_id'];
|
|
|
|
// Validate output folder is configured
|
|
if ($outputFolderId === 'XXXXXXXXX' || empty($outputFolderId)) {
|
|
echo json_encode([
|
|
'success' => false,
|
|
'stage' => 'config',
|
|
'error' => 'Output Box folder not configured',
|
|
'details' => 'The output_box_folder_id is not set in config.php',
|
|
'action' => 'Contact administrator to configure Box output folder'
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
// STAGE 7: Upload all CSVs to Box
|
|
$boxService = new BoxService();
|
|
$uploadedFiles = [];
|
|
$uploadErrors = [];
|
|
|
|
error_log("Uploading {$fileCount} CSV files to Box folder: {$outputFolderId}");
|
|
|
|
try {
|
|
// Authenticate with Box
|
|
$token = $boxService->authenticate();
|
|
|
|
// Upload each CSV file
|
|
foreach ($csvFiles as $csvFile) {
|
|
$filename = $csvFile['filename'];
|
|
$csvContent = $csvFile['content'];
|
|
|
|
try {
|
|
$url = 'https://upload.box.com/api/2.0/files/content';
|
|
|
|
$boundary = uniqid();
|
|
$delimiter = '-------------' . $boundary;
|
|
|
|
$postData = '';
|
|
$postData .= "--{$delimiter}\r\n";
|
|
$postData .= 'Content-Disposition: form-data; name="attributes"' . "\r\n\r\n";
|
|
$postData .= json_encode([
|
|
'name' => $filename,
|
|
'parent' => ['id' => $outputFolderId]
|
|
]) . "\r\n";
|
|
|
|
$postData .= "--{$delimiter}\r\n";
|
|
$postData .= 'Content-Disposition: form-data; name="file"; filename="' . $filename . '"' . "\r\n";
|
|
$postData .= 'Content-Type: text/csv' . "\r\n\r\n";
|
|
$postData .= $csvContent . "\r\n";
|
|
$postData .= "--{$delimiter}--\r\n";
|
|
|
|
$ch = curl_init($url);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_POST => true,
|
|
CURLOPT_POSTFIELDS => $postData,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => [
|
|
'Authorization: Bearer ' . $token,
|
|
'Content-Type: multipart/form-data; boundary=' . $delimiter,
|
|
'Content-Length: ' . strlen($postData)
|
|
],
|
|
CURLOPT_TIMEOUT => 60
|
|
]);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$curlError = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($curlError) {
|
|
throw new Exception('Upload failed: ' . $curlError);
|
|
}
|
|
|
|
if ($httpCode !== 201) {
|
|
$responseData = json_decode($response, true);
|
|
throw new Exception('HTTP ' . $httpCode . ': ' . ($responseData['message'] ?? $response));
|
|
}
|
|
|
|
$uploadedFile = json_decode($response, true);
|
|
$fileId = $uploadedFile['entries'][0]['id'] ?? null;
|
|
|
|
$uploadedFiles[] = [
|
|
'filename' => $filename,
|
|
'fileId' => $fileId,
|
|
'isoCode' => $csvFile['isoCode']
|
|
];
|
|
|
|
error_log("Uploaded: {$filename} (ID: {$fileId})");
|
|
|
|
} catch (Exception $fileError) {
|
|
error_log("Failed to upload {$filename}: " . $fileError->getMessage());
|
|
$uploadErrors[] = [
|
|
'filename' => $filename,
|
|
'error' => $fileError->getMessage()
|
|
];
|
|
}
|
|
}
|
|
|
|
// Check if all uploads succeeded
|
|
if (count($uploadErrors) > 0) {
|
|
$successCount = count($uploadedFiles);
|
|
throw new Exception("Uploaded {$successCount}/{$fileCount} files. " . count($uploadErrors) . " failed.");
|
|
}
|
|
|
|
// Send completion email
|
|
$emailService->notifyCompleted($user['email'], "{$fileCount} regional CSV files", count($uploadedFiles));
|
|
|
|
// Clear session data
|
|
unset($_SESSION['processed_csv']);
|
|
|
|
$folderUrl = 'https://app.box.com/folder/' . $outputFolderId;
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'stage' => 'complete',
|
|
'message' => "Successfully uploaded {$fileCount} CSV files to Box",
|
|
'data' => [
|
|
'uploadedFiles' => $uploadedFiles,
|
|
'fileCount' => $fileCount,
|
|
'folderUrl' => $folderUrl
|
|
]
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
error_log('Box upload exception: ' . $e->getMessage());
|
|
|
|
// Send error email
|
|
$emailService->notifyError($user['email'], $filename, $e->getMessage());
|
|
|
|
echo json_encode([
|
|
'success' => false,
|
|
'stage' => 'box_upload',
|
|
'error' => 'Failed to upload CSV to Box',
|
|
'details' => $e->getMessage(),
|
|
'action' => 'Check Box folder permissions and try again'
|
|
]);
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
error_log('Upload exception: ' . $e->getMessage());
|
|
|
|
echo json_encode([
|
|
'success' => false,
|
|
'stage' => 'exception',
|
|
'error' => 'Unexpected error occurred',
|
|
'details' => $e->getMessage(),
|
|
'file' => $e->getFile(),
|
|
'line' => $e->getLine()
|
|
]);
|
|
}
|