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

Add create assignment and get assignments endpoints in Exchange Oracle #1725

Merged
merged 1 commit into from
Mar 19, 2024
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
Expand Up @@ -10,6 +10,7 @@ import { WebhookModule } from './modules/webhook/webhook.module';
import { JwtAuthGuard } from './common/guards/jwt.auth';
import { JwtHttpStrategy } from './common/guards/strategy';
import { Web3Module } from './modules/web3/web3.module';
import { AssignmentModule } from './modules/assignment/assignment.module';

@Module({
providers: [
Expand All @@ -24,6 +25,7 @@ import { Web3Module } from './modules/web3/web3.module';
JwtHttpStrategy,
],
imports: [
AssignmentModule,
JobModule,
WebhookModule,
Web3Module,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ export enum JobStatus {
CANCELED = 'CANCELED',
}

export enum JobSortField {
CHAIN_ID = 'chain_id',
JOB_TYPE = 'job_type',
REWARD_AMOUNT = 'reward_amount',
CREATED_AT = 'created_at',
}

export enum JobFieldName {
JobDescription = 'job_description',
RewardAmount = 'reward_amount',
RewardToken = 'reward_token',
CreatedAt = 'created_at',
}

export enum AssignmentStatus {
ACTIVE = 'ACTIVE',
VALIDATION = 'VALIDATION',
Expand All @@ -13,16 +27,11 @@ export enum AssignmentStatus {
REJECTED = 'REJECTED',
}

export enum JobSortField {
export enum AssignmentSortField {
CHAIN_ID = 'chain_id',
JOB_TYPE = 'job_type',
STATUS = 'status',
REWARD_AMOUNT = 'reward_amount',
CREATED_AT = 'created_at',
}

export enum JobFieldName {
JobDescription = 'job_description',
RewardAmount = 'reward_amount',
RewardToken = 'reward_token',
CreatedAt = 'created_at',
EXPIRES_AT = 'expires_at',
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { NS } from '../../common/constant';
import { MigrationInterface, QueryRunner } from 'typeorm';

export class InitialMigration1710439119068 implements MigrationInterface {
name = 'InitialMigration1710439119068';
export class InitialMigration1710760785464 implements MigrationInterface {
name = 'InitialMigration1710760785464';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createSchema(NS, true);
Expand Down Expand Up @@ -49,6 +49,7 @@ export class InitialMigration1710439119068 implements MigrationInterface {
"job_id" integer NOT NULL,
"worker_address" character varying NOT NULL,
"status" "hmt"."assignments_status_enum" NOT NULL,
"expires_at" TIMESTAMP WITH TIME ZONE NOT NULL,
CONSTRAINT "PK_c54ca359535e0012b04dcbd80ee" PRIMARY KEY ("id")
)
`);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {
Body,
Controller,
Post,
UseGuards,
Request,
Get,
Query,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../common/guards/jwt.auth';
import { AssignmentService } from './assignment.service';
import { CreateAssignmentDto, GetAssignmentsDto } from './assignment.dto';
import { RequestWithUser } from '../../common/types/jwt';

@ApiTags('Assignment')
@Controller('assignment')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class AssignmentController {
constructor(private readonly assignmentService: AssignmentService) {}

@Post()
createAssignment(
@Request() req: RequestWithUser,
@Body() body: CreateAssignmentDto,
): Promise<any> {
return this.assignmentService.createAssignment(body, req.user);
}

@Get()
getJobs(
@Request() req: RequestWithUser,
@Query() query: GetAssignmentsDto,
): Promise<any> {
return this.assignmentService.getAssignmentList(
query,
req.user.reputationNetwork,
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsEnum, IsNumber, IsOptional, IsString } from 'class-validator';
import {
AssignmentStatus,
AssignmentSortField,
JobSortField,
JobStatus,
} from '../../common/enums/job';
import { PageOptionsDto } from '../../common/pagination/pagination.dto';

export class CreateAssignmentDto {
@ApiProperty({ name: 'chain_id' })
@Type(() => Number)
@IsNumber()
chainId: number;

@ApiProperty({ name: 'escrow_address' })
@IsString()
escrowAddress: string;
}

export class GetAssignmentsDto extends PageOptionsDto {
@ApiPropertyOptional({ name: 'chain_id' })
@IsOptional()
@Type(() => Number)
@IsNumber()
chainId: number;

@ApiPropertyOptional({ name: 'job_type' })
@IsOptional()
@IsString()
jobType: string;

@ApiPropertyOptional({ name: 'escrow_address' })
@IsOptional()
@IsString()
escrowAddress: string;

@ApiPropertyOptional({ enum: AssignmentStatus })
@IsEnum(AssignmentStatus)
@IsOptional()
status: AssignmentStatus;

@ApiPropertyOptional({
name: 'sort_field',
enum: JobSortField,
default: JobSortField.CREATED_AT,
})
@IsOptional()
@IsEnum(AssignmentSortField)
sortField?: AssignmentSortField = AssignmentSortField.CREATED_AT;
}

export class AssignmentDto {
assginmentId: number;
escrowAddress: string;
chainId: number;
jobType: string;
status: JobStatus;
url?: string;
rewardAmount: number;
rewardToken: string;
createdAt: number;
updatedAt?: number;
expiresAt: number;

constructor(
assginmentId: number,
escrowAddress: string,
chainId: number,
jobType: string,
status: JobStatus,
rewardAmount: number,
rewardToken: string,
createdAt: number,
expiresAt: number,
) {
this.assginmentId = assginmentId;
this.escrowAddress = escrowAddress;
this.chainId = chainId;
this.jobType = jobType;
this.status = status;
this.rewardAmount = rewardAmount;
this.rewardToken = rewardToken;
this.createdAt = createdAt;
this.expiresAt = expiresAt;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ export class AssignmentEntity extends BaseEntity {
})
public status: AssignmentStatus;

@Column({ type: 'timestamptz' })
public expiresAt: Date;

@ManyToOne(() => JobEntity, (job) => job.assignments, { eager: true })
job: JobEntity;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { SortDirection } from '../../common/enums/collection';
import { AssignmentSortField, AssignmentStatus } from '../../common/enums/job';
import { AssignmentEntity } from './assignment.entity';

export interface AssignmentFilterData {
chainId?: number;
escrowAddress?: string;
status?: AssignmentStatus;
sortField?: AssignmentSortField;
sort?: SortDirection;
skip: number;
pageSize: number;
reputationNetwork: string;
}

export interface ListResult {
entities: AssignmentEntity[];
itemCount: number;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JobEntity } from '../job/job.entity';
import { ConfigModule } from '@nestjs/config';
import { AssignmentController } from './assignment.controller';
import { AssignmentEntity } from './assignment.entity';
import { AssignmentRepository } from './assignment.repository';
import { AssignmentService } from './assignment.service';
import { JobRepository } from '../job/job.repository';
import { JobModule } from '../job/job.module';
import { Web3Module } from '../web3/web3.module';

@Module({
imports: [
TypeOrmModule.forFeature([AssignmentEntity]),
TypeOrmModule.forFeature([JobEntity]),
ConfigModule,
JobModule,
Web3Module,
],
controllers: [AssignmentController],
providers: [AssignmentService, AssignmentRepository, JobRepository],
exports: [AssignmentService],
})
export class AssignmentModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DataSource } from 'typeorm';
import { BaseRepository } from '../../database/base.repository';
import { AssignmentEntity } from './assignment.entity';
import { ChainId } from '@human-protocol/sdk';
import { AssignmentFilterData, ListResult } from './assignment.interface';
import { AssignmentSortField } from 'src/common/enums/job';

@Injectable()
export class AssignmentRepository extends BaseRepository<AssignmentEntity> {
constructor(
private dataSource: DataSource,
public readonly configService: ConfigService,
) {
super(AssignmentEntity, dataSource);
}

public async findOneByJobIdAndWorker(
jobId: ChainId,
workerAddress: string,
): Promise<AssignmentEntity | null> {
return this.findOne({
where: {
jobId,
workerAddress,
},
});
}

public async countByJobId(jobId: ChainId): Promise<number> {
return this.count({
where: {
jobId,
},
});
}

public async fetchFiltered(data: AssignmentFilterData): Promise<ListResult> {
const queryBuilder = await this.createQueryBuilder(
'assignment',
).leftJoinAndSelect('assignment.job', 'job', 'assignment.jobId = job.id');

if (data.sortField == AssignmentSortField.CHAIN_ID)
queryBuilder.orderBy(`job.${data.sortField}`, data.sort);
else if (data.sortField == AssignmentSortField.CREATED_AT)
queryBuilder.orderBy(`assignment.${data.sortField}`, data.sort);
else if (data.sortField == AssignmentSortField.STATUS)
queryBuilder.orderBy(`assignment.${data.sortField}`, data.sort);
else if (data.sortField == AssignmentSortField.EXPIRES_AT)
queryBuilder.orderBy(`assignment.${data.sortField}`, data.sort);

if (data.chainId !== undefined) {
queryBuilder.andWhere('job.chainId = :chainId', {
chainId: data.chainId,
});
}
if (data.escrowAddress) {
queryBuilder.andWhere('job.escrowAddress = :escrowAddress', {
escrowAddress: data.escrowAddress,
});
}
if (data.status !== undefined) {
queryBuilder.andWhere('assignment.status = :status', {
status: data.status,
});
}

queryBuilder.andWhere('job.reputationNetwork = :reputationNetwork', {
reputationNetwork: data.reputationNetwork,
});

queryBuilder.offset(data.skip).limit(data.pageSize);

const itemCount = await queryBuilder.getCount();
const { entities } = await queryBuilder.getRawAndEntities();

return { entities, itemCount };
}
}
Loading