Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { error } from '@sveltejs/kit';
import { formString } from '#lib/forms.ts';
import { api } from '#lib/server/api.ts';
import { complianceAccess, failed } from '#lib/compliance/server.ts';
import type { components } from '@usehuxley/api-client';
import type { Actions, PageServerLoad } from './$types';

type Outcome = components['schemas']['AssessmentResultValue'];
const OUTCOMES: Outcome[] = ['met', 'partially_met', 'not_met', 'not_applicable'];

export const load: PageServerLoad = async (event) => {
const { user } = await event.parent();
complianceAccess(user);
const client = api(event);
const id = event.params.id;
const [assessment, results] = await Promise.all([
client.GET('/api/v1/grc/assessments/{id}', { params: { path: { id } } }),
client.GET('/api/v1/grc/assessments/{id}/results', { params: { path: { id } } })
]);
if (!assessment.data)
error(assessment.response.status === 404 ? 404 : 503, 'No such assessment.');
return {
assessment: assessment.data,
results: results.data ?? [],
canAssess: user.grantedPermissions.includes('grc:assess')
};
};

export const actions: Actions = {
save: async (event) => {
const form = await event.request.formData();
const items = form
.getAll('requirementId')
.map(String)
.map((requirementId) => {
const r = formString(form, `result.${requirementId}`);
return {
requirementId,
result: OUTCOMES.find((o) => o === r) ?? null,
notes: formString(form, `notes.${requirementId}`) || null
};
});
if (items.length === 0) return { message: 'Nothing to save.' };
const { error: problem, response } = await api(event).PUT(
'/api/v1/grc/assessments/{id}/results',
{
params: { path: { id: event.params.id } },
body: items
}
);
if (!response.ok) return failed(response.status, problem, 'Could not save them.');
return { message: 'Saved.' };
},
complete: async (event) => {
const form = await event.request.formData();
const { error: problem, response } = await api(event).POST(
'/api/v1/grc/assessments/{id}/complete',
{
params: { path: { id: event.params.id } },
body: {
acceptSuggestions: form.get('acceptSuggestions') === 'on',
raiseFindings: form.get('raiseFindings') === 'on'
}
}
);
if (!response.ok) return failed(response.status, problem, 'Could not complete it.');
return { message: 'Completed.' };
}
};
142 changes: 142 additions & 0 deletions apps/web/src/routes/(app)/compliance/assessments/[id]/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { resolve } from '$app/paths';
import { Badge, Button, Card } from '@usehuxley/ui';
import { toasted } from '#lib/compliance/enhance.ts';
import type { PageProps } from './$types';

let { data }: PageProps = $props();
let a = $derived(data.assessment);
let open = $derived(a.status === 'in_progress' && data.canAssess);
const OUTCOMES = [
{ value: '', label: 'Not answered' },
{ value: 'met', label: 'Met' },
{ value: 'partially_met', label: 'Partially met' },
{ value: 'not_met', label: 'Not met' },
{ value: 'not_applicable', label: 'Not applicable' }
];
const label = (v: string | null | undefined) =>
OUTCOMES.find((o) => o.value === (v ?? ''))?.label;
const select = 'h-8 rounded-control border border-border-strong bg-surface px-2 text-sm text-fg';
</script>

<svelte:head>
<title>{a.name} · Huxley</title>
</svelte:head>

<div class="flex flex-col gap-5">
<div>
<a
href="{resolve('/(app)/compliance/programs/[id]', { id: a.programId })}?tab=assessments"
class="text-sm text-fg-muted hover:text-fg"
>
{a.programName}
</a>
<h1 class="text-[26px] leading-tight font-extrabold tracking-tight text-fg">{a.name}</h1>
<p class="mt-1 flex flex-wrap items-center gap-2 text-sm text-fg-subtle">
<span>
{a.frameworkName}
{a.version} · from {a.startedOn}{#if a.assessorName}
· {a.assessorName}{/if}
</span>
<Badge tone={a.status === 'completed' ? 'success' : 'info'}>
{a.status === 'completed' ? 'Completed' : 'In progress'} · {a.score}%
</Badge>
<span>
{a.counts.met} met, {a.counts.partiallyMet} partially, {a.counts.notMet} not met,
{a.counts.notApplicable} not applicable{#if a.counts.unanswered}, {a.counts.unanswered} to answer{/if}
</span>
</p>
</div>

<form method="POST" action="?/save" class="flex flex-col gap-4" use:enhance={toasted()}>
<Card>
<ol class="divide-y divide-border" aria-label="Assessment results">
{#each data.results as r (r.requirementId)}
<li
class="flex flex-wrap items-start gap-3 py-2.5"
style="padding-left: {Math.min(r.depth, 6) * 1.25}rem"
>
{#if r.inScope}
<div class="min-w-0 flex-1">
<span class="font-mono text-sm font-semibold text-fg">{r.ref}</span>
{#if r.title}<span class="ml-1 text-sm text-fg">{r.title}</span>{/if}
{#if r.statement}<p class="line-clamp-2 text-sm text-fg-muted">
{r.statement}
</p>{/if}
{#if r.suggested && r.suggested !== r.result}
<p class="text-xs text-fg-subtle">The controls suggest: {label(r.suggested)}</p>
{/if}
</div>
{#if open}
<input type="hidden" name="requirementId" value={r.requirementId} />
<div class="flex flex-col gap-1">
<label class="sr-only" for="result-{r.requirementId}">Result for {r.ref}</label>
<select
id="result-{r.requirementId}"
name="result.{r.requirementId}"
class={select}
>
{#each OUTCOMES as o (o.value)}
<option value={o.value} selected={(r.result ?? '') === o.value}>
{o.label}
</option>
{/each}
</select>
<label class="sr-only" for="notes-{r.requirementId}">Notes for {r.ref}</label>
<input
id="notes-{r.requirementId}"
name="notes.{r.requirementId}"
value={r.notes ?? ''}
maxlength={10000}
placeholder="Notes"
class="h-8 rounded-control border border-border-strong bg-surface px-2 text-sm text-fg"
/>
</div>
{:else}
<div class="text-right text-sm">
<Badge
tone={r.result === 'met'
? 'success'
: r.result === 'partially_met'
? 'warning'
: r.result === 'not_met'
? 'danger'
: 'neutral'}
>
{label(r.result)}
</Badge>
{#if r.notes}<p class="mt-1 max-w-xs text-xs text-fg-muted">{r.notes}</p>{/if}
</div>
{/if}
{:else if !r.assessable}
<p class="font-semibold text-fg">
<span class="font-mono text-sm">{r.ref}</span>
{r.title ?? ''}
</p>
{/if}
</li>
{/each}
</ol>
</Card>
{#if open}
<div><Button type="submit" variant="primary">Save results</Button></div>
{/if}
</form>

{#if open}
<Card title="Complete the assessment" description="Its score is frozen once it's complete.">
<form method="POST" action="?/complete" class="flex flex-col gap-2" use:enhance={toasted()}>
<label class="flex items-center gap-2 text-sm text-fg">
<input type="checkbox" name="acceptSuggestions" /> Take the controls' suggestion for anything
not answered
</label>
<label class="flex items-center gap-2 text-sm text-fg">
<input type="checkbox" name="raiseFindings" checked /> Raise a finding for each requirement
not met or partially met
</label>
<div><Button type="submit">Complete it</Button></div>
</form>
</Card>
{/if}
</div>
112 changes: 96 additions & 16 deletions apps/web/src/routes/(app)/compliance/programs/[id]/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { error } from '@sveltejs/kit';
import { error, redirect } from '@sveltejs/kit';
import { formString } from '#lib/forms.ts';
import { api } from '#lib/server/api.ts';
import { complianceAccess, failed } from '#lib/compliance/server.ts';
Expand All @@ -10,7 +10,15 @@ type ImplStatus = components['schemas']['ImplementationStatus'];
type Responsibility = components['schemas']['Responsibility'];
type ProgramStatus = components['schemas']['ComplianceProgramStatus'];

const TABS = ['overview', 'requirements', 'controls', 'requests', 'details'] as const;
const TABS = [
'overview',
'requirements',
'controls',
'requests',
'assessments',
'findings',
'details'
] as const;
const STATUSES: RequirementStatus[] = ['met', 'partial', 'not_met', 'gap', 'not_applicable'];

export const load: PageServerLoad = async (event) => {
Expand All @@ -28,20 +36,25 @@ export const load: PageServerLoad = async (event) => {
frameworks[0]?.versionId;
const status = STATUSES.find((s) => s === params.get('status'));
const q = params.get('q')?.trim() || undefined;
const [requirements, controls, catalog, signoff, requests, contacts] = await Promise.all([
versionId
? client.GET('/api/v1/grc/programs/{id}/requirements', {
params: { path: { id }, query: { versionId, status, q } }
})
: Promise.resolve({ data: [] }),
client.GET('/api/v1/grc/programs/{id}/controls', { params: { path: { id } } }),
client.GET('/api/v1/grc/frameworks'),
client.GET('/api/v1/grc/programs/{id}/signoff', { params: { path: { id } } }),
client.GET('/api/v1/grc/programs/{id}/evidence-requests', { params: { path: { id } } }),
user.activeModules.includes('crm') && user.grantedPermissions.includes('crm:read')
? client.GET('/api/v1/orgs/{id}/contacts', { params: { path: { id: program.data.orgId } } })
: Promise.resolve({ data: undefined })
]);
const [requirements, controls, catalog, signoff, requests, contacts, assessments, findings] =
await Promise.all([
versionId
? client.GET('/api/v1/grc/programs/{id}/requirements', {
params: { path: { id }, query: { versionId, status, q } }
})
: Promise.resolve({ data: [] }),
client.GET('/api/v1/grc/programs/{id}/controls', { params: { path: { id } } }),
client.GET('/api/v1/grc/frameworks'),
client.GET('/api/v1/grc/programs/{id}/signoff', { params: { path: { id } } }),
client.GET('/api/v1/grc/programs/{id}/evidence-requests', { params: { path: { id } } }),
user.activeModules.includes('crm') && user.grantedPermissions.includes('crm:read')
? client.GET('/api/v1/orgs/{id}/contacts', { params: { path: { id: program.data.orgId } } })
: Promise.resolve({ data: undefined }),
client.GET('/api/v1/grc/programs/{id}/assessments', { params: { path: { id } } }),
client.GET('/api/v1/grc/programs/{id}/findings', {
params: { path: { id }, query: { closed: params.get('closed') === 'on' } }
})
]);
const inProgram = new Set(frameworks.map((f) => f.versionId));
return {
program: program.data,
Expand All @@ -52,6 +65,10 @@ export const load: PageServerLoad = async (event) => {
controls: controls.data ?? [],
signoff: signoff.data ?? null,
requests: requests.data ?? [],
assessments: assessments.data ?? [],
findings: findings.data ?? [],
closedFindings: params.get('closed') === 'on',
canManageRisks: user.grantedPermissions.includes('risk:manage'),
contacts: (contacts.data?.items ?? []).map((c) => ({
value: c.id,
label: `${c.firstName} ${c.lastName}`.trim() || (c.email ?? 'Contact')
Expand Down Expand Up @@ -86,6 +103,69 @@ async function setFramework(event: Parameters<Actions[string]>[0], form: FormDat
}

export const actions: Actions = {
startAssessment: async (event) => {
const form = await event.request.formData();
const {
data,
error: problem,
response
} = await api(event).POST('/api/v1/grc/programs/{id}/assessments', {
params: { path: { id: event.params.id } },
body: {
versionId: formString(form, 'versionId'),
name: formString(form, 'name'),
kind: formString(form, 'kind') as components['schemas']['AssessmentKind'],
assessorName: formString(form, 'assessorName') || null
}
});
if (!data) return failed(response.status, problem, 'Could not start it.');
redirect(303, `/compliance/assessments/${data.id}`);
},
saveFinding: async (event) => {
const form = await event.request.formData();
const id = formString(form, 'findingId');
const dues = form.getAll('milestoneDue').map((v) => (typeof v === 'string' ? v : ''));
const milestones = form
.getAll('milestone')
.map(String)
.map((t, i) => ({
title: t.trim(),
dueOn: dues[i] || null,
done: form.getAll('milestoneDone').map(String).includes(String(i))
}))
.filter((m) => m.title);
const body = {
title: formString(form, 'title'),
description: formString(form, 'description') || null,
severity: formString(form, 'severity') as components['schemas']['FindingSeverity'],
status: formString(form, 'status') as components['schemas']['FindingStatus'],
dueOn: formString(form, 'dueOn') || null,
ownerId: formString(form, 'ownerId') || null,
resolution: formString(form, 'resolution') || null,
milestones,
version: id ? Number(formString(form, 'version')) : null
};
const res = id
? await api(event).PUT('/api/v1/grc/findings/{id}', { params: { path: { id } }, body })
: await api(event).POST('/api/v1/grc/programs/{id}/findings', {
params: { path: { id: event.params.id } },
body
});
if (!res.response.ok) return failed(res.response.status, res.error, 'Could not save it.');
return { message: 'Saved.' };
},
raiseRisk: async (event) => {
const form = await event.request.formData();
const {
data,
error: problem,
response
} = await api(event).POST('/api/v1/grc/findings/{id}/risk', {
params: { path: { id: formString(form, 'findingId') } }
});
if (!data) return failed(response.status, problem, 'Could not raise it.');
redirect(303, `/compliance/risks/${data.riskId}`);
},
requestEvidence: async (event) => {
const form = await event.request.formData();
const { error: problem, response } = await api(event).POST(
Expand Down
Loading