Skip to content

Commit

Permalink
Merge pull request #183 from credebl/159-develop-display-all-schema-list
Browse files Browse the repository at this point in the history
feat: get all ecosystem's schema
  • Loading branch information
KulkarniShashank authored Oct 30, 2023
2 parents a1147b3 + d28bf6d commit 36bd811
Show file tree
Hide file tree
Showing 9 changed files with 227 additions and 4 deletions.
38 changes: 38 additions & 0 deletions apps/api-gateway/src/ecosystem/ecosystem.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,44 @@ export class EcosystemController {
return res.status(HttpStatus.OK).json(finalResponse);
}

@Get('/:ecosystemId/schema')
@ApiOperation({ summary: 'Get all ecosystem schema', description: 'Get all ecosystem schema' })
@ApiResponse({ status: 200, description: 'Success', type: ApiResponseDto })
@UseGuards(AuthGuard('jwt'), EcosystemRolesGuard, OrgRolesGuard)
@ApiBearerAuth()
@EcosystemsRoles(EcosystemRoles.ECOSYSTEM_OWNER, EcosystemRoles.ECOSYSTEM_LEAD, EcosystemRoles.ECOSYSTEM_MEMBER)
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN, OrgRoles.ISSUER, OrgRoles.VERIFIER, OrgRoles.MEMBER)
@ApiQuery({
name: 'pageNumber',
type: Number,
required: false
})
@ApiQuery({
name: 'search',
type: String,
required: false
})
@ApiQuery({
name: 'pageSize',
type: Number,
required: false
})
async getAllEcosystemSchemas(
@Param('ecosystemId') ecosystemId: string,
@Param('orgId') orgId: string,
@Query() getAllEcosystemSchemaDto: GetAllEcosystemInvitationsDto,
@Res() res: Response
): Promise<Response> {

const schemaList = await this.ecosystemService.getAllEcosystemSchemas(ecosystemId, orgId, getAllEcosystemSchemaDto);
const finalResponse: IResponseType = {
statusCode: HttpStatus.OK,
message: ResponseMessages.ecosystem.success.allschema,
data: schemaList.response
};
return res.status(HttpStatus.OK).json(finalResponse);
}

@Get('/:orgId')
@ApiOperation({ summary: 'Get all organization ecosystems', description: 'Get all existing ecosystems of an specific organization' })
@ApiResponse({ status: 200, description: 'Success', type: ApiResponseDto })
Expand Down
10 changes: 10 additions & 0 deletions apps/api-gateway/src/ecosystem/ecosystem.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,16 @@ export class EcosystemService extends BaseService {
return this.sendNats(this.serviceProxy, 'get-endorsement-transactions', payload);
}

async getAllEcosystemSchemas(
ecosystemId: string,
orgId: string,
getAllEcosystemSchemaDto: GetAllEcosystemInvitationsDto
): Promise<{ response: object }> {
const { pageNumber, pageSize, search } = getAllEcosystemSchemaDto;
const payload = { ecosystemId, orgId, pageNumber, pageSize, search };
return this.sendNats(this.serviceProxy, 'get-all-ecosystem-schemas', payload);
}


async schemaEndorsementRequest(requestSchemaPayload: RequestSchemaDto, orgId: number, ecosystemId: string): Promise<object> {
const payload = { requestSchemaPayload, orgId, ecosystemId };
Expand Down
9 changes: 9 additions & 0 deletions apps/ecosystem/interfaces/endorsements.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,13 @@ export interface GetEndorsementsPayload {
pageSize: number;
search: string;
type: string;
}

export interface GetAllSchemaList {
ecosystemId: string;
orgId: string;
status: string;
pageNumber: number;
pageSize: number;
search: string;
}
10 changes: 10 additions & 0 deletions apps/ecosystem/src/ecosystem.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,16 @@ export class EcosystemController {
);
}


@MessagePattern({ cmd: 'get-all-ecosystem-schemas' })
async getAllEcosystemSchemas(
@Body() payload: GetEndorsementsPayload
): Promise<object> {
return this.ecosystemService.getAllEcosystemSchemas(
payload
);
}

@MessagePattern({ cmd: 'delete-ecosystem-invitations' })
async deleteInvitation(
@Body() payload: { invitationId: string }
Expand Down
85 changes: 84 additions & 1 deletion apps/ecosystem/src/ecosystem.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { SaveSchema, SchemaTransactionResponse, saveCredDef } from '../interface
import { ResponseMessages } from '@credebl/common/response-messages';
import { NotFoundException } from '@nestjs/common';
import { CommonConstants } from '@credebl/common/common.constant';
import { GetAllSchemaList } from '../interfaces/endorsements.interface';
// eslint-disable-next-line camelcase

@Injectable()
Expand Down Expand Up @@ -568,6 +569,66 @@ export class EcosystemRepository {
}
}


async getAllEcosystemSchemasDetails(payload: GetAllSchemaList): Promise<{
schemasCount: number;
schemasResult: {
createDateTime: Date;
createdBy: number;
name: string;
version: string;
attributes: string;
schemaLedgerId: string;
publisherDid: string;
issuerId: string;
orgId: number;
}[];
}> {
try {
const { ecosystemId, search, pageNumber, pageSize } = payload;

const schemaDetails = await this.prisma.endorsement_transaction.findMany({
where: {
type: endorsementTransactionType.SCHEMA,
status: endorsementTransactionStatus.SUBMITED,
ecosystemOrgs: {
ecosystem: {
id: ecosystemId
}
}
}
});

const schemaArray = [];
schemaDetails.map((schemaData) => schemaArray.push(schemaData.resourceId));

const schemasResult = await this.prisma.schema.findMany({
where: {
OR: [
{ version: { contains: search, mode: 'insensitive' } },
{ name: { contains: search, mode: 'insensitive' } },
{ schemaLedgerId: { contains: search, mode: 'insensitive' } }
],
schemaLedgerId: {
in: schemaArray
}
},
take: Number(pageSize),
skip: (pageNumber - 1) * pageSize,
orderBy: {
createDateTime: 'desc'
}
});
const schemasCount = schemaArray.length;

return { schemasCount, schemasResult };

} catch (error) {
this.logger.error(`error: ${JSON.stringify(error)}`);
throw error;
}
}

/**
* Description: Get getAgentEndPoint by orgId
* @param orgId
Expand Down Expand Up @@ -674,7 +735,8 @@ export class EcosystemRepository {
ecosystemOrgId,
responsePayload: '',
type,
requestBody
requestBody,
resourceId: ''
}
});
} catch (error) {
Expand Down Expand Up @@ -805,6 +867,27 @@ export class EcosystemRepository {
}
}

async updateResourse(
endorsementId: string,
resourceId: string
// eslint-disable-next-line camelcase,
): Promise<object> {
try {
const updatedTransaction = await this.prisma.endorsement_transaction.update({
where: { id: endorsementId },
data: {
resourceId
}
});

return updatedTransaction;

} catch (error) {
this.logger.error(`Error in updating endorsement transaction: ${error.message}`);
throw error;
}
}

async saveSchema(schemaResult: SaveSchema): Promise<schema> {
try {
const { name, version, attributes, schemaLedgerId, issuerId, createdBy, lastChangedBy, publisherDid, orgId, ledgerId } = schemaResult;
Expand Down
61 changes: 60 additions & 1 deletion apps/ecosystem/src/ecosystem.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { EcosystemOrgStatus, EcosystemRoles, endorsementTransactionStatus, endor
import { FetchInvitationsPayload } from '../interfaces/invitations.interface';
import { EcosystemMembersPayload } from '../interfaces/ecosystemMembers.interface';
import { CreateEcosystem, CredDefMessage, RequestCredDeffEndorsement, RequestSchemaEndorsement, SaveSchema, SchemaMessage, SignedTransactionMessage, saveCredDef, submitTransactionPayload } from '../interfaces/ecosystem.interfaces';
import { GetEndorsementsPayload } from '../interfaces/endorsements.interface';
import { GetAllSchemaList, GetEndorsementsPayload } from '../interfaces/endorsements.interface';
import { CommonConstants } from '@credebl/common/common.constant';
// eslint-disable-next-line camelcase
import { credential_definition, org_agents, platform_config, schema, user } from '@prisma/client';
Expand Down Expand Up @@ -812,6 +812,13 @@ export class EcosystemService {
await this.updateTransactionStatus(endorsementId);

if (endorsementTransactionPayload.type === endorsementTransactionType.SCHEMA) {

const updateSchemaId = await this._updateResourceId(endorsementId, endorsementTransactionType.SCHEMA, submitTransactionRequest);

if (!updateSchemaId) {

throw new InternalServerErrorException(ResponseMessages.ecosystem.error.updateSchemaId);
}
return this.handleSchemaSubmission(endorsementTransactionPayload, ecosystemMemberDetails, submitTransactionRequest);
} else if (endorsementTransactionPayload.type === endorsementTransactionType.CREDENTIAL_DEFINITION) {

Expand All @@ -830,7 +837,12 @@ export class EcosystemService {

throw new InternalServerErrorException(ResponseMessages.ecosystem.error.sumbitTransaction);
}
const updateCredDefId = await this._updateResourceId(endorsementId, endorsementTransactionType.CREDENTIAL_DEFINITION, submitTransactionRequest);

if (!updateCredDefId) {

throw new InternalServerErrorException(ResponseMessages.ecosystem.error.updateCredDefId);
}
return this.handleCredDefSubmission(endorsementTransactionPayload, ecosystemMemberDetails, submitTransactionRequest);
}
} catch (error) {
Expand Down Expand Up @@ -863,6 +875,26 @@ export class EcosystemService {
}
}

async _updateResourceId(endorsementId: string, transactionType: endorsementTransactionType, transactionDetails: object): Promise<object> {
try {
// eslint-disable-next-line prefer-destructuring
const message = transactionDetails['message'];
if (!message) {
throw new InternalServerErrorException(ResponseMessages.ecosystem.error.invalidMessage);
}

const resourceId = message[transactionType === endorsementTransactionType.SCHEMA ? 'schemaId' : 'credentialDefinitionId'];

if (!resourceId) {
throw new Error(`${ResponseMessages.ecosystem.error.invalidTransactionMessage} Missing "${transactionType === endorsementTransactionType.SCHEMA ? 'schemaId' : 'credentialDefinitionId'}" property.`);
}

return await this.ecosystemRepository.updateResourse(endorsementId, resourceId);
} catch (error) {
this.logger.error(`Error updating resource ID: ${JSON.stringify(error)}`);
}
}


async getAgentUrl(
orgAgentTypeId: number,
Expand Down Expand Up @@ -983,6 +1015,33 @@ export class EcosystemService {
}
}


async getAllEcosystemSchemas(ecosystemSchemas: GetAllSchemaList): Promise<object> {
try {

const response = await this.ecosystemRepository.getAllEcosystemSchemasDetails(ecosystemSchemas);

const schemasDetails = response?.schemasResult.map(schemaAttributeItem => {
const attributes = JSON.parse(schemaAttributeItem.attributes);
return { ...schemaAttributeItem, attributes };
});

const schemasResponse = {
totalItems: response.schemasCount,
hasNextPage: ecosystemSchemas.pageSize * ecosystemSchemas.pageNumber < response.schemasCount,
hasPreviousPage: 1 < ecosystemSchemas.pageNumber,
nextPage: ecosystemSchemas.pageNumber + 1,
previousPage: ecosystemSchemas.pageNumber - 1,
lastPage: Math.ceil(response.schemasCount / ecosystemSchemas.pageSize),
data: schemasDetails
};
return schemasResponse;
} catch (error) {
this.logger.error(`In error fetching all ecosystem schemas: ${JSON.stringify(error)}`);
throw new InternalServerErrorException(error);
}
}

/**
* @returns EndorsementTransaction Status message
*/
Expand Down
9 changes: 7 additions & 2 deletions libs/common/src/response-messages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,8 @@ export const ResponseMessages = {
fetchEndorsors: 'Endorser transactions fetched successfully',
DeclineEndorsementTransaction: 'Decline endorsement request successfully',
AutoEndorsementTransaction: 'The flag for transactions has been successfully set',
fetchMembers: 'Ecosystem members fetched successfully'
fetchMembers: 'Ecosystem members fetched successfully',
allschema: 'Schema details fetched sucessfully'
},
error: {
notCreated: 'Error while creating ecosystem',
Expand Down Expand Up @@ -240,7 +241,11 @@ export const ResponseMessages = {
invalidAgentUrl: 'Invalid agent url',
EndorsementTransactionNotFoundException: 'Endorsement transaction with status requested not found',
OrgOrEcosystemNotFoundExceptionForEndorsementTransaction: 'The endorsement transaction status cant be updated',
ecosystemOrgAlready: 'Organization is already part of the ecosystem. Please ensure that the organization is not duplicated.'
ecosystemOrgAlready: 'Organization is already part of the ecosystem. Please ensure that the organization is not duplicated.',
updateSchemaId: 'Error while updating the schema id',
updateCredDefId: 'Error while updating the credential-definition',
invalidMessage: 'Invalid transaction details. Missing "message" property.',
invalidTransactionMessage: 'Invalid transaction details'
}
},
bulkIssuance: {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `resourceId` to the `endorsement_transaction` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "endorsement_transaction" ADD COLUMN "resourceId" TEXT NOT NULL;
1 change: 1 addition & 0 deletions libs/prisma-service/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,7 @@ model endorsement_transaction {
status String
ecosystemOrgId String
requestBody Json?
resourceId String?
ecosystemOrgs ecosystem_orgs @relation(fields: [ecosystemOrgId], references: [id])
}

Expand Down

0 comments on commit 36bd811

Please sign in to comment.