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 | import { IgnoredValueTypes } from "@components/ProfilePage/BusinessProfileSetupNew/utils/principal.utils";
import * as Yup from "yup";
interface SourceObject {
[key: string]: boolean | SourceObject;
}
const extractValues = (
source: SourceObject,
target: SourceObject,
): SourceObject => {
const result: SourceObject = {};
const traverse = (
source: SourceObject,
target: SourceObject,
currentPath: string,
) => {
for (const key in source) {
if (Object.hasOwn(source, key) && source[key] === true) {
const targetValue = getObjectValueByKey(target, currentPath + key);
if (targetValue !== undefined) {
result[key] = targetValue;
}
} else if (typeof source[key] === "object") {
traverse(source[key] as SourceObject, target, currentPath + key + ".");
}
}
};
traverse(source, target, "");
return result;
};
const getObjectValueByKey = (obj: SourceObject, key: string): any => {
const keys = key.split(".");
let value = obj;
for (const k of keys) {
if (
typeof value === "object" &&
value !== null &&
Object.hasOwn(value, k)
) {
value = value[k] as any;
} else {
return undefined;
}
}
return value;
};
const countNullishValues = (obj: any): number => {
let count = 0;
const countNullishRecursive = (data: any) => {
if (!!data === false) {
count++;
} else if (typeof data === "object") {
for (const key in data) {
if (Object.hasOwn(data, key)) {
countNullishRecursive(data[key]);
}
}
}
};
countNullishRecursive(obj);
return count;
};
export const useCalculatePercentage = ({ isEdit }: { isEdit: boolean }) => {
const calculatePercentage = ({
action,
schema,
dirtyFields,
values,
}: {
action?: (value: React.SetStateAction<any>) => void;
schema: Yup.ObjectSchema<any>;
dirtyFields: Record<string, any>;
defaultValues: any;
values: any;
}) => {
const testableFields = extractTestableFields(schema.fields);
if (isEdit) {
const extractedValues = extractValues(dirtyFields, values);
const countEdited = countNullishValues(extractedValues);
const percentage = Math.floor(
((testableFields.length - countEdited) / testableFields.length) * 100,
);
action && action(percentage);
return percentage;
}
const areTestableFieldsDirty = testableFields.map((tf) => {
const fieldPath = tf[0];
const fieldPathParts = fieldPath.split(".");
let currentDirtyFields: any = dirtyFields;
for (const part of fieldPathParts) {
if (currentDirtyFields[part]) {
currentDirtyFields = currentDirtyFields[part];
} else {
currentDirtyFields = null;
break;
}
}
return isEdit ? !!values[fieldPath] : !!currentDirtyFields;
});
const numberOfFieldsToComplete = areTestableFieldsDirty.filter(
(tf) => !tf,
).length;
const percentage = Math.floor(
((testableFields.length - numberOfFieldsToComplete) * 100) /
testableFields.length,
);
action && action(percentage);
return percentage;
};
async function calculatePercentageNested(
schema: Yup.ObjectSchema<any>,
values: object,
nestKey?: string,
ignoreNoRequiredField?: boolean,
) {
try {
await schema.validate(values, {
abortEarly: false,
});
return 100;
} catch (err) {
if (err instanceof Yup.ValidationError) {
const invalidFields: string[] = [];
err.inner.forEach((error) => {
if (
error.path &&
(!nestKey || error.path.startsWith(nestKey)) &&
invalidFields.findIndex((fieldName) => fieldName === error.path) ===
-1
) {
invalidFields.push(error.path);
}
});
const numInvalidFields = invalidFields.length;
const numFields = countFields(schema, nestKey, ignoreNoRequiredField);
const numValidFields = numFields - numInvalidFields;
const percentComplete = (numValidFields / numFields) * 100;
return percentComplete;
} else {
throw err;
}
}
}
function calculatePercentageWithoutSchema(
values: object | undefined,
ignoredFields?: string[],
additionalSkipValues?: IgnoredValueTypes,
//this is for BOs, to be able to additionally check correct percentage for key with other dependency
//main key is always the actual field that we are checking against another value
//inner key is the filed we are checking against
//inner value is the value we shoud check for
//(ex: useBussinessAddress must be true to ignor some fields, but isNotUSResident should be false instead, so we have to treat them differently)
) {
if (!values) return 0;
try {
const allFields = new Set<string>();
const validationErrors: Set<string> = new Set();
if (Array.isArray(values)) {
values.forEach((obj) => {
Object.keys(obj).forEach((key) => {
if (
additionalSkipValues &&
additionalSkipValues[key] &&
(obj[additionalSkipValues[key]?.key] ===
additionalSkipValues[key]?.value ||
additionalSkipValues[key]?.value === "both")
) {
return;
}
if (!ignoredFields?.includes(key)) {
allFields.add(key);
}
});
});
} else {
Object.keys(values).forEach((key) => {
if (!ignoredFields?.includes(key)) {
allFields.add(key);
}
});
}
allFields.forEach((field) => {
//again we must double-check for additionally ignored values
const value = Array.isArray(values)
? values.some(
(obj) => {
return (
(field === "contactPhone" && obj[field]?.length < 3) || //after deleting phone it remains +1
(field === "files" && obj[field]?.allFiles?.length < 1) ||
(!obj[field] &&
(additionalSkipValues && additionalSkipValues[field]
? obj[additionalSkipValues[field]?.key] !==
additionalSkipValues[field]?.value
: true))
);
}, //fallback is true bc we do not have to check for other extras
)
: (field.toLowerCase().includes("phonenumber") &&
(values as any)[field]?.length < 3) ||
!(values as any)[field];
if (value && !validationErrors.has(field)) {
validationErrors.add(field);
}
});
if (validationErrors.size === 0) {
return 100;
}
const numInvalidFields = validationErrors.size;
const numFields = allFields.size;
const numValidFields = numFields - numInvalidFields;
const percentComplete = (numValidFields / numFields) * 100;
return percentComplete;
} catch (err) {
console.error("Unexpected error during validation:", err);
throw err;
}
}
return {
calculatePercentage,
calculatePercentageNested,
calculatePercentageWithoutSchema,
};
};
// Helper function to extract nested testable fields
const extractTestableFields = (
fields: any,
path: string[] = [],
): [string, any][] => {
return Object.entries(fields).flatMap(([key, value]) => {
const _fields =
(value as any).conditions.length > 0
? (value as any).conditions[0].fn()
: {};
if (_fields?.fields && Object.keys(_fields.fields).length > 0) {
return Object.entries(_fields.fields).flatMap(([_key, _value]) => {
const val = _value as any;
const _currentPath = path.concat(key, _key);
if (
val.exclusiveTests?.required ||
val.exclusiveTests[_key] === false
) {
return [[_currentPath.join("."), val]];
}
return [];
}) as [string, any][];
}
const currentPath = path.concat(key);
if ((value as any).tests && (value as any).tests.length > 0) {
return [[currentPath.join("."), value]];
} else if ((value as any).type === "object") {
return extractTestableFields((value as any).fields, currentPath);
} else {
return [];
}
});
};
function countFields(
schema: Yup.ObjectSchema<any>,
nestKey?: string,
ignoreNoRequiredField?: boolean,
): number {
let count = 0;
for (const key in schema.fields) {
const field = schema.fields[key];
if (!nestKey || key === nestKey) {
if (field instanceof Yup.object) {
count += countFields(
field as Yup.ObjectSchema<any>,
"",
ignoreNoRequiredField,
);
} else {
const isNotRequiredAndIgnored =
ignoreNoRequiredField && !field.exclusiveTests?.required;
if (!isNotRequiredAndIgnored) {
count++;
}
}
}
}
return count;
}
|