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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {bind, BindingScope} from '@loopback/core';
import {AnyObject, EntityNotFoundError, FilterBuilder, Options, repository} from '@loopback/repository';
import {BaseResponses, RegulatoryDashboards, RegulatoryDeclarations, RegulatoryParties} from '@logchain/models';
import {
RegulatoryCargosRepository,
RegulatoryDashboardsRepository,
RegulatoryDeclarationsRepository,
RegulatoryPartiesRepository,
UserRepository,
} from '@logchain/repositories';
import {BaseService} from '.';
import {RegulatoryDashboardsDto} from '@logchain/dtos';
import {
FilterOperatorEnum,
RegulatoryDashboardsFilterConditions,
RegulatoryDashboardsFilterFieldEnum,
RegulatoryDashboardsValueEnum,
} from '@logchain/types';
import {HttpErrors} from '@loopback/rest';
import _ from 'lodash';
import {Constants} from '@logchain/configs';
import {DateUtils} from '@logchain/utils';
@bind({scope: BindingScope.TRANSIENT})
export class RegulatoryDashboardsService extends BaseService<RegulatoryDashboards> {
protected filter_builder_declaration: FilterBuilder<RegulatoryDeclarations>;
constructor(
@repository(RegulatoryDashboardsRepository)
public dashboardRepo: RegulatoryDashboardsRepository,
@repository(RegulatoryDeclarationsRepository)
public regulatoryDeclarationsRepo: RegulatoryDeclarationsRepository,
@repository(RegulatoryPartiesRepository)
public regulatoryPartiesRepo: RegulatoryPartiesRepository,
@repository(RegulatoryCargosRepository)
public regulatoryCargosRepo: RegulatoryCargosRepository,
@repository(UserRepository)
public userRepository: UserRepository,
) {
super();
this.filter_builder_declaration = new FilterBuilder<RegulatoryDeclarations>();
}
private async validateAndProcessData(payload: Partial<RegulatoryDashboards>) {
const {filters = [], value = ''} = payload;
if (value !== RegulatoryDashboardsValueEnum.COUNT) {
throw new HttpErrors.BadRequest("Dashboard value does not allowed. ['Count']");
}
for (const filter of filters) {
this.validateFilterFieldAndRule(filter);
if (Constants.dynamicDateField[filter.field]) {
await this.processDynamicDateFilter(filter);
}
switch (filter.field) {
case RegulatoryDashboardsFilterFieldEnum.PARTY:
await this.processPartyFilter(filter);
break;
case RegulatoryDashboardsFilterFieldEnum.CARGO_RELEASE:
case RegulatoryDashboardsFilterFieldEnum.CARGO_RECEIPT:
await this.processCargoFilter(filter);
break;
default:
this.processDefaultFilter(filter);
break;
}
}
this.filter_builder_declaration.impose({
company_id: this.current_user.company_id,
});
}
private validateFilterFieldAndRule(filter: any) {
if (!RegulatoryDashboardsFilterConditions[filter.field]) {
throw new HttpErrors.BadRequest(
'Filter field does not allowed.' + Object.keys(RegulatoryDashboardsFilterConditions).toString(),
);
}
if (!RegulatoryDashboardsFilterConditions[filter.field].includes(filter.rule)) {
throw new HttpErrors.BadRequest('Filter rule does not allowed.');
}
}
private async processDynamicDateFilter(filter: any) {
if (!DateUtils.isIsoDate(filter.value) && (isNaN(+filter.value) || +filter.value <= 0)) {
throw new HttpErrors.BadRequest('Filter value must be a date or integer (greater than zero).');
}
if (!isNaN(+filter.value)) {
if (DateUtils.getDateAfterDays(+filter.value).startsWith('-')) {
throw new HttpErrors.BadRequest(`Invalidate date - Number is too high? (${filter.value}).`);
}
let customValue = filter.value;
let customField = null;
switch (filter.rule) {
case FilterOperatorEnum.LESS_THAN:
customValue = filter.value + ' days';
break;
case FilterOperatorEnum.LESS_THAN_EQUAL:
customValue = `{ "${FilterOperatorEnum.LESS_THAN}": "${+filter.value - 1} days" }`;
break;
case FilterOperatorEnum.EQUAL:
customField = 'and';
customValue = `[
{
"${filter.field}": { "${FilterOperatorEnum.GREATER_THAN_EQUAL}": "${filter.value} days" }
},
{
"${filter.field}": { "${FilterOperatorEnum.LESS_THAN}": "${+filter.value - 1} days" }
}
]`;
break;
case FilterOperatorEnum.GREATER_THAN:
customValue = `{ "${FilterOperatorEnum.GREATER_THAN_EQUAL}": "${+filter.value - 1} days" }`;
break;
case FilterOperatorEnum.GREATER_THAN_EQUAL:
customValue = filter.value + ' days';
break;
}
filter.value = filter.value + ' days';
filter._customValue = customValue;
filter._customField = customField;
}
}
private async processPartyFilter(filter: any) {
const condition: Record<string, string> = {};
condition['name1'] = filter.value;
const parties = await this.regulatoryPartiesRepo.find({
fields: ['declaration_id'],
where: condition,
});
const declarationIds = _.uniq(parties.map((party: RegulatoryParties) => party.declaration_id));
if (declarationIds.length) {
this.filter_builder_declaration.impose({
id: {inq: declarationIds},
});
}
}
private async processCargoFilter(filter: any) {
const condition: Record<string, string> = {};
const fieldName = `${filter.field}.loc_code`;
condition[fieldName] = filter.value;
const cargos = await this.regulatoryCargosRepo.find({
fields: ['declaration_id'],
where: condition,
});
const declarationIds = _.uniq(cargos.map((cargo: AnyObject) => cargo.declaration_id));
if (declarationIds.length) {
this.filter_builder_declaration.impose({
id: {inq: declarationIds},
});
}
}
private processDefaultFilter(filter: any) {
const condition: Record<string, AnyObject> = {};
const fieldName = filter._customField ?? filter.field;
condition[fieldName] = {};
if (filter._customValue) {
condition[fieldName][filter.rule] = (filter._customValue as unknown) as AnyObject;
if (typeof filter._customValue === 'string' && filter._customValue.includes('{')) {
condition[fieldName] = JSON.parse(filter._customValue);
}
} else {
condition[fieldName][filter.rule] = filter.value;
}
this.filter_builder_declaration.impose(condition);
}
/**
* Get list of dashboards
* @param {Options} options?
* @returns Promise
*/
async find(options?: Options): Promise<BaseResponses<RegulatoryDashboards>> {
const users = await this.userRepository.find({fields: ['id'], where: {company_id: this.current_user.company_id}});
const userIds = users.map(user => user.id);
this.filter_builder.impose({
created_by: {inq: userIds},
});
return this.dashboardRepo.findWithPaging(this.filter_builder.build());
}
async getByIdOrIdentifier(id: number, options?: Options): Promise<AnyObject> {
const dashboard = await this.dashboardRepo.findById(id, options);
let query = dashboard.query;
let m;
const regex = /\b\d+(?=\s*days\b)/gm;
while ((m = regex.exec(query)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
const value = m[0].split(' ').shift() ?? 0;
query = query.replace(m[0], DateUtils.getDateAfterDays(+value));
}
const {count = 0} = await this.regulatoryDeclarationsRepo.count(JSON.parse(query).where);
return {...dashboard, count};
}
/**
* Creates RegulatoryDashboards service
* @param {RegulatoryDashboardsDto} regulatoryDashboardsDto
* @returns Promise<RegulatoryDashboards>
*/
async create(regulatoryDashboardsDto: RegulatoryDashboardsDto, options: Options = {}): Promise<RegulatoryDashboards> {
await this.validateAndProcessData(regulatoryDashboardsDto);
regulatoryDashboardsDto.seq_no =
(
await this.dashboardRepo.count({
created_by: this.current_user.id,
})
).count + 1;
regulatoryDashboardsDto.query = JSON.stringify(this.filter_builder_declaration.build());
return this.dashboardRepo.create(regulatoryDashboardsDto, options);
}
/**
* Update RegulatoryDashboards
* @param {number} id
* @param {Partial<RegulatoryDashboards>} payload
* @param {Options} options?
* @returns Promise
*/
async updateByIdOrIdentifier(id: number, payload: RegulatoryDashboardsDto, options?: Options) {
const dashboard = await this.dashboardRepo.findById(id, options);
await this.validateAndProcessData(payload);
dashboard.title = payload.title ?? dashboard.title;
dashboard.value = payload.value ?? dashboard.value;
dashboard.filters = payload.filters ?? dashboard.filters;
dashboard.query = JSON.stringify(this.filter_builder_declaration.build());
await this.dashboardRepo.save(dashboard, options);
return dashboard;
}
/**
* Delete RegulatoryDashboards
* @param {number} id
* @param {Options} options?
*/
async deleteByIdOrIdentifier(id: number, options?: Options) {
this.addWhereIdOrIdentifier(id);
const dbRegulatoryDashboards = await this.dashboardRepo.findById(id, options);
if (!dbRegulatoryDashboards) {
throw new EntityNotFoundError(this.dashboardRepo.entityClass, id);
}
await this.dashboardRepo.deleteById(dbRegulatoryDashboards.id, options);
// return to write logs
return dbRegulatoryDashboards;
}
}
|