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 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x | import { bind, BindingScope, service } from '@loopback/core';
import {
EntityNotFoundError,
FilterBuilder,
Options,
OrClause,
repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { FilesMappingDto, VesselDto } from '../dtos';
import { BaseResponses, Vessel, VesselWithRelations, Status } from '../models';
import {
CompanyRepository,
FilesMappingRepository,
FlowJourneyPointRepository,
VesselRepository,
VesselViewRepository,
UserViewRepository,
VesselOverrideRepository,
} from '../repositories';
import { AnyObject, PdfTemplate } from '../types';
import { BaseService } from './base.service';
import { VerificationView, VesselView, VesselViewWithRelations } from '@logchain/models/views';
import { Constants } from '@logchain/configs';
import _ from 'lodash';
import { FlowService } from './flow.service';
@bind({ scope: BindingScope.TRANSIENT })
export class VesselService extends BaseService<Vessel> {
@service(FlowService)
public flowService: FlowService;
constructor(
@repository(VesselRepository)
public vessel_repo: VesselRepository,
@repository(VesselOverrideRepository)
public vessel_override_repo: VesselOverrideRepository,
@repository(VesselViewRepository)
public vessel_view_repo: VesselViewRepository,
@repository(FilesMappingRepository)
public files_mapping_repo: FilesMappingRepository,
@repository(CompanyRepository)
public comp_repo: CompanyRepository,
@repository(UserViewRepository)
public userRepository: UserViewRepository,
@repository(FlowJourneyPointRepository)
public flowJourneyPointRepository: FlowJourneyPointRepository,
) {
super();
}
/**
* Make sure we got the right access.
*/
public ensureRightAccessRecord(): void {
this.filter_builder.impose({
company_id: this.current_user.company_id,
hidden: false,
} as unknown as OrClause<Vessel>);
}
/**
* Make sure we got the right user access.
*/
public ensureUserAccessRecord(): void {
const where = this.filter_builder.filter.where as AnyObject;
if (where?.category_ids === undefined) {
this.filter_builder.impose({
granted_users: {
contains: [this.current_user.id],
},
} as AnyObject);
}
}
/**
* Get array Vessel based on filter.
* @param filter
*/
async find(): Promise<BaseResponses<VesselViewWithRelations>> {
this.ensureUserAccessRecord();
const filter_builder = new FilterBuilder<VesselView>();
filter_builder.filter = this.filter_builder.filter;
this.addExtraFilter(filter_builder);
this._addExcludeFields(filter_builder);
return this.vessel_view_repo.fillRelation(filter_builder);
}
/**
* update Vessel based on filter.
* @param id
* Vessel
*/
async updateByIdOrIdentifier(
id: number,
vessel: VesselDto,
options: Options = {}
): Promise<VesselWithRelations> {
this.addWhereIdOrIdentifier(id);
this._addIncludeCompany(this.filter_builder);
// Get instance of Vessel
const current_vessel = await this.vessel_repo.findOne(
this.filter_builder.build(),
);
if (!current_vessel) {
throw new EntityNotFoundError(this.vessel_repo.entityClass, id);
}
const vesselDto = new VesselDto(current_vessel as unknown as VesselDto);
// Can not switch status back to New
if (
vessel.status === Status.Vessel.New &&
current_vessel.status !== Status.Vessel.New
) {
throw new HttpErrors.BadRequest(
`Can not change status to new ${vessel.status}`,
);
} else if ([Status.Vessel.Cancelled, Status.Vessel.Completed].includes(current_vessel.status)) {
throw new HttpErrors.BadRequest(`This action was completed.`,);
}
// For external request
if (options?.type_id) {
const submittedType = (options?.type_id === Constants.Form.VesselArrival) ? Constants.VesselType.Arrival : Constants.VesselType.Departure;
if (current_vessel.action_type !== submittedType) {
throw new HttpErrors.BadRequest('Invalid Parameters: type_id.');
}
}
if (Constants.vesselFinishedStatuses.includes(vessel.status)) {
if (!vessel?.attachments?.length && !current_vessel?.documents?.length) {
// Validate vessel in case this form is not attachment form
if (!vessel.containers?.length) {
throw new HttpErrors.BadRequest('Missing Parameters: containers.');
}
// We need to make sure all submitted containers are allowed (not completed and cancelled)
const allowed_containers = await this.vessel_repo.getDefaultContainers(current_vessel.flow_id, current_vessel.action_type, current_vessel.journey_point_id);
const submitted_valid_containers = vessel.containers.filter((container: AnyObject) => {
return allowed_containers.includes(container.container_no);
});
if (submitted_valid_containers.length !== vessel.containers.length) {
throw new HttpErrors.BadRequest('Invalid Parameters: containers.');
}
}
}
// Check exits company_other
if (vessel.company_other_identifier) {
const company_other = await this.comp_repo.findOne({
where: {
identifier: vessel.company_other_identifier,
},
});
if (!company_other) {
throw new HttpErrors.BadRequest(
`${vessel.company_other_identifier} is not exists in company`,
);
}
vesselDto.company_other = company_other;
}
// Create override record
if (options?.oldDocument) {
const overriden_vessel = await this.vessel_override_repo.create({
original_id: current_vessel.id,
..._.omit(options.oldDocument, ['id', 'created_date', 'updated_date']),
});
// Transfer old attachments
await this.transferOldAttachments(
current_vessel.id,
overriden_vessel.id,
this.vessel_repo.getPostgresTableName(),
'Vessel'
);
// -------------------------------
}
// For external request
if (vessel.attachments && typeof(vessel.attachments) === 'string') {
// For external request user provide base64 content
const buf = Buffer.from(vessel.attachments as unknown as string, 'base64')
vessel.attachments = [`documents/vessels/${vesselDto.company.identifier}/${vesselDto.id}.pdf`];
const param = {
Key: vessel.attachments[0],
Body: buf,
ContentEncoding: 'base64',
ContentType: 'application/pdf',
ServerSideEncryption: 'AES256',
};
await this.s3_service.putObject(param);
}
// Process form upload
const { attachments = [] } = vessel;
if (attachments.length) {
for (const attachment of attachments as unknown as AnyObject[]) {
let uri = '';
if (typeof(attachment) !== 'string') {
uri = attachment.uri;
} else {
uri = attachment;
}
const metadata = await this.s3_service.getObjectMetadata(uri);
if (metadata) {
const e_tag = metadata.ETag?.slice(1, -1);
await this.files_mapping_repo.upsertWithWhere(
{
hash: e_tag,
external_id: id,
},
{
table_name: this.vessel_repo.getPostgresTableName(),
field_name: `Vessel`,
uri: uri,
version: metadata.VersionId,
external_id: id,
hash: e_tag,
last_update_date: metadata.LastModified,
added_reason: attachment.reason ?? '',
},
);
}
}
} else {
// Delete old attachments
await this.deleteOldAttachments(this.vessel_repo.getPostgresTableName(), id);
}
if ([...Constants.vesselFinishedStatuses, Status.Vessel.InProgress].includes(vessel.status)) {
vessel.system_actual_date = new Date();
}
// Update Vessel after finished all validation above
await this.vessel_repo.updateById(id, vessel);
vesselDto.status = vessel.status;
// Generate the pdf for the vessel.
if (
current_vessel.status !== vessel.status &&
Constants.vesselFinishedStatuses.includes(vessel.status)
) {
options.forPDFCreation = true; // This flag is used to create pdf with seperate file_mappings
const newest_vessel = await this.getByIdOrIdentifier(current_vessel.id, options) as unknown as VesselDto;
// Push pdf of overriden action to the last page of overriding action
if (options?.oldDocument) {
const files = options?.forAdditional ? newest_vessel.additional_documents : newest_vessel.documents;
files.unshift(new FilesMappingDto({ uri: options?.oldDocument.uri }));
}
const data: PdfTemplate = {
content: {
...newest_vessel,
timezone: newest_vessel?.company?.timezone ?? '',
validator_id: await this.getValidatorFromStep(newest_vessel.journey_point_id)
},
model_name: this.vessel_repo.getPostgresTableName(),
};
await this.generatePdf(data);
// Create new action date for remaining container
// #42870 - [Bug][Vessel Form] There is not a new record created after the action was completed on the form
if (!current_vessel.override_by_id
&& newest_vessel.cancelled_action !== Status.ActionAfterCancelled.NewAction
&& newest_vessel.allowed_containers?.length
&& !options?.oldDocument
) {
const oldDocument = await this.vessel_repo.findById(newest_vessel.id);
const createdParam = new VesselDto(_.omit(
oldDocument,
'id',
'containers',
'is_pdf_created',
'uri',
'version',
'hash',
'blockchain_tx',
'pdf_attempt',
'created_date',
'modified_date'
) as unknown as VesselDto);
createdParam.containers = newest_vessel.allowed_containers?.map(container_no => {
return {
container_no,
reference: '',
shipment: '',
}
}) ?? [];
await this.vessel_repo.create({
...createdParam,
status: Status.Vessel.New,
created_date: new Date(),
});
}
// ------------------------------------------------------
}
if (current_vessel.company_other_id) {
vesselDto.company_other = await this.comp_repo.findById(current_vessel.company_other_id);
}
const action = Constants.VesselTypeText[vesselDto?.action_type ?? 0] ?? '';
current_vessel.activity = {
str: '{0} is {1} for {2}',
args: [
current_vessel.override_by_id ? action + ' overridden' : action,
(vesselDto.status_name() as string).toLowerCase(),
vesselDto.company_other?.name ?? ''
]
};
return current_vessel;
}
/**
* Get Vessel by id or identifier
* @param id The user id
* @param filter The filter
* @returns Promise<Vessel | null>
*/
async getByIdOrIdentifier(id: number, options?: Options): Promise<VesselViewWithRelations> {
this.addWhereIdOrIdentifier(id);
// Load relation for Vessel
this.addExtraFilter(this.filter_builder);
this.addExtraCompanyFilter(this.filter_builder);
const filter_builder = new FilterBuilder<VesselView>();
filter_builder.filter = this.filter_builder.filter;
const vessel = await this.vessel_view_repo.findOne(
filter_builder.build(),
{
get_reference: true,
},
);
if (!vessel) {
throw new EntityNotFoundError(this.vessel_view_repo.entityClass, id);
}
// Get default container list for vessel form
vessel.allowed_containers = await this.vessel_repo.getDefaultContainers(vessel.flow_id, vessel.action_type, vessel.journey_point_id);
if (vessel.containers?.length && vessel.allowed_containers?.length) {
const selected_containers = vessel.containers.map((container: AnyObject) => {
return container.container_no;
});
vessel.allowed_containers = vessel.allowed_containers.filter((c: string) => !selected_containers.includes(c));
}
// ------------------------------------------
// Get all documents by flow_action_id
const all_documents = await this.vessel_repo.find({
fields: ['id'],
where: {
flow_action_id: vessel.flow_action_id,
}
});
// Init default data
vessel.documents = [];
vessel.additional_documents = [];
if (all_documents?.length) {
let document_ids = all_documents.map((d) => d.id);
if (options?.forPDFCreation) {
document_ids = [id];
}
const documents = await this.files_mapping_repo.find({
where: {
external_id: { inq: document_ids },
table_name: this.vessel_repo.getPostgresTableName(),
},
fields: {
external_id: false,
table_name: false,
},
order: ['last_update_date DESC'],
});
if (documents?.length) {
documents.map((d) => {
if (!d.added_reason) {
vessel.documents.push(d);
} else {
vessel.additional_documents.push(d);
}
});
}
}
// Fetch verification information
vessel.verification = await this.verification_view_repo.findOne({
where: {
external_id: vessel.id,
table_name: this.vessel_repo.getPostgresTableName(),
is_actor: false,
},
}) as VerificationView;
return vessel;
}
/**
* Validates the given ID and payload.
*
* @param {number} id - The ID to validate.
* @param {AnyObject} payload - The payload to validate.
* @throws {EntityNotFoundError} If the old document is not found.
* @return {Promise<any>} The result of the function.
*/
async validate(id: number, payload: AnyObject, options?: Options): Promise<AnyObject> {
const oldOriginalDocument = await this.vessel_repo.findById(id);
if (!oldOriginalDocument || ![Status.Vessel.Completed, Status.Vessel.Cancelled].includes(oldOriginalDocument.status)) {
throw new EntityNotFoundError(this.vessel_repo.entityClass, id);
}
const oldDocument = await this.vessel_repo.findOne({
where: {
flow_action_id: oldOriginalDocument.flow_action_id,
status: { nin: [Status.Vessel.New, Status.Vessel.InProgress] },
},
order: ['id DESC'],
limit: 1,
}) ?? oldOriginalDocument;
const createdParam = new VesselDto(_.omit(oldDocument, 'id') as unknown as VesselDto);
const newDocument = await this.vessel_repo.create({
...createdParam,
status: Status.Document.New,
created_date: new Date(),
hidden: true,
});
const updatedParams = {
attachments: payload.documents,
status: oldDocument.status,
} as VesselDto;
return this.updateByIdOrIdentifier(newDocument.id, updatedParams, {
oldDocument: oldDocument as unknown as VesselDto,
forAdditional: true,
...options,
});
}
/**
* Overrides an existing record with the provided payload.
*
* @param {number} id - The ID of the entry record to override.
* @return {Promise<VesselDto>} A promise that resolves to the newly created entry record.
* @throws {EntityNotFoundError} If the old document is not found.
*/
async override(id: number, payload: VesselDto): Promise<AnyObject> {
// Validate override document is valid for overriding
const oldDocument = await this.vessel_repo.findById(id);
// Make sure old document exists
if (!oldDocument) {
throw new EntityNotFoundError(this.vessel_repo.entityClass, id);
}
// ---------------------------------------
// Make sure overrided action must be completed
if (Constants.loadingFinishedStatuses.includes(oldDocument.status) === false) {
throw new HttpErrors.BadRequest('Action was not completed yet.');
}
// ---------------------------------------
// Make sure overrided action don't have modification about form type (form to attachment or vice versa)
if (oldDocument.form_type !== payload.form_type) {
throw new HttpErrors.BadRequest('The action can not be changed from form to attachment or vice versa.');
}
// ---------------------------------------
// Mapping from old document to override document
const createdParam = new VesselDto(oldDocument as unknown as VesselDto);
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.vessel_repo.updateById(oldDocument.id, { status: Status.Vessel.InProgress });
const newAction = await this.updateByIdOrIdentifier(oldDocument.id, createdParam, { oldDocument });
// ---------------------------------------
return newAction;
}
/**
* Add extra filter for Vessel
* @param filterBuilder The filter builder instance
* @param options The options
* @return Filter
*/
addExtraFilter(filterBuilder: FilterBuilder, options?: Options) {
super._addIncludeModifier(filterBuilder);
filterBuilder
.include({
relation: 'company_other',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
});
}
/**
* Add extra filter for Vessel company
* @param filterBuilder The filter builder instance
* @param options The options
* @return Filter
*/
addExtraCompanyFilter(filterBuilder: FilterBuilder, options?: Options) {
super._addIncludeModifier(filterBuilder);
filterBuilder.include({
relation: 'company',
scope: {
fields: {
id: true,
identifier: true,
name: true,
timezone: true,
},
},
});
}
/**
* Builds the query for vessel
* @param q The query string.
*/
async buildSearchQuery(q?: string) {
if (!q) {
return;
}
const ilike_value = this.buildILikeValue(q);
const or_clause: OrClause<VesselView> = {
or: [
{
flow_id: ilike_value as unknown as number,
},
{
flow_name: ilike_value,
},
{
container_no: ilike_value,
},
{
product_no: ilike_value,
},
],
};
this.filter_builder.impose(or_clause);
}
/**
* Add extra filter (excluded) on fields
* @param {FilterBuilder} filterBuilder
*/
private _addExcludeFields(filterBuilder: FilterBuilder) {
filterBuilder.fields({
remarks: false,
created_date: false,
});
}
}
|