Skip to content

Commit 2309403

Browse files
committed
refactor: clean up code
1 parent 933ce99 commit 2309403

File tree

4 files changed

+51
-35
lines changed

4 files changed

+51
-35
lines changed

constants/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ export const RESPONSE_MESSAGES = {
4646
FAILED_TO_FETCH_PRICE_FROM_API_500: (day: string, ticker: string) => { return { statusCode: 500, message: `Failed to fetch ${ticker} price for day ${day}` } },
4747
MISSING_WS_AUTH_KEY_400: { statusCode: 400, message: 'Missing WS_AUTH_KEY environment variable' },
4848
MISSING_PRICE_FOR_TRANSACTION_400: { statusCode: 400, message: 'Missing price for transaction.' },
49+
INVALID_PRICES_FOR_TX_ON_CSV_CREATION_500: (pricesLenght: number) => { return {statusCode: 500, message: `Missing price for transaction in CSV creation. ${pricesLenght}` }},
4950
INVALID_PRICE_STATE_400: { statusCode: 400, message: 'Missing expected quote price for transaction.' },
5051
COULD_NOT_GET_BLOCK_INFO_500: { statusCode: 500, message: "Couldn't get block info." },
5152
NETWORK_SLUG_NOT_PROVIDED_400: { statusCode: 400, message: "'networkSlug' not provided." },

pages/api/paybutton/download/transactions/[paybuttonId].ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import {
22
RESPONSE_MESSAGES,
33
NetworkTickersType,
4-
NETWORK_TICKERS,
54
NETWORK_IDS,
6-
SUPPORTED_QUOTES_FROM_ID
5+
SUPPORTED_QUOTES_FROM_ID,
6+
NETWORK_SLUGS_FROM_IDS
77
} from 'constants/index'
88
import { fetchTransactionsByPaybuttonId } from 'services/transactionService'
99
import { fetchPaybuttonById } from 'services/paybuttonService'
@@ -45,10 +45,13 @@ export default async (req: any, res: any): Promise<void> => {
4545
const timezone = userPreferredTimezone !== '' ? userPreferredTimezone : userReqTimezone
4646
let networkIdArray = Object.values(NETWORK_IDS)
4747
if (networkTicker !== undefined) {
48-
const slug = Object.keys(NETWORK_TICKERS).find(key => NETWORK_TICKERS[key] === networkTicker)
49-
const networkId = getNetworkIdFromSlug(slug ?? NETWORK_TICKERS.ecash)
48+
const slug = NETWORK_SLUGS_FROM_IDS[NETWORK_IDS[networkTicker]]
49+
if (slug === undefined) {
50+
throw new Error(RESPONSE_MESSAGES.INVALID_NETWORK_SLUG_400.message)
51+
}
52+
const networkId = getNetworkIdFromSlug(slug)
5053
networkIdArray = [networkId]
51-
}
54+
};
5255
const transactions = await fetchTransactionsByPaybuttonId(paybutton.id, networkIdArray)
5356
res.setHeader('Content-Type', 'text/csv')
5457
await downloadTxsFile(res, quoteSlug, timezone, transactions)

pages/api/payments/download/index.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
SUPPORTED_QUOTES_FROM_ID,
44
NetworkTickersType,
55
NETWORK_IDS,
6-
NETWORK_TICKERS
6+
NETWORK_SLUGS_FROM_IDS
77
} from 'constants/index'
88
import { downloadTxsFile, isNetworkValid } from 'utils/files'
99
import { setSession } from 'utils/setSession'
@@ -38,8 +38,11 @@ export default async (req: any, res: any): Promise<void> => {
3838
res.setHeader('Content-Type', 'text/csv')
3939
let networkIdArray = Object.values(NETWORK_IDS)
4040
if (networkTicker !== undefined) {
41-
const slug = Object.keys(NETWORK_TICKERS).find(key => NETWORK_TICKERS[key] === networkTicker)
42-
const networkId = getNetworkIdFromSlug(slug ?? NETWORK_TICKERS.ecash)
41+
const slug = NETWORK_SLUGS_FROM_IDS[NETWORK_IDS[networkTicker]]
42+
if (slug === undefined) {
43+
throw new Error(RESPONSE_MESSAGES.INVALID_NETWORK_SLUG_400.message)
44+
}
45+
const networkId = getNetworkIdFromSlug(slug)
4346
networkIdArray = [networkId]
4447
};
4548
const transactions = await fetchAllPaymentsByUserId(userId, networkIdArray)

utils/files.ts

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
NETWORK_TICKERS_FROM_ID,
1010
NetworkTickersType,
1111
PAYBUTTON_TRANSACTIONS_FILE_HEADERS,
12-
PRICE_API_DATE_FORMAT, RESPONSE_MESSAGES,
12+
PRICE_API_DATE_FORMAT, QUOTE_IDS, RESPONSE_MESSAGES,
1313
SUPPORTED_QUOTES,
1414
SupportedQuotesType
1515
} from '../constants/index'
@@ -22,7 +22,7 @@ export interface TransactionFileData {
2222
amount: Prisma.Decimal | number
2323
date: moment.Moment
2424
value: number
25-
rate: number
25+
rate: Prisma.Decimal
2626
transactionId: string
2727
currency: string
2828
address?: string
@@ -67,7 +67,7 @@ export const formatPaybuttonTransactionsFileData = (data: TransactionFileData):
6767
...data,
6868
amount: amount.toFixed(DECIMALS[networkTicker]),
6969
date: date.format(PRICE_API_DATE_FORMAT),
70-
value: value.toFixed(DECIMALS[networkTicker]),
70+
value: value.toFixed(DECIMALS.FIAT),
7171
rate: rate.toFixed(14)
7272
}
7373
}
@@ -126,45 +126,54 @@ export const collapseSmallPayments = (
126126
collapseThreshold: number
127127
): TransactionFileData[] => {
128128
const treatedPayments: TransactionFileData[] = []
129-
const tempGroups: Record<string, TransactionsWithPaybuttonsAndPrices[]> = {}
129+
const tempTxGroups: Record<string, TransactionsWithPaybuttonsAndPrices[]> = {}
130130
let totalPaymentsTreated = 0
131131

132132
const pushTempGroup = (groupKey: string): void => {
133-
const tempGroup = tempGroups[groupKey]
134-
if (tempGroup === undefined || tempGroup.length === 0) return
135-
if (tempGroup.length === 1) {
136-
pushTx(tempGroup[0])
137-
tempGroups[groupKey] = []
133+
const tempTxGroup = tempTxGroups[groupKey]
134+
if (tempTxGroup === undefined || tempTxGroup.length === 0) return
135+
if (tempTxGroup.length === 1) {
136+
pushTx(tempTxGroup[0])
137+
tempTxGroups[groupKey] = []
138138
return
139139
}
140-
const totalAmount = tempGroup.reduce((sum, p) => sum + Number(p.amount), 0)
141-
const totalValue = tempGroup.reduce((sum, p) => sum + Number(getTransactionValue(p)[currency]), 0)
142-
const rate = totalValue / totalAmount
143-
const buttonName = tempGroup[0].address.paybuttons[0].paybutton.name
144-
const notes = `${buttonName} - ${tempGroup.length.toString()} transactions`
140+
const totalAmount = tempTxGroup.reduce((sum, p) => sum + Number(p.amount), 0)
141+
const totalValue = tempTxGroup.reduce((sum, p) => sum + Number(getTransactionValue(p)[currency]), 0)
142+
const uniquePrices = new Set();
143+
tempTxGroup
144+
.forEach(tx =>{
145+
const price = tx.prices.find(p => p.price.quoteId === QUOTE_IDS[currency.toUpperCase()])!.price.value
146+
uniquePrices.add(Number(price))
147+
})
148+
if (uniquePrices.size !== 1) {
149+
throw new Error(RESPONSE_MESSAGES.INVALID_PRICES_FOR_TX_ON_CSV_CREATION_500(uniquePrices.size).message)
150+
}
151+
const rate = uniquePrices.values().next().value;
152+
const buttonName = tempTxGroup[0].address.paybuttons[0].paybutton.name
153+
const notes = `${buttonName} - ${tempTxGroup.length.toString()} transactions`
145154

146-
totalPaymentsTreated += tempGroup.length
155+
totalPaymentsTreated += tempTxGroup.length
147156

148157
treatedPayments.push({
149158
amount: totalAmount,
150159
value: totalValue,
151-
date: moment.tz(tempGroup[0].timestamp * 1000, timezone),
160+
date: moment.tz(tempTxGroup[0].timestamp * 1000, timezone),
152161
transactionId: DEFAULT_MULTI_VALUES_LINE_LABEL,
153162
rate,
154163
currency,
155164
address: DEFAULT_MULTI_VALUES_LINE_LABEL,
156-
newtworkId: tempGroup[0].address.networkId,
165+
newtworkId: tempTxGroup[0].address.networkId,
157166
notes
158167
} as TransactionFileData)
159168

160-
tempGroups[groupKey] = []
169+
tempTxGroups[groupKey] = []
161170
}
162171

163172
const pushTx = (tx: TransactionsWithPaybuttonsAndPrices): void => {
164173
const { timestamp, hash, address, amount } = tx
165174
const values = getTransactionValue(tx)
166175
const value = Number(values[currency])
167-
const rate = value / Number(amount)
176+
const rate = tx.prices.find(p => p.price.quoteId = QUOTE_IDS[currency.toUpperCase()])!.price.value
168177

169178
treatedPayments.push({
170179
amount,
@@ -194,10 +203,10 @@ export const collapseSmallPayments = (
194203
const nextGroupKey = nextDateKey === null || nextDateKeyUTC === null ? null : `${nextDateKey}_${nextDateKeyUTC}`
195204

196205
if (value < collapseThreshold) {
197-
if (tempGroups[groupKey] === undefined) tempGroups[groupKey] = []
198-
tempGroups[groupKey].push(tx)
206+
if (tempTxGroups[groupKey] === undefined) tempTxGroups[groupKey] = []
207+
tempTxGroups[groupKey].push(tx)
199208
} else {
200-
Object.keys(tempGroups).forEach(pushTempGroup)
209+
Object.keys(tempTxGroups).forEach(pushTempGroup)
201210
pushTx(tx)
202211
}
203212

@@ -206,7 +215,7 @@ export const collapseSmallPayments = (
206215
}
207216
})
208217

209-
Object.keys(tempGroups).forEach(pushTempGroup)
218+
Object.keys(tempTxGroups).forEach(pushTempGroup)
210219

211220
if (totalPaymentsTreated !== payments.length) {
212221
throw new Error('Error to collapse payments')
@@ -233,11 +242,11 @@ const sortPaymentsByNetworkId = (payments: TransactionsWithPaybuttonsAndPrices[]
233242

234243
const getPaybuttonTransactionsFileData = (transactions: TransactionsWithPaybuttonsAndPrices[], currency: SupportedQuotesType, timezone: string): TransactionFileData[] => {
235244
const paymentsFileData: TransactionFileData[] = []
236-
transactions.forEach(element => {
237-
const { amount, hash, address, timestamp } = element
238-
const value = getTransactionValueInCurrency(element, currency)
245+
transactions.forEach(tx => {
246+
const { amount, hash, address, timestamp } = tx
247+
const value = getTransactionValueInCurrency(tx, currency)
239248
const date = moment.tz(timestamp * 1000, timezone)
240-
const rate = value / amount.toNumber()
249+
const rate = tx.prices.find(p => p.price.quoteId = QUOTE_IDS[currency.toUpperCase()])!.price.value
241250
paymentsFileData.push({
242251
amount,
243252
date,

0 commit comments

Comments
 (0)