Skip to content

Commit

Permalink
feat: improve requirement assessment edit page server complexity
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohamed-Hacene committed Oct 4, 2024
1 parent 476ae11 commit a3861c6
Showing 1 changed file with 124 additions and 164 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,216 +4,176 @@ import { getModelInfo, urlParamModelVerboseName } from '$lib/utils/crud';
import { getSecureRedirect } from '$lib/utils/helpers';
import { modelSchema } from '$lib/utils/schemas';
import { listViewFields } from '$lib/utils/table';
import type { urlModel } from '$lib/utils/types';
import * as m from '$paraglide/messages';
import { tableSourceMapper, type TableSource } from '@skeletonlabs/skeleton';
import { tableSourceMapper } from '@skeletonlabs/skeleton';
import type { Actions } from '@sveltejs/kit';
import { fail, redirect } from '@sveltejs/kit';
import { setFlash } from 'sveltekit-flash-message/server';
import { setError, superValidate } from 'sveltekit-superforms';
import { superValidate } from 'sveltekit-superforms';
import { zod } from 'sveltekit-superforms/adapters';
import type { PageServerLoad } from './$types';
import { z } from 'zod';


export const load = (async ({ fetch, params }) => {
const URLModel = 'requirement-assessments';
const endpoint = `${BASE_API_URL}/${URLModel}/${params.id}/`;

const res = await fetch(endpoint);
const requirementAssessment = await res.json();

const compliance_assessment_score = await fetch(
`${BASE_API_URL}/compliance-assessments/${requirementAssessment.compliance_assessment.id}/global_score/`
).then((res) => res.json());
const requirement = await fetch(
`${BASE_API_URL}/requirement-nodes/${requirementAssessment.requirement}/`
).then((res) => res.json());
const parentRequirementNodeEndpoint = `${BASE_API_URL}/requirement-nodes/?urn=${requirement.parent_urn}`;
const parent = await fetch(parentRequirementNodeEndpoint)
.then((res) => res.json())
.then((res) => res.results[0]);

const baseUrl = BASE_API_URL;
const endpoint = `${baseUrl}/${URLModel}/${params.id}/`;

async function fetchJson(url: string) {
const res = await fetch(url);
if (!res.ok) {
console.error(`Failed to fetch data from ${url}: ${res.statusText}`);
return null;
}
return res.json();
}

const requirementAssessment = await fetchJson(endpoint);
const [compliance_assessment_score, requirement] = await Promise.all([
fetchJson(`${baseUrl}/compliance-assessments/${requirementAssessment.compliance_assessment.id}/global_score/`),
fetchJson(`${baseUrl}/requirement-nodes/${requirementAssessment.requirement}/`)
]);

const parent = await fetchJson(`${baseUrl}/requirement-nodes/?urn=${requirement.parent_urn}`)
.then(res => res.results[0]);

const model = getModelInfo(URLModel);

const object = { ...requirementAssessment };
for (const key in object) {
if (object[key] instanceof Object && 'id' in object[key]) {
object[key] = object[key].id;
}
}

Object.keys(object).forEach(key => {
if (object[key] instanceof Object && 'id' in object[key]) {
object[key] = object[key].id;
}
});
const schema = modelSchema(URLModel);
const form = await superValidate(object, zod(schema), { errors: true });

const foreignKeys: Record<string, any> = {};

if (model.foreignKeyFields) {
for (const keyField of model.foreignKeyFields) {
const queryParams = keyField.urlParams ? `?${keyField.urlParams}` : '';
const url = `${BASE_API_URL}/${keyField.urlModel}/${queryParams}`;
const response = await fetch(url);
if (response.ok) {
foreignKeys[keyField.field] = await response.json().then((data) => data.results);
} else {
console.error(`Failed to fetch data for ${keyField.field}: ${response.statusText}`);
}
await Promise.all(model.foreignKeyFields.map(async (keyField) => {
const queryParams = keyField.urlParams ? `?${keyField.urlParams}` : '';
const url = `${baseUrl}/${keyField.urlModel}/${queryParams}`;
const data = await fetchJson(url);
if (data) {
foreignKeys[keyField.field] = data.results;
}
}));
}

model.foreignKeys = foreignKeys;

const selectOptions: Record<string, any> = {};

if (model.selectFields) {
for (const selectField of model.selectFields) {
const url = `${BASE_API_URL}/${URLModel}/${selectField.field}/`;
const response = await fetch(url);
if (response.ok) {
selectOptions[selectField.field] = await response.json().then((data) =>
Object.entries(data).map(([key, value]) => ({
label: value,
value: key
}))
);
} else {
console.error(`Failed to fetch data for ${selectField.field}: ${response.statusText}`);
}
await Promise.all(model.selectFields.map(async (selectField) => {
const url = `${baseUrl}/${URLModel}/${selectField.field}/`;
const data = await fetchJson(url);
if (data) {
selectOptions[selectField.field] = Object.entries(data).map(([key, value]) => ({
label: value,
value: key
}));
}
}));
}

model['selectOptions'] = selectOptions;

model.selectOptions = selectOptions;

const measureCreateSchema = modelSchema('applied-controls');
const initialData = {
folder: requirementAssessment.folder.id
};

const measureCreateForm = await superValidate(initialData, zod(measureCreateSchema), {
errors: false
});

const measureCreateForm = await superValidate({ folder: requirementAssessment.folder.id }, zod(measureCreateSchema), { errors: false });

const measureModel = getModelInfo('applied-controls');

const measureSelectOptions: Record<string, any> = {};

if (measureModel.selectFields) {
for (const selectField of measureModel.selectFields) {
const url = `${BASE_API_URL}/applied-controls/${selectField.field}/`;
const response = await fetch(url);
if (response.ok) {
measureSelectOptions[selectField.field] = await response.json().then((data) =>
Object.entries(data).map(([key, value]) => ({
label: value,
value: key
}))
);
} else {
console.error(`Failed to fetch data for ${selectField.field}: ${response.statusText}`);
}
}
}

measureModel['selectOptions'] = measureSelectOptions;

const tables: Record<string, any> = {};

for (const key of ['applied-controls', 'evidences'] as urlModel[]) {
const keyEndpoint = `${BASE_API_URL}/${key}/?requirement_assessments=${params.id}`;
const response = await fetch(keyEndpoint);
if (response.ok) {
const data = await response.json().then((data) => data.results);

const bodyData = tableSourceMapper(data, listViewFields[key].body);

const table: TableSource = {
head: listViewFields[key].head,
body: bodyData,
meta: data
};
tables[key] = table;
} else {
console.error(`Failed to fetch data for ${key}: ${response.statusText}`);
await Promise.all(measureModel.selectFields.map(async (selectField) => {
const url = `${baseUrl}/applied-controls/${selectField.field}/`;
const data = await fetchJson(url);
if (data) {
measureSelectOptions[selectField.field] = Object.entries(data).map(([key, value]) => ({
label: value,
value: key
}));
}
}));
}

measureModel.selectOptions = measureSelectOptions;

const measureForeignKeys: Record<string, any> = {};

if (measureModel.foreignKeyFields) {
for (const keyField of measureModel.foreignKeyFields) {
if (keyField.field === 'folder') {
measureForeignKeys[keyField.field] = [requirementAssessment.folder];
continue;
}
const queryParams = keyField.urlParams ? `?${keyField.urlParams}` : '';
const url = `${BASE_API_URL}/${keyField.urlModel}/${queryParams}`;
const response = await fetch(url);
if (response.ok) {
measureForeignKeys[keyField.field] = await response.json().then((data) => data.results);
} else {
console.error(`Failed to fetch data for ${keyField.field}: ${response.statusText}`);
}
await Promise.all(measureModel.foreignKeyFields.map(async (keyField) => {
if (keyField.field === 'folder') {
measureForeignKeys[keyField.field] = [requirementAssessment.folder];
} else {
const queryParams = keyField.urlParams ? `?${keyField.urlParams}` : '';
const url = `${baseUrl}/${keyField.urlModel}/${queryParams}`;
const data = await fetchJson(url);
if (data) {
measureForeignKeys[keyField.field] = data.results;
}
}
}));
}

measureModel.foreignKeys = measureForeignKeys;


const tables: Record<string, any> = {};
await Promise.all(['applied-controls', 'evidences'].map(async (key) => {
const data = await fetchJson(`${baseUrl}/${key}/?requirement_assessments=${params.id}`);
if (data) {
tables[key] = {
head: listViewFields[key].head,
body: tableSourceMapper(data.results, listViewFields[key].body),
meta: data.results
};
}
}));

const evidenceModel = getModelInfo('evidences');
const evidenceCreateSchema = modelSchema('evidences');
const evidenceInitialData = {
requirement_assessments: [params.id],
folder: requirementAssessment.folder.id
};
const evidenceCreateForm = await superValidate(evidenceInitialData, zod(evidenceCreateSchema), {
errors: false
});

const evidenceCreateForm = await superValidate(
{ requirement_assessments: [params.id], folder: requirementAssessment.folder.id },
zod(evidenceCreateSchema),
{ errors: false }
);

const evidenceSelectOptions: Record<string, any> = {};

if (evidenceModel.selectFields) {
for (const selectField of evidenceModel.selectFields) {
const url = `${BASE_API_URL}/evidences/${selectField.field}/`;
const response = await fetch(url);
if (response.ok) {
evidenceSelectOptions[selectField.field] = await response.json().then((data) =>
Object.entries(data).map(([key, value]) => ({
label: value,
value: key
}))
);
} else {
console.error(`Failed to fetch data for ${selectField.field}: ${response.statusText}`);
}
await Promise.all(evidenceModel.selectFields.map(async (selectField) => {
const url = `${baseUrl}/evidences/${selectField.field}/`;
const data = await fetchJson(url);
if (data) {
evidenceSelectOptions[selectField.field] = Object.entries(data).map(([key, value]) => ({
label: value,
value: key
}));
}
}));
}

evidenceModel['selectOptions'] = evidenceSelectOptions;

evidenceModel.selectOptions = evidenceSelectOptions;

const evidenceForeignKeys: Record<string, any> = {};

if (evidenceModel.foreignKeyFields) {
for (const keyField of evidenceModel.foreignKeyFields) {
if (keyField.field === 'folder') {
evidenceForeignKeys[keyField.field] = [requirementAssessment.folder];
continue;
}
evidenceForeignKeys[keyField.field] = [];
evidenceModel.foreignKeyFields.forEach((keyField) => {
if (keyField.field === 'folder') {
evidenceForeignKeys[keyField.field] = [requirementAssessment.folder];
} else {
evidenceForeignKeys[keyField.field] = [];
}
});
}

evidenceModel.foreignKeys = evidenceForeignKeys;

return {
URLModel,
requirementAssessment,
compliance_assessment_score,
requirement,
parent,
model,
form,
measureCreateForm,
measureModel,
evidenceModel,
evidenceCreateForm,
tables
URLModel,
requirementAssessment,
compliance_assessment_score,
requirement,
parent,
model,
form,
measureCreateForm,
measureModel,
evidenceModel,
evidenceCreateForm,
tables
};
}) satisfies PageServerLoad;

Expand Down

0 comments on commit a3861c6

Please sign in to comment.