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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { Injectable, Logger } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { clone, isEmpty, pick, uniqBy } from 'lodash-es';
import { DataSource, In, IsNull, Repository, type InsertResult } from 'typeorm';
import {
CUSTOM_OBJECT_NAME_LENGTH,
CustomObject,
DataConnectionName,
Overwrite,
type Company,
type CustomObjectDefinition,
} from '@amalia/core/models';
import { OverwriteTypesEnum } from '@amalia/core/types';
import { FieldTransformer, getCustomObjectExternalId } from '@amalia/data-capture/connectors/library';
import { RecordContent, type DataConnectorObjectRecord } from '@amalia/data-capture/connectors/types';
import { toError } from '@amalia/ext/typescript';
@Injectable()
export class CustomObjectsService {
private readonly logger = new Logger(CustomObjectsService.name);
public constructor(
@InjectDataSource(DataConnectionName)
private readonly dataConnection: DataSource,
@InjectRepository(Overwrite)
private readonly overwriteRepository: Repository<Overwrite>,
) {}
/**
* Sanitize row before saving it in the database.
* @param content
*/
public static sanitizeContent(content: DataConnectorObjectRecord['content']): RecordContent {
const rowString = JSON.stringify(content);
if (!rowString.includes(String.raw`\u0000`)) {
return content;
}
const replaced = rowString.replace(String.raw`\u0000`, '');
return JSON.parse(replaced) as RecordContent;
}
/**
* Save bulk objects.
* @param company company of the new period
* @param objectDefinition
* @param rows
* @throws {NotFoundException, @nestjs/common/BadRequestException, Error}
*/
public async bulkSave(
company: Company,
objectDefinition: CustomObjectDefinition,
rows: DataConnectorObjectRecord[],
): Promise<InsertResult> {
// 1 - Format as a custom object
const customObjects = rows
.map((row): Omit<CustomObject, 'id'> => {
const content = CustomObjectsService.sanitizeContent(row.content);
const externalId = getCustomObjectExternalId(objectDefinition, content);
let name: string | undefined =
(objectDefinition.nameField &&
(content[objectDefinition.nameField] as number | string | undefined)?.toString()) ||
undefined;
// Truncate name if it's longer than column
if (name && name.length > CUSTOM_OBJECT_NAME_LENGTH - 4) {
name = `${name.slice(0, CUSTOM_OBJECT_NAME_LENGTH - 4)}...`;
}
return {
externalId,
name,
definitionId: objectDefinition.id,
companyId: company.id,
content,
url: row.url || undefined,
};
})
.filter(Boolean);
let saveResult: InsertResult;
try {
// Filter unique customObjects only, via their externalId
const customObjectsUnique = customObjects.filter(
(v, i, s) => s.map((elm) => elm.externalId).lastIndexOf(v.externalId) === i,
);
// Save custom objects.
saveResult = await this.dataConnection
.createQueryBuilder()
.insert()
.into(CustomObject)
.values(customObjectsUnique)
.orUpdate({
conflict_target: ['companyId', 'definitionId', 'externalId'],
overwrite: ['content', 'name', 'url'],
})
.execute();
// Fetch overwrites via the custom object external ids, only grab properties one applied to definition and required ids.
const overwritesForExternalIds =
customObjectsUnique.length === 0
? []
: await this.overwriteRepository.findBy({
company: { id: company.id },
appliesToDefinitionId: objectDefinition.id,
appliesToExternalId: In(customObjectsUnique.map((co) => co.externalId)),
statementId: IsNull(),
overwriteType: OverwriteTypesEnum.PROPERTY,
clearedAt: IsNull(),
});
// Apply overwrites
if (!isEmpty(overwritesForExternalIds)) {
const customObjectsWithOverwrites = uniqBy(
customObjectsUnique.filter((co) =>
overwritesForExternalIds.map((ov) => ov.appliesToExternalId).includes(co.externalId),
),
'externalId',
);
// Then we apply the overwrites on each custom object
const overwrittenCustomObjects = await Promise.all(
customObjectsWithOverwrites.map((co) =>
this.applyOverwrites(
objectDefinition,
co as CustomObject,
overwritesForExternalIds.filter((ov) => ov.appliesToExternalId === co.externalId),
),
),
);
// Save custom objects with overwrites.
saveResult = await this.dataConnection
.createQueryBuilder()
.insert()
.into(CustomObject)
.values(overwrittenCustomObjects)
.orUpdate({
conflict_target: ['companyId', 'definitionId', 'externalId'],
overwrite: ['content', 'name', 'url'],
})
.execute();
}
} catch (err) {
const error = toError(err);
this.logger.error({
message: 'Error on bulk saving custom objects',
error,
company: pick(company, ['id', 'name']),
});
throw err;
}
return saveResult;
}
private async applyOverwrites(
objectDefinition: CustomObjectDefinition,
customObject: CustomObject,
overwrites: Overwrite[],
): Promise<CustomObject> {
if (!overwrites.length) {
return customObject;
}
const overwrittenCustomObject = clone(customObject);
await Promise.all(
overwrites.map(async (overwrite: Overwrite) => {
const property = objectDefinition.properties[overwrite.field];
if (!property) {
this.logger.warn(
`We have an orphan overwrite to apply on a property ${overwrite.field} that does not exists anymore on definition ${objectDefinition.machineName}.`,
);
return null;
}
const overwrittenFieldValue = isEmpty(overwrite.overwriteValue)
? null
: FieldTransformer.transformField(customObject.content, overwrite.field, property.format)![overwrite.field];
// Updating the overwrite source value with the value of the new row
const finalOverwrite = {
...overwrite,
sourceValue: {
...(overwrite.sourceValue as object),
[overwrite.field]: overwrittenFieldValue,
},
};
// Updating the value of the new row with the overwritten value
overwrittenCustomObject.content[overwrite.field] = (overwrite.overwriteValue as RecordContent)[overwrite.field];
// Update the overwrite.
return this.overwriteRepository.save(finalOverwrite);
}),
);
return overwrittenCustomObject;
}
}
|