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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 1x 19x 19x 19x 19x 19x 19x 19x | import { bind, BindingScope, service } from '@loopback/core';
import { AnyObject, EntityNotFoundError, FilterBuilder, Options, repository, } from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { BolDto, FilesMappingDto } from '@logchain/dtos';
import { BaseResponses, Bol, Status } from '@logchain/models';
import { BolOverrideRepository, BolRepository, BolViewRepository, CompanyRepository, FilesMappingRepository, UserRepository, } from '@logchain/repositories';
import { BolDocumentType, PdfTemplate } from '@logchain/types';
import { BaseService } from './base.service';
import { BolView, VerificationView } from '@logchain/models/views';
import { FlowService } from './flow.service';
import { Constants } from '@logchain/configs';
import _ from 'lodash';
@bind({ scope: BindingScope.TRANSIENT })
export class BolService extends BaseService<Bol> {
bols_tbl_name = Bol.definition.settings['postgresql'].table;
@service(FlowService)
public flowService: FlowService;
constructor(
@repository(BolRepository)
public bol_repo: BolRepository,
@repository(BolOverrideRepository)
public bol_override_repo: BolOverrideRepository,
@repository(BolViewRepository)
public bol_view_repo: BolViewRepository,
@repository(FilesMappingRepository)
public files_mapping_repo: FilesMappingRepository,
@repository(CompanyRepository)
public comp_repo: CompanyRepository,
@repository(UserRepository)
public user_repo: UserRepository,
) {
super();
}
/**
* Get array Bol based on filter.
* @param filter
*/
async find(): Promise<BaseResponses<Bol>> {
const filter_builder = new FilterBuilder<BolView>();
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.bol_view_repo.fillRelation(filter_builder);
}
/**
* Build custom search query string for consignee,shipper name or identifier
* @param q
*/
async buildSearchQuery(q: string): Promise<void> {
if (!q) {
return;
}
const ilike_value = this.buildILikeValue(q);
const company_ids = await this.getCompaniesIdByQuery(ilike_value);
this.filter_builder.impose({
or: [
{
shipper_id: {
inq: company_ids,
},
},
{
consignee_id: {
inq: company_ids,
},
},
{
flow_id: ilike_value as unknown as number,
},
],
});
}
/**
* update Bol based on filter.
* @param id
* Bol
*/
async updateByIdOrIdentifier(id: number, bol: BolDto, options: Options = {}) {
const current_bol = await this.bol_repo.findOne({
where: {
id: id,
company_id: this.current_user.company_id,
},
});
if (!current_bol) {
throw new EntityNotFoundError(this.bol_repo.entityClass, id);
}
// cant not change status to new
if (bol.status === Status.Bol.New) {
throw new HttpErrors.BadRequest(
`Can not change status to new ${bol.status}`,
);
}
// In case override we need to transfer old documents to overidden action
if (options?.oldDocument) {
const overriden_bol = await this.bol_override_repo.create({
original_id: current_bol.id,
..._.omit(options.oldDocument, ['id', 'created_date', 'updated_date'])
});
await this.transferOldAttachments(
current_bol.id,
overriden_bol.id,
this.bol_repo.getPostgresTableName(),
Constants.BolDocumentTypeText[Constants.BolDocumentType.Report]
);
}
const { report, additional_document } = bol;
if (report || additional_document) {
if (report) {
await this._upsertBolDocuments(id, 'Report', report);
}
if (additional_document) {
await this._upsertBolDocuments(id, 'Additional', additional_document);
}
}
// check exits shipper
if (bol.shipper_identifier) {
const shipper = await this.comp_repo.findOne({
where: {
identifier: bol.shipper_identifier,
},
});
if (!shipper) {
throw new HttpErrors.BadRequest(
`${bol.shipper_identifier} is not exists in company`,
);
}
}
// check exits consignee
if (bol.consignee_identifier) {
const consignee = await this.comp_repo.findOne({
where: {
identifier: bol.consignee_identifier,
},
});
if (!consignee) {
throw new HttpErrors.BadRequest(
`${bol.consignee_identifier} is not exists in company`,
);
}
}
// check exits User
if (bol.forwarding_agent_identifier) {
const user = await this.user_repo.findOne({
where: {
identifier: bol.forwarding_agent_identifier,
},
});
if (!user) {
throw new HttpErrors.BadRequest(
`${bol.forwarding_agent_identifier} is not exists in User`,
);
}
}
bol.system_actual_date = new Date();
await this.bol_repo.updateById(id, bol);
if (current_bol.status !== bol.status && Constants.bolFinishedStatuses.includes(bol.status)) {
const reloaded_bol = await this.getByIdOrIdentifier(current_bol.id) as BolDto;
const timezone = reloaded_bol.company.timezone;
// Push pdf of overriden action to the last page of overriding action
if (options?.oldDocument) {
reloaded_bol.documents.push(new FilesMappingDto({ uri: options?.oldDocument.uri }));
}
const data: PdfTemplate = {
content: { ...reloaded_bol, timezone, validator_id: await this.getValidatorFromStep(reloaded_bol.journey_point_id)},
model_name: this.bols_tbl_name,
};
await this.generatePdf(data);
}
const inst_dto = new BolDto({ ...current_bol, ...bol } as BolDto);
if (inst_dto.shipper_id) {
inst_dto.shipper = await this.comp_repo.findById(inst_dto.shipper_id);
} else if (inst_dto.consignee_id) {
inst_dto.consignee = await this.comp_repo.findById(inst_dto.consignee_id);
}
const action = 'BOL';
current_bol.activity = {
str: '{0} for place of issuance {1} is {2} for {3}',
args: [
bol.override_by_id ? action + ' overridden' : action,
inst_dto.place_of_issuance,
(inst_dto.status_name() as string).toLowerCase(),
inst_dto.shipper?.name ?? inst_dto.consignee?.name
]
};
// return to write logs
return current_bol;
}
/**
* Overrides an existing record with the provided payload.
*
* @param {number} id - The ID of the entry record to override.
* @return {Promise<BolDto>} A promise that resolves to the newly created entry record.
* @throws {EntityNotFoundError} If the old document is not found.
*/
async override(id: number, payload: BolDto): Promise<AnyObject> {
// Validate override document is valid for overriding
const oldDocument = await this.bol_repo.findById(id);
// Make sure old document exists
if (!oldDocument) {
throw new EntityNotFoundError(this.bol_repo.entityClass, id);
}
// ---------------------------------------
// Make sure overrided action must be completed
if (Constants.bolFinishedStatuses.includes(oldDocument.status) === false) {
throw new HttpErrors.BadRequest('Action was not completed yet.');
}
// ---------------------------------------
// Mapping from old document to override document
const createdParam = new BolDto(oldDocument as BolDto);
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.bol_repo.updateById(oldDocument.id, { status: Status.Bol.InProgress });
const newAction = await this.updateByIdOrIdentifier(oldDocument.id, createdParam, { oldDocument });
// ---------------------------------------
return newAction;
}
/**
* Update or insert new documents for Bol.
* @param id The bol id.
* @param type The type of document.
* @param doc_uri The document uri from s3.
* @param company
*/
private async _upsertBolDocuments(id: number, type: BolDocumentType, doc_uri: string) {
const metadata = await this.s3_service.getObjectMetadata(doc_uri);
if (metadata) {
const msg =
type === 'Report'
? Constants.BolDocumentTypeText[Constants.BolDocumentType.Report]
: Constants.BolDocumentTypeText[Constants.BolDocumentType.Additional];
await this.files_mapping_repo.upsertWithWhere(
{
uri: doc_uri,
external_id: id,
},
{
table_name: this.bols_tbl_name,
field_name: msg,
uri: doc_uri,
version: metadata.VersionId,
external_id: id,
hash: metadata.ETag?.slice(1, -1),
},
);
}
}
/**
* Get Bol by id or identifier
* @param id The user id
* @param filter The filter
* @returns Promise<Bol | null>
*/
async getByIdOrIdentifier(id: number): Promise<Bol> {
this.filter_builder.where({
company_id: this.current_user.company_id,
id: id,
});
// Load relation for Bol
this.addExtraFilter(this.filter_builder);
this.addExtraCompanyFilter(this.filter_builder);
const bol = await this.bol_repo.findOne(this.filter_builder.build(), {
get_reference: true,
});
if (!bol) {
throw new EntityNotFoundError(this.bol_repo.entityClass, id);
}
bol.documents = await this.files_mapping_repo.find({
where: {
external_id: id,
table_name: this.bols_tbl_name,
},
});
// Fetch verification information
if (this?.verification_view_repo) {
bol.verification = await this.verification_view_repo.findOne({
where: {
external_id: bol.id,
table_name: this.bol_repo.getPostgresTableName(),
is_actor: false,
},
}) as VerificationView;
}
return bol;
}
/**
* Add extra filter for Bol
* @param filterBuilder The filter builder instance
* @param options The options
* @return Filter
*/
addExtraFilter(filterBuilder: FilterBuilder, options?: Options) {
super._addIncludeModifier(filterBuilder);
filterBuilder
.include({
relation: 'shipper',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'consignee',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
})
.include({
relation: 'forwarding_agent',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
});
}
/**
* Add extra filter for Bol 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,
},
},
});
}
/**
* Add extra excludes for Bol company
* @param filterBuilder The filter builder instance
* @return Filter
*/
_addExcludeFields(filterBuilder: FilterBuilder) {
filterBuilder.fields({
remarks: false,
modified_by: false,
created_date: false,
});
}
}
|