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

[DEV-3520] payment request supportIssue #1893

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion src/integration/sift/services/sift.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export class SiftService {
$payment_methods: [{ $payment_type: SiftPaymentMethodMap[order.sourcePaymentMethod] }],
$digital_orders: [
this.createDigitalOrder(
order.type === TransactionRequestType.Sell ? SiftAssetType.FIAT : SiftAssetType.CRYPTO,
order.type === TransactionRequestType.SELL ? SiftAssetType.FIAT : SiftAssetType.CRYPTO,
sourceCurrency,
targetCurrency,
order.estimatedAmount,
Expand Down
1 change: 1 addition & 0 deletions src/shared/services/process.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export enum Process {
PAYMENT_CONFIRMATIONS = 'PaymentConfirmations',
FIAT_OUTPUT_COMPLETE = 'FiatOutputComplete',
BLOCKCHAIN_FEE_UPDATE = 'BlockchainFeeUpdate',
TX_REQUEST_UID_SYNC = 'TxRequestUidSync',
USER_DATA_WALLET_SYNC = 'UserDataWalletSync',
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ export class BuyController {
),
};

await this.transactionRequestService.create(TransactionRequestType.Buy, dto, buyDto, user.id);
await this.transactionRequestService.create(TransactionRequestType.BUY, dto, buyDto, user.id);

return buyDto;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ export class BuyPaymentInfoDto extends BankInfoDto {
@ApiProperty({ description: 'Transaction request ID' })
id: number;

@ApiProperty({ description: 'UID of the transaction request' })
uid?: string;

@ApiProperty({ description: 'Price timestamp' })
timestamp: Date;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export class SwapPaymentInfoDto {
@ApiProperty({ description: 'Transaction request ID' })
id: number;

@ApiProperty({ description: 'UID of the transaction request' })
uid?: string;

@ApiProperty({ description: 'Price timestamp' })
timestamp: Date;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ export class SwapController {
error,
};

await this.transactionRequestService.create(TransactionRequestType.Swap, dto, swapDto, user.id);
await this.transactionRequestService.create(TransactionRequestType.SWAP, dto, swapDto, user.id);

return swapDto;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export class SellPaymentInfoDto {
@ApiProperty({ description: 'Transaction request ID' })
id: number;

@ApiProperty({ description: 'UID of the transaction request' })
uid?: string;

@ApiProperty({ description: 'Price timestamp' })
timestamp: Date;

Expand Down
2 changes: 1 addition & 1 deletion src/subdomains/core/sell-crypto/route/sell.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ export class SellController {
error,
};

await this.transactionRequestService.create(TransactionRequestType.Sell, dto, sellDto, user.id);
await this.transactionRequestService.create(TransactionRequestType.SELL, dto, sellDto, user.id);

return sellDto;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { createDefaultUser } from 'src/subdomains/generic/user/models/user/__mocks__/user.entity.mock';
import { TransactionRequest, TransactionRequestType } from '../entities/transaction-request.entity';

const defaultTransactionRequest: Partial<TransactionRequest> = {
id: 1,
type: TransactionRequestType.BUY,
uid: 'Q186C06388387A6FD',
user: createDefaultUser(),
};

export function createDefaultTransactionRequest(): TransactionRequest {
return createCustomTransactionRequest({});
}

export function createCustomTransactionRequest(customValues: Partial<TransactionRequest>): TransactionRequest {
return Object.assign(new TransactionRequest(), { ...defaultTransactionRequest, ...customValues });
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import { IEntity } from 'src/shared/models/entity';
import { UserData } from 'src/subdomains/generic/user/models/user-data/user-data.entity';
import { User } from 'src/subdomains/generic/user/models/user/user.entity';
import { Column, Entity, ManyToOne } from 'typeorm';
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
import { SupportIssue } from '../../support-issue/entities/support-issue.entity';
import { PaymentMethod } from '../dto/payment-method.enum';
import { QuoteError } from '../dto/transaction-helper/quote-error.enum';

export enum TransactionRequestType {
Buy = 'Buy',
Sell = 'Sell',
Swap = 'Swap',
BUY = 'Buy',
SELL = 'Sell',
SWAP = 'Swap',
}

@Entity()
export class TransactionRequest extends IEntity {
@Column()
type: TransactionRequestType;

// TODO: change to unique & nullable false
@Column({ length: 256, nullable: true })
uid: string;

@Column({ type: 'integer' })
routeId: number;

Expand Down Expand Up @@ -77,4 +83,13 @@ export class TransactionRequest extends IEntity {

@Column({ length: 'MAX', nullable: true })
siftResponse?: string;

@OneToMany(() => SupportIssue, (supportIssue) => supportIssue.transactionRequest)
supportIssues: SupportIssue[];

// --- ENTITY METHODS --- //

get userData(): UserData {
return this.user.userData;
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Blockchain } from 'src/integration/blockchain/shared/enums/blockchain.enum';
import { SiftService } from 'src/integration/sift/services/sift.service';
import { DfxLogger } from 'src/shared/services/dfx-logger';
import { DisabledProcess, Process } from 'src/shared/services/process.service';
import { Lock } from 'src/shared/utils/lock';
import { Util } from 'src/shared/utils/util';
import { BuyPaymentInfoDto } from 'src/subdomains/core/buy-crypto/routes/buy/dto/buy-payment-info.dto';
import { GetBuyPaymentInfoDto } from 'src/subdomains/core/buy-crypto/routes/buy/dto/get-buy-payment-info.dto';
import { GetSwapPaymentInfoDto } from 'src/subdomains/core/buy-crypto/routes/swap/dto/get-swap-payment-info.dto';
import { SwapPaymentInfoDto } from 'src/subdomains/core/buy-crypto/routes/swap/dto/swap-payment-info.dto';
import { GetSellPaymentInfoDto } from 'src/subdomains/core/sell-crypto/route/dto/get-sell-payment-info.dto';
import { SellPaymentInfoDto } from 'src/subdomains/core/sell-crypto/route/dto/sell-payment-info.dto';
import { MoreThan } from 'typeorm';
import { FindOptionsRelations, IsNull, MoreThan } from 'typeorm';
import { CryptoPaymentMethod, FiatPaymentMethod } from '../dto/payment-method.enum';
import { TransactionRequest, TransactionRequestType } from '../entities/transaction-request.entity';
import { TransactionRequestRepository } from '../repositories/transaction-request.repository';

export const QUOTE_UID_PREFIX = 'Q';

@Injectable()
export class TransactionRequestService {
private readonly logger = new DfxLogger(TransactionRequestService);
Expand All @@ -23,16 +28,37 @@ export class TransactionRequestService {
private readonly siftService: SiftService,
) {}

@Cron(CronExpression.EVERY_MINUTE)
@Lock(1800)
async uidSync() {
if (DisabledProcess(Process.TX_REQUEST_UID_SYNC)) return;

const entities = await this.transactionRequestRepo.find({ where: { uid: IsNull() }, take: 10000 });

for (const entity of entities) {
try {
const uid = Util.createHash(entity.type + new Date() + Util.randomId()).toUpperCase();

await this.transactionRequestRepo.update(entity.id, { uid });
} catch (e) {
this.logger.error(`Error in TransactionRequest sync ${entity.id}`, e);
}
}
}

async create(
type: TransactionRequestType,
request: GetBuyPaymentInfoDto | GetSellPaymentInfoDto | GetSwapPaymentInfoDto,
response: BuyPaymentInfoDto | SellPaymentInfoDto | SwapPaymentInfoDto,
userId: number,
): Promise<void> {
try {
const hash = Util.createHash(type + new Date() + Util.randomId()).toUpperCase();
const uid = `${QUOTE_UID_PREFIX}${hash.slice(0, 16)}`;

// create the entity
const transactionRequest = this.transactionRequestRepo.create({
type: type,
type,
routeId: response.routeId,
amount: response.amount,
estimatedAmount: response.estimatedAmount,
Expand All @@ -47,6 +73,7 @@ export class TransactionRequestService {
networkFee: response.fees.network,
totalFee: response.fees.total,
user: { id: userId },
uid,
});

let sourceCurrencyName: string;
Expand All @@ -55,7 +82,7 @@ export class TransactionRequestService {
let siftOrder: boolean;

switch (type) {
case TransactionRequestType.Buy:
case TransactionRequestType.BUY:
const buyRequest = request as GetBuyPaymentInfoDto;
const buyResponse = response as BuyPaymentInfoDto;

Expand All @@ -70,7 +97,7 @@ export class TransactionRequestService {
siftOrder = true;
break;

case TransactionRequestType.Sell:
case TransactionRequestType.SELL:
const sellResponse = response as SellPaymentInfoDto;

transactionRequest.sourcePaymentMethod = CryptoPaymentMethod.CRYPTO;
Expand All @@ -82,7 +109,7 @@ export class TransactionRequestService {
blockchain = sellResponse.asset.blockchain;
break;

case TransactionRequestType.Swap:
case TransactionRequestType.SWAP:
const convertResponse = response as SwapPaymentInfoDto;

transactionRequest.sourcePaymentMethod = CryptoPaymentMethod.CRYPTO;
Expand All @@ -97,6 +124,7 @@ export class TransactionRequestService {
// save
await this.transactionRequestRepo.save(transactionRequest);
response.id = transactionRequest.id;
response.uid = uid;

// create order at sift (without waiting)
if (siftOrder)
Expand Down Expand Up @@ -128,6 +156,13 @@ export class TransactionRequestService {
return request;
}

async getTransactionRequestByUid(
uid: string,
relations: FindOptionsRelations<TransactionRequest> = {},
): Promise<TransactionRequest | undefined> {
return this.transactionRequestRepo.findOne({ where: { uid }, relations });
}

async findAndComplete(
amount: number,
routeId: number,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@ export class TransactionService {
}

async update(id: number, dto: UpdateTransactionInternalDto | UpdateTransactionDto): Promise<Transaction> {
let entity = await this.getTransactionById(id);
let entity = await this.getTransactionById(id, { request: { supportIssues: true } });
if (!entity) throw new Error('Transaction not found');

Object.assign(entity, dto);

if (!(dto instanceof UpdateTransactionDto)) {
entity.externalId = dto.request?.externalTransactionId;

if (dto.resetMailSendDate) entity.mailSendDate = null;
if (dto.request) entity.supportIssues = [...entity.supportIssues, ...entity.request.supportIssues];
}

entity = await this.repo.save(entity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ export class TransactionIssueDto {
@IsInt()
id?: number;

@ApiPropertyOptional()
@IsOptional()
@IsString()
uid?: string;

@ApiPropertyOptional()
@IsOptional()
@IsString()
quoteUid?: string;

@ApiPropertyOptional()
@IsOptional()
@IsString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { IEntity } from 'src/shared/models/entity';
import { UserData } from 'src/subdomains/generic/user/models/user-data/user-data.entity';
import { LimitRequest } from 'src/subdomains/supporting/support-issue/entities/limit-request.entity';
import { Column, Entity, JoinColumn, ManyToOne, OneToMany, OneToOne } from 'typeorm';
import { TransactionRequest } from '../../payment/entities/transaction-request.entity';
import { Transaction } from '../../payment/entities/transaction.entity';
import { SupportMessage } from './support-message.entity';

Expand Down Expand Up @@ -54,6 +55,9 @@ export class SupportIssue extends IEntity {
@ManyToOne(() => Transaction, (transaction) => transaction.supportIssues, { nullable: true, eager: true })
transaction?: Transaction;

@ManyToOne(() => TransactionRequest, (request) => request.supportIssues, { nullable: true, eager: true })
transactionRequest?: TransactionRequest;

@OneToMany(() => SupportMessage, (supportMessage) => supportMessage.issue)
messages: SupportMessage[];

Expand Down
Loading
Loading