-prettier, fix type error

This commit is contained in:
Florian Dold 2022-09-16 17:04:32 +02:00
parent 374d3498d8
commit d6c545a0ba
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B

View File

@ -19,11 +19,14 @@
*/ */
import { import {
AbsoluteTime, AbsoluteTime,
addPaytoQueryParams, AmountJson, Amounts, addPaytoQueryParams,
AmountJson,
Amounts,
constructPayPullUri, constructPayPullUri,
constructPayPushUri, constructPayPushUri,
Logger, Logger,
OrderShortInfo, PaymentStatus, OrderShortInfo,
PaymentStatus,
RefundInfoShort, RefundInfoShort,
TalerProtocolTimestamp, TalerProtocolTimestamp,
Transaction, Transaction,
@ -33,7 +36,7 @@ import {
TransactionsResponse, TransactionsResponse,
TransactionType, TransactionType,
WithdrawalDetails, WithdrawalDetails,
WithdrawalType WithdrawalType,
} from "@gnu-taler/taler-util"; } from "@gnu-taler/taler-util";
import { import {
AbortStatus, AbortStatus,
@ -47,7 +50,7 @@ import {
TipRecord, TipRecord,
WalletRefundItem, WalletRefundItem,
WithdrawalGroupRecord, WithdrawalGroupRecord,
WithdrawalRecordType WithdrawalRecordType,
} from "../db.js"; } from "../db.js";
import { InternalWalletState } from "../internal-wallet-state.js"; import { InternalWalletState } from "../internal-wallet-state.js";
import { RetryTags } from "../util/retries.js"; import { RetryTags } from "../util/retries.js";
@ -140,55 +143,92 @@ export async function getTransactionById(
) { ) {
const withdrawalGroupId = rest[0]; const withdrawalGroupId = rest[0];
return await ws.db return await ws.db
.mktx((x) => [x.withdrawalGroups, x.exchangeDetails, x.exchanges, x.operationRetries]) .mktx((x) => [
x.withdrawalGroups,
x.exchangeDetails,
x.exchanges,
x.operationRetries,
])
.runReadWrite(async (tx) => { .runReadWrite(async (tx) => {
const withdrawalGroupRecord = await tx.withdrawalGroups.get( const withdrawalGroupRecord = await tx.withdrawalGroups.get(
withdrawalGroupId, withdrawalGroupId,
); );
if (!withdrawalGroupRecord) throw Error("not found") if (!withdrawalGroupRecord) throw Error("not found");
const opId = RetryTags.forWithdrawal(withdrawalGroupRecord); const opId = RetryTags.forWithdrawal(withdrawalGroupRecord);
const ort = await tx.operationRetries.get(opId); const ort = await tx.operationRetries.get(opId);
if (withdrawalGroupRecord.wgInfo.withdrawalType === WithdrawalRecordType.BankIntegrated) { if (
return buildTransactionForBankIntegratedWithdraw(withdrawalGroupRecord, ort); withdrawalGroupRecord.wgInfo.withdrawalType ===
WithdrawalRecordType.BankIntegrated
) {
return buildTransactionForBankIntegratedWithdraw(
withdrawalGroupRecord,
ort,
);
} }
if (withdrawalGroupRecord.wgInfo.withdrawalType === WithdrawalRecordType.PeerPullCredit) { if (
return buildTransactionForPullPaymentCredit(withdrawalGroupRecord, ort); withdrawalGroupRecord.wgInfo.withdrawalType ===
WithdrawalRecordType.PeerPullCredit
) {
return buildTransactionForPullPaymentCredit(
withdrawalGroupRecord,
ort,
);
} }
if (withdrawalGroupRecord.wgInfo.withdrawalType === WithdrawalRecordType.PeerPushCredit) { if (
return buildTransactionForPushPaymentCredit(withdrawalGroupRecord, ort); withdrawalGroupRecord.wgInfo.withdrawalType ===
WithdrawalRecordType.PeerPushCredit
) {
return buildTransactionForPushPaymentCredit(
withdrawalGroupRecord,
ort,
);
} }
const exchangeDetails = await getExchangeDetails(tx, withdrawalGroupRecord.exchangeBaseUrl,); const exchangeDetails = await getExchangeDetails(
if (!exchangeDetails) throw Error('not exchange details') tx,
withdrawalGroupRecord.exchangeBaseUrl,
return buildTransactionForManualWithdraw(withdrawalGroupRecord, exchangeDetails, ort); );
if (!exchangeDetails) throw Error("not exchange details");
return buildTransactionForManualWithdraw(
withdrawalGroupRecord,
exchangeDetails,
ort,
);
}); });
} else if (type === TransactionType.Payment) { } else if (type === TransactionType.Payment) {
const proposalId = rest[0]; const proposalId = rest[0];
return await ws.db return await ws.db
.mktx((x) => [x.purchases, x.tombstones, x.operationRetries]) .mktx((x) => [x.purchases, x.tombstones, x.operationRetries])
.runReadWrite(async (tx) => { .runReadWrite(async (tx) => {
const purchase = await tx.purchases.get(proposalId); const purchase = await tx.purchases.get(proposalId);
if (!purchase) throw Error("not found") if (!purchase) throw Error("not found");
const filteredRefunds = await Promise.all(Object.values(purchase.refunds).map(async r => { const filteredRefunds = await Promise.all(
const t = await tx.tombstones.get(makeEventId( Object.values(purchase.refunds).map(async (r) => {
TombstoneTag.DeleteRefund, const t = await tx.tombstones.get(
purchase.proposalId, makeEventId(
`${r.executionTime.t_s}`, TombstoneTag.DeleteRefund,
)) purchase.proposalId,
if (!t) return r `${r.executionTime.t_s}`,
return undefined ),
})); );
if (!t) return r;
return undefined;
}),
);
const cleanRefunds = filteredRefunds.filter((x): x is WalletRefundItem => !!x); const cleanRefunds = filteredRefunds.filter(
(x): x is WalletRefundItem => !!x,
);
const contractData = purchase.download.contractData; const contractData = purchase.download.contractData;
const refunds = mergeRefundByExecutionTime(cleanRefunds, Amounts.getZero(contractData.amount.currency)); const refunds = mergeRefundByExecutionTime(
cleanRefunds,
Amounts.getZero(contractData.amount.currency),
);
const payOpId = RetryTags.forPay(purchase); const payOpId = RetryTags.forPay(purchase);
const refundQueryOpId = RetryTags.forRefundQuery(purchase); const refundQueryOpId = RetryTags.forRefundQuery(purchase);
@ -197,24 +237,28 @@ export async function getTransactionById(
refundQueryOpId, refundQueryOpId,
); );
const err = payRetryRecord !== undefined ? payRetryRecord : refundQueryRetryRecord const err =
payRetryRecord !== undefined
? payRetryRecord
: refundQueryRetryRecord;
return buildTransactionForPurchase(purchase, refunds, err); return buildTransactionForPurchase(purchase, refunds, err);
}); });
} else if (type === TransactionType.Refresh) { } else if (type === TransactionType.Refresh) {
const refreshGroupId = rest[0]; const refreshGroupId = rest[0];
throw Error(`no tx for refresh`); throw Error(`no tx for refresh`);
} else if (type === TransactionType.Tip) { } else if (type === TransactionType.Tip) {
const tipId = rest[0]; const tipId = rest[0];
return await ws.db return await ws.db
.mktx((x) => [x.tips, x.operationRetries]) .mktx((x) => [x.tips, x.operationRetries])
.runReadWrite(async (tx) => { .runReadWrite(async (tx) => {
const tipRecord = await tx.tips.get(tipId); const tipRecord = await tx.tips.get(tipId);
if (!tipRecord) throw Error("not found") if (!tipRecord) throw Error("not found");
const retries = await tx.operationRetries.get(RetryTags.forTipPickup(tipRecord)); const retries = await tx.operationRetries.get(
return buildTransactionForTip(tipRecord, retries) RetryTags.forTipPickup(tipRecord),
);
return buildTransactionForTip(tipRecord, retries);
}); });
} else if (type === TransactionType.Deposit) { } else if (type === TransactionType.Deposit) {
const depositGroupId = rest[0]; const depositGroupId = rest[0];
@ -222,10 +266,12 @@ export async function getTransactionById(
.mktx((x) => [x.depositGroups, x.operationRetries]) .mktx((x) => [x.depositGroups, x.operationRetries])
.runReadWrite(async (tx) => { .runReadWrite(async (tx) => {
const depositRecord = await tx.depositGroups.get(depositGroupId); const depositRecord = await tx.depositGroups.get(depositGroupId);
if (!depositRecord) throw Error("not found") if (!depositRecord) throw Error("not found");
const retries = await tx.operationRetries.get(RetryTags.forDeposit(depositRecord)); const retries = await tx.operationRetries.get(
return buildTransactionForDeposit(depositRecord, retries) RetryTags.forDeposit(depositRecord),
);
return buildTransactionForDeposit(depositRecord, retries);
}); });
} else if (type === TransactionType.Refund) { } else if (type === TransactionType.Refund) {
const proposalId = rest[0]; const proposalId = rest[0];
@ -235,27 +281,38 @@ export async function getTransactionById(
.mktx((x) => [x.operationRetries, x.purchases, x.tombstones]) .mktx((x) => [x.operationRetries, x.purchases, x.tombstones])
.runReadWrite(async (tx) => { .runReadWrite(async (tx) => {
const purchase = await tx.purchases.get(proposalId); const purchase = await tx.purchases.get(proposalId);
if (!purchase) throw Error("not found") if (!purchase) throw Error("not found");
const theRefund = Object.values(purchase.refunds).find(r => `${r.executionTime.t_s}` === executionTimeStr) const theRefund = Object.values(purchase.refunds).find(
if (!theRefund) throw Error("not found") (r) => `${r.executionTime.t_s}` === executionTimeStr,
);
if (!theRefund) throw Error("not found");
const t = await tx.tombstones.get(makeEventId( const t = await tx.tombstones.get(
TombstoneTag.DeleteRefund, makeEventId(
purchase.proposalId, TombstoneTag.DeleteRefund,
executionTimeStr, purchase.proposalId,
)) executionTimeStr,
if (t) throw Error("deleted") ),
);
if (t) throw Error("deleted");
const contractData = purchase.download.contractData; const contractData = purchase.download.contractData;
const refunds = mergeRefundByExecutionTime([theRefund], Amounts.getZero(contractData.amount.currency)) const refunds = mergeRefundByExecutionTime(
[theRefund],
Amounts.getZero(contractData.amount.currency),
);
const refundQueryOpId = RetryTags.forRefundQuery(purchase); const refundQueryOpId = RetryTags.forRefundQuery(purchase);
const refundQueryRetryRecord = await tx.operationRetries.get( const refundQueryRetryRecord = await tx.operationRetries.get(
refundQueryOpId, refundQueryOpId,
); );
return buildTransactionForRefund(purchase, refunds[0], refundQueryRetryRecord); return buildTransactionForRefund(
purchase,
refunds[0],
refundQueryRetryRecord,
);
}); });
} else if (type === TransactionType.PeerPullDebit) { } else if (type === TransactionType.PeerPullDebit) {
const peerPullPaymentIncomingId = rest[0]; const peerPullPaymentIncomingId = rest[0];
@ -266,7 +323,7 @@ export async function getTransactionById(
peerPullPaymentIncomingId, peerPullPaymentIncomingId,
); );
if (!debit) throw Error("not found"); if (!debit) throw Error("not found");
return buildTransactionForPullPaymentDebit(debit) return buildTransactionForPullPaymentDebit(debit);
}); });
} else if (type === TransactionType.PeerPushDebit) { } else if (type === TransactionType.PeerPushDebit) {
const pursePub = rest[0]; const pursePub = rest[0];
@ -275,7 +332,7 @@ export async function getTransactionById(
.runReadWrite(async (tx) => { .runReadWrite(async (tx) => {
const debit = await tx.peerPushPaymentInitiations.get(pursePub); const debit = await tx.peerPushPaymentInitiations.get(pursePub);
if (!debit) throw Error("not found"); if (!debit) throw Error("not found");
return buildTransactionForPushPaymentDebit(debit) return buildTransactionForPushPaymentDebit(debit);
}); });
} else { } else {
const unknownTxType: never = type; const unknownTxType: never = type;
@ -283,8 +340,10 @@ export async function getTransactionById(
} }
} }
function buildTransactionForPushPaymentDebit(
function buildTransactionForPushPaymentDebit(pi: PeerPushPaymentInitiationRecord, ort?: OperationRetryRecord): Transaction { pi: PeerPushPaymentInitiationRecord,
ort?: OperationRetryRecord,
): Transaction {
return { return {
type: TransactionType.PeerPushDebit, type: TransactionType.PeerPushDebit,
amountEffective: pi.amount, amountEffective: pi.amount,
@ -301,15 +360,15 @@ function buildTransactionForPushPaymentDebit(pi: PeerPushPaymentInitiationRecord
exchangeBaseUrl: pi.exchangeBaseUrl, exchangeBaseUrl: pi.exchangeBaseUrl,
contractPriv: pi.contractPriv, contractPriv: pi.contractPriv,
}), }),
transactionId: makeEventId( transactionId: makeEventId(TransactionType.PeerPushDebit, pi.pursePub),
TransactionType.PeerPushDebit,
pi.pursePub,
),
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
}; };
} }
function buildTransactionForPullPaymentDebit(pi: PeerPullPaymentIncomingRecord, ort?: OperationRetryRecord): Transaction { function buildTransactionForPullPaymentDebit(
pi: PeerPullPaymentIncomingRecord,
ort?: OperationRetryRecord,
): Transaction {
return { return {
type: TransactionType.PeerPullDebit, type: TransactionType.PeerPullDebit,
amountEffective: Amounts.stringify(pi.contractTerms.amount), amountEffective: Amounts.stringify(pi.contractTerms.amount),
@ -327,11 +386,15 @@ function buildTransactionForPullPaymentDebit(pi: PeerPullPaymentIncomingRecord,
pi.peerPullPaymentIncomingId, pi.peerPullPaymentIncomingId,
), ),
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
function buildTransactionForPullPaymentCredit(wsr: WithdrawalGroupRecord, ort?: OperationRetryRecord): Transaction { function buildTransactionForPullPaymentCredit(
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.PeerPullCredit) throw Error("") wsr: WithdrawalGroupRecord,
ort?: OperationRetryRecord,
): Transaction {
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.PeerPullCredit)
throw Error("");
return { return {
type: TransactionType.PeerPullCredit, type: TransactionType.PeerPullCredit,
amountEffective: Amounts.stringify(wsr.denomsSel.totalCoinValue), amountEffective: Amounts.stringify(wsr.denomsSel.totalCoinValue),
@ -353,11 +416,15 @@ function buildTransactionForPullPaymentCredit(wsr: WithdrawalGroupRecord, ort?:
), ),
frozen: false, frozen: false,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
function buildTransactionForPushPaymentCredit(wsr: WithdrawalGroupRecord, ort?: OperationRetryRecord): Transaction { function buildTransactionForPushPaymentCredit(
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.PeerPushCredit) throw Error("") wsr: WithdrawalGroupRecord,
ort?: OperationRetryRecord,
): Transaction {
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.PeerPushCredit)
throw Error("");
return { return {
type: TransactionType.PeerPushCredit, type: TransactionType.PeerPushCredit,
amountEffective: Amounts.stringify(wsr.denomsSel.totalCoinValue), amountEffective: Amounts.stringify(wsr.denomsSel.totalCoinValue),
@ -375,11 +442,15 @@ function buildTransactionForPushPaymentCredit(wsr: WithdrawalGroupRecord, ort?:
), ),
frozen: false, frozen: false,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
function buildTransactionForBankIntegratedWithdraw(wsr: WithdrawalGroupRecord, ort?: OperationRetryRecord): Transaction { function buildTransactionForBankIntegratedWithdraw(
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.BankIntegrated) throw Error("") wsr: WithdrawalGroupRecord,
ort?: OperationRetryRecord,
): Transaction {
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.BankIntegrated)
throw Error("");
return { return {
type: TransactionType.Withdrawal, type: TransactionType.Withdrawal,
@ -387,9 +458,7 @@ function buildTransactionForBankIntegratedWithdraw(wsr: WithdrawalGroupRecord, o
amountRaw: Amounts.stringify(wsr.rawWithdrawalAmount), amountRaw: Amounts.stringify(wsr.rawWithdrawalAmount),
withdrawalDetails: { withdrawalDetails: {
type: WithdrawalType.TalerBankIntegrationApi, type: WithdrawalType.TalerBankIntegrationApi,
confirmed: wsr.wgInfo.bankInfo.timestampBankConfirmed confirmed: wsr.wgInfo.bankInfo.timestampBankConfirmed ? true : false,
? true
: false,
reservePub: wsr.reservePub, reservePub: wsr.reservePub,
bankConfirmationUrl: wsr.wgInfo.bankInfo.confirmUrl, bankConfirmationUrl: wsr.wgInfo.bankInfo.confirmUrl,
}, },
@ -402,11 +471,16 @@ function buildTransactionForBankIntegratedWithdraw(wsr: WithdrawalGroupRecord, o
), ),
frozen: false, frozen: false,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
function buildTransactionForManualWithdraw(wsr: WithdrawalGroupRecord, exchangeDetails: ExchangeDetailsRecord, ort?: OperationRetryRecord): Transaction { function buildTransactionForManualWithdraw(
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.BankManual) throw Error("") wsr: WithdrawalGroupRecord,
exchangeDetails: ExchangeDetailsRecord,
ort?: OperationRetryRecord,
): Transaction {
if (wsr.wgInfo.withdrawalType !== WithdrawalRecordType.BankManual)
throw Error("");
return { return {
type: TransactionType.Withdrawal, type: TransactionType.Withdrawal,
@ -416,8 +490,8 @@ function buildTransactionForManualWithdraw(wsr: WithdrawalGroupRecord, exchangeD
type: WithdrawalType.ManualTransfer, type: WithdrawalType.ManualTransfer,
reservePub: wsr.reservePub, reservePub: wsr.reservePub,
exchangePaytoUris: exchangePaytoUris:
exchangeDetails.wireInfo?.accounts.map( exchangeDetails.wireInfo?.accounts.map((x) =>
(x) => addPaytoQueryParams(x.payto_uri, { subject: wsr.reservePub }), addPaytoQueryParams(x.payto_uri, { subject: wsr.reservePub }),
) ?? [], ) ?? [],
}, },
exchangeBaseUrl: wsr.exchangeBaseUrl, exchangeBaseUrl: wsr.exchangeBaseUrl,
@ -429,10 +503,13 @@ function buildTransactionForManualWithdraw(wsr: WithdrawalGroupRecord, exchangeD
), ),
frozen: false, frozen: false,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
function buildTransactionForDeposit(dg: DepositGroupRecord, ort?: OperationRetryRecord): Transaction { function buildTransactionForDeposit(
dg: DepositGroupRecord,
ort?: OperationRetryRecord,
): Transaction {
return { return {
type: TransactionType.Deposit, type: TransactionType.Deposit,
amountRaw: Amounts.stringify(dg.effectiveDepositAmount), amountRaw: Amounts.stringify(dg.effectiveDepositAmount),
@ -441,17 +518,17 @@ function buildTransactionForDeposit(dg: DepositGroupRecord, ort?: OperationRetry
frozen: false, frozen: false,
timestamp: dg.timestampCreated, timestamp: dg.timestampCreated,
targetPaytoUri: dg.wire.payto_uri, targetPaytoUri: dg.wire.payto_uri,
transactionId: makeEventId( transactionId: makeEventId(TransactionType.Deposit, dg.depositGroupId),
TransactionType.Deposit,
dg.depositGroupId,
),
depositGroupId: dg.depositGroupId, depositGroupId: dg.depositGroupId,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
function buildTransactionForTip(tipRecord: TipRecord, ort?: OperationRetryRecord): Transaction { function buildTransactionForTip(
if (!tipRecord.acceptedTimestamp) throw Error("") tipRecord: TipRecord,
ort?: OperationRetryRecord,
): Transaction {
if (!tipRecord.acceptedTimestamp) throw Error("");
return { return {
type: TransactionType.Tip, type: TransactionType.Tip,
@ -460,18 +537,15 @@ function buildTransactionForTip(tipRecord: TipRecord, ort?: OperationRetryRecord
pending: !tipRecord.pickedUpTimestamp, pending: !tipRecord.pickedUpTimestamp,
frozen: false, frozen: false,
timestamp: tipRecord.acceptedTimestamp, timestamp: tipRecord.acceptedTimestamp,
transactionId: makeEventId( transactionId: makeEventId(TransactionType.Tip, tipRecord.walletTipId),
TransactionType.Tip,
tipRecord.walletTipId,
),
merchantBaseUrl: tipRecord.merchantBaseUrl, merchantBaseUrl: tipRecord.merchantBaseUrl,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
/** /**
* For a set of refund with the same executionTime. * For a set of refund with the same executionTime.
* *
*/ */
interface MergedRefundInfo { interface MergedRefundInfo {
executionTime: TalerProtocolTimestamp; executionTime: TalerProtocolTimestamp;
@ -480,40 +554,56 @@ interface MergedRefundInfo {
firstTimestamp: TalerProtocolTimestamp; firstTimestamp: TalerProtocolTimestamp;
} }
function mergeRefundByExecutionTime(rs: WalletRefundItem[], zero: AmountJson): MergedRefundInfo[] { function mergeRefundByExecutionTime(
rs: WalletRefundItem[],
zero: AmountJson,
): MergedRefundInfo[] {
const refundByExecTime = rs.reduce((prev, refund) => { const refundByExecTime = rs.reduce((prev, refund) => {
const key = `${refund.executionTime.t_s}`; const key = `${refund.executionTime.t_s}`;
//refunds counts if applied //refunds counts if applied
const effective = refund.type === RefundState.Applied ? Amounts.sub( const effective =
refund.refundAmount, refund.type === RefundState.Applied
refund.refundFee, ? Amounts.sub(
refund.totalRefreshCostBound, refund.refundAmount,
).amount : zero refund.refundFee,
const raw = refund.type === RefundState.Applied ? refund.refundAmount : zero refund.totalRefreshCostBound,
).amount
: zero;
const raw =
refund.type === RefundState.Applied ? refund.refundAmount : zero;
const v = prev.get(key) const v = prev.get(key);
if (!v) { if (!v) {
prev.set(key, { prev.set(key, {
executionTime: refund.executionTime, executionTime: refund.executionTime,
amountAppliedEffective: effective, amountAppliedEffective: effective,
amountAppliedRaw: raw, amountAppliedRaw: raw,
firstTimestamp: refund.obtainedTime firstTimestamp: refund.obtainedTime,
}) });
} else { } else {
//v.executionTime is the same //v.executionTime is the same
v.amountAppliedEffective = Amounts.add(v.amountAppliedEffective, effective).amount; v.amountAppliedEffective = Amounts.add(
v.amountAppliedRaw = Amounts.add(v.amountAppliedRaw).amount v.amountAppliedEffective,
v.firstTimestamp = TalerProtocolTimestamp.min(v.firstTimestamp, refund.obtainedTime); effective,
).amount;
v.amountAppliedRaw = Amounts.add(v.amountAppliedRaw).amount;
v.firstTimestamp = TalerProtocolTimestamp.min(
v.firstTimestamp,
refund.obtainedTime,
);
} }
return prev return prev;
}, {} as Map<string, MergedRefundInfo>); }, new Map<string, MergedRefundInfo>());
return Array.from(refundByExecTime.values()); return Array.from(refundByExecTime.values());
} }
function buildTransactionForRefund(purchaseRecord: PurchaseRecord, refundInfo: MergedRefundInfo, ort?: OperationRetryRecord): Transaction { function buildTransactionForRefund(
purchaseRecord: PurchaseRecord,
refundInfo: MergedRefundInfo,
ort?: OperationRetryRecord,
): Transaction {
const contractData = purchaseRecord.download.contractData; const contractData = purchaseRecord.download.contractData;
const info: OrderShortInfo = { const info: OrderShortInfo = {
@ -550,13 +640,16 @@ function buildTransactionForRefund(purchaseRecord: PurchaseRecord, refundInfo: M
pending: false, pending: false,
frozen: false, frozen: false,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
function buildTransactionForPurchase(purchaseRecord: PurchaseRecord, refundsInfo: MergedRefundInfo[], ort?: OperationRetryRecord): Transaction { function buildTransactionForPurchase(
purchaseRecord: PurchaseRecord,
refundsInfo: MergedRefundInfo[],
ort?: OperationRetryRecord,
): Transaction {
const contractData = purchaseRecord.download.contractData; const contractData = purchaseRecord.download.contractData;
const zero = Amounts.getZero(contractData.amount.currency) const zero = Amounts.getZero(contractData.amount.currency);
const info: OrderShortInfo = { const info: OrderShortInfo = {
merchant: contractData.merchant, merchant: contractData.merchant,
@ -571,25 +664,30 @@ function buildTransactionForPurchase(purchaseRecord: PurchaseRecord, refundsInfo
info.fulfillmentUrl = contractData.fulfillmentUrl; info.fulfillmentUrl = contractData.fulfillmentUrl;
} }
const totalRefund = refundsInfo.reduce((prev, cur) => { const totalRefund = refundsInfo.reduce(
return { (prev, cur) => {
raw: Amounts.add(prev.raw, cur.amountAppliedRaw).amount, return {
effective: Amounts.add(prev.effective, cur.amountAppliedEffective).amount, raw: Amounts.add(prev.raw, cur.amountAppliedRaw).amount,
} effective: Amounts.add(prev.effective, cur.amountAppliedEffective)
}, { .amount,
raw: zero, effective: zero };
} as { raw: AmountJson, effective: AmountJson }) },
{
raw: zero,
effective: zero,
} as { raw: AmountJson; effective: AmountJson },
);
const refunds: RefundInfoShort[] = refundsInfo.map(r => ({ const refunds: RefundInfoShort[] = refundsInfo.map((r) => ({
amountEffective: Amounts.stringify(r.amountAppliedEffective), amountEffective: Amounts.stringify(r.amountAppliedEffective),
amountRaw: Amounts.stringify(r.amountAppliedRaw), amountRaw: Amounts.stringify(r.amountAppliedRaw),
timestamp: r.executionTime, timestamp: r.executionTime,
transactionId: makeEventId( transactionId: makeEventId(
TransactionType.Refund, TransactionType.Refund,
purchaseRecord.proposalId, purchaseRecord.proposalId,
`${r.executionTime.t_s}` `${r.executionTime.t_s}`,
), ),
})) }));
return { return {
type: TransactionType.Payment, type: TransactionType.Payment,
@ -617,7 +715,7 @@ function buildTransactionForPurchase(purchaseRecord: PurchaseRecord, refundsInfo
info, info,
frozen: purchaseRecord.payFrozen ?? false, frozen: purchaseRecord.payFrozen ?? false,
...(ort?.lastError ? { error: ort.lastError } : {}), ...(ort?.lastError ? { error: ort.lastError } : {}),
} };
} }
/** /**
@ -703,7 +801,9 @@ export async function getTransactions(
} else if ( } else if (
wsr.wgInfo.withdrawalType === WithdrawalRecordType.BankIntegrated wsr.wgInfo.withdrawalType === WithdrawalRecordType.BankIntegrated
) { ) {
transactions.push(buildTransactionForBankIntegratedWithdraw(wsr, ort)); transactions.push(
buildTransactionForBankIntegratedWithdraw(wsr, ort),
);
} else { } else {
const exchangeDetails = await getExchangeDetails( const exchangeDetails = await getExchangeDetails(
tx, tx,
@ -714,7 +814,9 @@ export async function getTransactions(
return; return;
} }
transactions.push(buildTransactionForManualWithdraw(wsr, exchangeDetails, ort)); transactions.push(
buildTransactionForManualWithdraw(wsr, exchangeDetails, ort),
);
} }
}); });
@ -747,19 +849,28 @@ export async function getTransactions(
return; return;
} }
const filteredRefunds = await Promise.all(Object.values(pr.refunds).map(async r => { const filteredRefunds = await Promise.all(
const t = await tx.tombstones.get(makeEventId( Object.values(pr.refunds).map(async (r) => {
TombstoneTag.DeleteRefund, const t = await tx.tombstones.get(
pr.proposalId, makeEventId(
`${r.executionTime.t_s}`, TombstoneTag.DeleteRefund,
)) pr.proposalId,
if (!t) return r `${r.executionTime.t_s}`,
return undefined ),
})); );
if (!t) return r;
return undefined;
}),
);
const cleanRefunds = filteredRefunds.filter((x): x is WalletRefundItem => !!x); const cleanRefunds = filteredRefunds.filter(
(x): x is WalletRefundItem => !!x,
);
const refunds = mergeRefundByExecutionTime(cleanRefunds, Amounts.getZero(contractData.amount.currency)); const refunds = mergeRefundByExecutionTime(
cleanRefunds,
Amounts.getZero(contractData.amount.currency),
);
refunds.forEach(async (refundInfo) => { refunds.forEach(async (refundInfo) => {
const refundQueryOpId = RetryTags.forRefundQuery(pr); const refundQueryOpId = RetryTags.forRefundQuery(pr);
@ -768,9 +879,9 @@ export async function getTransactions(
); );
transactions.push( transactions.push(
buildTransactionForRefund(pr, refundInfo, refundQueryRetryRecord) buildTransactionForRefund(pr, refundInfo, refundQueryRetryRecord),
) );
}) });
const payOpId = RetryTags.forPay(pr); const payOpId = RetryTags.forPay(pr);
const refundQueryOpId = RetryTags.forRefundQuery(pr); const refundQueryOpId = RetryTags.forRefundQuery(pr);
@ -779,7 +890,10 @@ export async function getTransactions(
refundQueryOpId, refundQueryOpId,
); );
const err = payRetryRecord !== undefined ? payRetryRecord : refundQueryRetryRecord const err =
payRetryRecord !== undefined
? payRetryRecord
: refundQueryRetryRecord;
transactions.push(buildTransactionForPurchase(pr, refunds, err)); transactions.push(buildTransactionForPurchase(pr, refunds, err));
}); });