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 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 1x 19x 19x 19x 19x 19x 19x 19x | import { bind, /* inject, */ BindingScope, service } from '@loopback/core';
import {
AnyObject,
EntityNotFoundError,
FilterBuilder,
OrClause,
repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { BaseService } from './base.service';
import { Constants } from '../configs';
import { EirDto, FilesMappingDto, UserDto } from '../dtos';
import { BaseResponses, Eir, Status } from '../models';
import {
CompanyRepository,
EirOverrideRepository,
EirRepository,
EirViewRepository,
FilesMappingRepository,
UserRepository,
} from '../repositories';
import { EirDocumentType, PdfTemplate } from '../types';
import { EirView, VerificationView } from '@logchain/models/views';
import _ from 'lodash';
import { FlowService } from './flow.service';
@bind({ scope: BindingScope.TRANSIENT })
export class EirService extends BaseService<Eir> {
eirs_tbl_name = Eir.definition.settings['postgresql'].table;
@service(FlowService)
public flowService: FlowService;
constructor(
@repository(EirRepository)
public eir_repo: EirRepository,
@repository(EirOverrideRepository)
public eir_override_repo: EirOverrideRepository,
@repository(EirViewRepository)
public eirViewRepository: EirViewRepository,
@repository(FilesMappingRepository)
public filesMappingRepository: FilesMappingRepository,
@repository(CompanyRepository)
public comp_repo: CompanyRepository,
@repository(UserRepository)
public userRepository: UserRepository,
) {
super();
}
/**
* Get array Eir based on filter.
* @param filter
*/
async find(): Promise<BaseResponses<EirView>> {
const filter_builder = new FilterBuilder<EirView>();
filter_builder.filter = this.filter_builder.filter;
this.addExtraFilter(filter_builder);
this.addExcludeFields(filter_builder);
filter_builder.impose({
company_id: this.current_user.company_id,
});
return this.eirViewRepository.fillRelation(filter_builder);
}
/**
* Get Eir by id or identifier
* @param id The user id
* @param filter The filter
* @returns Promise<Eir | null>
*/
async getByIdOrIdentifier(id: number): Promise<Eir> {
this.filter_builder.where({
company_id: this.current_user.company_id,
id: id,
});
// Load relation for Eir
this.addExtraFilter(this.filter_builder);
this.buildExtraFilterGetId(this.filter_builder);
const eir = await this.eir_repo.findOne(this.filter_builder.build(), {
get_reference: true,
});
if (!eir) {
throw new EntityNotFoundError(this.eir_repo.entityClass, id);
}
eir.documents = await this.filesMappingRepository.find({
where: {
external_id: id,
table_name: this.eirs_tbl_name,
},
fields: {
external_id: false,
table_name: false,
},
order: ['last_update_date DESC'],
});
// Fetch verification information
eir.verification = await this.verification_view_repo.findOne({
where: {
external_id: eir.id,
table_name: this.eir_repo.getPostgresTableName(),
is_actor: false,
},
}) as VerificationView;
return eir;
}
/**
* Update eir by id or identifier.
* @param id The eir id.
* @param eir The new information for the eir.
*/
async updateByIdOrIdentifier(id: number, eir: EirDto, options?: AnyObject): Promise<Eir> {
const current_eir = await this.eir_repo.findOne({
where: {
id: id,
company_id: this.current_user.company_id,
},
});
if (!current_eir) {
throw new EntityNotFoundError(this.eir_repo.entityClass, id);
}
if (Constants.eirFinishedStatuses.includes(current_eir.status)) {
throw new HttpErrors.BadRequest(
'Can not update a Cancelled or Completed Eir.',
);
}
if (eir.type === Constants.EirType.Indirect && eir.status === Status.Eir.Completed) {
if (!eir.received_by_name_indirect && !eir.delivered_by_name_indirect) {
throw new HttpErrors.BadRequest(
'Need at least 1 receiver or deliver identifier for Indirect Eir.',
);
}
}
// Create override record
if (options?.oldDocument) {
const overriden_eir = await this.eir_override_repo.create({
original_id: current_eir.id,
..._.omit(options.oldDocument, ['id', 'created_date', 'updated_date']),
});
// Transfer old attachments
await this.transferOldAttachments(
current_eir.id,
overriden_eir.id,
this.eir_repo.getPostgresTableName(),
Constants.EirDocumentTypeText[Constants.EirDocumentType.Receipt],
);
}
// Update document
const { receipt, additional_document } = eir;
if (receipt || additional_document) {
if (receipt) {
await this._upsertEirDocuments(current_eir, 'Receipt', receipt);
} else {
// Clear old recept
await this.deleteOldAttachments(this.eir_repo.getPostgresTableName(), id, Constants.EirDocumentTypeText[Constants.EirDocumentType.Receipt]);
}
if (additional_document) {
await this._upsertEirDocuments(current_eir, 'Additional', additional_document);
} else {
// Clear old Additional
await this.deleteOldAttachments(this.eir_repo.getPostgresTableName(), id, Constants.EirDocumentTypeText[Constants.EirDocumentType.Additional]);
}
}
// check exits customer
if (eir.customer_identifier) {
const customer = await this.comp_repo.findOne({
where: {
identifier: eir.customer_identifier,
},
});
if (!customer) {
throw new HttpErrors.BadRequest(
`${eir.customer_identifier} is not exists in company`,
);
}
eir.customer_id = customer.id;
}
// check exits delivered
if (eir.delivered_company_identifier) {
const delivered_company = await this.comp_repo.findOne({
where: {
identifier: eir.delivered_company_identifier,
},
});
if (!delivered_company) {
throw new HttpErrors.BadRequest(
`${eir.delivered_company_identifier} of delivery is not exists in company`,
);
}
eir.delivered_company_id = delivered_company.id;
}
// check exits received
if (eir.received_company_identifier) {
const received = await this.comp_repo.findOne({
where: {
identifier: eir.received_company_identifier,
},
});
if (!received) {
throw new HttpErrors.BadRequest(
`${eir.received_company_identifier} of received is not exists in company`,
);
}
eir.received_company_id = received.id;
}
// check exits User
if (eir.delivered_by_identifier) {
const user = await this.userRepository.findOne({
where: {
identifier: eir.delivered_by_identifier,
company_id: eir.delivered_company_id
? eir.delivered_company_id
: current_eir.delivered_company_id,
},
});
if (!user) {
throw new HttpErrors.BadRequest(
`${eir.delivered_by_identifier} of delivery is not exists in user`,
);
}
eir.delivered_by = user.id;
}
if (eir.status !== Status.Eir.New) {
eir.received_by = this.current_user.id;
eir.system_actual_date = new Date();
}
await this.eir_repo.updateById(id, eir);
// Cancel all other's eirs.
if (eir.status === Status.Eir.Cancelled && eir.cancelled_action === Status.ActionAfterCancelled.StopContainer) {
await this.eir_repo.updateAll(
{ status: Status.Eir.Cancelled, cancelled_action: Status.ActionAfterCancelled.StopContainer },
{
flow_id: current_eir.flow_id,
container_no: current_eir.container_no,
status: { nin: Constants.eirFinishedStatuses }
});
}
// ------------------------------
if (
current_eir.status !== eir.status &&
Constants.eirFinishedStatuses.includes(eir.status)
) {
const loaded_eir = await this.getByIdOrIdentifier(id) as EirDto;
const timezone = loaded_eir.company.timezone;
// Magic here because we want user input their driver name but don't want to list down all users
if (loaded_eir?.driven_name) {
if (!loaded_eir?.delivered?.name) {
loaded_eir.delivered = new UserDto({
name: loaded_eir.driven_name
});
} else {
loaded_eir.delivered.name = loaded_eir.driven_name;
}
}
// Push pdf of overriden action to the last page of overriding action
if (options?.oldDocument) {
loaded_eir.documents.push(new FilesMappingDto({ uri: options?.oldDocument.uri }));
}
const data: PdfTemplate = {
content: { ...loaded_eir, timezone, validator_id: await this.getValidatorFromStep(loaded_eir.journey_point_id)},
model_name: this.eirs_tbl_name,
};
await this.generatePdf(data);
}
// return to write logs
const inst_dto = new EirDto({ ...current_eir, ...eir } as EirDto);
if (inst_dto.customer_id) {
inst_dto.customer = await this.comp_repo.findById(inst_dto.customer_id);
}
const action = 'EIR';
current_eir.activity = {
str: '{0} for container number {1} is {2} for {3}',
args: [
eir.override_by_id ? action + ' overridden' : action,
current_eir.container_no,
(inst_dto.status_name() as string).toLowerCase(),
inst_dto.customer?.name ?? ''
]
};
// return to write logs
return current_eir;
}
/**
* Overrides an existing record with the provided payload.
*
* @param {number} id - The ID of the entry record to override.
* @return {Promise<EirDto>} A promise that resolves to the newly created entry record.
* @throws {EntityNotFoundError} If the old document is not found.
*/
async override(id: number, payload: EirDto): Promise<AnyObject> {
// Validate override document is valid for overriding
const oldDocument = await this.eir_repo.findById(id);
// Make sure old document exists
if (!oldDocument) {
throw new EntityNotFoundError(this.eir_repo.entityClass, id);
}
// ---------------------------------------
// Make sure overrided action must be completed
if (Constants.eirFinishedStatuses.includes(oldDocument.status) === false) {
throw new HttpErrors.BadRequest('Action was not completed yet.');
}
// ---------------------------------------
// Make sure overrided action don't have modification about form type (Direct to Indirect or vice versa)
if (oldDocument.type !== payload.type) {
throw new HttpErrors.BadRequest('The action can not be changed from Direct to Indirect or vice versa.');
}
// ---------------------------------------
// Mapping from old document to override document
const createdParam = new EirDto(oldDocument as EirDto);
Object.assign(createdParam, payload);
createdParam.status = oldDocument.status;
createdParam.created_date = new Date();
createdParam.modified_date = new Date();
// Mark this action was overriden by current user
createdParam.override_by_id = this.current_user.id;
// ---------------------------------------
// Reset status to in progress
await this.eir_repo.updateById(oldDocument.id, { status: Status.Eir.InProgress });
const newAction = await this.updateByIdOrIdentifier(oldDocument.id, createdParam, { oldDocument });
// ---------------------------------------
return newAction;
}
/**
* Build extra filter for Get Eir
* @param filterBuilder The filter builder instance
* @return Filter
*/
buildExtraFilterGetId(filterBuilder: FilterBuilder): FilterBuilder {
filterBuilder.include({
relation: 'company',
scope: {
fields: {
id: true,
name: true,
identifier: true,
timezone: true,
},
},
});
return filterBuilder;
}
/**
* Add extra filter for Eir
* @param filterBuilder The filter builder instance
* @return Filter
*/
addExtraFilter(filterBuilder: FilterBuilder) {
super._addIncludeModifier(filterBuilder);
filterBuilder
.include({
relation: 'customer',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'delivered_company',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'received_company',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'delivered',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'received',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
});
}
/**
* Exclude filed for Search
* @param filterBuilder The filter builder instance
* @return Filter
*/
addExcludeFields(filterBuilder: FilterBuilder) {
filterBuilder.fields({
remarks: false,
modified_by: false,
created_date: false,
modified_date: false,
});
}
/**
* Update or insert new documents for Eir.
* @param id The Eir id.
* @param type The type of document.
* @param doc_uri The document uri from s3.
* @param company
*/
private async _upsertEirDocuments(current_eir: Eir, type: EirDocumentType, doc_uri: string) {
const metadata = await this.s3_service.getObjectMetadata(doc_uri);
if (metadata) {
const msg =
type === 'Receipt'
? Constants.EirDocumentTypeText[Constants.EirDocumentType.Receipt]
: Constants.EirDocumentTypeText[Constants.EirDocumentType.Additional];
await this.filesMappingRepository.upsertWithWhere(
{
external_id: current_eir.id,
table_name: this.eirs_tbl_name,
field_name: msg
},
{
table_name: this.eirs_tbl_name,
field_name: msg,
uri: doc_uri,
version: metadata.VersionId,
external_id: current_eir.id,
hash: metadata.ETag?.slice(1, -1),
},
);
}
}
/**
* Builds the query for eir
* @param q The query string.
*/
async buildSearchQuery(q?: string) {
if (!q) {
return;
}
// FILTER:
// customer.identifier OR
// customer.name OR
// delivered_company.identifier OR
// delivered_company.name OR
// received_company.identifier OR
// received_company.name OR
// contract_id OR receipt_no OR container_no
// Should be a LIKE search
const ilike_value = this.buildILikeValue(q);
const companies_id = await this.getCompaniesIdByQuery(ilike_value);
const or_clause: OrClause<Eir> = {
or: [
{
customer_id: {
inq: companies_id,
},
},
{
delivered_company_id: {
inq: companies_id,
},
},
{
received_company_id: {
inq: companies_id,
},
},
{
contract_id: ilike_value,
},
{
container_no: ilike_value,
},
{
receipt_no: ilike_value,
},
{
flow_id: ilike_value as unknown as number,
},
],
};
this.filter_builder.impose(or_clause);
}
}
|