All files / src/cronjobs retry-failed-pdf-generation.cronjob.ts

29.41% Statements 25/85
0% Branches 0/42
25% Functions 1/4
27.71% Lines 23/83

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  1x 1x   1x 1x 1x   1x     1x 1x     1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x                                                                                                                                                                                                                                                                
import { BaseEntity } from '@logchain/models';
import { DocumentRepository } from '@logchain/repositories';
import { BaseService, BolService, CargoService, DocumentService, EirService, EntryRecordService, LiftService, LoadingService, MessageService, OnLoadingService, ReheatingService, TransportService, VesselService, WeighbridgeService } from '@logchain/services';
import { PdfTemplate } from '@logchain/types';
import { service } from '@loopback/core';
import { CronJob, cronJob } from '@loopback/cron';
import { repository } from '@loopback/repository';
import { UserProfile } from 'components/aws/services';
import moment from 'moment';
 
@cronJob()
export class RetryFailedPdfGenerationCronJob extends CronJob {
  private readonly lock_key = '1701058646';
  constructor(
    @repository(DocumentRepository)
    public documentRepository: DocumentRepository,
    @service(DocumentService)
    public documentService: DocumentService,
    @service(TransportService)
    public transportService: TransportService,
    @service(LoadingService)
    public loadingService: LoadingService,
    @service(OnLoadingService)
    public onLoadingService: OnLoadingService,
    @service(LiftService)
    public liftService: LiftService,
    @service(EntryRecordService)
    public entryRecordService: EntryRecordService,
    @service(WeighbridgeService)
    public weighbridgeService: WeighbridgeService,
    @service(EirService)
    public eirService: EirService,
    @service(ReheatingService)
    public reheatingService: ReheatingService,
    @service(BolService)
    public bolService: BolService,
    @service(VesselService)
    public vesselService: VesselService,
    @service(CargoService)
    public cargoService: CargoService,
    @service(MessageService)
    public messageService: MessageService,
  ) {
    super({
      name: 'Retry failed pdf generation',
      onTick: async () => {
        await this.performCronJob();
      },
      cronTime: '*/2 * * * *', // Repeat at 10 minutes
      // cronTime: '*/20 * * * * *', // Repeat at 10 minutes
      start: true,
    });
  }
 
  async performCronJob() {
    const isUnLocked = await this.documentRepository.execute(`SELECT pg_try_advisory_lock(${this.lock_key});`);
    if (!isUnLocked[0].pg_try_advisory_lock) {
      return;
    }
 
    await this.documentRepository.execute(`SELECT pg_advisory_lock(${this.lock_key});`);
    const now = moment();
    
    const startAt = now.toDate();
    console.log(`*** Cronjob: ${this.name} started at ${startAt}`);
    // Your code start here
    
    const failedPdfDocuments = await this.documentRepository.getFailedPDFDocuments();
    if (failedPdfDocuments?.length) {
      for(const document of failedPdfDocuments) {
        const data: PdfTemplate = {
          content: {},
          model_name: document.document_name,
        };
        const userProfile = { id: document.modified_by ?? 0, company_id: document.company_id ?? 0 } as UserProfile;
        try {
          switch (document.document_name) {
            case 'documents': {
              this._bindUserProfile(this.documentService as BaseService<BaseEntity>, userProfile);
              data.content = await this.documentService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'transports': {
              this._bindUserProfile(this.transportService as BaseService<BaseEntity>, userProfile);
              data.content = await this.transportService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'loadings': {
              this._bindUserProfile(this.loadingService as BaseService<BaseEntity>, userProfile);
              data.content = await this.loadingService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'onloadings': {
              this._bindUserProfile(this.onLoadingService as BaseService<BaseEntity>, userProfile);
              data.content = await this.onLoadingService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'lifts': {
              this._bindUserProfile(this.liftService as BaseService<BaseEntity>, userProfile);
              data.content = await this.liftService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'entry_records': {
              this._bindUserProfile(this.entryRecordService as BaseService<BaseEntity>, userProfile);
              data.content = await this.entryRecordService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'weighbridges': {
              this._bindUserProfile(this.weighbridgeService as BaseService<BaseEntity>, userProfile);
              data.content = await this.weighbridgeService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'eirs': {
              this._bindUserProfile(this.eirService as BaseService<BaseEntity>, userProfile);
              data.content = await this.eirService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'reheating': {
              this._bindUserProfile(this.reheatingService as BaseService<BaseEntity>, userProfile);
              data.content = await this.reheatingService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'bols': {
              this._bindUserProfile(this.bolService as BaseService<BaseEntity>, userProfile);
              data.content = await this.bolService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'vessels': {
              this._bindUserProfile(this.vesselService as BaseService<BaseEntity>, userProfile);
              data.content = await this.vesselService.getByIdOrIdentifier(document.id);
              break;
            }
            case 'cargoes': {
              this._bindUserProfile(this.cargoService as BaseService<BaseEntity>, userProfile);
              data.content = await this.cargoService.getByIdOrIdentifier(document.id);
              break;
            }
          }
          
          if (data?.content && data?.model_name) {
            data.content = {...data.content, retry: true };
            await this.messageService.handleReplyMsg({
              message: {
                Body: JSON.stringify(data),
              },
            })
          }
        } catch (error) {
          console.error(`Failed with ${document.document_name} ${document.id}`, error);
        }
      }
    }
 
    // Your code end here
    const finishedAt = new Date();
    console.log(`*** Cronjob: ${this.name} finished at ${finishedAt}.`);
 
    await this.documentRepository.execute(`SELECT pg_advisory_unlock(${this.lock_key});`);
  }
 
  /**
   * Private function use to bind requesting company to global current_user
   * @param  {BaseService<BaseEntity>} serviceObj
   * @param  {UserProfile} profile
   */
  private _bindUserProfile(serviceObj: BaseService<BaseEntity>, profile: UserProfile) {
    if (!serviceObj.current_user) {
      serviceObj.current_user = profile;
    }
  }
}