Skip to content

Commit

Permalink
Merge pull request #109 from konecty/fix/inheritedFields-and-history
Browse files Browse the repository at this point in the history
Fix: Inherited fields and history creation
  • Loading branch information
silveirado authored Feb 9, 2024
2 parents f24a9f3 + 577c273 commit 9de0446
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 105 deletions.
4 changes: 3 additions & 1 deletion src/imports/konsistent/createHistory.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,13 @@ export default async function createHistory(metaName, action, id, data, updatedB

const historyQuery = { _id: changeId };

const userDetailFields = ["_id"].concat(get(meta, "fields._user.detailFields", ["name", "active"]));

// Define base data to history
const historyItem = {
dataId: id,
createdAt: updatedAt,
createdBy: updatedBy,
createdBy: get(updatedBy, userDetailFields),
data: historyData,
type: action,
};
Expand Down
13 changes: 7 additions & 6 deletions src/imports/konsistent/processIncomingChange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import createHistory from './createHistory';
import processReverseLookups from './processReverseLookups';
import * as References from './updateReferences';

import { DataDocument } from '@imports/types/data';
import omit from 'lodash/omit';
import { v4 as uuidV4 } from 'uuid';

Expand All @@ -13,25 +14,25 @@ const logTimeSpent = (startTime: [number, number], message: string) => {
logger.debug(`${totalTime[0]}s ${totalTime[1] / 1000000}ms => ${message}`);
};

export default async function processIncomingChange(metaName: string, incomingChange: object, action: Action, user: object) {
export default async function processIncomingChange(metaName: string, incomingChange: DataDocument, action: Action, user: object) {
try {
const keysToIgnore = ['_updatedAt', '_createdAt', '_deletedAt', '_updatedBy', '_createdBy', '_deletedBy'];
const dataId = uuidV4();
const changeId = uuidV4();

let startTime = process.hrtime();

if (action === 'update') {
await References.updateLookups(metaName, dataId, incomingChange);
await References.updateLookups(metaName, incomingChange._id, incomingChange);
logTimeSpent(startTime, `Updated lookup references for ${metaName}`);
}

await processReverseLookups(metaName, dataId, incomingChange, action);
await processReverseLookups(metaName, incomingChange._id, incomingChange, action);
logTimeSpent(startTime, `Process'd reverse lookups for ${metaName}`);

await References.updateRelations(metaName, action, dataId, incomingChange);
await References.updateRelations(metaName, action, incomingChange._id, incomingChange);
logTimeSpent(startTime, `Updated relation references for ${metaName}`);

await createHistory(metaName, action, dataId, omit(incomingChange, keysToIgnore), user, new Date(), '');
await createHistory(metaName, action, incomingChange._id, omit(incomingChange, keysToIgnore), user, new Date(), changeId);
logTimeSpent(startTime, `Created history for ${metaName}`);
} catch (err) {
const error = err as Error;
Expand Down
4 changes: 2 additions & 2 deletions src/imports/meta/copyDescriptionAndInheritedFields.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export async function copyDescriptionAndInheritedFields({ field, record, meta, a
idsToUpdate,
});
if (validateResult.success === true) {
Object.assign(value, { [inheritedField.fieldName]: validateResult.data });
Object.assign(objectNewValues, { [inheritedField.fieldName]: validateResult.data });
}
return validateResult;
} else {
Expand All @@ -55,7 +55,7 @@ export async function copyDescriptionAndInheritedFields({ field, record, meta, a
idsToUpdate,
});
if (validateResult.success === true) {
Object.assign(value, { [inheritedField.fieldName]: validateResult.data });
Object.assign(objectNewValues, { [inheritedField.fieldName]: validateResult.data });
}
return validateResult;
}
Expand Down
109 changes: 13 additions & 96 deletions src/imports/meta/validateAndProcessValueFor.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { copyDescriptionAndInheritedFields } from '../meta/copyDescriptionAndInh
import { removeInheritedFields } from '../meta/removeInheritedFields';
import { getNextCode } from './getNextCode';

import { errorReturn } from '@imports/utils/return';
import { BCRYPT_SALT_ROUNDS } from '../consts';

const regexUtils = {
Expand Down Expand Up @@ -74,80 +75,38 @@ const ALLOWED_CURRENCIES = ['BRL'];

export async function validateAndProcessValueFor({ meta, fieldName, value, actionType, objectOriginalValues, objectNewValues, idsToUpdate }) {
if (meta == null) {
return {
success: false,
errors: [
{
message: `MetaObject.Meta does not exists`,
},
],
};
return errorReturn(`MetaObject.Meta does not exists`);
}

const field = meta.fields[fieldName];

if (!field) {
return {
success: false,
errors: [
{
message: `Field ${fieldName} does not exists on ${meta._id}`,
},
],
};
return errorReturn(`Field ${fieldName} does not exists on ${meta._id}`);
}

// Validate required fields

if (field.isRequired === true && (value == null || (typeof value === 'string' && size(value) === 0))) {
return {
success: false,
errors: [
{
message: `Field ${fieldName} is required`,
},
],
};
return errorReturn(`Field ${fieldName} is required`);
}

// Validate List fields
if (field.isList === true) {
if (field.maxElements && field.maxElements > 0) {
if (!isArray(value) || value.length > field.maxElements) {
return {
success: false,
errors: [
{
message: `Value for field ${fieldName} must be array with the maximum of ${field.maxElements} item(s)`,
},
],
};
return errorReturn(`Value for field ${fieldName} must be array with the maximum of ${field.maxElements} item(s)`);
}
}

if (field.minElements && field.minElements > 0) {
if (!isArray(value) || value.length < field.minElements) {
return {
success: false,
errors: [
{
message: `Value for field ${fieldName} must be array with the minimum of ${field.minElements} item(s)`,
},
],
};
return errorReturn(`Value for field ${fieldName} must be array with the minimum of ${field.minElements} item(s)`);
}
}

if (field.isAllowDuplicates === false && isArray(value)) {
if (value.some((itemA, indexA) => value.some((itemB, indexB) => indexA !== indexB && isEqual(itemA, itemB)))) {
return {
success: false,
errors: [
{
message: `Value for field ${fieldName} must be array no duplicated values`,
},
],
};
return errorReturn(`Value for field ${fieldName} must be a list with no duplicated values`);
}
}
}
Expand All @@ -157,14 +116,7 @@ export async function validateAndProcessValueFor({ meta, fieldName, value, actio
if (isNumber(field.minSelected)) {
if (field.minSelected === 1) {
if (!value || (isArray(value) && value.length === 0)) {
return {
success: false,
errors: [
{
message: `Value for field ${fieldName} must be an array with at least 1 item`,
},
],
};
return errorReturn(`Value for field ${fieldName} must be an array with at least 1 item`);
}
}
}
Expand Down Expand Up @@ -197,26 +149,12 @@ export async function validateAndProcessValueFor({ meta, fieldName, value, actio
const collection = MetaObject.Collections[meta.name];

if (collection == null) {
return {
success: false,
errors: [
{
message: `Collection for ${meta.name} does not exists`,
},
],
};
return errorReturn(`Collection for ${meta.name} does not exists`);
}

const count = await collection.countDocuments(query);
if (count > 0) {
return {
success: false,
errors: [
{
message: `Value for field ${fieldName} must be unique`,
},
],
};
return errorReturn(`Value for field ${fieldName} must be unique`);
}
}

Expand Down Expand Up @@ -521,14 +459,7 @@ export async function validateAndProcessValueFor({ meta, fieldName, value, actio

if (isNumber(field.size) && field.size > 0) {
if (value.length > field.size) {
return {
success: false,
errors: [
{
message: `Value for field ${fieldName} must be less than ${field.size} characters`,
},
],
};
return errorReturn(`Value for field ${fieldName} must be less than ${field.size} characters`);
}
}

Expand Down Expand Up @@ -1051,27 +982,13 @@ export async function validateAndProcessValueFor({ meta, fieldName, value, actio

const lookupCollection = MetaObject.Collections[field.document];
if (lookupCollection == null) {
return {
success: false,
errors: [
{
message: `Collection ${field.document} not found`,
},
],
};
return errorReturn(`Collection ${field.document} not found`);
}

const record = await lookupCollection.findOne({ _id: value._id });

if (record == null) {
return {
success: false,
errors: [
{
message: `Record not found for field ${fieldName} with _id [${value._id}] on document [${field.document}]`,
},
],
};
return errorReturn(`Record not found for field ${fieldName} with _id [${value._id}] on document [${field.document}]`);
}

const inheritedFieldsResult = await copyDescriptionAndInheritedFields({
Expand Down

0 comments on commit 9de0446

Please sign in to comment.