Skip to content

Commit

Permalink
fix: staking request (#213)
Browse files Browse the repository at this point in the history
* staking request fulfilled reward

- update menstrual calendar cycle log model data
- update menstrual calendar handler
- update genetic analyst order fulfilled notification and log
- update order fulfilled calculate price and additional price

* change amount for reward

* conversion from USDT to DBIO

* fix format

* fix unit test

Co-authored-by: Hildegard Lydia <[email protected]>
  • Loading branch information
rubenkristian and hilyds authored Nov 17, 2022
1 parent 7ebbc90 commit b196b76
Show file tree
Hide file tree
Showing 10 changed files with 145 additions and 114 deletions.
28 changes: 28 additions & 0 deletions src/common/debio-conversion/debio-conversion.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,32 @@ export class DebioConversionService {
this.logger.log(`API conversion": ${error.message}`);
}
}

async getExchangeFromTo(from: string, to: string) {
try {
const res = await axios.get(
`${this.gCloudSecretManagerService
.getSecret('REDIS_STORE_URL')
.toString()}/cache`,
{
params: {
from,
to,
},
auth: {
username: this.gCloudSecretManagerService
.getSecret('REDIS_STORE_USERNAME')
.toString(),
password: this.gCloudSecretManagerService
.getSecret('REDIS_STORE_PASSWORD')
.toString(),
},
},
);

return res.data;
} catch (error) {
this.logger.log(`API conversion": ${error.message}`);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ import { MenstrualCycleLog } from '../../../../models/menstrual-calendar/menstru
import { BlockMetaData } from '../../../../models/block-meta-data';

export class MenstrualCycleLogAddedCommandIndexer {
menstrualCycleLog: MenstrualCycleLog;
menstrualCycleLog: Array<MenstrualCycleLog>;
accountId: string;
constructor(data: Array<any>, public readonly blockMetaData: BlockMetaData) {
const menstrualCycleLogData = data[0];
this.accountId = data[1].toString();
this.menstrualCycleLog = new MenstrualCycleLog(
menstrualCycleLogData.toHuman(),
);

const arrayMenstrualCycleLogData = menstrualCycleLogData.toHuman();

this.menstrualCycleLog = arrayMenstrualCycleLogData.map((cycleLog: any) => {
return new MenstrualCycleLog(cycleLog);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,30 @@ export class MenstrualCycleLogAddedHandler
constructor(private readonly elasticsearchService: ElasticsearchService) {}

async execute(command: MenstrualCycleLogAddedCommandIndexer) {
const {
menstrualCycleLog: {
id,
menstrualCalendarId,
date,
menstruation,
symptoms,
createdAt,
},
accountId,
blockMetaData,
} = command;
await this.elasticsearchService.create({
index: 'menstrual-cycle-log',
id: id,
const { menstrualCycleLog, accountId, blockMetaData } = command;

const bulk_data = [];

for (const cycleLog of menstrualCycleLog) {
bulk_data.push(
{ index: { _index: 'menstrual-cycle-log', _id: cycleLog.id } },
{
menstrual_calendar_cycle_log_id: cycleLog.id,
account_id: accountId,
menstrual_calendar_id: cycleLog.menstrualCalendarId,
date: cycleLog.date.getTime(),
menstruation: cycleLog.menstruation,
symptoms: cycleLog.symptoms,
created_at: cycleLog.createdAt.getTime(),
updated_at: null,
blockMetaData: blockMetaData,
},
);
}

await this.elasticsearchService.bulk({
refresh: 'wait_for',
body: {
menstrual_calendar_cycle_log_id: id,
account_id: accountId,
menstrual_calendar_id: menstrualCalendarId,
date: date.getTime(),
menstruation: menstruation,
symptoms: symptoms,
created_at: createdAt.getTime(),
updated_at: null,
blockMetaData: blockMetaData,
},
body: bulk_data,
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,20 @@ export class GeneticAnalysisOrderFulfilledHandler
const geneticAnalysisOrderHistory =
await this.loggingService.getLoggingByOrderId(geneticAnalysisOrder.id);

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

const amountToForward = totalPrice + totalAdditionalPrice;

const geneticAnalysisOrderLogging: TransactionLoggingDto = {
address: geneticAnalysisOrder.customerId,
amount: +geneticAnalysisOrder.prices[0].value,
amount: amountToForward / currencyUnit[geneticAnalysisOrder.currency],
created_at: geneticAnalysisOrder.updatedAt,
currency: geneticAnalysisOrder.currency.toUpperCase(),
parent_id: BigInt(geneticAnalysisOrderHistory.id),
Expand All @@ -55,7 +66,10 @@ export class GeneticAnalysisOrderFulfilledHandler

const serviceChargeLogging: TransactionLoggingDto = {
address: geneticAnalysisOrder.customerId,
amount: (+geneticAnalysisOrder.prices[0].value * 5) / 100, //5% prices
amount:
((amountToForward / currencyUnit[geneticAnalysisOrder.currency]) *
5) /
100, //5% prices
created_at: geneticAnalysisOrder.updatedAt,
currency: geneticAnalysisOrder.currency.toUpperCase(),
parent_id: BigInt(geneticAnalysisOrderHistory.id),
Expand All @@ -69,17 +83,6 @@ export class GeneticAnalysisOrderFulfilledHandler
await this.loggingService.create(serviceChargeLogging);
}

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

const amountToForward = totalPrice + totalAdditionalPrice;

const currDate = this.dateTimeProxy.new();

const receivePaymentNotification: NotificationDto = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,22 @@ export class OrderFulfilledHandler
const orderHistory = await this.loggingService.getLoggingByOrderId(
order.id,
);

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

const amountToForward = totalPrice + totalAdditionalPrice;

// Logging data input
const orderLogging: TransactionLoggingDto = {
address: order.customerId,
amount: +order.additionalPrices[0].value + +order.prices[0].value,
amount: amountToForward / currencyUnit[order.currency],
created_at: order.updatedAt,
currency: order.currency.toUpperCase(),
parent_id: orderHistory?.id ? BigInt(orderHistory.id) : BigInt(0),
Expand All @@ -79,22 +91,6 @@ export class OrderFulfilledHandler
return null;
}

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

const amountToForward = totalPrice + totalAdditionalPrice;

const exchange = await this.exchangeCacheService.getExchange();
const dbioToDai = exchange ? Number(exchange['dbioToDai']) : 1;

const daiPrice = amountToForward * dbioToDai;

if (order.orderFlow === ServiceFlow.StakingRequestService) {
const { hash: requestId } = await queryServiceRequestById(
this.substrateService.api,
Expand All @@ -106,7 +102,12 @@ export class OrderFulfilledHandler
this.substrateService.pair,
requestId,
);
await this.callbackSendReward(order, daiPrice, blockNumber);

await this.callbackSendReward(
order,
amountToForward / currencyUnit[order.currency],
blockNumber,
);
}

await this.escrowService.orderFulfilled(order);
Expand Down Expand Up @@ -138,6 +139,7 @@ export class OrderFulfilledHandler
this.logger.log(`labEthAddress: ${labEthAddress}`);
this.logger.log(`amountToForward: ${amountToForward}`);
} catch (err) {
console.log(err);
this.logger.log(err);
this.logger.log(`Forward payment failed | err -> ${err}`);
}
Expand All @@ -152,8 +154,18 @@ export class OrderFulfilledHandler
totalPrice: number,
blockNumber: string,
) {
const dbioRewardCustomer = convertToDbioUnitString(totalPrice);
const dbioRewardLab = convertToDbioUnitString(totalPrice / 10);
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 dbioCurrency = totalPrice * exchangeFromTo.conversion * daiToDbio;

const dbioRewardCustomer = dbioCurrency.toFixed(4);
const dbioRewardLab = (dbioCurrency / 10).toFixed(4);
// Send reward to customer
await sendRewards(
this.substrateService.api as any,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ describe('Data Staked Integration Tests', () => {
0,
lab.info.boxPublicKey,
serviceDataMock.serviceFlow,
0,
() => {
queryLastOrderHashByCustomer(api, pair.address).then((orderId) => {
queryOrderDetailByOrderID(api, orderId).then((res) => {
Expand Down Expand Up @@ -316,6 +317,7 @@ describe('Data Staked Integration Tests', () => {
0,
lab.info.boxPublicKey,
serviceDataMock.serviceFlow,
0,
() => {
queryLastOrderHashByCustomer(api, pair.address).then((orderId) => {
queryOrderDetailByOrderID(api, orderId).then((res) => {
Expand Down Expand Up @@ -425,6 +427,7 @@ describe('Data Staked Integration Tests', () => {
0,
lab.info.boxPublicKey,
serviceDataMock.serviceFlow,
0,
() => {
queryLastOrderHashByCustomer(api, pair.address).then((orderId) => {
queryOrderDetailByOrderID(api, orderId).then((res) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,14 @@ import { LabRating } from '../../../../../mock/models/rating/rating.entity';
import { TransactionRequest } from '../../../../../../src/common/transaction-logging/models/transaction-request.entity';
import { dummyCredentials } from '../../../../config';
import { EscrowService } from '../../../../../../src/common/escrow/escrow.service';
import { escrowServiceMockFactory } from '../../../../../unit/mock';
import {
escrowServiceMockFactory,
mailerManagerMockFactory,
} from '../../../../../unit/mock';
import {
DateTimeModule,
DebioConversionModule,
MailerManager,
NotificationModule,
ProcessEnvModule,
SubstrateModule,
Expand Down Expand Up @@ -175,6 +179,10 @@ describe('Order Failed Integration Tests', () => {
provide: EscrowService,
useFactory: escrowServiceMockFactory,
},
{
provide: MailerManager,
useFactory: mailerManagerMockFactory,
},
SubstrateListenerHandler,
OrderFailedHandler,
OrderFulfilledHandler,
Expand Down Expand Up @@ -232,6 +240,7 @@ describe('Order Failed Integration Tests', () => {
0,
lab.info.boxPublicKey,
serviceDataMock.serviceFlow,
0,
() => {
queryLastOrderHashByCustomer(api, pair.address).then((orderId) => {
queryOrderDetailByOrderID(api, orderId).then((res) => {
Expand Down Expand Up @@ -356,6 +365,7 @@ describe('Order Failed Integration Tests', () => {
0,
lab.info.boxPublicKey,
serviceDataMock.serviceFlow,
0,
() => {
queryLastOrderHashByCustomer(api, pair.address).then((orderId) => {
queryOrderDetailByOrderID(api, orderId).then((res) => {
Expand Down Expand Up @@ -460,6 +470,7 @@ describe('Order Failed Integration Tests', () => {
0,
lab.info.boxPublicKey,
serviceDataMock.serviceFlow,
0,
() => {
queryLastOrderHashByCustomer(api, pair.address).then((orderId) => {
queryOrderDetailByOrderID(api, orderId).then((res) => {
Expand Down
Loading

0 comments on commit b196b76

Please sign in to comment.