All files PropagateCommand.js

87.5% Statements 140/160
82.22% Branches 37/45
100% Functions 3/3
87.42% Lines 139/159

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                            27x           27x 27x 27x                         21x 21x     21x     20x     20x 20x           19x 1x     1x     19x     19x 20x   19x     19x             19x 20x 20x     20x   20x 20x 20x 20x       19x   19x       19x 19x 19x 19x     19x     19x     19x     19x 19x   2x 2x 2x     2x                   20x               20x     20x 16x   4x 4x       16x     16x 3x     3x     13x         13x 13x     13x   13x               21x     21x       21x 21x   1x 1x     20x 20x   20x               20x 20x       20x 20x 20x     20x     20x   20x                         16x 16x 16x     16x                         13x     13x     13x   13x         13x 13x 13x     13x                         13x 13x     13x         13x 13x   13x             13x               13x 8x 8x       5x             5x       5x           5x 1x       1x 1x     4x   2x                   1x 1x         1x 1x 1x                   4x 4x 4x     4x 4x   4x             5x     5x 5x       13x     13x   13x   13x 13x     13x     13x     13x 13x 13x   13x                         13x 13x       13x 13x 13x     13x     13x 13x   13x                 13x                                                  
import cliProgress from 'cli-progress';
 
import logger from '../services/LoggingService.js';
import ScanApiService from '../services/ScanApiService.js';
 
import appConfig from '../config/config.js';
 
/**
 * Propagate Command
 * Propagates arela_path from detected pedimentos to related files in the same directory
 * Optimized for large datasets with batch processing and progress tracking
 */
export class PropagateCommand {
  constructor(options = {}) {
    this.options = {
      batchSize: parseInt(options.batchSize) || 50, // Process 50 pedimentos at a time
      showStats: options.showStats || false,
      api: options.api || 'default',
    };
 
    this.scanApiService = null;
    this.tableName = null;
    this.stats = {
      startTime: Date.now(),
      pedimentosProcessed: 0,
      filesUpdated: 0,
      filesFailed: 0,
      directoriesProcessed: 0,
    };
  }
 
  /**
   * Main execution method
   */
  async execute() {
    try {
      console.log('šŸ”„ Starting arela propagate command\n');
 
      // Step 1: Validate configuration
      await this.#validateConfiguration();
 
      // Step 2: Initialize API service
      this.scanApiService = new ScanApiService();
 
      // Step 3: Fetch all tables for this instance
      const scanConfig = appConfig.getScanConfig();
      const tables = await this.scanApiService.getInstanceTables(
        scanConfig.companySlug,
        scanConfig.serverId,
        scanConfig.basePathFull,
      );
 
      if (tables.length === 0) {
        console.error(
          '\nāŒ No tables found for this instance. Run "arela scan" first.\n',
        );
        process.exit(1);
      }
 
      console.log(
        `šŸ“‹ Found ${tables.length} table${tables.length === 1 ? '' : 's'} to process:`,
      );
      for (const table of tables) {
        console.log(`   - ${table.tableName}`);
      }
      console.log();
 
      // Step 4: Process each table
      let totalStats = {
        pedimentosProcessed: 0,
        filesUpdated: 0,
        filesFailed: 0,
        directoriesProcessed: 0,
      };
 
      for (const table of tables) {
        console.log(`\nšŸ”„ Processing table: ${table.tableName}\n`);
        this.tableName = table.tableName;
 
        // Process this table
        const stats = await this.#processTable();
 
        totalStats.pedimentosProcessed += stats.pedimentosProcessed;
        totalStats.filesUpdated += stats.filesUpdated;
        totalStats.filesFailed += stats.filesFailed;
        totalStats.directoriesProcessed += stats.directoriesProcessed;
      }
 
      // Show combined results
      const duration = ((Date.now() - this.stats.startTime) / 1000).toFixed(2);
      const filesPerSec =
        totalStats.filesUpdated > 0
          ? (totalStats.filesUpdated / parseFloat(duration)).toFixed(1)
          : 0;
 
      console.log('\\nāœ… Propagation Complete!\\n');
      console.log(`šŸ“Š Total Results:`);
      console.log(`   Tables Processed: ${tables.length}`);
      console.log(
        `   Pedimentos Processed: ${totalStats.pedimentosProcessed.toLocaleString()}`,
      );
      console.log(
        `   Files Updated: ${totalStats.filesUpdated.toLocaleString()}`,
      );
      console.log(
        `   Files Failed: ${totalStats.filesFailed.toLocaleString()}`,
      );
      console.log(
        `   Directories Processed: ${totalStats.directoriesProcessed.toLocaleString()}`,
      );
      console.log(`   Duration: ${duration}s`);
      console.log(`   Speed: ${filesPerSec} files/sec\\n`);
    } catch (error) {
      logger.error('Propagation command failed:', error);
      console.error(`\\nāŒ Error: ${error.message}\\n`);
      Iif (process.env.VERBOSE || process.env.DEBUG) {
        console.error('Stack trace:', error.stack);
      }
      process.exit(1);
    }
  }
 
  /**
   * Process a single table
   * @private
   * @returns {Promise<Object>} Statistics for this table
   */
  async #processTable() {
    const tableStats = {
      pedimentosProcessed: 0,
      filesUpdated: 0,
      filesFailed: 0,
      directoriesProcessed: 0,
    };
 
    // Show initial statistics
    const initialStats = await this.#showInitialStats();
 
    // Mark files needing propagation (if we have pedimento sources)
    if (initialStats.pedimentoSources > 0) {
      await this.#markFilesForPropagation();
    } else {
      console.log('   ā„¹ļø  No pedimento sources found. Skipping.\\n');
      return tableStats;
    }
 
    // Check if there are files to propagate
    const statsAfterMarking = await this.scanApiService.getPropagationStats(
      this.tableName,
    );
    if (statsAfterMarking.pending === 0) {
      console.log(
        '   ā„¹ļø  All files already have arela_path. Nothing to propagate.\\n',
      );
      return tableStats;
    }
 
    console.log(
      `   šŸš€ Found ${statsAfterMarking.pending.toLocaleString()} files ready for propagation.\\n`,
    );
 
    // Process pedimentos and propagate arela_path
    const stats = await this.#processPropagation();
    Object.assign(tableStats, stats);
 
    // Show final statistics for this table
    await this.#showFinalStats();
 
    return tableStats;
  }
 
  /**
   * Validate scan configuration
   * @private
   */
  async #validateConfiguration() {
    logger.debug('Validating scan configuration...');
 
    // Set API target
    appConfig.setApiTarget(this.options.api);
 
    // Validate scan config (same as scan/identify commands)
    // Note: validateScanConfig() throws on error, doesn't return errors array
    try {
      appConfig.validateScanConfig();
    } catch (error) {
      console.error(`\\nāŒ ${error.message}\\n`);
      throw new Error('Invalid scan configuration');
    }
 
    console.log(`šŸŽÆ API Target: ${this.options.api}`);
    console.log(`šŸ“¦ Batch Size: ${this.options.batchSize}\\n`);
 
    logger.debug('Configuration validated');
  }
 
  /**
   * Show initial propagation statistics
   * @private
   */
  async #showInitialStats() {
    try {
      const stats = await this.scanApiService.getPropagationStats(
        this.tableName,
      );
 
      console.log('šŸ“ˆ Initial Status:');
      console.log(`   Total Files: ${stats.totalFiles.toLocaleString()}`);
      console.log(
        `   With arela_path: ${stats.withArelaPath.toLocaleString()}`,
      );
      console.log(
        `   Pedimento Sources: ${stats.pedimentoSources.toLocaleString()}`,
      );
      console.log(`   Errors: ${stats.errors.toLocaleString()}\n`);
 
      return stats;
    } catch (error) {
      logger.error('Failed to fetch initial stats:', error);
      throw new Error(`Failed to fetch propagation stats: ${error.message}`);
    }
  }
 
  /**
   * Mark files that need propagation
   * This is a preparation step that flags files for efficient processing
   * @private
   */
  async #markFilesForPropagation() {
    try {
      console.log('šŸ·ļø  Marking files needing propagation...');
      const result = await this.scanApiService.markFilesNeedingPropagation(
        this.tableName,
      );
      console.log(`āœ“ Marked ${result.markedCount.toLocaleString()} files\n`);
    } catch (error) {
      logger.error('Failed to mark files:', error);
      throw new Error(`Failed to mark files: ${error.message}`);
    }
  }
 
  /**
   * Process propagation in batches
   * Fetches pedimentos and propagates their arela_path to files in the same directory
   * @private
   */
  async #processPropagation() {
    console.log('šŸš€ Processing propagation...\n');
 
    // First, get the total count of pedimento sources
    const initialStats = await this.scanApiService.getPropagationStats(
      this.tableName,
    );
    const totalPedimentos = initialStats.pedimentoSources;
 
    Iif (totalPedimentos === 0) {
      console.log('ā„¹ļø  No pedimento sources found.\n');
      return;
    }
 
    let offset = 0;
    let hasMore = true;
    let processedCount = 0;
 
    // Create progress bar with actual total
    const progressBar = new cliProgress.SingleBar(
      {
        format:
          'šŸ“„ Propagating |{bar}| {percentage}% | {value}/{total} directories | {speed} files/sec | {filesUpdated} files updated',
        barCompleteChar: '\u2588',
        barIncompleteChar: '\u2591',
        hideCursor: true,
        clearOnComplete: false,
        stopOnComplete: true,
      },
      cliProgress.Presets.shades_classic,
    );
 
    const startTime = Date.now();
    let filesUpdated = 0;
 
    // Start progress bar with actual total
    progressBar.start(totalPedimentos, 0, {
      speed: '0',
      filesUpdated: 0,
    });
 
    try {
      while (hasMore) {
        // Fetch batch of pedimento sources
        const pedimentos = await this.scanApiService.fetchPedimentoSources(
          this.tableName,
          offset,
          this.options.batchSize,
        );
 
        // Validate response
        Iif (!pedimentos || !Array.isArray(pedimentos)) {
          logger.error(
            'Invalid response from fetchPedimentoSources:',
            pedimentos,
          );
          throw new Error('API returned invalid data format (expected array)');
        }
 
        if (pedimentos.length === 0) {
          hasMore = false;
          break;
        }
 
        // Process each pedimento's directory
        for (const pedimento of pedimentos) {
          const {
            id,
            directory_path,
            arela_path,
            rfc,
            detected_pedimento_year,
          } = pedimento;
 
          // Fetch files in the same directory
          const files =
            await this.scanApiService.fetchFilesNeedingPropagationByDirectory(
              this.tableName,
              directory_path,
            );
 
          // Validate response
          if (!files || !Array.isArray(files)) {
            logger.error(
              `Invalid response for directory ${directory_path}:`,
              files,
            );
            this.stats.filesFailed++;
            continue;
          }
 
          if (files.length > 0) {
            // Prepare batch update
            const updates = files.map((file) => ({
              id: file.id,
              arelaPath: arela_path,
              rfc: rfc,
              detectedPedimentoYear: detected_pedimento_year,
              propagatedFromId: id,
              propagationError: null,
            }));
 
            // Send batch update to API
            try {
              const result = await this.scanApiService.batchUpdatePropagation(
                this.tableName,
                updates,
              );
 
              filesUpdated += result.updated;
              this.stats.filesUpdated += result.updated;
              this.stats.filesFailed += result.errors;
            } catch (error) {
              logger.error(
                `Failed to update files in directory ${directory_path}:`,
                error,
              );
              this.stats.filesFailed += files.length;
            }
          }
 
          this.stats.directoriesProcessed++;
          this.stats.pedimentosProcessed++;
          processedCount++;
 
          // Update progress bar
          const elapsed = (Date.now() - startTime) / 1000;
          const speed = elapsed > 0 ? Math.round(filesUpdated / elapsed) : 0;
 
          progressBar.update(processedCount, {
            speed: speed.toString(),
            filesUpdated: filesUpdated.toLocaleString(),
          });
        }
 
        // Move to next batch
        offset += pedimentos.length;
 
        // Check if we got fewer results than requested (indicates last batch)
        Eif (pedimentos.length < this.options.batchSize) {
          hasMore = false;
        }
      }
    } finally {
      progressBar.stop();
    }
 
    const duration = ((Date.now() - startTime) / 1000).toFixed(2);
    const speed =
      duration > 0 ? Math.round(filesUpdated / parseFloat(duration)) : 0;
 
    console.log('\n   šŸ“Š Results:');
    console.log(
      `      Pedimentos Processed: ${this.stats.pedimentosProcessed.toLocaleString()}`,
    );
    console.log(
      `      Directories Processed: ${this.stats.directoriesProcessed.toLocaleString()}`,
    );
    console.log(
      `      Files Updated: ${this.stats.filesUpdated.toLocaleString()}`,
    );
    console.log(`      Errors: ${this.stats.filesFailed.toLocaleString()}`);
    console.log(`      Duration: ${duration}s`);
    console.log(`      Speed: ${speed} files/sec\n`);
 
    return {
      pedimentosProcessed: this.stats.pedimentosProcessed,
      filesUpdated: this.stats.filesUpdated,
      filesFailed: this.stats.filesFailed,
      directoriesProcessed: this.stats.directoriesProcessed,
    };
  }
 
  /**
   * Show final propagation statistics
   * @private
   */
  async #showFinalStats() {
    try {
      const stats = await this.scanApiService.getPropagationStats(
        this.tableName,
      );
 
      console.log('šŸ“ˆ Final Status:');
      console.log(`   Total Files: ${stats.totalFiles.toLocaleString()}`);
      console.log(
        `   With arela_path: ${stats.withArelaPath.toLocaleString()}`,
      );
      console.log(
        `   Needs Propagation: ${stats.needsPropagation.toLocaleString()}`,
      );
      console.log(`   Pending: ${stats.pending.toLocaleString()}`);
      console.log(`   Errors: ${stats.errors.toLocaleString()}`);
 
      Iif (stats.maxAttemptsReached > 0) {
        console.log(
          `\nāš ļø  ${stats.maxAttemptsReached} files reached max propagation attempts.`,
        );
        console.log(
          '   Run with increased max_propagation_attempts if needed, or review propagation errors.',
        );
      }
 
      Iif (this.options.showStats) {
        const duration = ((Date.now() - this.stats.startTime) / 1000).toFixed(
          2,
        );
        console.log('\nšŸ’» Performance Stats:');
        console.log(`   Total Duration: ${duration}s`);
        console.log(`   Memory Used: ${this.#getMemoryUsage()}`);
      }
    } catch (error) {
      logger.error('Failed to fetch final stats:', error);
      // Don't throw - command was successful even if we can't fetch final stats
    }
  }
 
  /**
   * Get formatted memory usage
   * @private
   */
  #getMemoryUsage() {
    const used = process.memoryUsage();
    return `${Math.round(used.heapUsed / 1024 / 1024)}MB`;
  }
}
 
export default PropagateCommand;