Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow adding evidences from applied control detail #181

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 17 additions & 56 deletions frontend/src/lib/components/Forms/ModelForm.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

export let form: SuperValidated<AnyZodObject>;
export let model: ModelInfo;
export let origin: string = "default";
export let origin = 'default';
export let closeModal = false;
export let parent: any;
export let suggestions: { [key: string]: any } = {};
Expand All @@ -42,14 +42,16 @@
$: shape = schema.shape || schema._def.schema.shape;
let updated_fields = new Set();

const modelFormId = `${Math.floor(Math.random()*Math.pow(10,16))}`;
const modelFormId = `${Math.floor(Math.random() * Math.pow(10, 16))}`;

onMount(() => {
const form = document.querySelector(`form[model-form-id="${modelFormId}"]`);
const first_input = form?.querySelector(`input:not([type]), input[type="password"], input[type="tel"], input[type="email"]`);
const first_input = form?.querySelector(
`input:not([type]), input[type="password"], input[type="tel"], input[type="email"]`
);
console.log(first_input);
first_input?.focus();
})
});
</script>

<SuperForm
Expand Down Expand Up @@ -84,7 +86,7 @@
.then((r) => {
form.form.update((currentData) => {
if (
origin === "edit" &&
origin === 'edit' &&
currentData['reference_control'] === initialData['reference_control'] &&
!updated_fields.has('reference_control')
) {
Expand Down Expand Up @@ -128,12 +130,7 @@
hide={initialData.project}
/>
<TextField {form} field="version" label={m.version()} />
<Select
{form}
options={model.selectOptions['status']}
field="status"
label={m.status()}
/>
<Select {form} options={model.selectOptions['status']} field="status" label={m.status()} />
<AutocompleteSelect
{form}
options={getOptions({ objects: model.foreignKeys['risk_matrix'] })}
Expand All @@ -155,13 +152,7 @@
field="reviewers"
label={m.reviewers()}
/>
<TextField
type="date"
{form}
field="eta"
label={m.eta()}
helpText={m.etaHelpText()}
/>
<TextField type="date" {form} field="eta" label={m.eta()} helpText={m.etaHelpText()} />
<TextField
type="date"
{form}
Expand Down Expand Up @@ -211,26 +202,15 @@
field="evidences"
label={m.evidences()}
/>
<TextField
type="date"
{form}
field="eta"
label={m.eta()}
helpText={m.etaHelpText()}
/>
<TextField type="date" {form} field="eta" label={m.eta()} helpText={m.etaHelpText()} />
<TextField
type="date"
{form}
field="expiry_date"
label={m.expiryDate()}
helpText={m.expiryDateHelpText()}
/>
<TextField
{form}
field="link"
label={m.link()}
helpText={m.linkHelpText()}
/>
<TextField {form} field="link" label={m.link()} helpText={m.linkHelpText()} />
<Select
{form}
options={model.selectOptions['effort']}
Expand Down Expand Up @@ -301,6 +281,8 @@
hide={initialData.folder}
/>
{:else if URLModel === 'evidences'}
<HiddenInput {form} field="applied_controls" />
<HiddenInput {form} field="requirement_assessments" />
<FileInput
{form}
helpText={object.attachment
Expand All @@ -316,12 +298,7 @@
label={m.domain()}
hide={initialData.applied_controls || initialData.requirement_assessments}
/>
<TextField
{form}
field="link"
label={m.link()}
helpText={m.linkHelpText()}
/>
<TextField {form} field="link" label={m.link()} helpText={m.linkHelpText()} />
{:else if URLModel === 'compliance-assessments'}
<AutocompleteSelect
{form}
Expand All @@ -331,12 +308,7 @@
hide={initialData.project}
/>
<TextField {form} field="version" label={m.version()} />
<Select
{form}
options={model.selectOptions['status']}
field="status"
label={m.status()}
/>
<Select {form} options={model.selectOptions['status']} field="status" label={m.status()} />
<AutocompleteSelect
{form}
options={getOptions({ objects: model.foreignKeys['framework'] })}
Expand All @@ -357,13 +329,7 @@
field="reviewers"
label={m.reviewers()}
/>
<TextField
type="date"
{form}
field="eta"
label={m.eta()}
helpText={m.etaHelpText()}
/>
<TextField type="date" {form} field="eta" label={m.eta()} helpText={m.etaHelpText()} />
<TextField
type="date"
{form}
Expand Down Expand Up @@ -411,12 +377,7 @@
/>
{/if}
{#if shape.is_active}
<Checkbox
{form}
field="is_active"
label={m.isActive()}
helpText={m.isActiveHelpText()}
/>
<Checkbox {form} field="is_active" label={m.isActive()} helpText={m.isActiveHelpText()} />
{/if}
{/if}
<div class="flex flex-row justify-between space-x-4">
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/lib/components/ModelTable/ModelTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
import Search from './Search.svelte';
import Th from './Th.svelte';
import ThFilter from './ThFilter.svelte';
import { formatDateOrDateTime } from '$lib/utils/datetime';
$: data = source.body.map((item: Record<string, any>, index: number) => {
return { ...item, meta: source.meta ? { ...source.meta[index] } : undefined };
});
Expand Down Expand Up @@ -242,7 +243,7 @@
{:else if value && value.hexcolor}
<p class="flex w-fit min-w-24 justify-center px-2 py-1 rounded-md ml-2 whitespace-nowrap" style="background-color: {value.hexcolor}">{value.name ?? value.str ?? '-'}</p>
{:else if ISO_8601_REGEX.test(value)}
{new Date(value).toLocaleString(languageTag())}
{formatDateOrDateTime(value, languageTag())}
{:else}
{#if localItems(languageTag())[toCamelCase(value)]}
{localItems(languageTag())[toCamelCase(value)]}
Expand Down
21 changes: 21 additions & 0 deletions frontend/src/lib/utils/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ interface ForeignKeyField {
urlParams?: string;
}

interface Field {
field: string;
type?: 'date' | 'datetime';
}

interface SelectField {
field: string;
}
Expand All @@ -76,6 +81,7 @@ export interface ModelMapEntry {
verboseName: string;
verboseNamePlural?: string;
urlModel?: urlModel;
detailViewFields?: Field[];
foreignKeyFields?: ForeignKeyField[];
reverseForeignKeyFields?: ForeignKeyField[];
selectFields?: SelectField[];
Expand Down Expand Up @@ -178,11 +184,26 @@ export const URL_MODEL_MAP: ModelMap = {
localFrGender: 'f',
verboseName: 'Applied control',
verboseNamePlural: 'Applied controls',
detailViewFields: [
{ field: 'id'},
{ field: 'folder' },
{ field: 'reference_control' },
{ field: 'category' },
{ field: 'effort' },
{ field: 'created_at', type: 'datetime' },
{ field: 'updated_at', type: 'datetime' },
{ field: 'name' },
{ field: 'description' },
{ field: 'eta', type: 'date' },
{ field: 'expiry_date', type: 'date' },
{ field: 'link' }
],
foreignKeyFields: [
{ field: 'reference_control', urlModel: 'reference-controls' },
{ field: 'folder', urlModel: 'folders' },
{ field: 'evidences', urlModel: 'evidences' }
],
reverseForeignKeyFields: [{ field: 'applied_controls', urlModel: 'evidences' }],
selectFields: [{ field: 'status' }, { field: 'category' }, { field: 'effort' }],
filters: [
{ field: 'reference_control' },
Expand Down
11 changes: 11 additions & 0 deletions frontend/src/lib/utils/datetime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function formatDateOrDateTime(isoString: string, locale = 'en-US'): string {
const hasTime = isoString.includes('T');

const date = new Date(isoString);

if (hasTime) {
return date.toLocaleString(locale);
} else {
return date.toLocaleDateString(locale);
}
}
19 changes: 18 additions & 1 deletion frontend/src/lib/utils/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { z, type AnyZodObject } from 'zod';

const toArrayPreprocessor = (value: unknown) => {
if (Array.isArray(value)) {
return value;
}

switch (typeof value) {
case 'string':
case 'number':
case 'bigint':
case 'boolean':
return [value];

default:
return value; // could not coerce, return the original and face the consequences during validation
}
};

export const loginSchema = z
.object({
username: z
Expand Down Expand Up @@ -182,7 +199,7 @@ export const ComplianceAssessmentSchema = baseNamedObject({
export const EvidenceSchema = baseNamedObject({
attachment: z.string().optional().nullable(),
folder: z.string(),
applied_controls: z.string().optional().array().optional(),
applied_controls: z.preprocess(toArrayPreprocessor, z.array(z.string().optional())).optional(),
requirement_assessments: z.string().optional().array().optional(),
link: z.string().optional().nullable()
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export const load: LayoutServerLoad = async ({ fetch, params }) => {
const deleteForm = await superValidate(z.object({ id: z.string().uuid() }));
const createSchema = modelSchema(e.urlModel);
initialData[e.field] = data.id;
if (data.folder) initialData['folder'] = data.folder.id ?? data.folder;
const createForm = await superValidate(initialData, createSchema, { errors: false });

const foreignKeys: Record<string, any> = {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,14 @@ export const actions: Actions = {

const model: string = urlParamModelVerboseName(urlModel);
if (model === 'User') {
return message(
createForm,
m.successfullyCreatedUser()
);
return message(createForm, m.successfullyCreatedUser());
}
return message(createForm, m.successfullyCreatedObject({object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase()}));
return message(
createForm,
m.successfullyCreatedObject({
object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase()
})
);
}
return { createForm };
},
Expand Down Expand Up @@ -104,7 +106,12 @@ export const actions: Actions = {
}
const model: string = urlParamModelVerboseName(params.model!);
// TODO: reference object by name instead of id
return message(deleteForm, m.successfullyDeletedObject({object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase()}));
return message(
deleteForm,
m.successfullyDeletedObject({
object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase()
})
);
}
return { deleteForm };
},
Expand Down Expand Up @@ -134,7 +141,13 @@ export const actions: Actions = {
}
const model: string = urlParamModelVerboseName(params.model!);
// TODO: reference object by name instead of id
return message(rejectForm, m.successfullyRejectedObject({object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase(), id: id}));
return message(
rejectForm,
m.successfullyRejectedObject({
object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase(),
id: id
})
);
},
accept: async ({ request, fetch, params }) => {
const formData = await request.formData();
Expand Down Expand Up @@ -162,7 +175,13 @@ export const actions: Actions = {
}
const model: string = urlParamModelVerboseName(params.model!);
// TODO: reference object by name instead of id
return message(acceptForm, m.successfullyValidatedObject({object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase(), id: id}));
return message(
acceptForm,
m.successfullyValidatedObject({
object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase(),
id: id
})
);
},
revoke: async ({ request, fetch, params }) => {
const formData = await request.formData();
Expand Down Expand Up @@ -190,6 +209,12 @@ export const actions: Actions = {
}
const model: string = urlParamModelVerboseName(params.model!);
// TODO: reference object by name instead of id
return message(revokeForm, m.successfullyRevokedObject({object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase(), id: id}));
return message(
revokeForm,
m.successfullyRevokedObject({
object: localItems(languageTag())[toCamelCase(model.toLowerCase())].toLowerCase(),
id: id
})
);
}
};
Loading
Loading