Skip to content

Commit

Permalink
Merge pull request #102 from Samagra-Anamaya/admin-apis
Browse files Browse the repository at this point in the history
Admin apis
  • Loading branch information
dhruv-1001 authored Nov 30, 2023
2 parents 15ac85d + f6140d9 commit 850747a
Show file tree
Hide file tree
Showing 9 changed files with 5,090 additions and 249 deletions.
5,036 changes: 4,815 additions & 221 deletions package-lock.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- AlterEnum
ALTER TYPE "SubmissionStatus" ADD VALUE 'FLAGGED';

-- CreateTable
CREATE TABLE "Feedback" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"count" INTEGER NOT NULL DEFAULT 1,
"feedbackData" JSONB NOT NULL,
"feedbackHistory" JSONB[],
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updateAt" TIMESTAMP(3) NOT NULL,
"submissionId" UUID NOT NULL,

CONSTRAINT "Feedback_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "Feedback" ADD CONSTRAINT "Feedback_submissionId_fkey" FOREIGN KEY ("submissionId") REFERENCES "Submission"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
15 changes: 14 additions & 1 deletion packages/bff/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ enum SubmissionStatus {
SUBMITTED
VERIFIED
PROCESSING
FLAGGED
FAILED
}

model Submission {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
submitterId String
submissionData Json
createdAt DateTime @default(now())
Expand All @@ -31,6 +32,18 @@ model Submission {
citizenId String?
errors Json?
meta Json?
Feedback Feedback[]
}

model Feedback {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
count Int @default(1)
feedbackData Json
feedbackHistory Json[]
createdAt DateTime @default(now())
updateAt DateTime @updatedAt
submission Submission @relation(fields: [submissionId], references: [id])
submissionId String @db.Uuid
}

enum defaultPassword {
Expand Down
9 changes: 4 additions & 5 deletions packages/bff/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { CustomLogger } from './common/logger';
import { SubmissionModule } from './submission/submission.module';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { ConfigModule } from '@nestjs/config';
import { MinioModule } from './minio/minio.module';
import { UploadService } from './upload/upload.service';
Expand Down Expand Up @@ -43,10 +42,10 @@ import { HttpModule } from '@nestjs/axios';
// EnumeratorModule,
//ScheduleModule,
UtilsModule,
EventEmitterModule.forRoot({
maxListeners: 50,
verboseMemoryLeak: true,
}),
// EventEmitterModule.forRoot({
// maxListeners: 50,
// verboseMemoryLeak: true,
// }),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'your-secret-key', // Change this to your secret key
Expand Down
53 changes: 52 additions & 1 deletion packages/bff/src/submission/dto/submission.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsInt, IsString, Min } from 'class-validator';
import { SubmissionStatus } from '@prisma/client';
import { IsEnum, IsIn, IsInt, IsString, Min } from 'class-validator';
export enum Gender {
male = 'male',
female = 'female',
Expand Down Expand Up @@ -57,6 +58,27 @@ export class GetAllSubmissionsDto {
})
@Min(1)
limit: number = 10;

@IsEnum(SubmissionStatus)
@ApiProperty({
description: 'Submission status',
example: 'SUBMITTED',
})
status: SubmissionStatus = undefined;

@IsIn(['createdAt', 'capturedAt', 'updatedAt'])
@ApiProperty({
description: 'Sort by createdAt, capturedAt, updatedAt',
example: 'createdAt',
})
sortBy: string = 'createdAt';

@IsIn(['asc', 'desc'])
@ApiProperty({
description: 'Sort order asc, desc',
example: 'desc',
})
order: string = 'desc';
}

// citizen.dto.ts
Expand Down Expand Up @@ -94,4 +116,33 @@ class BulkSubmissionDto {
villageId_2: CreateSubmissionDto[];
}

export class SubmissionQueryDto {
@IsString()
page: string;

@IsString()
limit: string;

@IsEnum(SubmissionStatus)
@ApiProperty({
description: 'Submission status',
example: 'SUBMITTED',
})
status: SubmissionStatus = undefined;

@IsIn(['createdAt', 'capturedAt', 'updatedAt'])
@ApiProperty({
description: 'Sort by createdAt, capturedAt, updatedAt',
example: 'createdAt',
})
sortBy: string = 'createdAt';

@IsIn(['asc', 'desc'])
@ApiProperty({
description: 'Sort order asc, desc',
example: 'desc',
})
order: string = 'desc';
}

export { BulkSubmissionDto };
28 changes: 22 additions & 6 deletions packages/bff/src/submission/submission.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
BulkSubmissionDto,
CreateSubmissionDto,
GetAllSubmissionsDto,
SubmissionQueryDto,
UpdateSubmissionDto,
} from './dto/submission.dto';
import { PrismaExceptionFilter } from 'src/exceptions/exception-filter';
Expand Down Expand Up @@ -58,8 +59,13 @@ export class SubmissionController {
try {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;

return this.submissionService.getSubmissions(page, limit);
return this.submissionService.getSubmissions(
page,
limit,
query.status,
query.sortBy,
query.order,
);
} catch (error) {
this.logger.error(error);
throw error;
Expand All @@ -69,12 +75,11 @@ export class SubmissionController {
@Get(':id')
async getSubmissionByVillageId(
@Param('id') id: number,
@Query('page') page: string,
@Query('limit') limit: string,
@Query() submissionQuery: SubmissionQueryDto,
): Promise<any> {
const validatedId = Number(id);
const validatedPage = Number(page) || 1;
const validatedLimit = Number(limit) || 10;
const validatedPage = Number(submissionQuery.page) || 1;
const validatedLimit = Number(submissionQuery.limit) || 10;

if (isNaN(validatedId) || isNaN(validatedPage) || isNaN(validatedLimit)) {
throw new BadRequestException('Invalid input parameters');
Expand All @@ -84,6 +89,9 @@ export class SubmissionController {
validatedId,
validatedPage,
validatedLimit,
submissionQuery.status,
submissionQuery.sortBy,
submissionQuery.order,
);
}

Expand Down Expand Up @@ -190,6 +198,14 @@ export class SubmissionController {
return await this.submissionService.raiseSubmissionFlag({ id, details });
}

@Post('/:id/submitFeedback')
async submitFeedback(
@Param('id') id: string,
@Body() feedbackDto: any,
): Promise<any> {
return await this.submissionService.saveFeedback(id, feedbackDto);
}

@Delete('deleteAll')
async deleteSubmission(): Promise<any> {
return this.submissionService.deleteAllSubmission();
Expand Down
83 changes: 76 additions & 7 deletions packages/bff/src/submission/submission.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { CustomLogger } from 'src/common/logger';
import { PrismaService } from 'src/prisma/prisma.service';
import { map } from 'lodash';
import * as bcrypt from 'bcrypt';
import { SubmissionStatus } from '@prisma/client';

@Injectable()
export class SubmissionService {
Expand Down Expand Up @@ -165,15 +166,29 @@ export class SubmissionService {
}
}

async getSubmissions(page: number, pageSize: number) {
async getSubmissions(
page: number,
pageSize: number,
status: SubmissionStatus,
sortBy: string,
order: string,
) {
const skip = (page - 1) * pageSize;
const orderBy = { [sortBy]: order };
const submissions = await this.prisma.submission.findMany({
where: {
status: status,
},
skip,
take: pageSize,
orderBy: { createdAt: 'desc' }, // Change to 'asc' for ascending order
orderBy: orderBy, // Change to 'asc' for ascending order
});
const totalCount = await this.prisma.submission.count({
where: {
status: status,
},
});

const totalCount = await this.prisma.submission.count();
return {
result: {
submissions,
Expand All @@ -188,6 +203,9 @@ export class SubmissionService {
id: number,
page: number,
pageSize: number,
status: SubmissionStatus,
sortBy: string,
order: string,
): Promise<any> {
const village = await this.prisma.villageData.findFirst({
where: { spdpVillageId: id },
Expand All @@ -197,16 +215,20 @@ export class SubmissionService {
throw new NotFoundException(`Village with spdpVillageId ${id} not found`);
}
const skip = (page - 1) * pageSize;

const orderBy = { [sortBy]: order };
const searchQuery = {
spdpVillageId: id,
status: status,
};
const [submissions, total] = await Promise.all([
this.prisma.submission.findMany({
where: { spdpVillageId: id },
where: searchQuery,
skip,
take: pageSize,
orderBy: { createdAt: 'desc' },
orderBy: orderBy,
}),
this.prisma.submission.count({
where: { spdpVillageId: id },
where: searchQuery,
}),
]);

Expand Down Expand Up @@ -337,4 +359,51 @@ export class SubmissionService {
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

async saveFeedback(id: string, feedbackBody: any) {
const submission = await this.prisma.submission.findFirst({
where: {
id,
},
});
if (!submission) {
throw new NotFoundException(`Submission with id: ${id} not found`);
}
const savedFeedback = await this.prisma.feedback.findFirst({
where: {
submissionId: id,
},
});
let feedback;
if (!savedFeedback) {
feedback = await this.prisma.feedback.create({
data: {
submissionId: id,
feedbackData: feedbackBody,
feedbackHistory: [],
},
});
} else {
savedFeedback.feedbackHistory.push(savedFeedback.feedbackData);
feedback = await this.prisma.feedback.updateMany({
where: {
submissionId: id,
},
data: {
count: { increment: 1 },
feedbackData: feedbackBody,
feedbackHistory: savedFeedback.feedbackHistory,
},
});
}
await this.prisma.submission.update({
where: {
id,
},
data: {
status: SubmissionStatus.FLAGGED,
},
});
return feedback;
}
}
Loading

0 comments on commit 850747a

Please sign in to comment.