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

[projectObject] allow adding geometry on new projectObject creation #791

Merged
merged 1 commit into from
Oct 26, 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
63 changes: 42 additions & 21 deletions backend/src/router/projectObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { TRPC } from '@backend/router';

import { nonEmptyString } from '@shared/schema/common';
import {
UpdateGeometry,
UpdateProjectObject,
UpsertProjectObject,
dbProjectObjectSchema,
Expand Down Expand Up @@ -303,9 +304,48 @@ export async function upsertProjectObject(
await updateObjectUsages(tx, { ...projectObject, id: upsertResult.id });
await updateObjectRoles(tx, { ...projectObject, id: upsertResult.id });

if (projectObject.geom) {
updateProjectObjectGeometry(
tx,
{
id: upsertResult.id,
features: projectObject.geom,
},
userId
);
}

return upsertResult;
}

async function updateProjectObjectGeometry(
tx: DatabaseTransactionConnection,
input: UpdateGeometry,
userId: string
) {
const { id, features } = input;

await addAuditEvent(tx, {
eventType: 'projectObject.updateGeometry',
eventData: input,
eventUser: userId,
});

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_object
SET geom = featureCollection.resultGeom
FROM featureCollection
WHERE id = ${id}
RETURNING id, ST_AsGeoJSON(geom) AS geom
`);
}

export const createProjectObjectRouter = (t: TRPC) =>
t.router({
upsert: t.procedure.input(upsertProjectObjectSchema).mutation(async ({ input, ctx }) => {
Expand All @@ -316,27 +356,8 @@ export const createProjectObjectRouter = (t: TRPC) =>
}),

updateGeometry: t.procedure.input(updateGeometrySchema).mutation(async ({ input, ctx }) => {
const { id, features } = input;

return getPool().transaction(async (tx) => {
await addAuditEvent(tx, {
eventType: 'projectObject.updateGeometry',
eventData: input,
eventUser: ctx.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_object
SET geom = featureCollection.resultGeom
FROM featureCollection
WHERE id = ${id}
RETURNING id, ST_AsGeoJSON(geom) AS geom
`);
return await getPool().transaction(async (tx) => {
return await updateProjectObjectGeometry(tx, input, ctx.user.id);
});
}),

Expand Down
15 changes: 12 additions & 3 deletions frontend/src/views/ProjectObject/ProjectObject.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Assignment, Euro, 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 { ReactElement, useMemo } from 'react';
import { ReactElement, useMemo, useState } from 'react';
import { useParams } from 'react-router';
import { Link } from 'react-router-dom';

Expand Down Expand Up @@ -82,6 +82,7 @@ export function ProjectObject(props: Props) {
projectObjectId: string;
tabView?: TabView;
};

const projectObjectId = routeParams?.projectObjectId;
const tabView = routeParams.tabView || 'default';
const tabs = projectObjectTabs(routeParams.projectId, props.projectType, projectObjectId);
Expand All @@ -95,6 +96,8 @@ export function ProjectObject(props: Props) {
{ enabled: Boolean(projectObjectId) }
);

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

const tr = useTranslations();
const notify = useNotifications();
const geometryUpdate = trpc.projectObject.updateGeometry.useMutation({
Expand Down Expand Up @@ -181,6 +184,7 @@ export function ProjectObject(props: Props) {
projectId={routeParams.projectId}
projectType={props.projectType}
projectObject={projectObject.data}
geom={geom}
/>
</Paper>
{/* <Paper sx={{ p: 3 }} variant="outlined">
Expand Down Expand Up @@ -215,6 +219,7 @@ export function ProjectObject(props: Props) {
>
{tabs.map((tab) => (
<Tab
disabled={!projectObject.data}
key={tab.tabView}
component={Link}
to={tab.url}
Expand All @@ -230,11 +235,15 @@ export function ProjectObject(props: Props) {
<MapWrapper
geoJson={projectObject?.data?.geom}
drawStyle={PROJ_OBJ_STYLE}
editable={Boolean(projectObjectId)}
editable={true}
vectorLayers={[projectLayer]}
fitExtent="vectorLayers"
onFeaturesSaved={(features) => {
geometryUpdate.mutate({ id: projectObjectId, features: features });
if (!projectObject.data) {
setGeom(features);
} else {
geometryUpdate.mutate({ id: projectObjectId, features });
}
}}
/>
</Box>
Expand Down
37 changes: 23 additions & 14 deletions frontend/src/views/ProjectObject/ProjectObjectForm.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, Save, Undo } from '@mui/icons-material';
import { Box, Button, InputAdornment, TextField } from '@mui/material';
import { Alert, Box, Button, InputAdornment, TextField } from '@mui/material';
import { useQueryClient } from '@tanstack/react-query';
import dayjs from 'dayjs';
import { useAtomValue } from 'jotai';
Expand All @@ -25,7 +25,6 @@ import { SapWBSSelect } from '@frontend/views/ProjectObject/SapWBSSelect';
import {
UpsertProjectObject,
newProjectObjectSchema,
updateProjectObjectSchema,
upsertProjectObjectSchema,
} from '@shared/schema/projectObject';

Expand All @@ -38,6 +37,7 @@ interface Props {
projectId: string;
projectType: ProjectTypePath;
projectObject?: UpsertProjectObject | null;
geom?: string | null;
}

export function ProjectObjectForm(props: Props) {
Expand Down Expand Up @@ -138,7 +138,9 @@ export function ProjectObjectForm(props: Props) {
},
});

const onSubmit = (data: UpsertProjectObject) => projectObjectUpsert.mutate(data);
const onSubmit = (data: UpsertProjectObject) => {
projectObjectUpsert.mutate({ ...data, geom: props.geom });
};

return (
<FormProvider {...form}>
Expand Down Expand Up @@ -330,17 +332,24 @@ export function ProjectObjectForm(props: Props) {
/>

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

{props.projectObject && 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 @@ -232,6 +232,7 @@
"projectObject.notifyGeometryUpdateTitle": "Kohteen sijainti päivitetty",
"projectObject.notifyGeometryUpdateFailedTitle": "Virhe tallentaessa kohteen sijaintia",
"projectObject.noTasks": "Kohteella ei ole tehtäviä",
"projectObjectForm.infoNoGeom": "Olet luomassa kohdetta ilman aluetta",
"projectObjectForm.createBtnLabel": "Luo kohde",
"projectObjectForm.saveBtnLabel": "Tallenna",
"sessionExpiredWarning.infoText": "Istuntosi on vanhentunut. Jatkaaksesi keskeneräisiä töitäsi, uusi istunto.",
Expand Down
1 change: 1 addition & 0 deletions shared/src/schema/projectObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const newProjectObjectSchema = z.object({
height: z.coerce.number().optional().nullable(),
objectUserRoles: z.array(projectObjectUserRoleSchema),
budgetUpdate: partialBudgetUpdateSchema.optional().nullable(),
geom: z.string().optional().nullable(),
});

export const updateProjectObjectSchema = newProjectObjectSchema.partial().extend({
Expand Down