All files IdentifyCommand.js

95.36% Statements 144/151
76.11% Branches 51/67
100% Functions 7/7
95.3% Lines 142/149

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                                                  24x 24x 24x                     21x   21x   21x     20x     20x     20x 1x 1x     20x 20x   20x 20x 20x     20x 20x           19x 1x         18x     18x 18x       18x             18x 18x     18x           18x 18x 18x     18x   18x   18x 18x 18x 18x 18x 18x 18x 18x   18x 1x               3x   3x 2x 2x     3x                           18x 18x 18x 18x 18x 18x     18x   18x 3x   3x 1x         3x             15x   15x     15x               15x   15x 15x 15x 15x 15x     15x 16x     16x           16x 6x     10x     10x     10x           10x 10x 11x   11x     10x 10x 10x     10x     15x   15x                             10x 10x   10x 11x 11x   11x   11x 1x                           10x 10x 10x 1x                         9x     8x 3x                           5x     5x 5x   5x 4x       1x 1x 1x             5x                     1x         1x 1x   1x   1x 1x         1x                           10x                       5x           5x 5x     5x                   1x           1x 1x 3x 3x       1x               1x 1x   1x       1x 1x 1x 1x 1x         1x 1x 1x 1x     1x             1x    
import cliProgress from 'cli-progress';
import fs from 'fs';
import pLimit from 'p-limit';
 
import logger from '../services/LoggingService.js';
 
import appConfig from '../config/config.js';
import ErrorHandler from '../errors/ErrorHandler.js';
import { ConfigurationError } from '../errors/ErrorTypes.js';
import FileDetectionService from '../file-detection.js';
 
/**
 * Identify Command Handler
 * Optimized replacement for "detect --detect-pdfs"
 * Identifies pedimento-simplificado documents in files scanned by "arela scan"
 *
 * Key improvements over legacy detect command:
 * - Works with dynamic scan_* tables instead of uploader table
 * - Uses configured API instead of direct Supabase access
 * - Detects locally to leverage CLI host resources
 * - Batch processing for efficient API communication
 * - Real-time progress tracking
 */
export class IdentifyCommand {
  constructor() {
    this.errorHandler = new ErrorHandler(logger);
    this.scanApiService = null; // Will be initialized in execute
    this.detectionService = new FileDetectionService();
  }
 
  /**
   * Execute the identify command
   * @param {Object} options - Command options
   * @param {string} options.api - API target (default, agencia, cliente)
   * @param {number} options.batchSize - Batch size for API operations
   * @param {boolean} options.showStats - Show performance statistics
   */
  async execute(options = {}) {
    const startTime = Date.now();
 
    try {
      // Validate scan configuration (need same config as scan command)
      appConfig.validateScanConfig();
 
      // Import ScanApiService dynamically
      const { default: ScanApiService } = await import(
        '../services/ScanApiService.js'
      );
      this.scanApiService = new ScanApiService();
 
      // Set API target if specified
      if (options.api) {
        appConfig.setApiTarget(options.api);
        this.scanApiService = new ScanApiService();
      }
 
      const scanConfig = appConfig.getScanConfig();
      const batchSize = parseInt(options.batchSize) || 100;
 
      logger.info('šŸ” Starting arela identify command');
      logger.info(`šŸŽÆ API Target: ${options.api || 'default'}`);
      logger.info(`šŸ“¦ Batch Size: ${batchSize}`);
 
      // Fetch all tables for this instance
      logger.info('\nšŸ“Š Fetching instance tables...');
      const tables = await this.scanApiService.getInstanceTables(
        scanConfig.companySlug,
        scanConfig.serverId,
        scanConfig.basePathFull,
      );
 
      if (tables.length === 0) {
        throw new ConfigurationError(
          'No tables found for this instance. Run "arela scan" first.',
        );
      }
 
      logger.info(
        `šŸ“‹ Found ${tables.length} table${tables.length === 1 ? '' : 's'} to process`,
      );
      for (const table of tables) {
        logger.info(`   - ${table.tableName}`);
      }
 
      // Process each table
      let totalStats = {
        processed: 0,
        detected: 0,
        errors: 0,
        pending: 0,
      };
 
      for (const table of tables) {
        logger.info(`\nšŸ” Processing table: ${table.tableName}`);
 
        // Get detection statistics for this table
        const stats = await this.#processTable(
          table.tableName,
          batchSize,
          startTime,
        );
 
        totalStats.processed += stats.processed;
        totalStats.detected += stats.detected;
        totalStats.errors += stats.errors;
      }
 
      const duration = ((Date.now() - startTime) / 1000).toFixed(2);
      const avgSpeed =
        duration > 0 ? Math.round(totalStats.processed / duration) : 0;
 
      logger.success(`\nāœ… Identification Complete!`);
      logger.info(`\nšŸ“Š Total Results:`);
      logger.info(`   Tables Processed: ${tables.length}`);
      logger.info(`   Files Processed: ${totalStats.processed}`);
      logger.info(`   Pedimentos Detected: ${totalStats.detected}`);
      logger.info(`   Errors: ${totalStats.errors}`);
      logger.info(`   Duration: ${duration}s`);
      logger.info(`   Speed: ${avgSpeed} files/sec`);
 
      if (options.showStats) {
        this.#showDetailedStats(
          startTime,
          totalStats.processed,
          totalStats.detected,
          totalStats.errors,
        );
      }
    } catch (error) {
      logger.error('āŒ Identification failed:', error.message);
 
      if (error instanceof ConfigurationError) {
        logger.error('\nConfiguration errors:');
        error.errors.forEach((err) => logger.error(`  - ${err}`));
      }
 
      throw error;
    }
  }
 
  /**
   * Process a single table
   * @private
   * @param {string} tableName - Table name to process
   * @param {number} batchSize - Batch size
   * @param {number} startTime - Start time for speed calculation
   * @returns {Promise<Object>} Processing statistics
   */
  async #processTable(tableName, batchSize, startTime) {
    // Get detection statistics first
    const initialStats = await this.scanApiService.getDetectionStats(tableName);
    logger.info(`   Total PDFs: ${initialStats.totalPdfs}`);
    logger.info(`   Detected: ${initialStats.detected}`);
    logger.info(`   Pending: ${initialStats.pending}`);
    logger.info(`   Not Pedimento: ${initialStats.notPedimento || 0}`);
    logger.info(
      `   Max Attempts Reached: ${initialStats.maxAttemptsReached || 0}`,
    );
    logger.info(`   Errors: ${initialStats.errors}`);
 
    if (initialStats.pending === 0) {
      logger.info('   āœ… All PDFs processed. Skipping.');
 
      if (initialStats.maxAttemptsReached > 0) {
        logger.info(
          `   āš ļø  ${initialStats.maxAttemptsReached} PDFs reached max attempts.`,
        );
      }
 
      return {
        processed: 0,
        detected: 0,
        errors: 0,
      };
    }
 
    logger.info(`   šŸš€ Processing ${initialStats.pending} pending PDFs...`);
 
    logger.info(`   šŸš€ Processing ${initialStats.pending} pending PDFs...`);
 
    // Setup progress bar
    const progressBar = new cliProgress.SingleBar({
      format:
        '   šŸ“„ |{bar}| {percentage}% | {value}/{total} files | {speed} files/sec',
      barCompleteChar: '\u2588',
      barIncompleteChar: '\u2591',
      hideCursor: true,
    });
 
    progressBar.start(initialStats.pending, 0, { speed: 0 });
 
    let processedCount = 0;
    let detectedCount = 0;
    let errorCount = 0;
    let hasMore = true;
    let batchNumber = 0;
 
    // Process in batches
    while (hasMore) {
      batchNumber++;
 
      // Fetch from offset 0 since processed files are filtered out
      const response = await this.scanApiService.fetchPdfsForDetection(
        tableName,
        0,
        batchSize,
      );
 
      if (!response.data || response.data.length === 0) {
        break;
      }
 
      const files = response.data;
 
      // Detect files locally with concurrent processing
      const detectionResults = await this.#detectFilesLocally(files, 10);
 
      // Batch update to API
      const updateResult = await this.scanApiService.batchUpdateDetection(
        tableName,
        detectionResults,
      );
 
      // Update statistics
      processedCount += files.length;
      detectedCount += detectionResults.filter(
        (r) => r.detectedType === 'pedimento_simplificado',
      ).length;
      errorCount += detectionResults.filter((r) => r.detectionError).length;
 
      // Update progress bar
      const elapsed = (Date.now() - startTime) / 1000;
      const speed = elapsed > 0 ? Math.round(processedCount / elapsed) : 0;
      progressBar.update(processedCount, { speed });
 
      // Check if there are more files
      hasMore = response.hasMore;
    }
 
    progressBar.stop();
 
    return {
      processed: processedCount,
      detected: detectedCount,
      errors: errorCount,
    };
  }
 
  /**
   * Detect files locally using FileDetectionService
   * @private
   * @param {Array} files - Files to detect
   * @param {number} concurrency - Maximum concurrent detections
   * @returns {Promise<Array>} Detection results
   */
  async #detectFilesLocally(files, concurrency = 10) {
    const limit = pLimit(concurrency);
    const basePath = appConfig.getBasePath();
 
    const detectionPromises = files.map((file) =>
      limit(async () => {
        try {
          // Check if file exists on filesystem
          const absolutePath = file.absolute_path;
 
          if (!fs.existsSync(absolutePath)) {
            return {
              id: file.id,
              detectedType: null,
              detectedPedimento: null,
              detectedPedimentoYear: null,
              rfc: null,
              arelaPath: null,
              detectionError:
                'FILE_NOT_FOUND: File does not exist on filesystem. May have been moved or deleted after scan.',
              isNotPedimento: false,
            };
          }
 
          // Check file size - skip very large files
          const stats = fs.statSync(absolutePath);
          const maxSizeBytes = 50 * 1024 * 1024; // 50MB
          if (stats.size > maxSizeBytes) {
            return {
              id: file.id,
              detectedType: null,
              detectedPedimento: null,
              detectedPedimentoYear: null,
              rfc: null,
              arelaPath: null,
              detectionError: `FILE_TOO_LARGE: File size ${(stats.size / 1024 / 1024).toFixed(2)}MB exceeds ${maxSizeBytes / 1024 / 1024}MB limit.`,
              isNotPedimento: false,
            };
          }
 
          // Detect using existing FileDetectionService
          const result = await this.detectionService.detectFile(absolutePath);
 
          // If detection succeeded and found a pedimento
          if (result.detectedType === 'pedimento_simplificado') {
            return {
              id: file.id,
              detectedType: result.detectedType,
              detectedPedimento: result.detectedPedimento,
              detectedPedimentoYear: result.detectedPedimentoYear,
              rfc: result.rfc,
              arelaPath: result.arelaPath,
              detectionError: result.error,
              isNotPedimento: false,
            };
          }
 
          // If no detection, determine if it's definitely not a pedimento
          // This helps avoid re-processing files we know aren't pedimentos
          const isNotPedimento = this.#isDefinitelyNotPedimento(result, file);
 
          // Build descriptive error message
          let detectionError = null;
          Iif (result.error) {
            detectionError = `DETECTION_ERROR: ${result.error}`;
          } else if (isNotPedimento) {
            detectionError =
              'NOT_PEDIMENTO: File does not match pedimento-simplificado pattern. Missing key markers: "FORMA SIMPLIFICADA DE PEDIMENTO".';
          } else {
            // Partial match - might be a pedimento with missing fields
            const missingFields = this.#getMissingFields(result);
            if (missingFields.length > 0) {
              detectionError = `INCOMPLETE_PEDIMENTO: Detected as potential pedimento but missing fields: ${missingFields.join(', ')}. Matcher may need improvement.`;
            } else E{
              detectionError =
                'UNKNOWN_ERROR: Detection completed but no pedimento found. Check file content and matcher patterns.';
            }
          }
 
          return {
            id: file.id,
            detectedType: result.detectedType,
            detectedPedimento: result.detectedPedimento,
            detectedPedimentoYear: result.detectedPedimentoYear,
            rfc: result.rfc,
            arelaPath: result.arelaPath,
            detectionError,
            isNotPedimento,
          };
        } catch (error) {
          logger.warn(
            `Failed to detect ${file.relative_path}: ${error.message}`,
          );
 
          // Categorize the error
          let errorCategory = 'UNKNOWN_ERROR';
          Iif (error.message.includes('ENOENT')) {
            errorCategory = 'FILE_NOT_FOUND';
          } else Iif (error.message.includes('timeout')) {
            errorCategory = 'TIMEOUT';
          } else if (error.message.includes('PDF')) {
            errorCategory = 'PDF_PARSE_ERROR';
          } else Eif (error.message.includes('extract')) {
            errorCategory = 'TEXT_EXTRACTION_ERROR';
          }
 
          return {
            id: file.id,
            detectedType: null,
            detectedPedimento: null,
            detectedPedimentoYear: null,
            rfc: null,
            arelaPath: null,
            detectionError: `${errorCategory}: ${error.message}`,
            isNotPedimento: false,
          };
        }
      }),
    );
 
    return Promise.all(detectionPromises);
  }
 
  /**
   * Determine if a file is definitely not a pedimento
   * @private
   * @param {Object} result - Detection result
   * @param {Object} file - File metadata
   * @returns {boolean} True if definitely not a pedimento
   */
  #isDefinitelyNotPedimento(result, file) {
    // If we got any pedimento-related fields, it might be a pedimento
    Iif (result.detectedPedimento || result.rfc || result.arelaPath) {
      return false;
    }
 
    // Check if the text contains the required pedimento marker
    // This must match the criteria in pedimento-simplificado.js match function
    const text = result.text || '';
    const hasRequiredMarker = /FORMA SIMPLIFICADA DE PEDIMENTO/i.test(text);
 
    // If the required marker is not found, it's definitely not a pedimento
    return !hasRequiredMarker;
  }
 
  /**
   * Get list of missing required fields for pedimento
   * @private
   * @param {Object} result - Detection result
   * @returns {Array<string>} Missing field names
   */
  #getMissingFields(result) {
    const requiredFields = [
      { key: 'detectedPedimento', name: 'numPedimento' },
      { key: 'rfc', name: 'rfc' },
      { key: 'detectedPedimentoYear', name: 'year' },
    ];
 
    const missing = [];
    for (const field of requiredFields) {
      Eif (!result[field.key]) {
        missing.push(field.name);
      }
    }
 
    return missing;
  }
 
  /**
   * Show detailed performance statistics
   * @private
   */
  #showDetailedStats(startTime, processedCount, detectedCount, errorCount) {
    const duration = (Date.now() - startTime) / 1000;
    const avgSpeed = duration > 0 ? (processedCount / duration).toFixed(2) : 0;
    const detectionRate =
      processedCount > 0
        ? ((detectedCount / processedCount) * 100).toFixed(1)
        : 0;
 
    logger.info('\nšŸ“ˆ Detailed Statistics:');
    logger.info(`   Total Processing Time: ${duration.toFixed(2)}s`);
    logger.info(`   Average Speed: ${avgSpeed} files/sec`);
    logger.info(`   Detection Rate: ${detectionRate}%`);
    logger.info(
      `   Error Rate: ${errorCount > 0 ? ((errorCount / processedCount) * 100).toFixed(1) : 0}%`,
    );
 
    // Memory usage
    const memUsage = process.memoryUsage();
    logger.info('\nšŸ’¾ Memory Usage:');
    logger.info(`   RSS: ${(memUsage.rss / 1024 / 1024).toFixed(2)} MB`);
    logger.info(
      `   Heap Used: ${(memUsage.heapUsed / 1024 / 1024).toFixed(2)} MB`,
    );
    logger.info(
      `   Heap Total: ${(memUsage.heapTotal / 1024 / 1024).toFixed(2)} MB`,
    );
  }
}
 
// Export singleton instance
const identifyCommand = new IdentifyCommand();
export default identifyCommand;