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

Feat/marxan 1471 allow cloning published projects #1010

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
4 changes: 4 additions & 0 deletions api/apps/api/src/modules/clone/export/domain/export/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,8 @@ export class Export extends AggregateRoot {
#allPiecesReady = () => this.pieces.every((piece) => piece.isReady());

isCloning = () => Boolean(this.importResourceId);

isForProject() {
return this.resourceKind === ResourceKind.Project;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ export class ImportId {
static create(): ImportId {
return new ImportId(v4());
}

toString() {
return this.value;
}
}
14 changes: 14 additions & 0 deletions api/apps/api/src/modules/projects/dto/export.project.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,17 @@ export class RequestProjectCloneResponseDto {
})
projectId!: string;
}

export class RequestPublishedProjectCloneResponseDto {
@ApiProperty({
description: 'ID of the import',
example: '6fbec34e-04a7-4131-be14-c245f2435a6c',
})
importId!: string;

@ApiProperty({
description: 'ID of the new project',
example: '6fbec34e-04a7-4131-be14-c245f2435a6c',
})
projectId!: string;
}
9 changes: 2 additions & 7 deletions api/apps/api/src/modules/projects/projects.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,16 @@ import {
} from '@marxan-api/decorators/acl.decorator';
import { locationNotFound } from '@marxan-api/modules/clone/export/application/get-archive.query';
import {
RequestProjectExportResponseDto,
RequestProjectExportBodyDto,
GetLatestExportResponseDto,
RequestProjectCloneResponseDto,
RequestProjectExportBodyDto,
RequestProjectExportResponseDto,
} from './dto/export.project.dto';
import { ScenarioLockResultPlural } from '@marxan-api/modules/access-control/scenarios-acl/locks/dto/scenario.lock.dto';
import { RequestProjectImportResponseDto } from './dto/import.project.response.dto';
import {
unknownError as fileRepositoryUnknownError,
fileNotFound,
} from '@marxan/cloning-files-repository';
import { ProxyService } from '@marxan-api/modules/proxy/proxy.service';
import { TilesOpenApi } from '@marxan/tiles';
import { mapAclDomainToHttpError } from '@marxan-api/utils/acl.utils';
import { scenarioResource } from '@marxan-api/modules/scenarios/scenario.api.entity';
import { invalidExportZipFile } from '../clone/infra/import/generate-export-from-zip-file.command';

@UseGuards(JwtAuthGuard)
Expand Down
2 changes: 1 addition & 1 deletion api/apps/api/src/modules/projects/projects.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,6 @@ import { TypeormExportRepository } from '../clone/export/adapters/typeorm-export
ProjectsController,
],
// @ToDo Remove TypeOrmModule after project publish will stop use the ProjectRepository
exports: [ProjectsCrudService, TypeOrmModule],
exports: [ProjectsCrudService, TypeOrmModule, ProjectsService],
})
export class ProjectsModule {}
34 changes: 33 additions & 1 deletion api/apps/api/src/modules/projects/projects.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ import {
GenerateExportFromZipFile,
GenerateExportFromZipFileError,
} from '../clone/infra/import/generate-export-from-zip-file.command';
import { unknownError } from '@marxan/cloning-files-repository';
import {
ImportProject,
ImportProjectCommandResult,
Expand All @@ -77,6 +76,14 @@ export const notFound = Symbol(`project not found`);
export const exportNotFound = Symbol(`project export not found`);
export const apiEventDataNotFound = Symbol(`missing data in api event`);

// Check where to centralize this symbols
export const exportResourceKindIsNotProject = Symbol(
`export is not for a project`,
);
export const exportIsNotStandalone = Symbol(`export is not standalone`);
export const projectIsNotPublished = Symbol(`project is not published`);
export const projectNotFoundForExport = Symbol(`project not found`);

@Injectable()
export class ProjectsService {
constructor(
Expand Down Expand Up @@ -328,6 +335,14 @@ export class ProjectsService {
return right(void 0);
}

async find(projectId: string): Promise<Project | undefined> {
try {
return this.projectsCrud.getById(projectId);
} catch {
return undefined;
}
}

async updateBlmValues(
projectId: string,
userId: string,
Expand Down Expand Up @@ -381,6 +396,23 @@ export class ProjectsService {
return right(res);
}

async clone(
exportId: ExportId,
userId: UserId,
): Promise<Either<any, ImportProjectCommandResult>> {
const exportInstance = await this.exportRepository.find(exportId);
if (!exportInstance) return left(exportNotFound);
if (!exportInstance.isForProject())
return left(exportResourceKindIsNotProject);
if (exportInstance.importResourceId) return left(exportIsNotStandalone);

const project = await this.find(exportInstance.resourceId.value);
if (!project) return left(projectNotFoundForExport);
if (!project.isPublic) return left(projectIsNotPublished);

return this.commandBus.execute(new ImportProject(exportId, userId));
}

async remove(
projectId: string,
userId: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ import {
import {
accessDenied,
alreadyPublished,
sameUnderModerationStatus,
internalError,
notFound,
PublishedProjectService,
notPublished,
PublishedProjectService,
sameUnderModerationStatus,
underModerationError,
} from '../published-project.service';
import { JwtAuthGuard } from '@marxan-api/guards/jwt-auth.guard';
Expand Down Expand Up @@ -55,6 +55,11 @@ import {
} from 'nestjs-base-service';
import { PublishedProjectSerializer } from '../published-project.serializer';
import { PublishProjectDto } from '../dto/publish-project.dto';
import { RequestPublishedProjectCloneResponseDto } from '@marxan-api/modules/projects/dto/export.project.dto';
import { ProjectsService } from '@marxan-api/modules/projects/projects.service';
import { ExportId } from '@marxan-api/modules/clone';
import { UserId } from '@marxan/domain-ids';
import { mapAclDomainToHttpError } from '@marxan-api/utils/acl.utils';

@IsMissingAclImplementation()
@UseGuards(JwtAuthGuard)
Expand All @@ -65,6 +70,7 @@ export class PublishProjectController {
constructor(
private readonly publishedProjectService: PublishedProjectService,
private readonly serializer: PublishedProjectSerializer,
private readonly projectsService: ProjectsService,
) {}

@Post(':id/publish')
Expand Down Expand Up @@ -278,4 +284,34 @@ export class PublishProjectController {

return await this.serializer.serialize(result.right);
}

@ApiNotFoundResponse()
@ApiOperation({
description:
'Clones a public project and makes the user the owner of the new project.',
})
@ApiOkResponse({ type: RequestPublishedProjectCloneResponseDto })
@Post('published-projects/:exportId/clone')
async clone(
@Req() req: RequestWithAuthenticatedUser,
@Param('exportId') exportId: string,
): Promise<RequestPublishedProjectCloneResponseDto> {
const cloneResult = await this.projectsService.clone(
new ExportId(exportId),
new UserId(req.user.id),
);

if (isLeft(cloneResult)) {
throw mapAclDomainToHttpError(cloneResult.left, {
userId: req.user.id,
resourceType: projectResource.name.plural,
exportId,
});
}

return {
importId: cloneResult.right.importId,
projectId: cloneResult.right.projectId,
};
}
}
38 changes: 36 additions & 2 deletions api/apps/api/src/utils/acl.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,22 @@ import {
unknownPngWebshotError,
} from '@marxan/webshot';
import { notFound as notFoundSpec } from '@marxan-api/modules/scenario-specification/application/last-updated-specification.query';
import { projectIsMissingInfoForRegularPus } from '@marxan-api/modules/projects/projects.service';
import {
exportIsNotStandalone,
exportNotFound,
exportResourceKindIsNotProject,
projectIsMissingInfoForRegularPus,
projectIsNotPublished,
projectNotFoundForExport,
} from '@marxan-api/modules/projects/projects.service';

interface ErrorHandlerOptions {
projectId?: string;
range?: [number, number];
resourceType?: string;
scenarioId?: string;
userId?: string;
exportId?: string;
}

export const mapAclDomainToHttpError = (
Expand Down Expand Up @@ -105,7 +113,12 @@ export const mapAclDomainToHttpError = (
| typeof bestSolutionNotFound
| typeof unknownPdfWebshotError
| typeof unknownPngWebshotError
| typeof unknownError,
| typeof unknownError
| typeof exportNotFound
| typeof exportResourceKindIsNotProject
| typeof exportIsNotStandalone
| typeof projectNotFoundForExport
| typeof projectIsNotPublished,
options?: ErrorHandlerOptions,
) => {
switch (errorToCheck) {
Expand Down Expand Up @@ -213,6 +226,27 @@ export const mapAclDomainToHttpError = (
return new NotFoundException(
`Could not find spec for scenario with ID: ${options?.scenarioId}.`,
);

case exportNotFound:
return new NotFoundException(
`Could not find export with ID: ${options?.exportId}`,
);
case exportResourceKindIsNotProject:
return new BadRequestException(
`Export with ID ${options?.exportId} is not a project export`,
);
case exportIsNotStandalone:
return new BadRequestException(
`Export with ID ${options?.exportId} is not a standalone export`,
);
case projectNotFoundForExport:
return new NotFoundException(
`Project not found for export with ID ${options?.exportId}`,
);
case projectIsNotPublished:
return new ForbiddenException(
`Trying to clone project export with ID ${options?.exportId} which is not a published project`,
);
default:
const _exhaustiveCheck: never = errorToCheck;
return _exhaustiveCheck;
Expand Down
2 changes: 1 addition & 1 deletion api/apps/api/test/project/import-project.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ export const getFixtures = async () => {
}, 6000);
},
);
expect(res!.data?.importId).toEqual(importId.value);
expect(res.data?.importId).toEqual(importId.value);
},
};
};
Loading