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

fix: reward finalized #284

Merged
merged 1 commit into from
Feb 1, 2023
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 @@ -4,16 +4,13 @@ import { Option } from '@polkadot/types';
import { OrderFulfilledCommand } from './order-fulfilled.command';
import {
DateTimeProxy,
DebioConversionService,
NotificationService,
SubstrateService,
TransactionLoggingService,
} from '@common/index';
import {
Order,
queryEthAdressByAccountId,
sendRewards,
ServiceFlow,
} from '@debionetwork/polkadot-provider';
import { TransactionLoggingDto } from '@common/transaction-logging/dto/transaction-logging.dto';
import { NotificationDto } from '@common/notification/dto/notification.dto';
Expand All @@ -33,7 +30,6 @@ export class OrderFulfilledHandler
private readonly substrateService: SubstrateService,
private readonly notificationService: NotificationService,
private readonly dateTimeProxy: DateTimeProxy,
private readonly exchangeCacheService: DebioConversionService,
) {}

async execute(command: OrderFulfilledCommand) {
Expand Down Expand Up @@ -93,14 +89,6 @@ export class OrderFulfilledHandler
return null;
}

if (order.orderFlow === ServiceFlow.StakingRequestService) {
await this.callbackSendReward(
order,
amountToForward / currencyUnit[order.currency],
blockNumber,
);
}

await this.loggingService.create(orderLogging);

const currDateTime = this.dateTimeProxy.new();
Expand Down Expand Up @@ -135,114 +123,6 @@ export class OrderFulfilledHandler
}
}

private async callbackSendReward(
order: Order,
totalPrice: number,
blockNumber: string,
) {
const exchangeFromTo = await this.exchangeCacheService.getExchangeFromTo(
order.currency.toUpperCase(),
'DAI',
);
const exchange = await this.exchangeCacheService.getExchange();
const dbioToDai = exchange ? exchange['dbioToDai'] : 1;
const daiToDbio = 1 / dbioToDai;

const rewardCustomer = totalPrice * exchangeFromTo.conversion * daiToDbio;
const rewardLab = rewardCustomer / 10;
const fixedRewardCustomer = rewardCustomer.toFixed(0);
const fixedRewardLab = rewardLab.toFixed(0);
const dbioRewardCustomer = (
BigInt(fixedRewardCustomer) * BigInt(currencyUnit.DBIO)
).toString();
const dbioRewardLab = (
BigInt(fixedRewardLab) * BigInt(currencyUnit.DBIO)
).toString();

// Send reward to Customer
await sendRewards(
this.substrateService.api as any,
this.substrateService.pair,
order.customerId,
dbioRewardCustomer,
async () => {
// Send reward to Lab
await sendRewards(
this.substrateService.api as any,
this.substrateService.pair,
order.sellerId,
dbioRewardLab,
);
},
);

// Write Logging Notification Customer Reward From Request Service
const customerNotificationInput: NotificationDto = {
role: 'Customer',
entity_type: 'Order',
entity: 'Order Fulfilled',
reference_id: order.dnaSampleTrackingId,
description: `Congrats! You’ve received ${fixedRewardCustomer} DBIO as a reward for completing the request test for [] from the service requested, kindly check your balance.`,
read: false,
created_at: this.dateTimeProxy.new(),
updated_at: this.dateTimeProxy.new(),
deleted_at: null,
from: 'Debio Network',
to: order.customerId,
block_number: blockNumber,
};

await this.callbackInsertNotificationLogging(customerNotificationInput);

// Write Logging Reward Customer Staking Request Service
const dataCustomerLoggingInput: TransactionLoggingDto = {
address: order.customerId,
amount: rewardCustomer,
created_at: new Date(),
currency: 'DBIO',
parent_id: BigInt(0),
ref_number: order.id,
transaction_type: TransactionTypeList.Reward,
transaction_status: TransactionStatusList.CustomerStakeRequestService,
};
await this.loggingService.create(dataCustomerLoggingInput);

// Write Logging Notification Lab Reward From Request Service
const labNotificationInput: NotificationDto = {
role: 'Lab',
entity_type: 'Reward',
entity: 'Request Service Staking',
reference_id: order.dnaSampleTrackingId,
description: `Congrats! You’ve received ${fixedRewardLab} DBIO for completing the request test for [] from the service requested.`,
read: false,
created_at: this.dateTimeProxy.new(),
updated_at: this.dateTimeProxy.new(),
deleted_at: null,
from: 'Debio Network',
to: order.sellerId,
block_number: blockNumber,
};

await this.callbackInsertNotificationLogging(labNotificationInput);

// Write Logging Reward Lab
const dataLabLoggingInput: TransactionLoggingDto = {
address: order.customerId,
amount: rewardLab,
created_at: new Date(),
currency: 'DBIO',
parent_id: BigInt(0),
ref_number: order.id,
transaction_type: TransactionTypeList.Reward,
transaction_status: TransactionStatusList.LabProvideRequestedService,
};
await this.loggingService.create(dataLabLoggingInput);
}

private async callbackInsertNotificationLogging(data: NotificationDto) {
await this.notificationService.insert(data);
}

private convertToDate(date: Date) {
return new Date(Number(date.toString().split(',').join('')));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import {
Order,
queryOrderDetailByOrderID,
queryServiceRequestById,
RequestStatus,
sendRewards,
ServiceFlow,
ServiceRequest,
setOrderPaid,
} from '@debionetwork/polkadot-provider';
Expand All @@ -9,6 +13,7 @@ import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { NotificationDto } from '@common/notification/dto/notification.dto';
import {
DateTimeProxy,
DebioConversionService,
NotificationService,
SubstrateService,
TransactionLoggingService,
Expand All @@ -17,6 +22,7 @@ import { TransactionLoggingDto } from '@common/transaction-logging/dto/transacti
import { ServiceRequestUpdatedCommand } from './service-request-updated.command';
import { TransactionTypeList } from '@common/transaction-type/models/transaction-type.list';
import { TransactionStatusList } from '@common/transaction-status/models/transaction-status.list';
import currencyUnit from '@listeners/substrate-listener/models/currencyUnit';

@Injectable()
@CommandHandler(ServiceRequestUpdatedCommand)
Expand All @@ -28,6 +34,7 @@ export class ServiceRequestUpdatedHandler
);

constructor(
private readonly exchangeCacheService: DebioConversionService,
private readonly loggingService: TransactionLoggingService,
private readonly dateTimeProxy: DateTimeProxy,
private readonly substrateService: SubstrateService,
Expand All @@ -42,19 +49,45 @@ export class ServiceRequestUpdatedHandler
await queryServiceRequestById(this.substrateService.api, requestId)
).normalize();

switch (status) {
case RequestStatus.Claimed:
await this.onStatusClaimed(serviceRequest, blockMetaData.blockNumber);
break;
case RequestStatus.Processed:
await this.onStatusProcess(serviceRequest);
break;
case RequestStatus.Unstaked:
await this.onStatusUnstaked(serviceRequest);
break;
case RequestStatus.WaitingForUnstaked:
await this.onStatusWaitingForUnstaked(serviceRequest);
break;
if (status === RequestStatus.Claimed) {
await this.onStatusClaimed(serviceRequest, blockMetaData.blockNumber);
} else if (status === RequestStatus.Processed) {
await this.onStatusProcess(serviceRequest);
} else if (status === RequestStatus.Unstaked) {
await this.onStatusUnstaked(serviceRequest);
} else if (status === RequestStatus.WaitingForUnstaked) {
await this.onStatusWaitingForUnstaked(serviceRequest);
} else if (status === RequestStatus.Finalized) {
await this.onStatusFinalized(
serviceRequest,
blockMetaData.blockNumber.toString(),
);
}
}

async onStatusFinalized(serviceRequest: ServiceRequest, blockNumber: string) {
const orderDetail = await queryOrderDetailByOrderID(
this.substrateService.api,
serviceRequest.orderId,
);

const totalPrice = orderDetail.prices.reduce(
(acc, price) => acc + Number(price.value.split(',').join('')),
0,
);
const totalAdditionalPrice = orderDetail.additionalPrices.reduce(
(acc, price) => acc + Number(price.value.split(',').join('')),
0,
);

const amountToForward = totalPrice + totalAdditionalPrice;

if (orderDetail.orderFlow === ServiceFlow.StakingRequestService) {
await this.callbackSendReward(
orderDetail,
amountToForward / currencyUnit[orderDetail.currency],
blockNumber,
);
}
}

Expand Down Expand Up @@ -141,4 +174,111 @@ export class ServiceRequestUpdatedHandler

await this.notificationService.insert(serviceAvailableNotificationInput);
}

private async callbackInsertNotificationLogging(data: NotificationDto) {
await this.notificationService.insert(data);
}

private async callbackSendReward(
order: Order,
totalPrice: number,
blockNumber: string,
) {
const exchangeFromTo = await this.exchangeCacheService.getExchangeFromTo(
order.currency.toUpperCase(),
'DAI',
);
const exchange = await this.exchangeCacheService.getExchange();
const dbioToDai = exchange ? exchange['dbioToDai'] : 1;
const daiToDbio = 1 / dbioToDai;

const rewardCustomer = totalPrice * exchangeFromTo.conversion * daiToDbio;
const rewardLab = rewardCustomer / 10;
const fixedRewardCustomer = rewardCustomer.toFixed(0);
const fixedRewardLab = rewardLab.toFixed(0);
const dbioRewardCustomer = (
BigInt(fixedRewardCustomer) * BigInt(currencyUnit.DBIO)
).toString();
const dbioRewardLab = (
BigInt(fixedRewardLab) * BigInt(currencyUnit.DBIO)
).toString();

// Send reward to Customer
await sendRewards(
this.substrateService.api as any,
this.substrateService.pair,
order.customerId,
dbioRewardCustomer,
);

// Write Logging Notification Customer Reward From Request Service
const customerNotificationInput: NotificationDto = {
role: 'Customer',
entity_type: 'Order',
entity: 'Order Fulfilled',
reference_id: order.dnaSampleTrackingId,
description: `Congrats! You’ve received ${fixedRewardCustomer} DBIO as a reward for completing the request test for [] from the service requested, kindly check your balance.`,
read: false,
created_at: this.dateTimeProxy.new(),
updated_at: this.dateTimeProxy.new(),
deleted_at: null,
from: 'Debio Network',
to: order.customerId,
block_number: blockNumber,
};

await this.callbackInsertNotificationLogging(customerNotificationInput);

// Write Logging Reward Customer Staking Request Service
const dataCustomerLoggingInput: TransactionLoggingDto = {
address: order.customerId,
amount: rewardCustomer,
created_at: new Date(),
currency: 'DBIO',
parent_id: BigInt(0),
ref_number: order.id,
transaction_type: TransactionTypeList.Reward,
transaction_status: TransactionStatusList.CustomerStakeRequestService,
};
await this.loggingService.create(dataCustomerLoggingInput);

// Send reward to Lab
await sendRewards(
this.substrateService.api as any,
this.substrateService.pair,
order.sellerId,
dbioRewardLab,
);

// Write Logging Notification Lab Reward From Request Service
const labNotificationInput: NotificationDto = {
role: 'Lab',
entity_type: 'Reward',
entity: 'Request Service Staking',
reference_id: order.dnaSampleTrackingId,
description: `Congrats! You’ve received ${fixedRewardLab} DBIO for completing the request test for [] from the service requested.`,
read: false,
created_at: this.dateTimeProxy.new(),
updated_at: this.dateTimeProxy.new(),
deleted_at: null,
from: 'Debio Network',
to: order.sellerId,
block_number: blockNumber,
};

await this.callbackInsertNotificationLogging(labNotificationInput);

// Write Logging Reward Lab
const dataLabLoggingInput: TransactionLoggingDto = {
address: order.customerId,
amount: rewardLab,
created_at: new Date(),
currency: 'DBIO',
parent_id: BigInt(0),
ref_number: order.id,
transaction_type: TransactionTypeList.Reward,
transaction_status: TransactionStatusList.LabProvideRequestedService,
};
await this.loggingService.create(dataLabLoggingInput);
}
}