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

[api] Add cost surface piece exporter and importer [MRXN23-111] [MRXN23-19] [MRXN23-112] [MRXN23-20] #1503

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddClonePieceForProjectCostSurfaces1695040870835
implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TYPE clone_piece_enum ADD VALUE 'project-cost-surfaces'`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TYPE "clone_piece_enum_tmp" AS ENUM(
'export-config',
'project-metadata',
'project-custom-protected-areas',
'planning-area-gadm',
'planning-area-custom',
'planning-area-custom-geojson',
'planning-units-grid',
'planning-units-grid-geojson',
'scenario-metadata',
'scenario-planning-units-data',
'scenario-run-results',
'scenario-protected-areas',
'project-custom-features',
'features-specification',
'scenario-features-data',
'scenario-input-folder',
'scenario-output-folder',
'marxan-execution-metadata',
'project-puvspr-calculations'
);
`);

await queryRunner.query(`
ALTER TABLE export_components
ALTER COLUMN piece TYPE clone_piece_enum_tmp;
`);
await queryRunner.query(`
ALTER TABLE import_components
ALTER COLUMN piece TYPE clone_piece_enum_tmp;
`);

await queryRunner.query(`
DROP TYPE clone_piece_enum;
`);
await queryRunner.query(`
ALTER TYPE clone_piece_enum_tmp RENAME TO clone_piece_enum;
`);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ const getFixtures = async () => {
ClonePiece.PlanningUnitsGrid,
ClonePiece.PlanningUnitsGridGeojson,
ClonePiece.ProjectCustomProtectedAreas,
ClonePiece.ProjectCostSurfaces,
ClonePiece.ProjectCustomFeatures,
ClonePiece.ProjectPuvsprCalculations,
];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export class ExportResourcePiecesAdapter implements ExportResourcePieces {
ExportComponent.newOne(id, ClonePiece.PlanningUnitsGrid),
ExportComponent.newOne(id, ClonePiece.PlanningUnitsGridGeojson),
ExportComponent.newOne(id, ClonePiece.ProjectCustomProtectedAreas),
ExportComponent.newOne(id, ClonePiece.ProjectCostSurfaces),
ExportComponent.newOne(id, ClonePiece.ProjectCustomFeatures),
ExportComponent.newOne(id, ClonePiece.ProjectPuvsprCalculations),
...scenarioPieces,
Expand Down
12 changes: 5 additions & 7 deletions api/apps/api/src/modules/cost-surface/cost-surface.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { CostSurface } from '@marxan-api/modules/cost-surface/cost-surface.api.e
import { Repository } from 'typeorm';
import { ProjectAclService } from '@marxan-api/modules/access-control/projects-acl/project-acl.service';
import { Either, left, right } from 'fp-ts/lib/Either';
import { projectNotEditable, projectNotVisible } from "@marxan-api/modules/projects/projects.service";
import {
projectNotEditable,
projectNotVisible,
} from '@marxan-api/modules/projects/projects.service';
import { UploadCostSurfaceShapefileDto } from '@marxan-api/modules/cost-surface/dto/upload-cost-surface-shapefile.dto';
import { UpdateCostSurfaceDto } from '@marxan-api/modules/cost-surface/dto/update-cost-surface.dto';
import { CostSurfaceCalculationPort } from '@marxan-api/modules/cost-surface/ports/project/cost-surface-calculation.port';
Expand Down Expand Up @@ -149,12 +152,7 @@ export class CostSurfaceService {
CostRange
>
> {
if (
!(await this.projectAclService.canViewProject(
userId,
projectId,
))
) {
if (!(await this.projectAclService.canViewProject(userId, projectId))) {
return left(projectNotVisible);
}
const costRange = await this.costSurfaceRepository.findOne({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ export class ProjectCostSurfaceController {
@UseGuards(JwtAuthGuard)
@ApiParam({
name: 'costSurfaceId',
description: 'The id of the Cost Surface for which to retrieve [min,max] cost range',
description:
'The id of the Cost Surface for which to retrieve [min,max] cost range',
})
@ApiParam({
name: 'projectId',
Expand Down
6 changes: 4 additions & 2 deletions api/apps/api/src/modules/projects/projects.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,10 @@ import { GetScenarioFailure } from '@marxan-api/modules/blm/values/blm-repos';
import stream from 'stream';
import { AppConfig } from '@marxan-api/utils/config.utils';
import { WebshotBasicPdfConfig } from '@marxan/webshot/webshot.dto';
import { ScenariosService } from '@marxan-api/modules/scenarios/scenarios.service';
import {
ScenariosService,
SubmitProtectedAreaError,
} from '@marxan-api/modules/scenarios/scenarios.service';
import {
OutputProjectSummariesService,
outputProjectSummaryNotFound,
Expand All @@ -122,7 +125,6 @@ import {
} from '@marxan-api/modules/projects/protected-area/add-protected-area.service';
import { ensureShapefileHasRequiredFiles } from '@marxan-api/utils/file-uploads.utils';
import { CostSurfaceService } from '@marxan-api/modules/cost-surface/cost-surface.service';

export { validationFailed } from '../planning-areas';

export const projectNotFound = Symbol(`project not found`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { ScenarioOutputFolderPieceExporter } from './scenario-output-folder.piec
import { ScenarioPlanningUnitsDataPieceExporter } from './scenario-planning-units-data.piece-exporter';
import { ScenarioProtectedAreasPieceExporter } from './scenario-protected-areas.piece-exporter';
import { ScenarioRunResultsPieceExporter } from './scenario-run-results.piece-exporter';
import { ProjectCostSurfacesPieceExporter } from '@marxan-geoprocessing/export/pieces-exporters/project-cost-surfaces.piece-exporter';

@Module({
imports: [
Expand All @@ -52,6 +53,7 @@ import { ScenarioRunResultsPieceExporter } from './scenario-run-results.piece-ex
ExportConfigProjectPieceExporter,
ExportConfigScenarioPieceExporter,
ProjectCustomFeaturesPieceExporter,
ProjectCostSurfacesPieceExporter,
PlanningAreaGadmPieceExporter,
PlanningAreaCustomPieceExporter,
PlanningAreaCustomGeojsonPieceExporter,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { geoprocessingConnections } from '@marxan-geoprocessing/ormconfig';
import { ClonePiece, ExportJobInput, ExportJobOutput } from '@marxan/cloning';
import { ComponentLocation, ResourceKind } from '@marxan/cloning/domain';
import { ClonePieceRelativePathResolver } from '@marxan/cloning/infrastructure/clone-piece-data';
import {
ProjectCustomFeature,
ProjectCustomFeaturesContent,
} from '@marxan/cloning/infrastructure/clone-piece-data/project-custom-features';
import { CloningFilesRepository } from '@marxan/cloning-files-repository';
import { GeometrySource } from '@marxan/geofeatures';
import { Injectable, Logger } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import { isLeft } from 'fp-ts/lib/Either';
import { Readable } from 'stream';
import { EntityManager } from 'typeorm';
import {
ExportPieceProcessor,
PieceExportProvider,
} from '../pieces/export-piece-processor';
import { ProjectsPuEntity } from '@marxan-jobs/planning-unit-geometry';
import { ProjectCostSurfacesContent } from '@marxan/cloning/infrastructure/clone-piece-data/project-cost-surfaces';

type CreationStatus = ProjectCustomFeature['creation_status'];

type ProjectCostSurfacesSelectResult = {
id: string;
name: string;
min: number;
max: number;
is_default: boolean;
};

type CostSurfaceDataSelectResult = {
cost_surface_id: string;
cost: number;
projects_pu_id: number;
};

@Injectable()
@PieceExportProvider()
export class ProjectCostSurfacesPieceExporter implements ExportPieceProcessor {
private readonly logger: Logger = new Logger(
ProjectCostSurfacesPieceExporter.name,
);

constructor(
private readonly fileRepository: CloningFilesRepository,
@InjectEntityManager(geoprocessingConnections.apiDB)
private readonly apiEntityManager: EntityManager,
@InjectEntityManager(geoprocessingConnections.default)
private readonly geoprocessingEntityManager: EntityManager,
) {}

isSupported(piece: ClonePiece, kind: ResourceKind): boolean {
return (
piece === ClonePiece.ProjectCostSurfaces && kind === ResourceKind.Project
);
}

async run(input: ExportJobInput): Promise<ExportJobOutput> {
const costSurfaces: ProjectCostSurfacesSelectResult[] = await this.apiEntityManager
.createQueryBuilder()
.select(['cs.id', 'cs.name', 'cs.min', 'cs.max', 'cs.is_default'])
.from('cost_surfaces', 'cs')
.where('cs.project_id = :projectId', { projectId: input.resourceId })
.execute();

const costSurfacesIds = costSurfaces.map((costSurface) => costSurface.id);
let costSurfaceData: CostSurfaceDataSelectResult[] = [];
let projectPusMap: Record<string, number> = {};

if (!costSurfacesIds) {
const errorMessage = `${ProjectCostSurfacesPieceExporter.name} - Project Cost Surfaces - couldn't find cost surfaces for project ${input.resourceId}`;
this.logger.error(errorMessage);
throw new Error(errorMessage);
}
costSurfaceData = await this.geoprocessingEntityManager
.createQueryBuilder()
.select(['cost_surface_id', 'cost', 'projects_pu_id'])
.from('cost_surface_pu_data', 'scpd')
.where('cost_surface_id IN (:...costSurfacesIds)', {
costSurfacesIds,
})
.execute();

projectPusMap = await this.getProjectPusMap(input.resourceId);

const fileContent: ProjectCostSurfacesContent = {
costSurfaces: costSurfaces.map(({ id, ...costSurface }) => ({
...costSurface,
data: costSurfaceData
.filter(
(data: CostSurfaceDataSelectResult) => data.cost_surface_id === id,
)
.map(({ cost_surface_id, projects_pu_id, ...data }) => {
const puid = projectPusMap[projects_pu_id];
return { puid, ...data };
}),
})),
};
Comment on lines +88 to +100
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just a note on style - my recommendation for these kinds of "augmentations" is to use named functions to make what we're doing via array operations (filter, map, etc.), spreads and so on clearer.

In practice here we're combining a lookup of cost surface costs with the setter part of a lens, using lower-level primitives: which is ok and works, but makes even a tiny snippet of code like this less legible than something like const fileContent: ProjectCostSurfacesContent = addCostDataToCostSurfaces(costSurfaces, costSurfaceCostData)

but no need to do anything here! (and as always, these kinds of style comments can be highly opinable)


const relativePath = ClonePieceRelativePathResolver.resolveFor(
ClonePiece.ProjectCostSurfaces,
);

const outputFile = await this.fileRepository.saveCloningFile(
input.exportId,
Readable.from(JSON.stringify(fileContent)),
relativePath,
);

if (isLeft(outputFile)) {
const errorMessage = `${ProjectCostSurfacesPieceExporter.name} - Project Cost Surfaces - couldn't save file - ${outputFile.left.description}`;
this.logger.error(errorMessage);
throw new Error(errorMessage);
}

return {
...input,
uris: [new ComponentLocation(outputFile.right, relativePath)],
};
}

private async getProjectPusMap(
projectId: string,
): Promise<Record<string, number>> {
const projectPus: {
id: string;
puid: number;
}[] = await this.geoprocessingEntityManager
.createQueryBuilder()
.select(['id', 'puid'])
.from(ProjectsPuEntity, 'ppus')
.where('ppus.project_id = :projectId', { projectId })
.execute();

const projectPuIdByPuid: Record<string, number> = {};
projectPus.forEach(({ puid, id }) => {
projectPuIdByPuid[id] = puid;
});

return projectPuIdByPuid;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { ScenarioMetadataPieceImporter } from './scenario-metadata.piece-importe
import { ScenarioPlanningUnitsDataPieceImporter } from './scenario-planning-units-data.piece-importer';
import { ScenarioProtectedAreasPieceImporter } from './scenario-protected-areas.piece-importer';
import { ScenarioRunResultsPieceImporter } from './scenario-run-results.piece-importer';
import { ProjectCostSurfacesPieceImporter } from '@marxan-geoprocessing/import/pieces-importers/project-cost-surfaces.piece-importer';

@Module({
imports: [
Expand All @@ -37,6 +38,7 @@ import { ScenarioRunResultsPieceImporter } from './scenario-run-results.piece-im
PlanningUnitsGridPieceImporter,
ProjectCustomProtectedAreasPieceImporter,
ProjectCustomFeaturesPieceImporter,
ProjectCostSurfacesPieceImporter,
ScenarioProtectedAreasPieceImporter,
ScenarioPlanningUnitsDataPieceImporter,
ScenarioRunResultsPieceImporter,
Expand Down
Loading