-
Notifications
You must be signed in to change notification settings - Fork 4
Feat/export csv payments #926
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
46834ac
feat: add fetchAllPaymentsByUserId method
lissavxo a82fa6c
feat: add address to payment
lissavxo 2492d5d
feat: download payments csv
lissavxo ee415cf
feat: download csv payments button
lissavxo c9ef1fd
feat: filter network payments csv
lissavxo c5858df
fix: payments csv filename
lissavxo d81ff00
refactor: code clean up
lissavxo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| import moment from 'moment-timezone' | ||
| import { | ||
| RESPONSE_MESSAGES, | ||
| DEFAULT_PAYBUTTON_CSV_FILE_DELIMITER, | ||
| SupportedQuotesType, | ||
| SUPPORTED_QUOTES_FROM_ID, | ||
| PAYBUTTON_TRANSACTIONS_FILE_HEADERS, | ||
| NETWORK_TICKERS, | ||
| NetworkTickersType, | ||
| NETWORK_IDS | ||
| } from 'constants/index' | ||
| import { fetchAllPaymentsByUserId } from 'services/transactionService' | ||
| import { TransactionFileData, formatNumberHeaders, formatPaybuttonTransactionsFileData, isNetworkValid, streamToCSV } from 'utils/files' | ||
| import { setSession } from 'utils/setSession' | ||
| import { NextApiResponse } from 'next' | ||
| import { fetchUserProfileFromId } from 'services/userService' | ||
| import { Payment } from 'redis/types' | ||
| import { getNetworkIdFromSlug } from 'services/networkService' | ||
|
|
||
| const getPaymentsFileData = (payment: Payment, currency: SupportedQuotesType, timezone: string): TransactionFileData => { | ||
| const { values, hash, timestamp, address } = payment | ||
| const amount = values.amount | ||
| const value = Number(values.values[currency]) | ||
| const date = moment.tz(timestamp * 1000, timezone) | ||
| const rate = value / Number(amount) | ||
|
|
||
| return { | ||
| amount, | ||
| date, | ||
| transactionId: hash, | ||
| value, | ||
| rate, | ||
| currency, | ||
| address | ||
| } | ||
| } | ||
|
|
||
| const sortPaymentsByNetworkId = (payments: Payment[]): Payment[] => { | ||
| const groupedByNetworkIdPayments = payments.reduce<Record<number, Payment[]>>((acc, payment) => { | ||
| const networkId = payment.networkId | ||
| if (acc[networkId] === undefined || acc[networkId] === null) { | ||
| acc[networkId] = [] | ||
| } | ||
| acc[networkId].push(payment) | ||
| return acc | ||
| }, {}) | ||
|
|
||
| return Object.values(groupedByNetworkIdPayments).reduce( | ||
| (acc, curr) => acc.concat(curr), | ||
| [] | ||
| ) | ||
| } | ||
|
|
||
| const downloadPaymentsFileByUserId = async ( | ||
| userId: string, | ||
| res: NextApiResponse, | ||
| currency: SupportedQuotesType, | ||
| timezone: string, | ||
| networkTicker?: NetworkTickersType): Promise<void> => { | ||
| let networkIdArray = Object.values(NETWORK_IDS) | ||
| if (networkTicker !== undefined) { | ||
| const slug = Object.keys(NETWORK_TICKERS).find(key => NETWORK_TICKERS[key] === networkTicker) | ||
| const networkId = getNetworkIdFromSlug(slug ?? NETWORK_TICKERS.ecash) | ||
| networkIdArray = [networkId] | ||
| } | ||
| const payments = await fetchAllPaymentsByUserId(userId, networkIdArray) | ||
| const sortedPayments = await sortPaymentsByNetworkId(payments) | ||
| const mappedPaymentsData = sortedPayments.map(payment => { | ||
| const data = getPaymentsFileData(payment, currency, timezone) | ||
| return formatPaybuttonTransactionsFileData(data) | ||
| }) | ||
| const headers = Object.keys(PAYBUTTON_TRANSACTIONS_FILE_HEADERS) | ||
| const humanReadableHeaders = formatNumberHeaders(Object.values(PAYBUTTON_TRANSACTIONS_FILE_HEADERS), currency) | ||
|
|
||
| streamToCSV( | ||
| mappedPaymentsData, | ||
| headers, | ||
| DEFAULT_PAYBUTTON_CSV_FILE_DELIMITER, | ||
| res, | ||
| humanReadableHeaders | ||
| ) | ||
| } | ||
|
|
||
| export default async (req: any, res: any): Promise<void> => { | ||
| try { | ||
| if (req.method !== 'GET') { | ||
| throw new Error(RESPONSE_MESSAGES.METHOD_NOT_ALLOWED.message) | ||
| } | ||
|
|
||
| await setSession(req, res) | ||
|
|
||
| const userId = req.session.userId | ||
| const user = await fetchUserProfileFromId(userId) | ||
|
|
||
| let quoteId: number | ||
| if (req.query.currency === undefined || req.query.currency === '' || Number.isNaN(req.query.currency)) { | ||
| quoteId = user.preferredCurrencyId | ||
| } else { | ||
| quoteId = req.query.currency as number | ||
| } | ||
| const quoteSlug = SUPPORTED_QUOTES_FROM_ID[quoteId] | ||
| const userReqTimezone = req.headers.timezone as string | ||
| const userPreferredTimezone = user?.preferredTimezone | ||
| const timezone = userPreferredTimezone !== '' ? userPreferredTimezone : userReqTimezone | ||
| const networkTickerReq = req.query.network as string | ||
|
|
||
| const networkTicker = (networkTickerReq !== '' && isNetworkValid(networkTickerReq as NetworkTickersType)) ? networkTickerReq.toUpperCase() as NetworkTickersType : undefined | ||
| res.setHeader('Content-Type', 'text/csv') | ||
| await downloadPaymentsFileByUserId(userId, res, quoteSlug, timezone, networkTicker) | ||
| } catch (error: any) { | ||
| switch (error.message) { | ||
| case RESPONSE_MESSAGES.METHOD_NOT_ALLOWED.message: | ||
| res.status(RESPONSE_MESSAGES.METHOD_NOT_ALLOWED.statusCode) | ||
| .json(RESPONSE_MESSAGES.METHOD_NOT_ALLOWED) | ||
| break | ||
| case RESPONSE_MESSAGES.MISSING_PRICE_FOR_TRANSACTION_400.message: | ||
| res.status(RESPONSE_MESSAGES.MISSING_PRICE_FOR_TRANSACTION_400.statusCode) | ||
| .json(RESPONSE_MESSAGES.MISSING_PRICE_FOR_TRANSACTION_400) | ||
| break | ||
| default: | ||
| res.status(500).json({ message: error.message }) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Better to use
new Sethere already and down where this array is used with.includesjust use the Set method.haswhich does the same