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 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 3x 1x 1x 1x 1x 1x 11x 11x 11x 11x 1x 10x 10x 1x 9x 9x 9x 4x 3x 3x 3x 1x 2x 8x 1x 1x 1x 7x 1x 1x 1x 6x 1x 1x 1x 5x 1x 1x 1x 4x 2x 2x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 3x 4x 4x 4x 4x 4x 2x 4x 4x 2x 4x 4x 4x 3x 3x 3x 3x 3x 2x 2x 3x 3x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 1x 4x 4x 4x 4x 6x 4x 3x 4x 4x 2x 2x 2x 4x 4x 2x 1x 1x 1x 1x 1x 1x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 5x 5x 1x | import { bind, BindingScope, service } from '@loopback/core';
import {
EntityNotFoundError,
FilterBuilder,
Options,
OrClause,
repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { FilesMappingDto, OnLoadingDto, UserForRequestDto } from '../dtos';
import { BaseResponses, OnLoading, OnLoadingWithRelations, Status } from '../models';
import {
CompanyRepository,
FilesMappingRepository,
OnLoadingOverrideRepository,
OnLoadingRepository,
OnLoadingViewRepository,
UserRepository,
} from '../repositories';
import { AnyObject, PdfTemplate } from '../types';
import { BaseService } from './base.service';
import { isBoolean } from 'lodash';
import { OnLoadingView, VerificationView } from '@logchain/models/views';
import { Constants } from '@logchain/configs';
import _ from 'lodash';
import { FlowService } from './flow.service';
@bind({ scope: BindingScope.TRANSIENT })
export class OnLoadingService extends BaseService<OnLoading> {
@service(FlowService)
public flowService: FlowService;
constructor(
@repository(OnLoadingRepository)
public onLoadingRepository: OnLoadingRepository,
@repository(OnLoadingOverrideRepository)
public onLoadingOverrideRepository: OnLoadingOverrideRepository,
@repository(OnLoadingViewRepository)
public onLoadingViewRepository: OnLoadingViewRepository,
@repository(FilesMappingRepository)
public files_mapping_repo: FilesMappingRepository,
@repository(CompanyRepository)
public comp_repo: CompanyRepository,
@repository(UserRepository)
public userRepository: UserRepository,
) {
super();
}
/**
* Make sure we got the right access.
*/
public ensureRightAccessRecord(): void {
this.filter_builder.impose({
company_id: this.current_user.company_id,
});
}
/**
* Get array OnLoading based on filter.
* @param filter
*/
async find(): Promise<BaseResponses<OnLoadingView>> {
const filter_builder = new FilterBuilder<OnLoadingView>();
filter_builder.filter = this.filter_builder.filter;
this.addExtraFilter(filter_builder);
this._addExcludeFields(filter_builder);
return this.onLoadingViewRepository.fillRelation(filter_builder);
}
/**
* update OnLoading based on filter.
* @param id
* OnLoading
*/
async updateByIdOrIdentifier(
id: number,
onLoading: OnLoadingDto,
options: Options = {}
): Promise<OnLoadingWithRelations> {
this.addWhereIdOrIdentifier(id);
this._addIncludeCompany(this.filter_builder);
// Get instance of OnLoading
const current_OnLoading = await this.onLoadingRepository.findOne(
this.filter_builder.build(), options
);
if (!current_OnLoading) {
throw new EntityNotFoundError(this.onLoadingRepository.entityClass, id);
}
const onLoadingDto = new OnLoadingDto(current_OnLoading as OnLoadingDto);
// Can not switch status back to New
if (
onLoading.status === Status.OnLoading.New &&
current_OnLoading.status !== Status.OnLoading.New
) {
throw new HttpErrors.BadRequest(
`Can not change status to new ${onLoading.status}`,
);
} else Iif ([Status.OnLoading.Cancelled, Status.OnLoading.Completed].includes(current_OnLoading.status)) {
throw new HttpErrors.BadRequest(`This action was completed.`,);
}
Iif (options?.type_id) {
const submittedType = (options?.type_id === Constants.Form.OnLoading) ? Constants.OnLoadingType.OnLoading : Constants.OnLoadingType.Offloading;
if (current_OnLoading.type !== submittedType) {
throw new HttpErrors.BadRequest('Invalid Parameters: type_id.');
}
}
if (onLoading.status === Status.OnLoading.Completed) {
if (!onLoading.attachments) {
Iif (onLoading.actual_weight === undefined) {
throw new HttpErrors.BadRequest('Required Parameters: actual_weight.');
} else Iif (onLoading.expected_weight === undefined) {
throw new HttpErrors.BadRequest('Required Parameters: expected_weight.');
}
if (onLoading.actual_weight <= 0) {
throw new HttpErrors.BadRequest('Invalid Parameters: actual_weight.');
} else Iif (onLoading.expected_weight <= 0) {
throw new HttpErrors.BadRequest('Invalid Parameters: expected_weight.');
}
}
}
// Check exits company_other
if (onLoading.company_other_identifier) {
const company_other = await this.comp_repo.findOne({
where: {
identifier: onLoading.company_other_identifier,
},
});
Eif (!company_other) {
throw new HttpErrors.BadRequest(
`${onLoading.company_other_identifier} is not exists in company`,
);
}
}
// Check exits delivered
if (onLoading.delivered_company_identifier) {
const delivered = await this.comp_repo.findOne({
where: {
identifier: onLoading.delivered_company_identifier,
},
});
Eif (!delivered) {
throw new HttpErrors.BadRequest(
`${onLoading.delivered_company_identifier} is not exists in company`,
);
}
}
// Check exits delivered_identifier in users table
if (onLoading.delivered_identifier) {
const user = await this.userRepository.findOne({
where: {
identifier: onLoading.delivered_identifier,
},
});
Eif (!user) {
throw new HttpErrors.BadRequest(
`${onLoading.delivered_identifier} is not exists in User`,
);
}
}
// Check exits supervise_identifier in users table
if (onLoading.supervise_identifier) {
const user = await this.userRepository.findOne({
where: {
identifier: onLoading.supervise_identifier,
},
});
Eif (!user) {
throw new HttpErrors.BadRequest(
`${onLoading.supervise_identifier} is not exists in User`,
);
}
}
// Create override record
if (options?.oldDocument) {
const overriden_onloading = await this.onLoadingOverrideRepository.create({
original_id: current_OnLoading.id,
..._.omit(options.oldDocument, ['id', 'created_date', 'updated_date']),
});
// Transfer old attachments
await this.transferOldAttachments(
current_OnLoading.id,
overriden_onloading.id,
this.onLoadingRepository.getPostgresTableName(),
'OnLoading'
);
// -------------------------------
}
Iif (onLoading.attachments && typeof(onLoading.attachments) === 'string') {
// For external request user provide base64 content
const buf = Buffer.from(onLoading.attachments as unknown as string, 'base64')
onLoading.attachments = [`documents/onLoadings/${onLoadingDto.company.identifier}/${onLoadingDto.id}.pdf`];
const param = {
Key: onLoading.attachments[0],
Body: buf,
ContentEncoding: 'base64',
ContentType: 'application/pdf',
ServerSideEncryption: 'AES256',
};
await this.s3_service.putObject(param);
}
// Process form upload
const { attachments = [] } = onLoading;
if (attachments.length) {
for (const attachment of attachments as unknown as AnyObject[]) {
let uri = '';
Eif (typeof(attachment) !== 'string') {
uri = attachment.uri;
} else {
uri = attachment;
}
const metadata = await this.s3_service.getObjectMetadata(uri);
Eif (metadata) {
const e_tag = metadata.ETag?.slice(1, -1);
await this.files_mapping_repo.upsertWithWhere(
{
hash: e_tag,
external_id: id,
},
{
table_name: this.onLoadingRepository.getPostgresTableName(),
field_name: `OnLoading`,
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.onLoadingRepository.getPostgresTableName(), id);
}
// The last one who did the update will be the supervise.
onLoading.supervise_by = this.current_user.id;
Eif ([...Constants.onloadingFinishedStatuses, Status.OnLoading.InProgress].includes(onLoading.status)) {
onLoading.system_actual_date = new Date();
}
// Set default value for boolean when this field is null or empty string.
Eif (!isBoolean(onLoading.is_weight_in_contract)) {
if (!isBoolean(current_OnLoading.is_weight_in_contract)) {
onLoading.is_weight_in_contract = false;
}
}
Eif (!isBoolean(onLoading.is_weight_safe)) {
if (!isBoolean(current_OnLoading.is_weight_safe)) {
onLoading.is_weight_safe = false;
}
}
await this.onLoadingRepository.updateById(id, onLoading);
// Cancel all other's action data.
Iif (onLoading.status === Status.OnLoading.Cancelled && onLoading.cancelled_action === Status.ActionAfterCancelled.StopContainer) {
await this.onLoadingRepository.updateAll(
{ status: Status.OnLoading.Cancelled, cancelled_action: Status.ActionAfterCancelled.StopContainer },
{
flow_id: current_OnLoading.flow_id,
tank_no: current_OnLoading.tank_no,
status: { nin: Constants.onloadingFinishedStatuses }
});
}
// ------------------------------
// Generate the pdf for the OnLoading.
if (
current_OnLoading.status !== onLoading.status &&
Constants.onloadingFinishedStatuses.includes(onLoading.status)
) {
options.forPDFCreation = true; // This flag is used to create pdf with seperate file_mappings
const newest_OnLoading = await this.getByIdOrIdentifier(current_OnLoading.id, options) as unknown as OnLoadingDto;
const timezone = newest_OnLoading.company.timezone;
// Magic here because we want user input their driver name but don't want to list down all users
Iif (newest_OnLoading?.driven_name) {
if (!newest_OnLoading?.delivered?.name) {
newest_OnLoading.delivered = new UserForRequestDto({
name: newest_OnLoading.driven_name
});
} else {
newest_OnLoading.delivered.name = newest_OnLoading.driven_name;
}
}
// Push pdf of overriden action to the last page of overriding action
if (options?.oldDocument) {
const files = options?.forAdditional ? newest_OnLoading.additional_documents : newest_OnLoading.documents;
files.unshift(new FilesMappingDto({ uri: options?.oldDocument.uri }));
}
const data: PdfTemplate = {
content: {
...newest_OnLoading,
timezone,
validator_id: await this.getValidatorFromStep(newest_OnLoading.journey_point_id)
},
model_name: this.onLoadingRepository.getPostgresTableName(),
};
await this.generatePdf(data);
}
// return to write logs
const current_onloading_dto = new OnLoadingDto({ ...current_OnLoading, ...onLoading });
Eif (current_onloading_dto.company_other_id) {
current_onloading_dto.company_other = await this.comp_repo.findById(current_onloading_dto.company_other_id);
}
const action = Constants.OnLoadingTypeText[current_OnLoading?.type ?? 0];
current_OnLoading.activity = {
str: '{0} for container number {1} is {2} for {3}',
args: [
action,
current_OnLoading.tank_no,
(current_onloading_dto.status_name() as string).toLowerCase(),
current_onloading_dto.company_other?.name ?? ''
]
};
return current_OnLoading;
}
/**
* Get OnLoading by id or identifier
* @param id The user id
* @param filter The filter
* @returns Promise<OnLoading | null>
*/
async getByIdOrIdentifier(id: number, options?: Options): Promise<OnLoadingWithRelations> {
this.addWhereIdOrIdentifier(id);
// Load relation for OnLoading
this.addExtraFilter(this.filter_builder);
this.addExtraCompanyFilter(this.filter_builder);
const onLoading = await this.onLoadingRepository.findOne(
this.filter_builder.build(),
{
get_reference: options?.get_reference ?? true,
},
);
if (!onLoading) {
throw new EntityNotFoundError(this.onLoadingRepository.entityClass, id);
}
// Get all documents by flow_action_id
const all_documents = await this.onLoadingRepository.find({
fields: ['id'],
where: {
flow_action_id: onLoading.flow_action_id,
}
});
// Init default data
onLoading.documents = [];
onLoading.additional_documents = [];
Eif (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.onLoadingRepository.getPostgresTableName(),
},
fields: {
external_id: false,
table_name: false,
},
order: ['last_update_date DESC'],
});
if (documents?.length) {
documents.map((d) => {
Eif (!d.added_reason) {
onLoading.documents.push(d);
} else {
onLoading.additional_documents.push(d);
}
});
}
}
// Fetch verification information
onLoading.verification = await this.verification_view_repo.findOne({
where: {
external_id: onLoading.id,
table_name: this.onLoadingRepository.getPostgresTableName(),
is_actor: false,
},
}) as VerificationView;
return onLoading;
}
/**
* 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.onLoadingRepository.findById(id);
Iif (!oldOriginalDocument || ![Status.OnLoading.Completed, Status.OnLoading.Cancelled].includes(oldOriginalDocument.status)) {
throw new EntityNotFoundError(this.onLoadingRepository.entityClass, id);
}
const oldDocument = await this.onLoadingRepository.findOne({
where: {
flow_action_id: oldOriginalDocument.flow_action_id,
status: { nin: [Status.OnLoading.New, Status.OnLoading.InProgress] },
},
order: ['id DESC'],
limit: 1,
}) ?? oldOriginalDocument;
const createdParam = new OnLoadingDto(_.omit(oldDocument, 'id') as OnLoadingDto);
const newDocument = await this.onLoadingRepository.create({
...createdParam,
status: Status.OnLoading.New,
created_date: new Date(),
});
const updatedParams = {
attachments: payload.documents,
status: oldDocument.status,
} as OnLoadingDto;
return this.updateByIdOrIdentifier(newDocument.id, updatedParams, {
oldDocument: oldDocument as OnLoadingDto,
forAdditional: true,
...options,
});
}
/**
* Overrides an existing record with the provided payload.
*
* @param {number} id - The ID of the entry record to override.
* @return {Promise<OnLoadingDto>} A promise that resolves to the newly created entry record.
* @throws {EntityNotFoundError} If the old document is not found.
*/
async override(id: number, payload: OnLoadingDto, options?: Options): Promise<AnyObject> {
// Validate override document is valid for overriding
const oldDocument = await this.onLoadingRepository.findById(id);
// Make sure old document exists
Iif (!oldDocument) {
throw new EntityNotFoundError(this.onLoadingRepository.entityClass, id);
}
// ---------------------------------------
// Make sure overrided action must be completed
if (Constants.onloadingFinishedStatuses.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)
Iif (oldDocument.expected_weight !== null && oldDocument.expected_weight !== undefined && payload.attachments?.length) {
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 OnLoadingDto(oldDocument as OnLoadingDto);
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.onLoadingRepository.updateById(oldDocument.id, { status: Status.OnLoading.InProgress });
const newAction = await this.updateByIdOrIdentifier(oldDocument.id, createdParam, { ...options, oldDocument });
// ---------------------------------------
return newAction;
}
/**
* Add extra filter for OnLoading
* @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,
},
},
})
.include({
relation: 'delivered_company',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'delivered',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'supervise',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
});
}
/**
* Add extra filter for OnLoading 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,
},
},
});
}
/**
* Adds the specified fields to the exclusion list in the given FilterBuilder.
*
* @param {FilterBuilder} filterBuilder - The FilterBuilder instance to modify.
*/
_addExcludeFields(filterBuilder: FilterBuilder) {
filterBuilder.fields({
is_weight_safe: false,
is_weight_in_contract: false,
remarks: false,
created_date: false,
});
}
/**
* Builds the query for OnLoading
* @param q The query string.
*/
async buildSearchQuery(q?: string) {
if (!q) {
return;
}
// FILTER:
// OR vehicle_no
// OR tank_no
// OR order_no Should be a LIKE search
const ilike_value = this.buildILikeValue(q);
const or_clause: OrClause<OnLoading> = {
or: [
{
vehicle_no: ilike_value,
},
{
tank_no: ilike_value,
},
{
order_no: ilike_value,
},
{
flow_id: ilike_value as unknown as number,
},
],
};
const companies_id = await this.getCompaniesIdByQuery(ilike_value);
if (companies_id) {
or_clause.or = [
...or_clause.or,
{
company_other_id: {
inq: companies_id,
},
},
{
delivered_company_id: {
inq: companies_id,
},
},
];
}
this.filter_builder.impose(or_clause);
}
}
|