All files / src/services/scan attachment.service.ts

11.5% Statements 13/113
0% Branches 0/72
0% Functions 0/20
11.22% Lines 11/98

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 2911x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import {bind, BindingScope, inject} from '@loopback/core';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {AttachmentRepository} from '@logchain/repositories/scan/attachment.repository';
import {AttachmentType, TimelineStep} from '@logchain/types';
import {AwsS3Service, AwsServiceBindings} from '@logchain/components/aws';
import {AwsConfigs} from '@logchain/configs';
import {TimelineEventRepository} from '@logchain/repositories/scan/timeline-event.repository';
import {v4 as uuidv4} from 'uuid';
import {buildAttachmentViewUrl} from '@logchain/utils/attachment-link.util';
 
@bind({
  scope: BindingScope.TRANSIENT,
})
export class AttachmentService {
  constructor(
    @repository(AttachmentRepository)
    public attachmentRepo: AttachmentRepository,
 
    @repository(TimelineEventRepository)
    public timelineRepo: TimelineEventRepository,
 
    @inject(AwsServiceBindings.S3_SERVICE)
    private s3Service: AwsS3Service,
  ) {}
 
  /**
   * Upload attachment
   */
  async upload(pmoId: number, type: AttachmentType, file: Express.Multer.File) {
    if (!file) {
      throw new HttpErrors.BadRequest('No file uploaded');
    }
 
    const ext = file.originalname.split('.').pop() ?? 'bin';
 
    const s3Key = `scan/attachments/pmo-${pmoId}/` + `${type.toLowerCase()}-${Date.now()}.${ext}`;
 
    await this.s3Service.putObject({
      Key: s3Key,
      Body: file.buffer,
      ContentType: file.mimetype,
    });
 
    const attachment = await this.attachmentRepo.create({
      pmo_id: pmoId,
      type,
      file_url: s3Key,
    });
    const signedUrl = await this.generateSignedUrl(attachment.file_url!);
 
    return {
      ...attachment,
      signed_url: signedUrl,
    };
  }
 
  async uploadMulti(pmoIds: number[], type: AttachmentType, file: Express.Multer.File) {
    if (!file) throw new HttpErrors.BadRequest('No file uploaded');
    if (!pmoIds.length) throw new HttpErrors.BadRequest('No PMO IDs provided');
 
    const primaryPmoId = pmoIds[0];
    const ext = file.originalname.split('.').pop() ?? 'bin';
    const s3Key = `scan/attachments/pmo-${primaryPmoId}/${type.toLowerCase()}-${Date.now()}.${ext}`;
 
    await this.s3Service.putObject({
      Key: s3Key,
      Body: file.buffer,
      ContentType: file.mimetype,
    });
 
    const groupUid = uuidv4();
 
    const records = await Promise.all(
      pmoIds.map(pmoId =>
        this.attachmentRepo.create({
          pmo_id: pmoId,
          type,
          file_url: s3Key,
          group_uid: groupUid,
          created_at: new Date(),
        }),
      ),
    );
 
    const primary = records.find(r => r.pmo_id === primaryPmoId) ?? records[0];
    const signedUrl = await this.generateSignedUrl(primary.file_url!);
 
    return {...primary, signed_url: signedUrl};
  }
 
  /**
   * Get by PMO
   */
  async findByPmoId(pmoId: number) {
    const attachments = await this.attachmentRepo.find({
      where: {
        pmo_id: pmoId,
      },
 
      order: ['created_at DESC'],
    });
 
    return Promise.all(
      attachments.map(async item => {
        const signedUrl = await this.generateSignedUrl(item.file_url!);
 
        return {
          ...item,
 
          signed_url: signedUrl,
        };
      }),
    );
  }
 
  async findDirectByPmoIdAndType(pmoId: number, type?: AttachmentType) {
    const attachments = await this.attachmentRepo.find({
      where: {
        pmo_id: pmoId,
        type,
      },
      order: ['created_at DESC'],
    });
 
    return Promise.all(
      attachments.map(async item => {
        const signedUrl = await this.generateSignedUrl(item.file_url!);
 
        return {
          ...item,
          signed_url: signedUrl,
        };
      }),
    );
  }
 
  async findByPmoIdAndType(pmoId: number, type?: AttachmentType) {
    const [attachments, events] = await Promise.all([
      this.attachmentRepo.find({
        where: {pmo_id: pmoId},
        order: ['created_at DESC'],
      }),
      this.timelineRepo.find({
        where: {pmoId: pmoId},
        order: ['event_time ASC'],
      }),
    ]);
 
    return Promise.all(
      attachments.map(async item => {
        const targetStepCode = type ? this.mapTypeToStep(type) : null;
        const stepCode = this.mapTypeToStep(item.type as AttachmentType);
        if (!stepCode) {
          return {
            ...item,
            signed_url: await this.generateSignedUrl(item.file_url!),
          };
        }
        if (type && targetStepCode && targetStepCode === stepCode) {
          const sameStepEvents = events.filter(e => e.step_code === targetStepCode);
          if (!sameStepEvents.length) {
            return {
              ...item,
              signed_url: await this.generateSignedUrl(item.file_url!),
            };
          }
 
          const latestEvent = sameStepEvents[sameStepEvents.length - 1];
          if (!latestEvent.event_time) return null;
 
          if (item.created_at < latestEvent.event_time) return null;
          return {
            ...item,
            signed_url: await this.generateSignedUrl(item.file_url!),
          };
        }
 
        const sameStepEvents = events.filter(e => e.step_code === stepCode);
        if (!sameStepEvents.length) {
          return {
            ...item,
            signed_url: await this.generateSignedUrl(item.file_url!),
          };
        }
 
        const latestEvent = sameStepEvents[sameStepEvents.length - 1];
        const toTime = latestEvent.event_time;
        if (!toTime) return null;
 
        const prevEvent = sameStepEvents.length > 1 ? sameStepEvents[sameStepEvents.length - 2] : null;
        const fromTime = prevEvent?.event_time ?? null;
 
        if (fromTime) {
          if (item.created_at <= fromTime || item.created_at > toTime) return null;
        } else {
          if (item.created_at > toTime) return null;
        }
        return {
          ...item,
          signed_url: await this.generateSignedUrl(item.file_url!),
        };
      }),
    ).then(results => results.filter(Boolean));
  }
 
  private mapTypeToStep(type: AttachmentType): TimelineStep | null {
    switch (type) {
      case AttachmentType.DROPPED:
        return TimelineStep.DROPPED;
      case AttachmentType.RECEIVED:
        return TimelineStep.RECEIVED;
      case AttachmentType.PACKING:
        return TimelineStep.PACKING;
      case AttachmentType.PACKED:
        return TimelineStep.PACKED;
      case AttachmentType.PICKUP:
        return TimelineStep.PICKUP;
      case AttachmentType.PICKED:
        return TimelineStep.PICKED;
      default:
        return null;
    }
  }
 
  async deleteGroup(id: number, pmoIds: number[]) {
    const attachment = await this.attachmentRepo.findById(id);
    if (!attachment) throw new HttpErrors.NotFound('Attachment not found');
 
    const groupUid = attachment.group_uid;
 
    if (!groupUid) {
      return this.delete(id);
    }
 
    const toDelete = await this.attachmentRepo.find({
      where: {
        group_uid: groupUid,
        pmo_id: {inq: pmoIds},
      },
    });
 
    if (!toDelete.length) return {success: true, deleted: 0};
    const totalCount = await this.attachmentRepo.count({group_uid: groupUid});
 
    await Promise.all(toDelete.map(a => this.attachmentRepo.deleteById(a.id)));
 
    if (totalCount.count <= 1) {
      await this.s3Service.deleteObject(attachment.file_url!);
    }
 
    return {success: true, deleted: toDelete.length};
  }
 
  /**
   * Delete attachment
   */
  async delete(id: number) {
    const attachment = await this.attachmentRepo.findById(id);
 
    if (!attachment) {
      throw new HttpErrors.NotFound('Attachment not found');
    }
 
    // delete S3 object
    await this.s3Service.deleteObject(attachment.file_url);
 
    // delete DB
    await this.attachmentRepo.deleteById(id);
 
    return {
      success: true,
    };
  }
 
  async generateSignedUrl(key: string) {
    const {s3Config} = AwsConfigs;
 
    return this.s3Service.s3.getSignedUrlPromise('getObject', {
      Bucket: s3Config.bucketName,
      Key: key,
 
      Expires: 60 * 60, // 1 hour
    });
  }
 
  buildViewUrl(id: number): string {
    return buildAttachmentViewUrl(id);
  }
}