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

[project] allow adding geometry on new project creation #774

Merged
merged 1 commit into from
Oct 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
43 changes: 22 additions & 21 deletions backend/src/components/project/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
PartialBudgetUpdate,
Relation,
UpdateGeometry,
YearBudget,
projectRelationsSchema,
relationsSchema,
updateGeometryResultSchema,
Expand Down Expand Up @@ -131,28 +130,30 @@ export async function getRelatedProjects(id: string) {
FROM related_projects`);
}

export async function updateProjectGeometry(geometryUpdate: UpdateGeometry, user: User) {
export async function updateProjectGeometry(
tx: DatabaseTransactionConnection,
geometryUpdate: UpdateGeometry,
user: User
) {
const { id, features } = geometryUpdate;
return getPool().transaction(async (tx) => {
await addAuditEvent(tx, {
eventType: 'project.updateGeometry',
eventData: geometryUpdate,
eventUser: user.id,
});
return tx.one(sql.type(updateGeometryResultSchema)`
WITH featureCollection AS (
SELECT ST_Collect(
ST_GeomFromGeoJSON(value->'geometry')
) AS resultGeom
FROM jsonb_array_elements(${features}::jsonb)
)
UPDATE app.project
SET geom = featureCollection.resultGeom
FROM featureCollection
WHERE id = ${id} AND ${id} IN (SELECT id FROM app.project_investment)
RETURNING id, ST_AsGeoJSON(geom) AS geom
`);
await addAuditEvent(tx, {
eventType: 'project.updateGeometry',
eventData: geometryUpdate,
eventUser: user.id,
});
return tx.one(sql.type(updateGeometryResultSchema)`
WITH featureCollection AS (
SELECT ST_Collect(
ST_GeomFromGeoJSON(value->'geometry')
) AS resultGeom
FROM jsonb_array_elements(${features}::jsonb)
)
UPDATE app.project
SET geom = featureCollection.resultGeom
FROM featureCollection
WHERE id = ${id} AND ${id} IN (SELECT id FROM app.project_investment)
RETURNING id, ST_AsGeoJSON(geom) AS geom
`);
}

function budgetWhereFragment(budgetInput: BudgetInput) {
Expand Down
12 changes: 12 additions & 0 deletions backend/src/components/project/investment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { z } from 'zod';

import { addAuditEvent } from '@backend/components/audit';
import { codeIdFragment } from '@backend/components/code';
import { updateProjectGeometry } from '@backend/components/project';
import {
baseProjectUpsert,
validateUpsertProject as baseProjectValidate,
Expand Down Expand Up @@ -106,6 +107,17 @@ export async function projectUpsert(project: InvestmentProject, user: User) {
)
);

if (project.geom) {
updateProjectGeometry(
tx,
{
id: upsertResult.id,
features: project.geom,
},
user
);
}

return getProject(upsertResult.id, tx);
});
}
Expand Down
5 changes: 4 additions & 1 deletion backend/src/router/project/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { deleteProject, getProject } from '@backend/components/project/base';
import { projectSearch } from '@backend/components/project/search';
import { startReportJob } from '@backend/components/taskQueue/reportQueue';
import { getPool } from '@backend/db';
import { TRPC } from '@backend/router';

import {
Expand Down Expand Up @@ -42,7 +43,9 @@ export const createProjectRouter = (t: TRPC) =>
}),

updateGeometry: t.procedure.input(updateGeometrySchema).mutation(async ({ input, ctx }) => {
return updateProjectGeometry(input, ctx.user);
return await getPool().transaction(async (tx) => {
return updateProjectGeometry(tx, input, ctx.user);
});
}),

getBudget: t.procedure.input(getBudgetInputSchema).query(async ({ input }) => {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Map/MapToolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { css } from '@emotion/react';
import {
Check,
DeleteForeverTwoTone,
EditTwoTone,
PanToolAltTwoTone,
PentagonTwoTone,
RoundedCornerTwoTone,
SaveTwoTone,
UndoTwoTone,
} from '@mui/icons-material';
import { Box, Divider, IconButton, Tooltip } from '@mui/material';
Expand Down Expand Up @@ -144,7 +144,7 @@ export function MapToolbar(props: Props) {
color="primary"
onClick={props.onSaveClick}
>
<SaveTwoTone />
<Check />
</IconButton>
</Box>
</Tooltip>
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/Map/MapWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -234,10 +234,11 @@ export function MapWrapper(props: Props) {
onToolChange={(tool) => setSelectedTool(tool)}
onSaveClick={() => {
selectionSource.clear();
setDirty(false);
onFeaturesSaved?.(
getGeoJSONFeaturesString(
drawSource.getFeatures(),
projection?.getCode() || mapOptions.projection.code
projection?.getCode() ?? mapOptions.projection.code
)
);
}}
Expand Down
14 changes: 10 additions & 4 deletions frontend/src/views/Project/InvestmentProject.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AccountTree, Euro, ListAlt, Map } from '@mui/icons-material';
import { Box, Breadcrumbs, Chip, Paper, Tab, Tabs, Typography } from '@mui/material';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { useMemo } from 'react';
import { useMemo, useState } from 'react';
import { useParams } from 'react-router';
import { Link } from 'react-router-dom';

Expand Down Expand Up @@ -75,6 +75,8 @@ export function InvestmentProject() {
{ enabled: Boolean(projectId), queryKey: ['investmentProject.get', { id: projectId }] }
);

const [geom, setGeom] = useState<string | null>(null);

const tr = useTranslations();
const notify = useNotifications();
const geometryUpdate = trpc.project.updateGeometry.useMutation({
Expand Down Expand Up @@ -154,7 +156,7 @@ export function InvestmentProject() {

<div css={pageContentStyle}>
<Paper sx={{ p: 3, height: '100%' }} variant="outlined">
<InvestmentProjectForm project={project.data} />
<InvestmentProjectForm edit={!projectId} project={project.data} geom={geom} />
{project.data && (
<DeleteProjectDialog
projectId={project.data.id}
Expand Down Expand Up @@ -196,9 +198,13 @@ export function InvestmentProject() {
geoJson={project?.data?.geom}
drawStyle={PROJECT_AREA_STYLE}
fitExtent="geoJson"
editable={Boolean(projectId)}
editable={true}
onFeaturesSaved={(features) => {
geometryUpdate.mutate({ id: projectId, features: features });
if (!project.data) {
setGeom(features);
} else {
geometryUpdate.mutate({ id: projectId, features });
}
}}
vectorLayers={[projectObjectsLayer]}
/>
Expand Down
39 changes: 25 additions & 14 deletions frontend/src/views/Project/InvestmentProjectForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { css } from '@emotion/react';
import { zodResolver } from '@hookform/resolvers/zod';
import { AddCircle, Edit, HourglassFullTwoTone, Save, Undo } from '@mui/icons-material';
import { Box, Button, TextField, Typography } from '@mui/material';
import { Alert, Box, Button, TextField, Typography } from '@mui/material';
import { useQueryClient } from '@tanstack/react-query';
import dayjs from 'dayjs';
import { useAtomValue } from 'jotai';
Expand Down Expand Up @@ -32,15 +32,17 @@ const newProjectFormStyle = css`
`;

interface InvestmentProjectFormProps {
edit: boolean;
project?: DbInvestmentProject | null;
geom: string | null;
}

export function InvestmentProjectForm(props: InvestmentProjectFormProps) {
const tr = useTranslations();
const notify = useNotifications();
const queryClient = useQueryClient();
const navigate = useNavigate();
const [editing, setEditing] = useState(!props.project);
const [editing, setEditing] = useState(props.edit);
const currentUser = useAtomValue(authAtom);

const readonlyProps = useMemo(() => {
Expand Down Expand Up @@ -130,7 +132,9 @@ export function InvestmentProjectForm(props: InvestmentProjectFormProps) {
},
});

const onSubmit = (data: InvestmentProject | DbInvestmentProject) => projectUpsert.mutate(data);
const onSubmit = (data: InvestmentProject | DbInvestmentProject) => {
projectUpsert.mutate({ ...data, geom: props.geom });
};

return (
<FormProvider {...form}>
Expand Down Expand Up @@ -268,17 +272,24 @@ export function InvestmentProjectForm(props: InvestmentProjectFormProps) {
/>

{!props.project && (
<Button
disabled={!form.formState.isValid}
type="submit"
sx={{ mt: 2 }}
variant="contained"
color="primary"
size="small"
endIcon={<AddCircle />}
>
{tr('newProject.createBtnLabel')}
</Button>
<>
{(!props.geom || props.geom === '[]') && (
<Alert sx={{ mt: 1 }} severity="info">
{tr('newProject.infoNoGeom')}
</Alert>
)}
<Button
disabled={!form.formState.isValid}
type="submit"
sx={{ mt: 2 }}
variant="contained"
color="primary"
size="small"
endIcon={<AddCircle />}
>
{tr('newProject.createBtnLabel')}
</Button>
</>
)}

{props.project && editing && (
Expand Down
1 change: 1 addition & 0 deletions shared/src/language/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"newProject.ownerTooltip": "Valitse omistaja",
"newProject.committeeTooltip": "Valitse lautakunta",
"newProject.basicInfoSectionLabel": "Perustiedot",
"newProject.infoNoGeom": "Olet luomassa hankkeen ilman aluetta",
"newProject.createBtnLabel": "Lisää hanke",
"project.relatedProjectsTabLabel": "Sidoshankkeet",
"newProject.documentsSectionTitle": "Asiakirjat",
Expand Down
1 change: 1 addition & 0 deletions shared/src/schema/project/investment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const investmentProjectSchema = upsertProjectSchema.extend({
owner: nonEmptyString,
personInCharge: nonEmptyString,
committees: z.array(codeId).superRefine((committees) => committees.length > 0),
geom: z.string().nullable().optional(),
});

export type InvestmentProject = z.infer<typeof investmentProjectSchema>;
Expand Down