All files PushCommand.js

93.86% Statements 153/163
79.41% Branches 54/68
100% Functions 6/6
93.78% Lines 151/161

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                                  29x               28x 28x     28x 28x 2x 2x 2x       28x 28x 28x     28x 28x   28x 2x 2x       28x   28x 28x     28x 28x     28x         28x 1x   28x 1x       28x 28x           27x 1x     1x     27x     27x 26x       27x             27x 26x     26x     26x   26x 4x 4x     22x         22x               22x 22x 22x     22x 22x 22x 22x       27x       27x       27x 27x 27x 27x 27x 27x 27x 27x   1x 1x 1x                   28x   28x 28x   1x     27x 27x 1x     27x               26x 26x 26x 26x 26x 1x   26x 1x       26x 1x 1x 2x 2x                                   22x               22x 22x   22x     22x                             22x           22x   22x           22x 14x 14x       8x 8x 8x           8x     8x 8x 8x 6x   2x         8x   8x 8x                 8x 8x       22x   22x               8x 8x   8x               8x               8x   8x             8x 8x 1x 1x         7x 7x     7x                     7x 6x 6x 6x   1x 1x             7x               7x   7x 7x       7x     7x 7x     7x 6x       7x 7x 7x 7x     7x                       6x               6x       6x 6x 6x                                   1x                  
import cliProgress from 'cli-progress';
import FormData from 'form-data';
import fs from 'fs';
import fetch from 'node-fetch';
import path from 'path';
 
import logger from '../services/LoggingService.js';
import ScanApiService from '../services/ScanApiService.js';
 
import appConfig from '../config/config.js';
 
/**
 * Push Command Handler
 * Uploads files with arela_path to storage API
 */
export class PushCommand {
  constructor() {
    this.scanApiService = new ScanApiService();
  }
 
  /**
   * Execute the push command
   * @param {Object} options - Command options
   */
  async execute(options) {
    try {
      console.log('\nšŸš€ Starting arela push command\n');
 
      // Validate scan configuration (same config as scan/identify/propagate)
      const errors = this.#validateConfig();
      if (errors.length > 0) {
        console.error('āš ļø Configuration errors:');
        errors.forEach((err) => console.error(`   - ${err}`));
        process.exit(1);
      }
 
      // Get configuration
      const scanConfig = appConfig.getScanConfig();
      const pushConfig = appConfig.getPushConfig();
      const tableName = scanConfig.tableName;
 
      // Set API target for scan/push operations
      const scanApiTarget = options.api || options.scanApi || 'default';
      const pushApiTarget = options.pushApi || scanApiTarget;
 
      if (scanApiTarget !== 'default') {
        appConfig.setApiTarget(scanApiTarget);
        this.scanApiService = new ScanApiService(); // Reinitialize with new target
      }
 
      // Get upload API configuration
      const uploadApiConfig = appConfig.getApiConfig(pushApiTarget);
 
      console.log(`šŸŽÆ Scan API Target: ${scanApiTarget}`);
      console.log(
        `šŸŽÆ Upload API Target: ${pushApiTarget} → ${uploadApiConfig.baseUrl}`,
      );
      console.log(`šŸ“¦ Fetch Batch Size: ${options.batchSize}`);
      console.log(`šŸ“¤ Upload Batch Size: ${options.uploadBatchSize}`);
 
      // Apply filters
      const filters = {
        rfcs: options.rfcs || pushConfig.rfcs || [],
        years: options.years || pushConfig.years || [],
      };
 
      if (filters.rfcs.length > 0) {
        console.log(`šŸ” RFC Filter: ${filters.rfcs.join(', ')}`);
      }
      if (filters.years.length > 0) {
        console.log(`šŸ” Year Filter: ${filters.years.join(', ')}`);
      }
 
      // Fetch all tables for this instance
      console.log('\\nšŸ“Š Fetching instance tables...');
      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}`);
      }
 
      // Process each table
      let totalResults = {
        processed: 0,
        uploaded: 0,
        errors: 0,
        startTime: Date.now(),
      };
 
      for (const table of tables) {
        console.log(`\\nšŸš€ Processing table: ${table.tableName}\\n`);
 
        // Get initial statistics for this table
        const initialStats = await this.scanApiService.getPushStats(
          table.tableName,
        );
        this.#displayStats('  Table Status', initialStats);
 
        if (initialStats.pending === 0) {
          console.log('  āœ… No files pending upload. Skipping.\\n');
          continue;
        }
 
        console.log(
          `\\n  šŸš€ Uploading ${initialStats.pending} pending files...\\n`,
        );
 
        // Process files for this table
        const results = await this.#processFiles(
          table.tableName,
          filters,
          parseInt(options.batchSize),
          parseInt(options.uploadBatchSize),
          uploadApiConfig,
        );
 
        totalResults.processed += results.processed;
        totalResults.uploaded += results.uploaded;
        totalResults.errors += results.errors;
 
        // Display results for this table
        console.log('\\n  šŸ“Š Table Results:');
        console.log(`     Files Processed: ${results.processed}`);
        console.log(`     Uploaded: ${results.uploaded}`);
        console.log(`     Errors: ${results.errors}\\n`);
      }
 
      // Display combined results
      const duration = ((Date.now() - totalResults.startTime) / 1000).toFixed(
        1,
      );
      const speed =
        totalResults.processed > 0
          ? (totalResults.processed / parseFloat(duration)).toFixed(0)
          : 0;
 
      console.log('\\nāœ… Push Complete!\\n');
      console.log('šŸ“Š Total Results:');
      console.log(`   Tables Processed: ${tables.length}`);
      console.log(`   Files Processed: ${totalResults.processed}`);
      console.log(`   Uploaded: ${totalResults.uploaded}`);
      console.log(`   Errors: ${totalResults.errors}`);
      console.log(`   Duration: ${duration}s`);
      console.log(`   Speed: ${speed} files/sec\\n`);
    } catch (error) {
      console.error('\nāŒ Push failed:', error.message);
      logger.error('Push command error:', error);
      process.exit(1);
    }
  }
 
  /**
   * Validate configuration
   * @private
   * @returns {string[]} Array of error messages
   */
  #validateConfig() {
    const errors = [];
 
    try {
      appConfig.validateScanConfig();
    } catch (err) {
      return [err.message];
    }
 
    const scanConfig = appConfig.getScanConfig();
    if (!scanConfig.tableName) {
      errors.push('Could not generate table name from configuration');
    }
 
    return errors;
  }
 
  /**
   * Display statistics
   * @private
   */
  #displayStats(title, stats) {
    console.log(`\nšŸ“ˆ ${title}:`);
    console.log(`   Total with arela_path: ${stats.totalWithArelaPath}`);
    console.log(`   Uploaded: ${stats.uploaded}`);
    console.log(`   Pending: ${stats.pending}`);
    if (stats.errors > 0) {
      console.log(`   Errors: ${stats.errors}`);
    }
    if (stats.maxAttemptsReached > 0) {
      console.log(`   Max Attempts Reached: ${stats.maxAttemptsReached}`);
    }
 
    // Show top RFCs if available
    if (stats.byRfc && stats.byRfc.length > 0) {
      console.log('\n   šŸ“Š Top RFCs:');
      stats.byRfc.slice(0, 5).forEach((rfc) => {
        const percent = ((rfc.uploaded / rfc.total) * 100).toFixed(1);
        console.log(
          `      ${rfc.rfc}: ${rfc.uploaded}/${rfc.total} (${percent}%)`,
        );
      });
    }
  }
 
  /**
   * Process files in batches
   * @private
   */
  async #processFiles(
    tableName,
    filters,
    batchSize,
    uploadBatchSize,
    uploadApiConfig,
  ) {
    const results = {
      processed: 0,
      uploaded: 0,
      errors: 0,
      startTime: Date.now(),
    };
 
    // Get total count first for accurate progress
    const initialStats = await this.scanApiService.getPushStats(tableName);
    const totalToProcess = initialStats.pending;
 
    let hasMore = true;
 
    // Create progress bar with known total
    const progressBar = new cliProgress.SingleBar({
      format:
        'šŸ“¤ |{bar}| {percentage}% | {value}/{total} | {speed}/s | āœ“{uploaded} āœ—{errors}',
      barCompleteChar: 'ā–ˆ',
      barIncompleteChar: 'ā–‘',
      hideCursor: true,
      clearOnComplete: false,
      stopOnComplete: true,
    });
 
    // Always use offset=0 because uploaded files are removed from pending query results
    // After each batch upload, those files are no longer "pending", so the next query
    // at offset=0 will naturally return the next batch of unprocessed files
 
    // Start progress bar with known total
    progressBar.start(totalToProcess, 0, {
      speed: 0,
      uploaded: 0,
      errors: 0,
    });
 
    while (hasMore) {
      // Fetch batch of files (always offset=0 since uploaded files are removed from pending)
      const files = await this.scanApiService.fetchFilesForPush(tableName, {
        ...filters,
        offset: 0,
        limit: batchSize,
      });
 
      if (files.length === 0) {
        hasMore = false;
        break;
      }
 
      // Upload files in smaller batches
      for (let i = 0; i < files.length; i += uploadBatchSize) {
        const uploadBatch = files.slice(i, i + uploadBatchSize);
        const batchResults = await this.#uploadBatch(
          uploadBatch,
          uploadApiConfig,
        );
 
        // Update results in database
        await this.scanApiService.batchUpdateUpload(tableName, batchResults);
 
        // Update counters
        batchResults.forEach((result) => {
          results.processed++;
          if (result.uploaded) {
            results.uploaded++;
          } else {
            results.errors++;
          }
        });
 
        // Update progress bar
        const elapsed = (Date.now() - results.startTime) / 1000;
        const speed =
          elapsed > 0 ? (results.processed / elapsed).toFixed(0) : 0;
        progressBar.update(results.processed, {
          speed,
          uploaded: results.uploaded,
          errors: results.errors,
        });
      }
 
      // Check if there are more files
      // If we got fewer files than requested, we've processed all pending files
      Eif (files.length < batchSize) {
        hasMore = false;
      }
    }
 
    progressBar.stop();
 
    return results;
  }
 
  /**
   * Upload a batch of files
   * @private
   */
  async #uploadBatch(files, uploadApiConfig) {
    const uploadPromises = files.map((file) =>
      this.#uploadFile(file, uploadApiConfig),
    );
    return Promise.all(uploadPromises);
  }
 
  /**
   * Upload a single file
   * @private
   */
  async #uploadFile(file, uploadApiConfig) {
    const result = {
      id: file.id,
      uploaded: false,
      uploadError: null,
      uploadPath: null,
      uploadedToStorageId: null,
    };
 
    try {
      // Check if file exists
      Iif (!fs.existsSync(file.absolute_path)) {
        result.uploadError =
          'FILE_NOT_FOUND: File does not exist on filesystem';
        return result;
      }
 
      // Get file stats
      const stats = fs.statSync(file.absolute_path);
      if (!stats.isFile()) {
        result.uploadError = 'NOT_A_FILE: Path is not a regular file';
        return result;
      }
 
      // Construct upload path using arela_path
      // arela_path format: RFC/Year/Patente/Aduana/Pedimento/
      const uploadPath = `${file.arela_path}${file.file_name}`;
      result.uploadPath = uploadPath;
 
      // Upload file using storage API
      const response = await this.#uploadToStorageApi(
        file.absolute_path,
        uploadPath,
        uploadApiConfig,
        {
          rfc: file.rfc,
          year: file.detected_pedimento_year,
          originalPath: file.relative_path,
        },
      );
 
      if (response.success) {
        result.uploaded = true;
        result.uploadedToStorageId = response.fileId;
        logger.info(`āœ“ Uploaded: ${file.file_name} → ${uploadPath}`);
      } else {
        result.uploadError = `UPLOAD_FAILED: ${response.error || 'Unknown error'}`;
        logger.error(`āœ— Failed: ${file.file_name} - ${result.uploadError}`);
      }
    } catch (error) {
      result.uploadError = `UPLOAD_ERROR: ${error.message}`;
      logger.error(`āœ— Error uploading ${file.file_name}:`, error.message);
    }
 
    return result;
  }
 
  /**
   * Upload file to storage API
   * @private
   */
  async #uploadToStorageApi(filePath, uploadPath, apiConfig, metadata = {}) {
    try {
      // Create form data
      const form = new FormData();
      form.append('files', fs.createReadStream(filePath));
 
      // uploadPath format: RFC/Year/Patente/Aduana/Pedimento/filename
      // Extract folder structure (arela_path without filename)
      const folderStructure = path.dirname(uploadPath);
 
      // Use batch-upload-and-process endpoint (same as legacy upload)
      form.append('bucket', appConfig.getPushConfig().bucket);
      form.append('folderStructure', folderStructure);
 
      // Add RFC for multi-database routing
      if (metadata.rfc) {
        form.append('rfc', metadata.rfc);
      }
 
      // Enable auto-detection
      form.append('autoDetect', 'true');
      form.append('autoOrganize', 'false');
      form.append('batchSize', '1');
      form.append('clientVersion', appConfig.packageVersion);
 
      // Upload file
      const response = await fetch(
        `${apiConfig.baseUrl}/api/storage/batch-upload-and-process`,
        {
          method: 'POST',
          headers: {
            'x-api-key': apiConfig.token,
            ...form.getHeaders(),
          },
          body: form,
        },
      );
 
      Iif (!response.ok) {
        const errorText = await response.text();
        return {
          success: false,
          error: `HTTP ${response.status}: ${errorText}`,
        };
      }
 
      const result = await response.json();
 
      // batch-upload-and-process returns { uploaded: [], detected: [], errors: [] }
      // Check if upload was successful
      if (result.uploaded && result.uploaded.length > 0) {
        const uploadedFile = result.uploaded[0];
        return {
          success: true,
          fileId: uploadedFile.fileId,
          path: uploadedFile.path,
        };
      } else Eif (result.errors && result.errors.length > 0) {
        const error = result.errors[0];
        return {
          success: false,
          error: error.error || 'Upload failed',
        };
      } else {
        return {
          success: false,
          error: 'Unknown upload error - no files uploaded',
        };
      }
    } catch (error) {
      return {
        success: false,
        error: error.message,
      };
    }
  }
}
 
export default PushCommand;