All files / src/services transport.service.ts

18.52% Statements 15/81
0% Branches 0/42
10% Functions 1/10
16.46% Lines 13/79

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 2901x 1x           1x   1x 1x             1x     1x 19x       19x   19x   19x   19x   19x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
import { bind, BindingScope } from '@loopback/core';
import {
  EntityNotFoundError,
  FilterBuilder,
  Options,
  repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { TransportDto } from '../dtos';
import { BaseResponses, CompanyLocation, Status, Transport } from '../models';
import {
  CompanyLocationRepository,
  CompanyPersonaRepository,
  TransportRepository,
  UserRepository,
} from '../repositories';
import { PdfTemplate } from '../types';
import { BaseService } from './base.service';
 
@bind({ scope: BindingScope.TRANSIENT })
export class TransportService extends BaseService<Transport> {
  transport_tbl_name = Transport.definition.settings['postgresql'].table;
 
  constructor(
    @repository(TransportRepository)
    public transport_repo: TransportRepository,
    @repository(CompanyPersonaRepository)
    public company_persona_repo: CompanyPersonaRepository,
    @repository(CompanyLocationRepository)
    public company_location_repo: CompanyLocationRepository,
    @repository(UserRepository)
    public user_repo: UserRepository,
  ) {
    super();
  }
 
  /**
   * Make sure we got the right access.
   */
  public ensureRightAccessRecord(): void {
    this.filter_builder.impose({
      company_id: this.current_user.company_id,
    });
  }
 
  /**
   * Find transports based on the filter.
   */
  async find(): Promise<BaseResponses<Transport>> {
    // add creator, modifier
    this.addExtraFilter(this.filter_builder);
 
    const transport = await this.transport_repo.findWithPaging(
      this.filter_builder.build(),
    );
    const { data } = transport;
    await this._getMoreData(data);
    return transport;
  }
 
  /**
   * Get more data for transport.
   * @param data The transport data.
   */
  private async _getMoreData(data: Transport[]) {
    if (!data.length) {
      return;
    }
 
    const comp_persona_ids: number[] = [];
    data.forEach(({ production }) => {
      if (production) {
        comp_persona_ids.push(production.company_persona_id);
      }
    });
 
    if (comp_persona_ids.length) {
      const companies = await this.company_persona_repo.find({
        include: [
          {
            relation: 'company',
          },
        ],
        where: {
          id: {
            inq: comp_persona_ids,
          },
        },
      });
 
      const mapping_companies: { [x: string]: string } = {};
      for (const iterator of companies) {
        mapping_companies[iterator.id] = iterator.company.name;
      }
 
      data.forEach(({ production }) => {
        if (production) {
          production.company =
            mapping_companies[production.company_persona_id.toString()];
        }
      });
    }
  }
 
  /**
   * Gets by id or identifier
   * @param id The id of transports
   * @returns Promise<Transport>
   */
  async getByIdOrIdentifier(id: string | number): Promise<Transport> {
    this.addWhereIdOrIdentifier(id);
    // add modifier
    this._addIncludeModifier(this.filter_builder);
    this.addExtraFilter(this.filter_builder);
    const transports = await this.transport_repo.findOne(
      this.filter_builder.build(),
      {
        get_reference: true,
      },
    );
 
    if (!transports) {
      throw new EntityNotFoundError(this.transport_repo.entityClass, id);
    }
 
    await this._getMoreData([transports]);
    return transports;
  }
 
  /**
   * Builds the query for trade lane
   * @param q The query string.
   */
  async buildSearchQuery(q?: string) {
    if (!q) {
      return;
    }
 
    const company_location_ids = await this.transport_repo.getCompanyLocationIdByQuery(
      this.buildILikeValue(q),
    );
 
    this.filter_builder.impose({
      or: [
        {
          production_location_id: {
            inq: company_location_ids,
          },
        },
      ],
    });
  }
 
  /**
   * Update transport by id or identifier
   * @param id The id or identifier of transport
   * @param transport The new transport info
   * @returns Promise<Transport>
   */
  async updateByIdOrIdentifier(
    id: number,
    transport: TransportDto,
  ): Promise<Transport> {
    const { driven_by_identifier, status } = transport;
 
    // Required IF status is set to 1 (In Progress) ELSE field is Optional
    if (status === Status.Transport.InProgress && !transport.location_start) {
      throw new HttpErrors.BadRequest(`Location start is required!`);
    }
 
    // Required IF status is set to 4 (Completed) ELSE field is Optional
    if (status === Status.Transport.Completed) {
      if (!transport.location_end || !transport.travel_screenshot) {
        throw new HttpErrors.BadRequest(
          `Some information are required to complete the transport: location_end, travel_screenshot`,
        );
      }
 
      // ensure the travel_screenshot is exists.
      await this.ensureS3ObjectExists(transport.travel_screenshot);
    }
 
    this.addWhereIdOrIdentifier(id);
    const current_transport = await this.transport_repo.findOne(
      this.filter_builder.build(),
    );
 
    if (!current_transport) {
      throw new EntityNotFoundError(this.transport_repo.entityClass, id);
    }
 
    const new_status = Status.Transport.New;
    if (status === new_status && current_transport.status !== new_status) {
      throw new HttpErrors.BadRequest(`Can not set status to new: ${status}`);
    }
 
    const completedStatus = [
      Status.Transport.Cancelled,
      Status.Transport.Completed,
    ];
    if (completedStatus.includes(current_transport.status)) {
      throw new HttpErrors.BadRequest(
        `Cannot update the transport: current status is ${current_transport.status}`,
      );
    }
 
    if (driven_by_identifier) {
      const new_driver = await this.user_repo.findByIdWithActiveStatus(
        driven_by_identifier,
      );
 
      transport.driven_by = new_driver.id;
    }
 
    // Updated when status is set to 1 (In Progress)
    if (transport.status === Status.Transport.InProgress) {
      transport.actual_start_time = new Date();
    }
 
    // Updated when status is set to 4 (Completed)
    if (
      transport.status === Status.Transport.Completed ||
      transport.status === Status.Transport.Cancelled
    ) {
      transport.actual_end_time = new Date();
    }
    await this.transport_repo.updateById(id, transport);
    // Generate the pdf for the loading.
    if (
      current_transport.status !== transport.status &&
      completedStatus.includes(transport.status)
    ) {
      const newest_trans = await this.getByIdOrIdentifier(current_transport.id) as TransportDto;
      const timezone = newest_trans.company.timezone;
      const data: PdfTemplate = {
        content: { ...newest_trans, timezone, validator_id: await this.getValidatorFromStep(newest_trans.journey_point_id)},
        model_name: this.transport_tbl_name,
      };
      await this.generatePdf(data);
    }
    return current_transport;
  }
 
  /**
   * Build extra filter for user
   * @param filterBuilder The filter builder instance
   * @param options The options
   * @return Filter
   */
  addExtraFilter(options?: Options): void {
    //add Company
    this.filter_builder.include({
      relation: 'company',
      scope: {
        fields: {
          id: true,
          identifier: true,
          name: true,
          timezone: true,
        },
      },
    });
    //add Driver
    this.filter_builder.include({
      relation: 'driver',
      scope: {
        fields: {
          id: true,
          identifier: true,
          name: true,
        },
      },
    });
    //add Production
    this.filter_builder.include({
      relation: 'production',
      scope: {
        fields: [
          'id',
          'name',
          'address',
          'google_map_link',
          'company_persona_id',
          'coordinates',
        ],
      },
    });
  }
}