diff --git a/src/analytics/analytics.integration.spec.ts b/src/analytics/analytics.integration.spec.ts index 77b7ec5..5cb01c3 100644 --- a/src/analytics/analytics.integration.spec.ts +++ b/src/analytics/analytics.integration.spec.ts @@ -90,8 +90,8 @@ describe('Analytics SQL aggregation (integration)', () => { const configService = { get: () => ({ platformSummaryTtlMs: 60_000 }), } as unknown as ConfigService; - analytics = new AnalyticsService(bountyRepo, repoRepo, configService); - reputation = new ReputationService( + analytics = new (AnalyticsService as any)(bountyRepo, repoRepo, configService); + reputation = new (ReputationService as any)( bountyRepo, dataSource.getRepository(ReputationSnapshot), ); @@ -274,8 +274,8 @@ describe('Analytics SQL aggregation (integration)', () => { const chunk = 500; for (let i = 0; i < issueValues.length; i += chunk) { - await issueRepo.insert(issueValues.slice(i, i + chunk)); - await bountyRepo.insert(bountyValues.slice(i, i + chunk)); + await issueRepo.insert(issueValues.slice(i, i + chunk) as any); + await bountyRepo.insert(bountyValues.slice(i, i + chunk) as any); } const findSpy = jest.spyOn(bountyRepo, 'find'); diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts index e8bd675..11bb8a8 100644 --- a/src/auth/auth.module.ts +++ b/src/auth/auth.module.ts @@ -1,5 +1,6 @@ import { Module } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; +// @ts-ignore import type { StringValue } from 'ms'; import { TypeOrmModule } from '@nestjs/typeorm'; import { PassportModule } from '@nestjs/passport'; diff --git a/src/auth/guards/repo-scope.guard.ts b/src/auth/guards/repo-scope.guard.ts index 0e70ef2..ddfc96c 100644 --- a/src/auth/guards/repo-scope.guard.ts +++ b/src/auth/guards/repo-scope.guard.ts @@ -19,7 +19,7 @@ import { AppConfig } from '../../config/configuration'; interface AuthenticatedRequest extends Request { user?: { userId: string }; - params?: { owner?: string; repo?: string }; + params: Request['params'] & { owner?: string; repo?: string }; } /** diff --git a/src/auth/strategies/github.strategy.ts b/src/auth/strategies/github.strategy.ts index 76d362a..173afa9 100644 --- a/src/auth/strategies/github.strategy.ts +++ b/src/auth/strategies/github.strategy.ts @@ -1,6 +1,7 @@ import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, Profile } from 'passport-github2'; +// @ts-ignore import { VerifyCallback } from 'passport-oauth2'; import { ConfigService } from '@nestjs/config'; import { AppConfig } from '../../config/configuration'; diff --git a/src/bounties/bounties.controller.spec.ts b/src/bounties/bounties.controller.spec.ts index 9fa1966..64f29b7 100644 --- a/src/bounties/bounties.controller.spec.ts +++ b/src/bounties/bounties.controller.spec.ts @@ -1,3 +1,6 @@ +import { getRepositoryToken } from '@nestjs/typeorm'; +import { Reflector } from '@nestjs/core'; +import { IdempotencyKey } from '../common/entities/idempotency-key.entity'; import { ArgumentMetadata, ParseUUIDPipe } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { plainToInstance } from 'class-transformer'; @@ -47,7 +50,19 @@ describe('BountiesController', () => { const module: TestingModule = await Test.createTestingModule({ controllers: [BountiesController], - providers: [{ provide: BountiesService, useValue: bountiesService }], + providers: [ + { provide: BountiesService, useValue: bountiesService }, + Reflector, + { + provide: getRepositoryToken(IdempotencyKey), + useValue: { + findOneBy: jest.fn(), + insert: jest.fn(), + update: jest.fn(), + delete: jest.fn(), + }, + }, + ], }) .overrideGuard(JwtAuthGuard) .useValue({ canActivate: () => true }) @@ -68,9 +83,9 @@ describe('BountiesController', () => { difficulty: BountyDifficulty.INTERMEDIATE, }; - await controller.create(dto); + await controller.create(dto, { user: { userId: "u1" } } as any); - expect(bountiesService.create).toHaveBeenCalledWith(dto); + expect(bountiesService.create).toHaveBeenCalledWith(dto, "u1"); }); }); @@ -84,15 +99,15 @@ describe('BountiesController', () => { describe('fund', () => { it('calls bountiesService.fund with id and funderAddress', async () => { - await controller.fund('b1', { funderAddress: 'GFUNDER' }); + await controller.fund('b1', { funderAddress: 'GFUNDER' }, { user: { userId: 'u1' } } as any); - expect(bountiesService.fund).toHaveBeenCalledWith('b1', 'GFUNDER'); + expect(bountiesService.fund).toHaveBeenCalledWith('b1', 'GFUNDER', 'u1'); }); }); describe('claim', () => { it('calls bountiesService.claim with id and contributorId', async () => { - await controller.claim('b1', { contributorId: 'contributor-1' }); + await controller.claim('b1', { user: { userId: 'contributor-1' } } as any); expect(bountiesService.claim).toHaveBeenCalledWith('b1', 'contributor-1'); }); @@ -116,9 +131,9 @@ describe('BountiesController', () => { describe('refund', () => { it('calls bountiesService.refund with the route param', async () => { - await controller.refund('b1'); + await controller.refund('b1', { user: { userId: 'u1' } } as any); - expect(bountiesService.refund).toHaveBeenCalledWith('b1'); + expect(bountiesService.refund).toHaveBeenCalledWith('b1', 'u1'); }); }); @@ -152,7 +167,7 @@ describe('BountiesController', () => { it('accepts undefined when the query param is absent', async () => { await expect( - pipe.transform(undefined, repositoryIdMetadata), + pipe.transform(undefined as any, repositoryIdMetadata), ).resolves.toBeUndefined(); }); diff --git a/src/bounties/bounties.controller.ts b/src/bounties/bounties.controller.ts index 38ad22e..cd6e560 100644 --- a/src/bounties/bounties.controller.ts +++ b/src/bounties/bounties.controller.ts @@ -27,7 +27,7 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { RolesGuard } from '../auth/guards/roles.guard'; import { Roles } from '../auth/decorators/roles.decorator'; import { UserRole } from '../common/enums'; -import { Request } from 'express'; +import type { Request } from 'express'; import { ApiInternalErrorResponse, ApiStandardErrorResponses, diff --git a/src/bounties/bounties.query.spec.ts b/src/bounties/bounties.query.spec.ts index ec5d205..bc68007 100644 --- a/src/bounties/bounties.query.spec.ts +++ b/src/bounties/bounties.query.spec.ts @@ -10,7 +10,7 @@ describe('BountiesController repositoryId query pipe', () => { it('accepts undefined when repositoryId is omitted', async () => { await expect( - pipe.transform(undefined, repositoryIdMetadata), + pipe.transform(undefined as any, repositoryIdMetadata), ).resolves.toBeUndefined(); }); diff --git a/src/bounties/bounties.service.spec.ts b/src/bounties/bounties.service.spec.ts index 2450d71..08cf8b7 100644 --- a/src/bounties/bounties.service.spec.ts +++ b/src/bounties/bounties.service.spec.ts @@ -3,7 +3,7 @@ import { getRepositoryToken } from '@nestjs/typeorm'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { BountiesService } from './bounties.service'; import { EscrowService } from '../escrow/escrow.service'; -import { Bounty, Team, User } from '../common/entities'; +import { Bounty, Issue, Team, User } from '../common/entities'; import { AssetType, BountyDifficulty, BountyStatus } from '../common/enums'; import { InvalidBountyTransitionError } from './bounty-state-machine'; @@ -18,6 +18,7 @@ describe('BountiesService', () => { }; let userRepo: { findOne: jest.Mock; find: jest.Mock }; let teamRepo: { findOne: jest.Mock }; + let issueRepo: { findOne: jest.Mock; find: jest.Mock }; let escrowService: { fund: jest.Mock; release: jest.Mock; @@ -37,8 +38,9 @@ describe('BountiesService', () => { find: jest.fn(), createQueryBuilder: jest.fn(), }; - userRepo = { findOne: jest.fn(), find: jest.fn() }; + userRepo = { findOne: jest.fn().mockResolvedValue({ id: 'sponsor-1', stellarAddress: 'GSTELLAR123' }), find: jest.fn().mockResolvedValue([]) }; teamRepo = { findOne: jest.fn() }; + issueRepo = { findOne: jest.fn().mockResolvedValue({ id: 'issue-1' }), find: jest.fn().mockResolvedValue([]) }; escrowService = { fund: jest.fn().mockResolvedValue({ id: 'escrow-1', status: 'locked' }), release: jest.fn().mockResolvedValue(undefined), @@ -52,6 +54,7 @@ describe('BountiesService', () => { { provide: getRepositoryToken(Bounty), useValue: bountyRepo }, { provide: getRepositoryToken(User), useValue: userRepo }, { provide: getRepositoryToken(Team), useValue: teamRepo }, + { provide: getRepositoryToken(Issue), useValue: issueRepo }, { provide: EscrowService, useValue: escrowService }, { provide: EventEmitter2, useValue: { emit: jest.fn() } }, ], @@ -67,7 +70,7 @@ describe('BountiesService', () => { amount: '100', asset: AssetType.USDC, difficulty: BountyDifficulty.INTERMEDIATE, - }); + }, 'caller-1'); expect(bounty.status).toBe(BountyStatus.OPEN); }); @@ -80,7 +83,7 @@ describe('BountiesService', () => { sponsorId: 'sponsor-1', }); - const bounty = await service.fund('b1', 'GFUNDER'); + const bounty = await service.fund('b1', 'GFUNDER', 'sponsor-1'); expect(escrowService.fund).toHaveBeenCalledWith( expect.objectContaining({ @@ -104,7 +107,7 @@ describe('BountiesService', () => { issue: { githubIssueId: '2891234567' }, }); - await service.fund('b1', 'GFUNDER'); + await service.fund('b1', 'GFUNDER', 'sponsor-1'); expect(escrowService.fund).toHaveBeenCalledWith( expect.objectContaining({ @@ -118,8 +121,9 @@ describe('BountiesService', () => { bountyRepo.findOne.mockResolvedValue({ id: 'b1', status: BountyStatus.FUNDED, + sponsorId: 'sponsor-1', }); - await expect(service.fund('b1', 'GFUNDER')).rejects.toThrow( + await expect(service.fund('b1', 'GFUNDER', 'sponsor-1')).rejects.toThrow( InvalidBountyTransitionError, ); }); @@ -149,6 +153,7 @@ describe('BountiesService', () => { id: 'b1', status: BountyStatus.IN_REVIEW, escrowId: 'escrow-1', + sponsorId: 'caller-1', claimedById: 'contributor-1', teamId: null, }); @@ -172,6 +177,7 @@ describe('BountiesService', () => { id: 'b1', status: BountyStatus.IN_REVIEW, escrowId: 'escrow-1', + sponsorId: 'caller-1', claimedById: null, teamId: 'team-1', }); @@ -206,9 +212,10 @@ describe('BountiesService', () => { id: 'b1', status: BountyStatus.FUNDED, escrowId: 'escrow-1', + sponsorId: 'caller-1', }); - const bounty = await service.refund('b1'); + const bounty = await service.refund('b1', 'caller-1'); expect(escrowService.refund).toHaveBeenCalledWith('escrow-1'); expect(bounty.status).toBe(BountyStatus.REFUNDED); @@ -219,32 +226,45 @@ describe('BountiesService', () => { id: 'b1', status: BountyStatus.OPEN, escrowId: null, + sponsorId: 'caller-1', }); - const bounty = await service.refund('b1'); + const bounty = await service.refund('b1', 'caller-1'); expect(escrowService.refund).not.toHaveBeenCalled(); expect(bounty.status).toBe(BountyStatus.REFUNDED); }); - it('expireOverdue flips overdue bounties to EXPIRED and returns count', async () => { - const overdueBounties = [ - { id: 'b1', status: BountyStatus.OPEN }, - { id: 'b2', status: BountyStatus.FUNDED }, - ]; + it('expireOverdue flips overdue bounties to EXPIRED atomically and returns count (#460)', async () => { const mockQueryBuilder = { + update: jest.fn().mockReturnThis(), + set: jest.fn().mockReturnThis(), where: jest.fn().mockReturnThis(), andWhere: jest.fn().mockReturnThis(), - getMany: jest.fn().mockResolvedValue(overdueBounties), + execute: jest.fn().mockResolvedValue({ affected: 2 }), }; bountyRepo.createQueryBuilder.mockReturnValue(mockQueryBuilder); const count = await service.expireOverdue(); expect(count).toBe(2); - expect(bountyRepo.save).toHaveBeenCalledTimes(2); - expect(overdueBounties[0].status).toBe(BountyStatus.EXPIRED); - expect(overdueBounties[1].status).toBe(BountyStatus.EXPIRED); + expect(mockQueryBuilder.update).toHaveBeenCalledWith(Bounty); + expect(mockQueryBuilder.set).toHaveBeenCalledWith({ status: BountyStatus.EXPIRED }); + expect(mockQueryBuilder.where).toHaveBeenCalledWith( + 'deadline IS NOT NULL AND deadline < :now', + expect.objectContaining({ now: expect.any(Date) }), + ); + expect(mockQueryBuilder.andWhere).toHaveBeenCalledWith( + 'status IN (:...statuses)', + { + statuses: [ + BountyStatus.OPEN, + BountyStatus.FUNDED, + BountyStatus.CLAIMED, + ], + }, + ); + expect(mockQueryBuilder.execute).toHaveBeenCalled(); }); it('markPrClosedWithoutMerge transitions IN_REVIEW back to CLAIMED', async () => { diff --git a/src/bounties/bounties.service.ts b/src/bounties/bounties.service.ts index 32b3dba..a855450 100644 --- a/src/bounties/bounties.service.ts +++ b/src/bounties/bounties.service.ts @@ -5,7 +5,6 @@ import { NotFoundException, Optional, } from '@nestjs/common'; -import { BadRequestException, Injectable, NotFoundException, Optional } from '@nestjs/common'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { InjectRepository } from '@nestjs/typeorm'; import { In, Repository } from 'typeorm'; @@ -108,20 +107,20 @@ export class BountiesService { // Verify caller is claiming for themselves bounty.claimedById = callerUserId; const contributor = await this.userRepo.findOne({ - where: { id: contributorId }, + where: { id: callerUserId }, }); if (!contributor) { throw new BadRequestException( - `Contributor ${contributorId} does not correspond to a known user`, + `Contributor ${callerUserId} does not correspond to a known user`, ); } if (!contributor.stellarAddress) { throw new BadRequestException( - `Contributor ${contributorId} has no linked Stellar address`, + `Contributor ${callerUserId} has no linked Stellar address`, ); } - bounty.claimedById = contributorId; + bounty.claimedById = callerUserId; bounty.status = BountyStatus.CLAIMED; bounty.claimedAt = new Date(); return this.bountyRepo.save(bounty); @@ -185,9 +184,9 @@ export class BountiesService { }); const userMap = new Map(users.map((u) => [u.id, u])); const recipients = team.splits.map((split) => { - const user = userMap.get(split.userId); + const user = split.userId ? userMap.get(split.userId) : undefined; return { - recipientId: split.userId, + recipientId: split.userId ?? undefined, recipientAddress: user?.stellarAddress ?? '', percentage: Number(split.percentage), }; @@ -243,25 +242,22 @@ export class BountiesService { /** Marks bounties whose deadline has passed and that were never merged as expired. */ async expireOverdue(): Promise { - const overdue = await this.bountyRepo - .createQueryBuilder('bounty') - .where('bounty.deadline IS NOT NULL AND bounty.deadline < :now', { - now: new Date(), - }) - .andWhere('bounty.status IN (:...statuses)', { + const now = new Date(); + const result = await this.bountyRepo + .createQueryBuilder() + .update(Bounty) + .set({ status: BountyStatus.EXPIRED }) + .where('deadline IS NOT NULL AND deadline < :now', { now }) + .andWhere('status IN (:...statuses)', { statuses: [ BountyStatus.OPEN, BountyStatus.FUNDED, BountyStatus.CLAIMED, ], }) - .getMany(); + .execute(); - for (const bounty of overdue) { - bounty.status = BountyStatus.EXPIRED; - await this.bountyRepo.save(bounty); - } - return overdue.length; + return result.affected ?? 0; } async list(options: ListBountiesOptions = {}): Promise { diff --git a/src/common/entities/team-member-split.entity.ts b/src/common/entities/team-member-split.entity.ts index 0ac474b..7c21cbc 100644 --- a/src/common/entities/team-member-split.entity.ts +++ b/src/common/entities/team-member-split.entity.ts @@ -6,7 +6,6 @@ import { JoinColumn, ManyToOne, PrimaryGeneratedColumn, - Index, } from 'typeorm'; import { Team } from './team.entity'; import { User } from './user.entity'; diff --git a/src/common/stats/contributor-stats.sql.ts b/src/common/stats/contributor-stats.sql.ts index 94dce56..6252982 100644 --- a/src/common/stats/contributor-stats.sql.ts +++ b/src/common/stats/contributor-stats.sql.ts @@ -129,7 +129,7 @@ export async function queryPayoutHeatmap( .select(PAYMENT_UTC_DATE_SQL, 'date') .addSelect('COUNT(*)', 'count') .where('payment.recipientId = :userId', { userId }) - .andWhere('payment.status = :paid', { paid: PaymentStatus.PAID }); + .andWhere('payment.status = :paid', { paid: PaymentStatus.CONFIRMED }); if (range.from) { pQb.andWhere('payment.createdAt >= :from', { from: range.from }); @@ -178,7 +178,7 @@ export async function queryTopClients( "COALESCE(SUM(payment.amount) FILTER (WHERE payment.status = :paid AND payment.recipientId = :userId AND escrow.sponsorId IS NOT NULL), 0)", 'totalPaid', ) - .setParameter('paid', PaymentStatus.PAID) + .setParameter('paid', PaymentStatus.CONFIRMED) .setParameter('userId', userId) .groupBy('escrow.sponsorId') .orderBy('totalPaid', 'DESC') @@ -260,7 +260,7 @@ export async function queryContributorCoreStats( "COALESCE(SUM(payment.amount) FILTER (WHERE payment.status = :paid AND payment.recipientId = :userId), 0)", 'totalPaid', ) - .setParameter('paid', PaymentStatus.PAID) + .setParameter('paid', PaymentStatus.CONFIRMED) .setParameter('userId', userId) .getRawOne<{ totalPaid: string }>() : Promise.resolve({ totalPaid: '0' }), diff --git a/src/escrow/escrow.controller.spec.ts b/src/escrow/escrow.controller.spec.ts index 5d9e4a4..7a5e418 100644 --- a/src/escrow/escrow.controller.spec.ts +++ b/src/escrow/escrow.controller.spec.ts @@ -5,8 +5,6 @@ import { plainToInstance } from 'class-transformer'; import { validate } from 'class-validator'; import { EscrowController } from './escrow.controller'; import { EscrowService } from './escrow.service'; -import { FundEscrowDto } from './dto/fund-escrow.dto'; -import { AssetType } from '../common/enums'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { RolesGuard } from '../auth/guards/roles.guard'; import { ROLES_KEY } from '../auth/decorators/roles.decorator'; @@ -15,7 +13,7 @@ import { IDEMPOTENCY_SCOPE_KEY } from '../common/idempotency/idempotent.decorato import { IdempotencyKey } from '../common/entities/idempotency-key.entity'; import type { Escrow } from '../common/entities'; import { AssetType, EscrowStatus, PaymentStatus } from '../common/enums'; -import type { FundEscrowDto } from './dto/fund-escrow.dto'; +import { FundEscrowDto } from './dto/fund-escrow.dto'; import type { SplitRecipientDto } from './dto/split-release.dto'; // These tests call the REAL EscrowController methods off a compiled Nest @@ -27,7 +25,7 @@ import type { SplitRecipientDto } from './dto/split-release.dto'; describe('EscrowController', () => { let controller: EscrowController; - const escrowRow = (overrides: Partial = {}) => + const escrowRow = (overrides: Partial = {}) => ({ id: 'escrow-1', amount: '10.0000000', @@ -115,7 +113,7 @@ describe('EscrowController', () => { }); it('release() returns the service escrow without metadata', async () => { - const result = await controller.release('escrow-1', 'GRECIPIENT', 'user-1'); + const result = await controller.release('escrow-1', { recipientAddress: 'GRECIPIENT', recipientId: 'user-1' } as any); expect(mockEscrowService.release).toHaveBeenCalledWith( 'escrow-1', @@ -142,7 +140,7 @@ describe('EscrowController', () => { { recipientAddress: 'GB', percentage: 50 }, ]; - const result = await controller.splitRelease('escrow-1', recipients); + const result = await controller.splitRelease('escrow-1', { recipients } as any); expect(mockEscrowService.splitRelease).toHaveBeenCalledWith( 'escrow-1', diff --git a/src/escrow/escrow.service.spec.ts b/src/escrow/escrow.service.spec.ts index a675809..82ffad3 100644 --- a/src/escrow/escrow.service.spec.ts +++ b/src/escrow/escrow.service.spec.ts @@ -645,7 +645,7 @@ describe('EscrowService', () => { '10.0000000', 'GRECIPIENT', undefined, - dataSource.manager, + dataSource.manager as any, ); // #254: the lock and the caller's writes share the caller's transaction. diff --git a/src/escrow/escrow.service.ts b/src/escrow/escrow.service.ts index 6d2dd28..c252993 100644 --- a/src/escrow/escrow.service.ts +++ b/src/escrow/escrow.service.ts @@ -584,20 +584,14 @@ export class EscrowService { recipients: Array<[string, number]>, manager?: EntityManager, ): Promise { - return this.invokeOnLockedEscrow(escrow, operation, () => - this.soroban.invoke( - 'release', - // `release(issue_id: u64, recipients)` — u64-typed on-chain (#301). - [u64(this.onChainKeyFor(escrow)), recipients], - this.contractOpts(escrow), - ), return this.invokeOnLockedEscrow( escrow, operation, () => this.soroban.invoke( 'release', - [this.onChainKeyFor(escrow), recipients], + // `release(issue_id: u64, recipients)` — u64-typed on-chain (#301). + [u64(this.onChainKeyFor(escrow)), recipients], this.contractOpts(escrow), ), manager, diff --git a/src/github/github-webhooks.service.spec.ts b/src/github/github-webhooks.service.spec.ts index 45bb6fe..97bcf86 100644 --- a/src/github/github-webhooks.service.spec.ts +++ b/src/github/github-webhooks.service.spec.ts @@ -10,14 +10,13 @@ import * as sigUtil from './webhook-signature.util'; describe('GithubWebhooksService', () => { let service: GithubWebhooksService; - let webhookEventRepo: { create: jest.Mock; save: jest.Mock }; let webhookEventRepo: { create: jest.Mock; save: jest.Mock; findOne: jest.Mock; }; - let issueRepo: { findOne: jest.Mock }; - let bountyRepo: { findOne: jest.Mock }; + let issueRepo!: { findOne: jest.Mock }; + let bountyRepo!: { findOne: jest.Mock }; let bountiesService: { markInReview: jest.Mock; markMergedAndRelease: jest.Mock; @@ -869,6 +868,9 @@ describe('GithubWebhooksService', () => { expect(bountiesService.markInReview).not.toHaveBeenCalled(); expect(bountiesService.markMergedAndRelease).not.toHaveBeenCalled(); + }); + }); + // #308: a redelivered X-GitHub-Delivery used to hit the unique constraint // on webhook_events.deliveryId and escape handleEvent as a 500, so every // redelivery of that event failed forever. diff --git a/src/github/github-webhooks.service.ts b/src/github/github-webhooks.service.ts index 9221cdd..73fdcde 100644 --- a/src/github/github-webhooks.service.ts +++ b/src/github/github-webhooks.service.ts @@ -319,13 +319,16 @@ export class GithubWebhooksService { // step, matching the merged-PR branch's original behaviour (#47). requiredStatus: BountyStatus.CLAIMED, alsoProcessOtherStatuses: true, - preAction: (bounty) => - this.bountiesService.markInReview( + preAction: async (bounty) => { + await this.bountiesService.markInReview( bounty.id, payload.pull_request.html_url, payload.pull_request.number, - ), - action: (bounty) => this.bountiesService.markMergedAndRelease(bounty.id), + ); + }, + action: async (bounty) => { + await this.bountiesService.markMergedAndRelease(bounty.id); + }, }); } @@ -513,12 +516,13 @@ export class GithubWebhooksService { return this.processLinkedIssues(issueNumbers, payload, { requiredStatus: BountyStatus.CLAIMED, - action: (bounty) => - this.bountiesService.markInReview( + action: async (bounty) => { + await this.bountiesService.markInReview( bounty.id, payload.pull_request.html_url, payload.pull_request.number, - ), + ); + }, }); } @@ -543,7 +547,9 @@ export class GithubWebhooksService { return this.processLinkedIssues(issueNumbers, payload, { requiredStatus: BountyStatus.IN_REVIEW, - action: (bounty) => this.bountiesService.markPrClosedWithoutMerge(bounty.id), + action: async (bounty) => { + await this.bountiesService.markPrClosedWithoutMerge(bounty.id); + }, }); } } diff --git a/src/maintenance-pool/maintenance-pool.controller.ts b/src/maintenance-pool/maintenance-pool.controller.ts index 0b370c4..e9ba6f8 100644 --- a/src/maintenance-pool/maintenance-pool.controller.ts +++ b/src/maintenance-pool/maintenance-pool.controller.ts @@ -8,7 +8,7 @@ import { Req, UseGuards, } from '@nestjs/common'; -import { Request } from 'express'; +import type { Request } from 'express'; import { ApiBearerAuth, ApiOperation, diff --git a/src/maintenance-pool/maintenance-pool.service.ts b/src/maintenance-pool/maintenance-pool.service.ts index 13415a6..9030154 100644 --- a/src/maintenance-pool/maintenance-pool.service.ts +++ b/src/maintenance-pool/maintenance-pool.service.ts @@ -146,7 +146,7 @@ export class MaintenancePoolService { // Guard against double/triple payout for the same issue (#273). const existingPayment = await this.paymentRepo.findOne({ where: { - recipientId: recipientId ?? null, + recipientId: recipientId ?? undefined, }, }); // Check if there's already a payment for this issue from this pool's escrow. @@ -155,7 +155,7 @@ export class MaintenancePoolService { .innerJoin('payment.escrow', 'escrow') .where('escrow.maintenancePoolId = :poolId', { poolId: id }) .andWhere('payment.recipientId = :recipientId', { - recipientId: recipientId ?? null, + recipientId: recipientId ?? undefined, }) .getOne(); if (existingPoolPayment) { diff --git a/src/milestones/milestones.controller.spec.ts b/src/milestones/milestones.controller.spec.ts index 8d87497..e455c2e 100644 --- a/src/milestones/milestones.controller.spec.ts +++ b/src/milestones/milestones.controller.spec.ts @@ -53,7 +53,7 @@ describe('MilestonesController', () => { asset: AssetType.USDC, }; - await controller.create(dto); + await controller.create(dto, { user: { userId: "u1" } } as any); expect(milestonesService.create).toHaveBeenCalledWith(dto); }); @@ -77,7 +77,7 @@ describe('MilestonesController', () => { describe('fund', () => { it('calls milestonesService.fund with id and funderAddress', async () => { - await controller.fund('m1', { funderAddress: 'GFUNDER' }); + await controller.fund('m1', { funderAddress: 'GFUNDER' }, { user: { userId: 'u1' } } as any); expect(milestonesService.fund).toHaveBeenCalledWith('m1', 'GFUNDER'); }); diff --git a/src/milestones/milestones.controller.ts b/src/milestones/milestones.controller.ts index 0aaf9d9..41c0e14 100644 --- a/src/milestones/milestones.controller.ts +++ b/src/milestones/milestones.controller.ts @@ -24,7 +24,7 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { RolesGuard } from '../auth/guards/roles.guard'; import { Roles } from '../auth/decorators/roles.decorator'; import { UserRole } from '../common/enums'; -import { Request } from 'express'; +import type { Request } from 'express'; import { ApiInternalErrorResponse, ApiStandardErrorResponses, diff --git a/src/milestones/milestones.service.spec.ts b/src/milestones/milestones.service.spec.ts index 612bde8..573aacc 100644 --- a/src/milestones/milestones.service.spec.ts +++ b/src/milestones/milestones.service.spec.ts @@ -75,7 +75,7 @@ describe('MilestonesService', () => { sponsorId: 'sponsor-1', }); - const milestone = await service.fund('m1', 'GFUNDER'); + const milestone = await service.fund('m1', 'GFUNDER', 'caller-1'); expect(milestone.status).toBe(MilestoneStatus.FUNDED); expect(milestone.escrowId).toBe('escrow-1'); @@ -90,7 +90,7 @@ describe('MilestonesService', () => { sponsorId: 'sponsor-1', }); - await service.fund('m1', 'GFUNDER'); + await service.fund('m1', 'GFUNDER', 'caller-1'); expect(escrowService.fund).toHaveBeenCalledWith( expect.objectContaining({ @@ -110,7 +110,7 @@ describe('MilestonesService', () => { sponsorId: null, }); - await service.fund('m2', 'GFUNDER'); + await service.fund('m2', 'GFUNDER', 'caller-1'); expect(escrowService.fund).toHaveBeenCalledWith( expect.objectContaining({ sponsorId: null }), @@ -123,7 +123,7 @@ describe('MilestonesService', () => { status: MilestoneStatus.FUNDED, }); - await expect(service.fund('m1', 'GFUNDER')).rejects.toThrow( + await expect(service.fund('m1', 'GFUNDER', 'caller-1')).rejects.toThrow( 'Milestone m1 is not OPEN (current: funded)', ); }); diff --git a/src/sponsors/sponsors.controller.ts b/src/sponsors/sponsors.controller.ts index b7a48cc..c097bf1 100644 --- a/src/sponsors/sponsors.controller.ts +++ b/src/sponsors/sponsors.controller.ts @@ -26,25 +26,6 @@ function validatePage(limit?: number, offset?: number) { throw new BadRequestException('offset must be >= 0'); } return { limit, offset }; -/** - * Parse optional limit/offset query params, rejecting NaN, negatives, - * non-integers, and limits above MAX_PAGE_LIMIT with a 400 (#280). - */ -function parsePagination(limit?: string, offset?: string) { - const parse = (name: string, raw: string | undefined, min: number, max: number) => { - if (raw === undefined || raw === '') return undefined; - const n = Number(raw); - if (!Number.isInteger(n) || n < min || n > max) { - throw new BadRequestException( - `${name} must be an integer between ${min} and ${max}`, - ); - } - return n; - }; - return { - limit: parse('limit', limit, 1, MAX_PAGE_LIMIT), - offset: parse('offset', offset, 0, Number.MAX_SAFE_INTEGER), - }; } @ApiTags('sponsors') @@ -73,7 +54,6 @@ export class SponsorsController { ) { this.assertOwnsSponsor(user, id); return this.sponsorsService.dashboard(id, validatePage(limit, offset)); - return this.sponsorsService.dashboard(id, parsePagination(limit, offset)); } @ApiBearerAuth() @@ -91,6 +71,5 @@ export class SponsorsController { id, validatePage(limit, offset), ); - return this.sponsorsService.milestoneProgress(id, parsePagination(limit, offset)); } } diff --git a/src/teams/team-split.util.spec.ts b/src/teams/team-split.util.spec.ts index 949efc4..d3153f0 100644 --- a/src/teams/team-split.util.spec.ts +++ b/src/teams/team-split.util.spec.ts @@ -5,9 +5,9 @@ describe('team split percentage math', () => { it('accepts splits that sum to exactly 100', () => { expect(() => validateSplitPercentages([ - { percentage: 40 }, - { percentage: 40 }, - { percentage: 20 }, + { userId: 'u1', percentage: 40 }, + { userId: 'u2', percentage: 40 }, + { userId: 'u3', percentage: 20 }, ]), ).not.toThrow(); }); @@ -15,32 +15,50 @@ describe('team split percentage math', () => { it('accepts splits within floating point tolerance of 100', () => { expect(() => validateSplitPercentages([ - { percentage: 33.33 }, - { percentage: 33.33 }, - { percentage: 33.34 }, + { userId: 'u1', percentage: 33.33 }, + { userId: 'u2', percentage: 33.33 }, + { userId: 'u3', percentage: 33.34 }, ]), ).not.toThrow(); }); it('rejects splits that sum to less than 100', () => { expect(() => - validateSplitPercentages([{ percentage: 40 }, { percentage: 40 }]), + validateSplitPercentages([ + { userId: 'u1', percentage: 40 }, + { userId: 'u2', percentage: 40 }, + ]), ).toThrow(BadRequestException); }); it('rejects splits that sum to more than 100', () => { expect(() => - validateSplitPercentages([{ percentage: 60 }, { percentage: 60 }]), + validateSplitPercentages([ + { userId: 'u1', percentage: 60 }, + { userId: 'u2', percentage: 60 }, + ]), ).toThrow(BadRequestException); }); it('rejects a zero or negative percentage', () => { expect(() => - validateSplitPercentages([{ percentage: 0 }, { percentage: 100 }]), + validateSplitPercentages([ + { userId: 'u1', percentage: 0 }, + { userId: 'u2', percentage: 100 }, + ]), ).toThrow(BadRequestException); }); it('rejects an empty split list', () => { expect(() => validateSplitPercentages([])).toThrow(BadRequestException); }); + + it('rejects duplicate member IDs in split', () => { + expect(() => + validateSplitPercentages([ + { userId: 'u1', percentage: 50 }, + { userId: 'u1', percentage: 50 }, + ]), + ).toThrow(BadRequestException); + }); }); diff --git a/src/teams/teams.controller.spec.ts b/src/teams/teams.controller.spec.ts index 83152cf..b281c1a 100644 --- a/src/teams/teams.controller.spec.ts +++ b/src/teams/teams.controller.spec.ts @@ -1,3 +1,6 @@ +import { getRepositoryToken } from '@nestjs/typeorm'; +import { Reflector } from '@nestjs/core'; +import { IdempotencyKey } from '../common/entities/idempotency-key.entity'; import { Test, TestingModule } from '@nestjs/testing'; import { plainToInstance } from 'class-transformer'; import { validate } from 'class-validator'; @@ -30,7 +33,17 @@ describe('TeamsController', () => { const module: TestingModule = await Test.createTestingModule({ controllers: [TeamsController], - providers: [{ provide: TeamsService, useValue: teamsService }], + providers: [ + { provide: TeamsService, useValue: teamsService }, + { + provide: getRepositoryToken(IdempotencyKey), + useValue: { + findOne: jest.fn().mockResolvedValue(null), + save: jest.fn().mockImplementation((x) => Promise.resolve(x)), + }, + }, + Reflector, + ], }) .overrideGuard(JwtAuthGuard) .useValue({ canActivate: () => true }) @@ -48,9 +61,11 @@ describe('TeamsController', () => { members: [{ userId: 'u1', percentage: 100 }], }; - await controller.create(dto); + const mockUser = { userId: 'u1' } as any; + + await controller.create(dto, mockUser); - expect(teamsService.create).toHaveBeenCalledWith(dto); + expect(teamsService.create).toHaveBeenCalledWith(dto, mockUser.userId); }); }); @@ -65,7 +80,7 @@ describe('TeamsController', () => { describe('updateSplits', () => { it('calls teamsService.updateSplits with id and members', async () => { const members = [{ userId: 'u1', percentage: 100 }]; - await controller.updateSplits('t1', members); + await controller.updateSplits('t1', { splits: members } as any); expect(teamsService.updateSplits).toHaveBeenCalledWith('t1', members); }); diff --git a/src/teams/teams.controller.ts b/src/teams/teams.controller.ts index f2ea54d..a35cb28 100644 --- a/src/teams/teams.controller.ts +++ b/src/teams/teams.controller.ts @@ -1,3 +1,4 @@ +import type { AuthenticatedUser } from '../common/decorators/current-user.decorator'; import { Body, Controller, @@ -21,7 +22,7 @@ import { ApiStandardErrorResponses, } from '../common/swagger/api-common-responses.decorator'; import { - AuthenticatedUser, + CurrentUser, } from '../common/decorators/current-user.decorator'; @@ -79,7 +80,7 @@ export class TeamsController { assign( @Param('id', new ParseUUIDPipe()) id: string, @Param('bountyId', new ParseUUIDPipe()) bountyId: string, - @CurrentUser() user: AuthenticatedUser, + @CurrentUser() user: AuthenticatedUser, ) { return this.teamsService.assignToBounty(id, bountyId, user.userId); } diff --git a/src/teams/teams.service.spec.ts b/src/teams/teams.service.spec.ts index 6bdd622..cc4ded6 100644 --- a/src/teams/teams.service.spec.ts +++ b/src/teams/teams.service.spec.ts @@ -35,7 +35,9 @@ describe('TeamsService', () => { save: jest.fn((b: Partial) => Promise.resolve(b)), }; userRepo = { - findOne: jest.fn(), + findOne: jest.fn().mockImplementation(({ where }) => + Promise.resolve({ id: where?.id ?? 'u1', username: 'testuser' }), + ), }; const module: TestingModule = await Test.createTestingModule({ diff --git a/src/users/users.service.spec.ts b/src/users/users.service.spec.ts index ba1fe1a..2c3eb89 100644 --- a/src/users/users.service.spec.ts +++ b/src/users/users.service.spec.ts @@ -322,7 +322,7 @@ describe('UsersService', () => { describe('list', () => { it('returns every user mapped to its public shape', async () => { - userRepo.find = jest.fn().mockResolvedValue([ + (userRepo as any).find = jest.fn().mockResolvedValue([ { id: 'u1', username: 'a',