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

Fix base project validation #374

Merged
merged 1 commit into from
Mar 23, 2023
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
25 changes: 25 additions & 0 deletions backend/src/components/project/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,31 @@ export async function validateUpsertProject(
) {
const validationErrors: FormErrors<UpsertProject> = { errors: {} };

if (values?.id) {
const estimateRange = await getPool().maybeOne(sql.untyped`
SELECT
extract(year FROM ${values?.startDate}::date) <= min(cost_estimate.year) AS "validStartDate",
extract(year FROM ${values?.endDate}::date) >= max(cost_estimate.year) AS "validEndDate"
FROM app.cost_estimate
WHERE project_id = ${values?.id}
GROUP BY project_id;
`);

if (estimateRange?.validStartDate === false) {
validationErrors.errors['startDate'] = fieldError('project.error.costEstimateNotIncluded');
}

if (estimateRange?.validEndDate === false) {
validationErrors.errors['endDate'] = fieldError('project.error.costEstimateNotIncluded');
}
}

// Check that project start date is not after end date
if (values.startDate >= values.endDate) {
validationErrors.errors['startDate'] = fieldError('project.error.endDateBeforeStartDate');
validationErrors.errors['endDate'] = fieldError('project.error.endDateBeforeStartDate');
}

// Check that SAP project ID is not changed if project has project objects
// with selected SAP WBS elements
if (values?.id) {
Expand Down
21 changes: 17 additions & 4 deletions backend/src/components/project/detailplan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ import { z } from 'zod';

import { addAuditEvent } from '@backend/components/audit';
import { codeIdFragment } from '@backend/components/code';
import { baseProjectUpsert } from '@backend/components/project/base';
import {
baseProjectUpsert,
validateUpsertProject as baseProjectValidate,
} from '@backend/components/project/base';
import { getPool, sql } from '@backend/db';
import { logger } from '@backend/logging';

import { hasErrors } from '@shared/formerror';
import { projectIdSchema } from '@shared/schema/project/base';
import { DetailplanProject, dbDetailplanSchema } from '@shared/schema/project/detailplan';
import { User } from '@shared/schema/user';
Expand Down Expand Up @@ -65,6 +70,11 @@ export async function getProject(id: string, tx?: DatabaseTransactionConnection)

export async function projectUpsert(project: DetailplanProject, user: User) {
return await getPool().transaction(async (tx) => {
if (hasErrors(await baseProjectValidate(tx, project))) {
logger.error('projectUpsert: validation failed', { project });
throw new Error('Invalid project data');
}

const id = await baseProjectUpsert(tx, project, user);
await addAuditEvent(tx, {
eventType: 'detailplanProject.upsertProject',
Expand Down Expand Up @@ -110,7 +120,10 @@ export async function projectUpsert(project: DetailplanProject, user: User) {
});
}

export async function validateUpsertProject(input: DetailplanProject) {
// !FIXME: implement, first validate base project, then detailplan project
return { errors: {} };
export async function validateUpsertProject(
project: DetailplanProject,
tx: DatabaseTransactionConnection | null
) {
const conn = tx ?? getPool();
return baseProjectValidate(conn, project);
}
47 changes: 17 additions & 30 deletions backend/src/components/project/investment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ import { z } from 'zod';

import { addAuditEvent } from '@backend/components/audit';
import { codeIdFragment } from '@backend/components/code';
import { baseProjectUpsert } from '@backend/components/project/base';
import {
baseProjectUpsert,
validateUpsertProject as baseProjectValidate,
} from '@backend/components/project/base';
import { getPool, sql } from '@backend/db';
import { logger } from '@backend/logging';

import { hasErrors } from '@shared/formerror';
import { projectIdSchema } from '@shared/schema/project/base';
import { InvestmentProject, dbInvestmentProjectSchema } from '@shared/schema/project/investment';
import { User } from '@shared/schema/user';
Expand Down Expand Up @@ -51,6 +56,11 @@ export async function getProject(id: string, tx?: DatabaseTransactionConnection)

export async function projectUpsert(project: InvestmentProject, user: User) {
return getPool().transaction(async (tx) => {
if (hasErrors(await validateUpsertProject(project, tx))) {
logger.error('Invalid project', { project });
throw new Error('Invalid project');
}

const id = await baseProjectUpsert(tx, project, user);
await addAuditEvent(tx, {
eventType: 'investmentProject.upsertProject',
Expand Down Expand Up @@ -100,33 +110,10 @@ export async function projectUpsert(project: InvestmentProject, user: User) {
});
}

export async function validateUpsertProject(input: InvestmentProject) {
// !FIXME: implement, first validate base project, then common project
/*
if (values?.id) {
const estimateRange = await getPool().maybeOne(sql.untyped`
SELECT
extract(year FROM ${values?.startDate}::date) <= min(cost_estimate.year) AS "validStartDate",
extract(year FROM ${values?.endDate}::date) >= max(cost_estimate.year) AS "validEndDate"
FROM app.cost_estimate
WHERE project_id = ${values?.id}
GROUP BY project_id;
`);

if (estimateRange?.validStartDate === false) {
validationErrors.errors['startDate'] = fieldError('project.error.costEstimateNotIncluded');
}

if (estimateRange?.validEndDate === false) {
validationErrors.errors['endDate'] = fieldError('project.error.costEstimateNotIncluded');
}
}

// Check that project start date is not after end date
if (values.startDate >= values.endDate) {
validationErrors.errors['startDate'] = fieldError('project.error.endDateBeforeStartDate');
validationErrors.errors['endDate'] = fieldError('project.error.endDateBeforeStartDate');
}
*/
return { errors: {} };
export async function validateUpsertProject(
project: InvestmentProject,
tx: DatabaseTransactionConnection | null
) {
const conn = tx ?? getPool();
return baseProjectValidate(conn, project);
}
2 changes: 1 addition & 1 deletion backend/src/router/project/detailplan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async function getNotificationMailTemplate(
export const createDetailplanProjectRouter = (t: TRPC) =>
t.router({
upsertValidate: t.procedure.input(z.any()).query(async ({ input }) => {
return validateUpsertProject(input);
return validateUpsertProject(input, null);
}),

upsert: t.procedure.input(detailplanProjectSchema).mutation(async ({ input, ctx }) => {
Expand Down
2 changes: 1 addition & 1 deletion backend/src/router/project/investment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { investmentProjectSchema } from '@shared/schema/project/investment';
export const createInvestmentProjectRouter = (t: TRPC) =>
t.router({
upsertValidate: t.procedure.input(z.any()).query(async ({ input }) => {
return validateUpsertProject(input);
return validateUpsertProject(input, null);
}),

upsert: t.procedure.input(investmentProjectSchema).mutation(async ({ input, ctx }) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export function DetailplanProjectForm(props: Props) {
const errors = await Promise.all([serverErrors, shapeErrors]);
return {
values,
errors: mergeErrors<DbDetailplanProject>(errors).errors,
errors: mergeErrors(errors).errors,
};
};
}, []);
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/views/Project/InvestmentProjectForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export function InvestmentProjectForm(props: InvestmentProjectFormProps) {
const errors = await Promise.all([serverErrors, shapeErrors]);
return {
values,
errors: mergeErrors<InvestmentProject>(errors).errors,
errors: mergeErrors(errors).errors,
};
};
}, []);
Expand Down