diff --git a/apps/api/src/vault/vault.service.ts b/apps/api/src/vault/vault.service.ts index 4282e3ddc..a9702baa2 100644 --- a/apps/api/src/vault/vault.service.ts +++ b/apps/api/src/vault/vault.service.ts @@ -13,6 +13,12 @@ import { PrismaService } from '../prisma/prisma.service' import { CreateVaultDto } from './dto/create-vault.dto' import { UpdateVaultDto } from './dto/update-vault.dto' +type VaultWithWithdrawalSum = Prisma.VaultGetPayload<{ + include: { campaign: { select: { id: true; title: true } } } +}> & { + withdrawnAmount: number +} + @Injectable() export class VaultService { constructor( @@ -25,8 +31,33 @@ export class VaultService { return await this.prisma.vault.create({ data: createVaultDto.toEntity() }) } - async findAll(): Promise { - return await this.prisma.vault.findMany() + async findAll(): Promise { + const result = await this.prisma.$queryRaw` + SELECT + v.id, + v.campaign_id as "campaignId", + v.created_at as "createdAt", + v.updated_at as "updatedAt", + v.currency, v."blockedAmount", + v.name, + v.amount, + json_build_object('id', campaign.id, 'title', campaign.title) AS campaign, + COALESCE(SUM(w."successfullWithdrawn")::INTEGER, 0) as "withdrawnAmount" + FROM vaults v + LEFT JOIN LATERAL ( + SELECT SUM(amount)::INTEGER as "successfullWithdrawn" + FROM withdrawals + WHERE status::text = 'succeeded' AND source_vault_id::uuid = v.id::uuid + )as w + ON TRUE + + LEFT JOIN LATERAL ( + SELECT id, title FROM campaigns WHERE id::uuid = v.campaign_id::uuid + ) as campaign ON TRUE + + GROUP BY v.id, campaign.id, campaign.title + ` + return result } async findByCampaignId(campaignId: string): Promise {