All files / src/cronjobs import-pmo.cronjob.ts

11.73% Statements 21/179
13.29% Branches 21/158
5.88% Functions 1/17
11.05% Lines 19/172

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 3661x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                           1x 1x 1x 1x 1x 1x 1x 1x 1x       1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import { CronJob, cronJob } from '@loopback/cron';
import { repository } from '@loopback/repository';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import SftpClient from 'ssh2-sftp-client';
import * as XLSX from 'xlsx';
import { PmoRepository } from '@logchain/repositories';
 
interface PmoRecord {
  Order?: string;
  Equipment?: string;
  PO?: string;
  ModuleNum?: string;
  ESN?: string;
  SerialNumber?: string;
  POQty?: string;
  MaterialDescription?: string;
  PartTransferOrder?: string;
  DataUploadDate?: string | number;
  SupplierName?: string;
  OutboundLogicticsPartner?: string;
  OutboundTrackingNumber?: string;
  Remark?: string;
  Material?: string;
  Customer?: string;
}
 
function parseExcelDate(dateStr: string | number | undefined): Date {
  if (!dateStr) return new Date();
  if (typeof dateStr === 'number') {
    const parsed = XLSX.SSF.parse_date_code(dateStr);
    if (parsed) {
      return new Date(parsed.y, parsed.m - 1, parsed.d, parsed.H, parsed.M, parsed.S);
    }
    return new Date();
  }
  const [datePart, timePart] = dateStr.trim().split(' ');
  const [month, day, year] = datePart.split('/');
  const [hour, minute] = (timePart ?? '0:0').split(':');
  return new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
}
 
/**
 * Parse timestamp from filename in format: OuthouseOrderReport_ddmmyyyyhhmmss
 * @param filename The filename to parse
 * @returns Date object or null if parsing fails
 */
function parseTimestampFromFilename(filename: string): Date | null {
  // Pattern: OuthouseOrderReport_ddmmyyyyhhmmss (with optional .csv extension)
  const match = filename.match(/OuthouseOrderReport_(\d{2})(\d{2})(\d{4})(\d{2})(\d{2})(\d{2})/i);
  
  if (!match) {
    return null;
  }
 
  const day = parseInt(match[1], 10);
  const month = parseInt(match[2], 10);
  const year = parseInt(match[3], 10);
  const hour = parseInt(match[4], 10);
  const minute = parseInt(match[5], 10);
  const second = parseInt(match[6], 10);
 
  if (month < 1 || month > 12 || day < 1 || day > 31 || 
      hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
    return null;
  }
 
  try {
    return new Date(year, month - 1, day, hour, minute, second);
  } catch (err) {
    console.warn(`Failed to parse timestamp from filename: ${filename}`);
    return null;
  }
}
 
@cronJob()
export class ImportPmoCronJob extends CronJob {
  private readonly DATA_FILE_PATH = path.join(__dirname, '../../data/SSOT_Open_Outhouse_Order_Report.csv');
  private readonly SFTP_HOST = process.env.PMO_SFTP_HOST ?? '';
  private readonly SFTP_PORT = Number(process.env.PMO_SFTP_PORT ?? 22);
  private readonly SFTP_USER = process.env.PMO_SFTP_USER ?? '';
  private readonly SFTP_PASSWORD = process.env.PMO_SFTP_PASSWORD ?? '';
  private readonly SFTP_ENV_DIR = process.env.PMO_SFTP_ENV_DIR ?? 'DEV';
  private readonly SFTP_REMOTE_DIR = (process.env.PMO_SFTP_REMOTE_DIR ?? '/SSOT') + '/' + this.SFTP_ENV_DIR;
  private readonly SFTP_ARCHIVE_DIR = (process.env.PMO_SFTP_ARCHIVE_DIR ?? '/Archived') + '/' + this.SFTP_ENV_DIR;
 
  constructor( 
    @repository(PmoRepository)
    public pmoRepository: PmoRepository,
  ) {
    super({
      name: 'Import PMO from CSV',
      onTick: async () => {
        await this.performCronJob();
      },
      //cronTime: '* * * * *', // Run every minute
      cronTime: '20 * * * *',
      start: true,
    });
  }
 
  private async downloadLatestPmoFileFromSftp(): Promise<string> {
    const sftp = new SftpClient();
    let isConnected = false;
 
    try {
      await sftp.connect({
        host: this.SFTP_HOST,
        port: this.SFTP_PORT,
        username: this.SFTP_USER,
        password: this.SFTP_PASSWORD,
      });
      isConnected = true;
 
      const remoteDirCandidates = [
        this.SFTP_REMOTE_DIR,
        this.SFTP_REMOTE_DIR.replace(/^\//, ''),
      ].filter((value, index, self) => value && self.indexOf(value) === index);
 
      let remoteDir = '';
      let files: SftpClient.FileInfo[] = [];
 
      for (const candidate of remoteDirCandidates) {
        try {
          files = await sftp.list(candidate);
          remoteDir = candidate;
          break;
        } catch (err) {
          console.warn(`*** Cronjob: ${this.name} - failed to list remote dir ${candidate}:`, err);
        }
      }
 
      if (!remoteDir) {
        throw new Error(`Cannot access remote directory: ${this.SFTP_REMOTE_DIR}`);
      }
 
      const matchingFiles = files
        .filter(file => {
          if (file.type !== '-') return false;
          const timestamp = parseTimestampFromFilename(file.name);
          return timestamp !== null;
        })
        .map(file => ({
          fileInfo: file,
          timestamp: parseTimestampFromFilename(file.name)!,
        }))
        .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
 
      if (matchingFiles.length === 0) {
        throw new Error(`No files matching pattern OuthouseOrderReport_ddmmyyyyhhmmss found in remote directory: ${remoteDir}`);
      }
 
      const latestFile = matchingFiles[0].fileInfo;
      const remoteFilePath = path.posix.join(remoteDir, latestFile.name);
      fs.mkdirSync(path.dirname(this.DATA_FILE_PATH), {recursive: true});
      await sftp.get(remoteFilePath, this.DATA_FILE_PATH);
 
      console.log(`*** Cronjob: ${this.name} - downloaded ${remoteFilePath} to ${this.DATA_FILE_PATH}`);
      return remoteFilePath;
    } finally {
      if (isConnected) {
        await sftp.end();
      }
    }
  }
 
  private async moveImportedFileToArchive(remoteFilePath: string): Promise<string> {
    const sftp = new SftpClient();
    let isConnected = false;
 
    try {
      await sftp.connect({
        host: this.SFTP_HOST,
        port: this.SFTP_PORT,
        username: this.SFTP_USER,
        password: this.SFTP_PASSWORD,
      });
      isConnected = true;
 
      const archiveDirExists = await sftp.exists(this.SFTP_ARCHIVE_DIR);
      if (!archiveDirExists) {
        await sftp.mkdir(this.SFTP_ARCHIVE_DIR, true);
      }
 
      const fileName = path.posix.basename(remoteFilePath);
      //I want append timestamp to the file name in case there are multiple files with the same name in the archive folder
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const archivedFileName = `${path.parse(fileName).name}_${timestamp}${path.parse(fileName).ext}`;
      const archiveFilePath = path.posix.join(this.SFTP_ARCHIVE_DIR, archivedFileName);
      await sftp.rename(remoteFilePath, archiveFilePath);
 
      console.log(`*** Cronjob: ${this.name} - moved ${remoteFilePath} to ${archiveFilePath}`);
      return archiveFilePath;
    } finally {
      if (isConnected) {
        await sftp.end();
      }
    }
  }
 
  private async zipArchivedFile(archiveFilePath: string): Promise<void> {
    const sftp = new SftpClient();
    let isConnected = false;
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pmo-archive-'));
    const archivedFileName = path.posix.basename(archiveFilePath);
    const localArchivedFilePath = path.join(tempDir, archivedFileName);
    const zipFileName = `${archivedFileName}.zip`;
    const localZipFilePath = path.join(tempDir, zipFileName);
    const remoteZipFilePath = path.posix.join(path.posix.dirname(archiveFilePath), zipFileName);
 
    try {
      await sftp.connect({
        host: this.SFTP_HOST,
        port: this.SFTP_PORT,
        username: this.SFTP_USER,
        password: this.SFTP_PASSWORD,
      });
      isConnected = true;
 
      await sftp.get(archiveFilePath, localArchivedFilePath);
      await this.createZipFromSingleFile(localArchivedFilePath, localZipFilePath, archivedFileName);
      await sftp.put(localZipFilePath, remoteZipFilePath);
      await sftp.delete(archiveFilePath);
 
      console.log(`*** Cronjob: ${this.name} - zipped ${archiveFilePath} to ${remoteZipFilePath}`);
    } finally {
      if (isConnected) {
        await sftp.end();
      }
      if (fs.existsSync(localArchivedFilePath)) {
        fs.unlinkSync(localArchivedFilePath);
      }
      if (fs.existsSync(localZipFilePath)) {
        fs.unlinkSync(localZipFilePath);
      }
      fs.rmdirSync(tempDir, {recursive: true});
    }
  }
 
  private async createZipFromSingleFile(
    inputFilePath: string,
    outputZipPath: string,
    archivedEntryName: string,
  ): Promise<void> {
    const archiver = require('archiver');
 
    await new Promise<void>((resolve, reject) => {
      const output = fs.createWriteStream(outputZipPath);
      const archive = archiver('zip', {zlib: {level: 9}});
 
      output.on('close', () => resolve());
      output.on('error', (err: Error) => reject(err));
      archive.on('error', (err: Error) => reject(err));
 
      archive.pipe(output);
      archive.file(inputFilePath, {name: archivedEntryName});
      archive.finalize();
    });
  }
 
  async performCronJob() {
    const startAt = new Date();
    console.log(`*** Cronjob: ${this.name} started at ${startAt}`);
 
    const pgTimezone = await this.pmoRepository.getPostgresTimezone();
    console.log(`*** Cronjob: ${this.name} - PostgreSQL timezone: ${pgTimezone}, Node.js timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`);
 
    //I want to set node js timezone to match postgres timezone to avoid confusion when comparing dates
    process.env.TZ = pgTimezone;
    console.log(`*** Cronjob: ${this.name} - Node.js timezone set to: ${process.env.TZ}`);
    try {
      const remoteFilePath = await this.downloadLatestPmoFileFromSftp();
 
      if (!fs.existsSync(this.DATA_FILE_PATH)) {
        console.warn(`*** Cronjob: ${this.name} - data file not found at ${this.DATA_FILE_PATH}`);
        return;
      }
 
      const workbook = XLSX.readFile(this.DATA_FILE_PATH);
      const sheetName = workbook.SheetNames[0];
      const sheet = workbook.Sheets[sheetName];
      const records: PmoRecord[] = XLSX.utils.sheet_to_json<PmoRecord>(sheet);
 
      if (!Array.isArray(records) || records.length === 0) {
        console.warn(`*** Cronjob: ${this.name} - no records found in CSV file`);
        return;
      }
 
      let imported = 0;
      let skipped = 0;
 
      for (const record of records) {
        const order = record['Order'] ?? '';
        const equipment = record['Equipment'] ?? '';
        const partTransferOrder = record['Material'] ?? '';
        const dataUploadDate = parseExcelDate(record['DataUploadDate']);
 
        // Skip rows with no meaningful data
        if (!order && !equipment && !partTransferOrder) {
          skipped++;
          continue;
        }
 
        const payload: {
          code: string;
          eq_no: number;
          po: string;
          trent_type: string;
          esn: number;
          serial_no: string;
          qty: number;
          description: string;
          part_no: string;
          part_desc: string;
          equipment: number;
          order_no: number;
          repair_vendor: string;
          forwarder: string;
          tracking_no: string;
          synced_date: Date;
          remark: string;
          status?: number;
        } = {
          code: order,
          eq_no: Number(record['Equipment'] ?? 0),
          po: record['PO'] ?? '',
          trent_type: record['Customer'] ?? '',
          esn: Number(record['ESN'] ?? 0),
          serial_no: record['SerialNumber'] ?? '',
          qty: Number(record['POQty'] ?? 0),
          description: record['MaterialDescription'] ?? '',
          part_no: partTransferOrder,
          part_desc: record['MaterialDescription'] ?? '',
          equipment: Number(record['Equipment'] ?? 0),
          order_no: Number(record['Order'] ?? 0),
          repair_vendor: record['SupplierName'] ?? '',
          forwarder: record['OutboundLogicticsPartner'] ?? '',
          tracking_no : record['OutboundTrackingNumber'] ?? '',
          synced_date: dataUploadDate,
          remark: record['Remark'] ?? '',
        };
 
        const existing = await this.pmoRepository.findOne({ where: { code: order } });
        if (existing ) {
          if (!existing.synced_date || (existing.synced_date && dataUploadDate > existing.synced_date)){
            console.log(existing.code,dataUploadDate,existing.synced_date);
            await this.pmoRepository.updateById(existing.id, payload);
            imported++;
          }
        } else {
          payload.status = 1; // Default status
          await this.pmoRepository.create(payload);
          imported++;
        }
      }
      console.log(`*** Cronjob: ${this.name} - imported ${imported} records, skipped ${skipped} records`);
      const archivedFilePath = await this.moveImportedFileToArchive(remoteFilePath);
      await this.zipArchivedFile(archivedFilePath);
    } catch (err) {
      console.error(`*** Cronjob: ${this.name} - error:`, err);
    }
    const finishedAt = new Date();
    console.log(`*** Cronjob: ${this.name} finished at ${finishedAt}`);
  }
}