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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 1x 18x 18x 18x 18x 18x 18x 18x | import { bind, /* inject, */ BindingScope, service } from '@loopback/core';
import {
EntityNotFoundError,
FilterBuilder,
Options,
OrClause,
repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { omit } from 'lodash';
import { FilesMappingDto, ReheatingDto } from '../dtos';
import { BaseResponses, Reheating, Status } from '../models';
import {
CompanyRepository,
ReheatingHistoryRepository,
ReheatingOverrideRepository,
ReheatingRepository,
UserRepository,
} from '../repositories';
import { AnyObject, PdfTemplate } from '../types';
import { BaseService } from './base.service';
import { FlowService } from './flow.service';
import { Constants } from '@logchain/configs';
import _ from 'lodash';
import { ReheatingView } from '@logchain/models/views';
import { ReheatingViewRepository } from '@logchain/repositories/reheating.view.repository';
@bind({ scope: BindingScope.TRANSIENT })
export class ReheatingService extends BaseService<Reheating> {
reh_tbl_name = Reheating.definition.settings['postgresql'].table;
@service(FlowService)
public flowService: FlowService;
constructor(
@repository(ReheatingRepository)
public reh_repo: ReheatingRepository,
@repository(ReheatingViewRepository)
public reh_view_repo: ReheatingViewRepository,
@repository(ReheatingOverrideRepository)
public reh_override_repo: ReheatingOverrideRepository,
@repository(CompanyRepository)
public comp_repo: CompanyRepository,
@repository(UserRepository)
public user_repo: UserRepository,
@repository(ReheatingHistoryRepository)
public reh_histories_repo: ReheatingHistoryRepository,
) {
super();
}
/**
* Get array Reheating based on filter.
* @param filter
*/
async find(): Promise<BaseResponses<ReheatingView>> {
const filter_builder = new FilterBuilder<ReheatingView>();
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.reh_view_repo.fillRelation(filter_builder);
}
/**
* update Reheating based on filter.
* @param id
* Reheating
*/
async updateByIdOrIdentifier(id: number, payload: ReheatingDto, options: Options = {}): Promise<Reheating> {
// Do not allow change status to back to new
if (payload.status === Status.Reheating.New) {
throw new HttpErrors.BadRequest(`Can not change status to new ${payload.status}`);
}
const { remarks, actual_temp } = payload;
const current_reheating = await this.reh_repo.findOne({
where: {
id: id,
company_id: this.current_user.company_id,
},
});
if (!current_reheating) {
throw new EntityNotFoundError(this.reh_repo.entityClass, id);
}
payload.system_actual_date = new Date();
payload.actual_start_date = new Date();
// Backup old reheating and reheating history
if (options?.oldDocument) {
await this.reh_override_repo.create({
original_id: current_reheating.id,
..._.omit(options.oldDocument, ['id', 'created_date', 'updated_date', 'histories'])
});
await this.reh_repo.updateById(id, omit(payload, ['histories']));
} else {
// Update Reheating
await this.reh_repo.updateById(id, omit(payload, ['remarks', 'actual_temp', 'histories']));
}
if (remarks || actual_temp) {
const history = {
reheating_id: current_reheating.id,
remarks: remarks,
actual_temp: actual_temp,
progress: typeof payload.progress === 'number' ? payload.progress : current_reheating.progress,
created_date: new Date().toString(),
};
await this.reh_histories_repo.create(history);
}
if (Constants.reheatingFinishedStatuses.includes(payload.status)) {
const reloaded_inst = await this.getByIdOrIdentifier(current_reheating.id) as ReheatingDto;
const timezone = reloaded_inst.company.timezone;
// Push pdf of overriden action to the last page of overriding action
if (options?.oldDocument) {
reloaded_inst.documents.push(new FilesMappingDto({ uri: options?.oldDocument.uri }));
}
const data: PdfTemplate = {
content: { ...reloaded_inst, timezone, validator_id: await this.getValidatorFromStep(reloaded_inst.journey_point_id)},
model_name: this.reh_tbl_name,
};
await this.generatePdf(data);
}
// return to write logs
return current_reheating;
}
/**
* Get Reheating by id or identifier
* @param id The user id
* @param filter The filter
* @returns Promise<Reheating | null>
*/
async getByIdOrIdentifier(id: number): Promise<Reheating> {
this.filter_builder.where({
company_id: this.current_user.company_id,
id: id,
});
// Load relation for Reheating
this.addExtraFilter(this.filter_builder);
this.addExtraRequestHistoryFilter(this.filter_builder);
this.addExtraCompanyFilter(this.filter_builder); // For saving pdf.
const reh = await this.reh_repo.findOne(this.filter_builder.build(), {
get_reference: true,
});
if (!reh) {
throw new EntityNotFoundError(this.reh_repo.entityClass, id);
}
// For override record
if (reh.override_by_id) {
reh.documents = await this.files_mapping_repo1.find({
where: {
external_id: reh.id,
table_name: this.reh_repo.getPostgresTableName(),
},
fields: {
external_id: false,
table_name: false,
},
order: ['id DESC'],
limit: 1,
});
}
return reh;
}
/**
* Overrides an existing record with the provided payload.
*
* @param {number} id - The ID of the entry record to override.
* @return {Promise<ReheatingDto>} A promise that resolves to the newly created entry record.
* @throws {EntityNotFoundError} If the old document is not found.
*/
async override(id: number, payload: ReheatingDto): Promise<AnyObject> {
// Validate override document is valid for overriding
const oldDocument = await this.reh_repo.findById(id);
// Make sure old document exists
if (!oldDocument) {
throw new EntityNotFoundError(this.reh_repo.entityClass, id);
}
// ---------------------------------------
// Make sure overrided action must be completed
if (oldDocument.progress !== 100) {
throw new HttpErrors.BadRequest('Action was not completed yet.');
}
// ---------------------------------------
// Mapping from old document to override document
const createdParam = new ReheatingDto(oldDocument as ReheatingDto);
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.reh_repo.updateById(oldDocument.id, { status: Status.Loading.InProgress });
const newAction = await this.updateByIdOrIdentifier(oldDocument.id, createdParam, { oldDocument });
// ---------------------------------------
return newAction;
}
/**
* Add extra filter for Reheating
* @param filterBuilder The filter builder instance
* @param options The options
* @return Filter
*/
addExtraFilter(filterBuilder: FilterBuilder, options?: Options) {
super._addIncludeModifier(filterBuilder);
filterBuilder.include({
relation: 'customer',
scope: {
fields: {
id: true,
identifier: true,
name: true,
},
},
});
}
/**
* Add extra filter for Reheating company
* @param filterBuilder The filter builder instance
* @param options The options
* @return Filter
*/
addExtraCompanyFilter(filterBuilder: FilterBuilder, options?: Options) {
filterBuilder.include({
relation: 'company',
scope: {
fields: {
id: true,
identifier: true,
name: true,
timezone: true,
},
},
});
}
/**
* Add extra filter for Reheating company
* @param filterBuilder The filter builder instance
* @param options The options
* @return Filter
*/
addExtraRequestHistoryFilter(
filterBuilder: FilterBuilder,
options?: Options,
) {
filterBuilder.include({
relation: 'histories',
scope: {
fields: {
id: true,
remarks: true,
progress: true,
reheating_id: true,
actual_temp: true,
created_date: true,
},
},
});
}
/**
* Add extra excludes for Reheating company
* @param filterBuilder The filter builder instance
* @param options The options
* @return Filter
*/
_addExcludeFields(filterBuilder: FilterBuilder) {
filterBuilder.fields({
remarks: false,
modified_by: false,
created_date: false,
});
}
/**
* Builds the query for trade lane
* @param q The query string.
*/
async buildSearchQuery(q?: string) {
if (!q) {
return;
}
const ilike_value = this.buildILikeValue(q);
// FILTER: customer.identifier
// OR customer.name
// OR container_no
// OR product_code Should be a LIKE search
const or_clause: OrClause<Reheating> = {
or: [
{
container_no: ilike_value,
},
{
product_code: 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,
{
customer_id: {
inq: companies_id,
},
},
];
}
this.filter_builder.impose(or_clause);
}
}
|