Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | import cliProgress from 'cli-progress';
import { globby } from 'globby';
import mime from 'mime-types';
import path from 'path';
import databaseService from '../services/DatabaseService.js';
import logger from '../services/LoggingService.js';
import watchService from '../services/WatchService.js';
import uploadServiceFactory from '../services/upload/UploadServiceFactory.js';
import appConfig from '../config/config.js';
import ErrorHandler from '../errors/ErrorHandler.js';
import {
ConfigurationError,
FileOperationError,
} from '../errors/ErrorTypes.js';
import FileOperations from '../utils/FileOperations.js';
import fileSanitizer from '../utils/FileSanitizer.js';
import pathDetector from '../utils/PathDetector.js';
/**
* Upload Command Handler
* Handles the main upload functionality
*/
export class UploadCommand {
constructor() {
this.errorHandler = new ErrorHandler(logger);
}
/**
* Execute the upload command
* @param {Object} options - Command options
*/
async execute(options) {
try {
// Prevent direct uploads while in watch mode
if (watchService.isWatchActive()) {
logger.error('ā Cannot upload directly while in watch mode');
logger.info('š” Files in watch mode are processed automatically');
logger.info(
'š” Stop watch mode first (Ctrl+C) before using upload command',
);
return {
success: false,
reason: 'Watch mode is active - cannot upload directly',
source: null,
stats: {
successCount: 0,
detectedCount: 0,
organizedCount: 0,
failureCount: 0,
skippedCount: 0,
},
};
}
// Validate configuration
this.#validateOptions(options);
// Initialize services
const uploadService = await uploadServiceFactory.getUploadService(
options.forceSupabase,
);
const sources = appConfig.getUploadSources();
const basePath = appConfig.getBasePath();
// Log command start
logger.info(`Starting upload with ${uploadService.getServiceName()}`);
if (options.clearLog) {
logger.clearLogFile();
logger.info('Log file cleared');
}
// Process each source with configurable concurrency
let globalResults = {
successCount: 0,
detectedCount: 0,
organizedCount: 0,
failureCount: 0,
skippedCount: 0,
};
// Determine processing strategy based on configuration
const maxConcurrentSources =
appConfig.performance?.maxConcurrentSources || 1;
if (maxConcurrentSources > 1 && sources.length > 1) {
// Parallel source processing
logger.info(
`Processing ${sources.length} sources with concurrency: ${maxConcurrentSources}`,
);
// Process sources in batches to control concurrency
for (let i = 0; i < sources.length; i += maxConcurrentSources) {
const sourceBatch = sources.slice(i, i + maxConcurrentSources);
const sourcePromises = sourceBatch.map(async (source) => {
const sourcePath = path
.resolve(basePath, source)
.replace(/\\/g, '/');
logger.info(`Processing folder: ${sourcePath}`);
try {
const files = await this.#discoverFiles(sourcePath);
logger.info(`Found ${files.length} files in ${source}`);
const result = await this.#processFilesInBatches(
files,
options,
uploadService,
basePath,
source,
sourcePath,
);
this.#logSourceSummary(source, result, options);
return { success: true, source, result };
} catch (error) {
this.errorHandler.handleError(error, { source, sourcePath });
return { success: false, source, error: error.message };
}
});
// Wait for this batch of sources to complete
const results = await Promise.allSettled(sourcePromises);
results.forEach((result) => {
if (result.status === 'fulfilled') {
const sourceResult = result.value;
if (sourceResult.success) {
this.#updateGlobalResults(globalResults, sourceResult.result);
} else {
globalResults.failureCount++;
}
} else {
globalResults.failureCount++;
}
});
}
} else {
// Sequential source processing (original behavior)
for (const source of sources) {
const sourcePath = path.resolve(basePath, source).replace(/\\/g, '/');
logger.info(`Processing folder: ${sourcePath}`);
try {
const files = await this.#discoverFiles(sourcePath);
logger.info(`Found ${files.length} files to process`);
const result = await this.#processFilesInBatches(
files,
options,
uploadService,
basePath,
source,
sourcePath,
);
this.#updateGlobalResults(globalResults, result);
this.#logSourceSummary(source, result, options);
} catch (error) {
this.errorHandler.handleError(error, { source, sourcePath });
globalResults.failureCount++;
}
}
}
this.#logFinalSummary(globalResults, options, uploadService);
// Handle additional phases if requested
if (options.runAllPhases && options.statsOnly) {
await this.#runAdditionalPhases(options);
}
} catch (error) {
this.errorHandler.handleFatalError(error, { command: 'upload', options });
}
}
/**
* Validate command options
* @private
* @param {Object} options - Options to validate
*/
#validateOptions(options) {
try {
appConfig.validateConfiguration(options.forceSupabase);
} catch (error) {
throw new ConfigurationError(error.message);
}
if (
options.batchSize &&
(options.batchSize < 1 || options.batchSize > 100)
) {
throw new ConfigurationError('Batch size must be between 1 and 100');
}
}
/**
* Discover files in a source path
* @private
* @param {string} sourcePath - Path to discover files in
* @returns {Promise<string[]>} Array of file paths
*/
async #discoverFiles(sourcePath) {
try {
if (!FileOperations.fileExists(sourcePath)) {
throw new FileOperationError(
`Source path does not exist: ${sourcePath}`,
);
}
const stats = FileOperations.getFileStats(sourcePath);
if (stats?.isDirectory()) {
return await globby([`${sourcePath}/**/*`], { onlyFiles: true });
} else {
return [sourcePath];
}
} catch (error) {
throw new FileOperationError(
`Failed to discover files in ${sourcePath}`,
sourcePath,
{ originalError: error.message },
);
}
}
/**
* Process files in batches
* @private
* @param {string[]} files - Files to process
* @param {Object} options - Processing options
* @param {Object} uploadService - Upload service instance
* @param {string} basePath - Base path
* @param {string} source - Source name
* @param {string} sourcePath - Source path
* @returns {Promise<Object>} Processing results
*/
async #processFilesInBatches(
files,
options,
uploadService,
basePath,
source,
sourcePath,
) {
const batchSize =
parseInt(options.batchSize) || appConfig.performance.batchSize || 50;
const results = {
successCount: 0,
detectedCount: 0,
organizedCount: 0,
failureCount: 0,
skippedCount: 0,
};
// Get processed paths if available
const processedPaths = options.skipProcessed
? databaseService.getProcessedPaths()
: new Set();
// Create progress bar
const progressBar = new cliProgress.SingleBar({
format: `š¤ ${source} |{bar}| {percentage}% | {value}/{total} | Success: {success} | Errors: {errors}`,
barCompleteChar: 'ā',
barIncompleteChar: 'ā',
hideCursor: true,
clearOnComplete: false,
stopOnComplete: true,
stream: process.stderr, // Use stderr to separate from stdout logging
});
progressBar.start(files.length, 0, { success: 0, errors: 0 });
// Process files in batches
for (let i = 0; i < files.length; i += batchSize) {
const batch = files.slice(i, i + batchSize);
try {
const batchResult = await this.#processBatch(
batch,
options,
uploadService,
basePath,
processedPaths,
);
this.#updateResults(results, batchResult);
progressBar.update(Math.min(i + batchSize, files.length), {
success: results.successCount,
errors: results.failureCount,
});
// Delay between batches if configured
if (appConfig.performance.batchDelay > 0) {
await new Promise((resolve) =>
setTimeout(resolve, appConfig.performance.batchDelay),
);
}
} catch (error) {
this.errorHandler.handleError(error, {
batch: i / batchSize + 1,
batchSize,
});
results.failureCount += batch.length;
}
}
progressBar.stop();
return results;
}
/**
* Process a batch of files
* @private
* @param {string[]} batch - Files in this batch
* @param {Object} options - Processing options
* @param {Object} uploadService - Upload service
* @param {string} basePath - Base path
* @param {Set} processedPaths - Already processed paths
* @returns {Promise<Object>} Batch results
*/
async #processBatch(batch, options, uploadService, basePath, processedPaths) {
const batchResults = {
successCount: 0,
detectedCount: 0,
organizedCount: 0,
failureCount: 0,
skippedCount: 0,
};
if (options.statsOnly) {
// Stats-only mode: just record file information
const fileObjects = batch.map((filePath) => ({
path: filePath,
originalName: path.basename(filePath),
stats: FileOperations.getFileStats(filePath),
}));
try {
const result = await databaseService.insertStatsOnlyToUploaderTable(
fileObjects,
{
...options,
quietMode: options.quietMode || false, // Pass through quiet mode flag
},
);
batchResults.successCount = result.totalInserted;
batchResults.skippedCount = result.totalSkipped;
} catch (error) {
throw new Error(`Failed to insert stats: ${error.message}`);
}
} else {
// Upload mode: process files with controlled concurrency to match API replicas
const maxConcurrentApiCalls =
appConfig.performance?.maxApiConnections || 10;
// Process batch in chunks to respect API replica limits
const allResults = [];
for (let i = 0; i < batch.length; i += maxConcurrentApiCalls) {
const chunk = batch.slice(i, i + maxConcurrentApiCalls);
// Process this chunk concurrently (up to API replica count)
const chunkPromises = chunk.map(async (filePath) => {
try {
const result = await this.#processFile(
filePath,
options,
uploadService,
basePath,
processedPaths,
);
return { success: true, filePath, result };
} catch (error) {
this.errorHandler.handleError(error, { filePath });
return { success: false, filePath, error: error.message };
}
});
// Wait for this chunk to complete before starting the next
const chunkResults = await Promise.allSettled(chunkPromises);
allResults.push(...chunkResults);
// Small delay between chunks to prevent overwhelming API
if (i + maxConcurrentApiCalls < batch.length) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
}
// Process all results and update batch results
allResults.forEach((result) => {
if (result.status === 'fulfilled') {
const fileResult = result.value;
if (fileResult.success) {
if (fileResult.result && fileResult.result.skipped) {
batchResults.skippedCount++;
} else {
batchResults.successCount++;
if (fileResult.result && fileResult.result.detectedCount) {
batchResults.detectedCount += fileResult.result.detectedCount;
}
if (fileResult.result && fileResult.result.organizedCount) {
batchResults.organizedCount += fileResult.result.organizedCount;
}
}
} else {
batchResults.failureCount++;
}
} else {
batchResults.failureCount++;
}
});
}
return batchResults;
}
/**
* Process a single file
* @private
*/
async #processFile(
filePath,
options,
uploadService,
basePath,
processedPaths,
) {
// Skip if already processed
if (processedPaths.has(filePath)) {
return { skipped: true };
}
// Prepare file for upload
const sanitizedName = fileSanitizer.sanitizeFileName(
path.basename(filePath),
);
const pathInfo = pathDetector.extractYearAndPedimentoFromPath(
filePath,
basePath,
);
let uploadPath = sanitizedName;
if (pathInfo.detected && options.autoDetectStructure) {
uploadPath = `${pathInfo.year}/${pathInfo.pedimento}/${sanitizedName}`;
}
const fileObject = {
path: filePath,
name: sanitizedName,
contentType: this.#getMimeType(filePath),
};
// Upload based on service type
let result = { successCount: 1 };
if (uploadService.getServiceName() === 'Arela API') {
result = await uploadService.upload([fileObject], {
...options,
uploadPath,
});
} else {
// Supabase direct upload
const uploadResult = await uploadService.upload([fileObject], {
uploadPath,
});
// Check if upload was successful
if (!uploadResult.success) {
throw new Error(`Supabase upload failed: ${uploadResult.error}`);
}
result = { successCount: 1 };
}
logger.info(`SUCCESS: ${path.basename(filePath)} -> ${uploadPath}`);
return {
skipped: false,
detectedCount: result.detectedCount || 0,
organizedCount: result.organizedCount || 0,
};
}
/**
* Get MIME type for file
* @private
*/
#getMimeType(filePath) {
return mime.lookup(filePath) || 'application/octet-stream';
}
/**
* Update results object
* @private
*/
#updateResults(target, source) {
target.successCount += source.successCount;
target.detectedCount += source.detectedCount;
target.organizedCount += source.organizedCount;
target.failureCount += source.failureCount;
target.skippedCount += source.skippedCount;
}
/**
* Update global results
* @private
*/
#updateGlobalResults(global, source) {
this.#updateResults(global, source);
}
/**
* Log source summary
* @private
*/
#logSourceSummary(source, result, options) {
console.log(`\nš¦ Summary for ${source}:`);
if (options.statsOnly) {
console.log(` š Stats recorded: ${result.successCount}`);
console.log(` āļø Duplicates: ${result.skippedCount}`);
} else {
console.log(` ā
Uploaded: ${result.successCount}`);
if (result.detectedCount)
console.log(` š Detected: ${result.detectedCount}`);
if (result.organizedCount)
console.log(` š Organized: ${result.organizedCount}`);
console.log(` āļø Skipped: ${result.skippedCount}`);
}
console.log(` ā Errors: ${result.failureCount}`);
}
/**
* Log final summary
* @private
*/
#logFinalSummary(results, options, uploadService) {
console.log(`\n${'='.repeat(60)}`);
if (options.statsOnly) {
console.log(`š STATS COLLECTION COMPLETED`);
console.log(` š Total stats recorded: ${results.successCount}`);
console.log(` āļø Total duplicates: ${results.skippedCount}`);
} else {
console.log(
`šÆ ${uploadService.getServiceName().toUpperCase()} UPLOAD COMPLETED`,
);
console.log(` ā
Total uploaded: ${results.successCount}`);
if (results.detectedCount)
console.log(` š Total detected: ${results.detectedCount}`);
if (results.organizedCount)
console.log(` š Total organized: ${results.organizedCount}`);
console.log(` āļø Total skipped: ${results.skippedCount}`);
}
console.log(` ā Total errors: ${results.failureCount}`);
console.log(` š Log file: ${logger.getLogFilePath()}`);
console.log(`${'='.repeat(60)}\n`);
}
/**
* Run additional phases
* @private
*/
async #runAdditionalPhases(options) {
try {
// Phase 2: PDF Detection
console.log('\nš === PHASE 2: PDF Detection ===');
const detectionResult = await databaseService.detectPedimentosInDatabase({
batchSize:
parseInt(options.batchSize) || appConfig.performance.batchSize || 50,
});
console.log(
`ā
Phase 2 Complete: ${detectionResult.detectedCount} detected, ${detectionResult.errorCount} errors`,
);
// Additional phases would be implemented here
console.log('\nš All phases completed successfully!');
} catch (error) {
this.errorHandler.handleError(error, { phase: 'additional-phases' });
throw error;
}
}
}
export default UploadCommand;
|