chore: server code formatting

This commit is contained in:
Rafael Taranto 2025-05-12 15:35:00 +01:00
parent aedabcbdee
commit 68517170e2
234 changed files with 9824 additions and 6195 deletions

View file

@ -4,7 +4,9 @@ const pgp = require('pg-promise')()
const db = require('../../db')
const getBills = filters => {
const deviceStatement = !_.isNil(filters.deviceId) ? `WHERE device_id = ${pgp.as.text(filters.deviceId)}` : ``
const deviceStatement = !_.isNil(filters.deviceId)
? `WHERE device_id = ${pgp.as.text(filters.deviceId)}`
: ``
const batchStatement = filter => {
switch (filter) {
case 'none':
@ -12,7 +14,9 @@ const getBills = filters => {
case 'any':
return `WHERE b.cashbox_batch_id IS NOT NULL`
default:
return _.isNil(filter) ? `` : `WHERE b.cashbox_batch_id = ${pgp.as.text(filter)}`
return _.isNil(filter)
? ``
: `WHERE b.cashbox_batch_id = ${pgp.as.text(filter)}`
}
}
@ -22,10 +26,12 @@ const getBills = filters => {
const sql2 = `SELECT b.id, b.fiat, b.fiat_code, b.created, b.cashbox_batch_id, b.device_id FROM empty_unit_bills b ${deviceStatement} ${!_.isNil(filters.deviceId) && !_.isNil(filters.batch) ? `AND ${_.replace('WHERE', '', batchStatement(filters.batch))}` : `${batchStatement(filters.batch)}`}`
return Promise.all([db.any(sql), db.any(sql2)])
.then(([bills, operationalBills]) => _.map(_.mapKeys(_.camelCase), _.concat(bills, operationalBills)))
return Promise.all([db.any(sql), db.any(sql2)]).then(
([bills, operationalBills]) =>
_.map(_.mapKeys(_.camelCase), _.concat(bills, operationalBills)),
)
}
module.exports = {
getBills
getBills,
}

View file

@ -2,7 +2,10 @@ const db = require('../../db')
const uuid = require('uuid')
const _ = require('lodash/fp')
const pgp = require('pg-promise')()
const { loadLatestConfigOrNone, saveConfig } = require('../../../lib/new-settings-loader')
const {
loadLatestConfigOrNone,
saveConfig,
} = require('../../../lib/new-settings-loader')
const getCustomInfoRequests = (onlyEnabled = false) => {
const sql = onlyEnabled
@ -12,38 +15,57 @@ const getCustomInfoRequests = (onlyEnabled = false) => {
return res.map(item => ({
id: item.id,
enabled: item.enabled,
customRequest: item.custom_request
customRequest: item.custom_request,
}))
})
}
const addCustomInfoRequest = (customRequest) => {
const sql = 'INSERT INTO custom_info_requests (id, custom_request) VALUES ($1, $2)'
const addCustomInfoRequest = customRequest => {
const sql =
'INSERT INTO custom_info_requests (id, custom_request) VALUES ($1, $2)'
const id = uuid.v4()
return db.none(sql, [id, customRequest]).then(() => ({ id }))
}
const removeCustomInfoRequest = (id) => {
const removeCustomInfoRequest = id => {
return loadLatestConfigOrNone()
.then(cfg => saveConfig({triggers: _.remove(x => x.customInfoRequestId === id, cfg.triggers ?? [])}))
.then(() => db.none('UPDATE custom_info_requests SET enabled = false WHERE id = $1', [id]))
.then(() => ({ id }));
.then(cfg =>
saveConfig({
triggers: _.remove(
x => x.customInfoRequestId === id,
cfg.triggers ?? [],
),
}),
)
.then(() =>
db.none('UPDATE custom_info_requests SET enabled = false WHERE id = $1', [
id,
]),
)
.then(() => ({ id }))
}
const editCustomInfoRequest = (id, customRequest) => {
return db.none('UPDATE custom_info_requests SET custom_request = $1 WHERE id=$2', [customRequest, id]).then(() => ({ id, customRequest }))
return db
.none('UPDATE custom_info_requests SET custom_request = $1 WHERE id=$2', [
customRequest,
id,
])
.then(() => ({ id, customRequest }))
}
const getAllCustomInfoRequestsForCustomer = (customerId) => {
const getAllCustomInfoRequestsForCustomer = customerId => {
const sql = `SELECT * FROM customers_custom_info_requests WHERE customer_id = $1`
return db.any(sql, [customerId]).then(res => res.map(item => ({
customerId: item.customer_id,
infoRequestId: item.info_request_id,
customerData: item.customer_data,
override: item.override,
overrideAt: item.override_at,
overrideBy: item.override_by
})))
return db.any(sql, [customerId]).then(res =>
res.map(item => ({
customerId: item.customer_id,
infoRequestId: item.info_request_id,
customerData: item.customer_data,
override: item.override,
overrideAt: item.override_at,
overrideBy: item.override_by,
})),
)
}
const getCustomInfoRequestForCustomer = (customerId, infoRequestId) => {
@ -55,12 +77,12 @@ const getCustomInfoRequestForCustomer = (customerId, infoRequestId) => {
customerData: item.customer_data,
override: item.override,
overrideAt: item.override_at,
overrideBy: item.override_by
overrideBy: item.override_by,
}
})
}
const batchGetAllCustomInfoRequestsForCustomer = (customerIds) => {
const batchGetAllCustomInfoRequestsForCustomer = customerIds => {
const sql = `SELECT * FROM customers_custom_info_requests WHERE customer_id IN ($1^)`
return db.any(sql, [_.map(pgp.as.text, customerIds).join(',')]).then(res => {
const map = _.groupBy('customer_id', res)
@ -72,40 +94,49 @@ const batchGetAllCustomInfoRequestsForCustomer = (customerIds) => {
customerData: item.customer_data,
override: item.override,
overrideAt: item.override_at,
overrideBy: item.override_by
overrideBy: item.override_by,
}))
})
})
}
const getCustomInfoRequest = (infoRequestId) => {
const getCustomInfoRequest = infoRequestId => {
const sql = `SELECT * FROM custom_info_requests WHERE id = $1`
return db.one(sql, [infoRequestId]).then(item => ({
id: item.id,
enabled: item.enabled,
customRequest: item.custom_request
customRequest: item.custom_request,
}))
}
const batchGetCustomInfoRequest = (infoRequestIds) => {
const batchGetCustomInfoRequest = infoRequestIds => {
if (infoRequestIds.length === 0) return Promise.resolve([])
const sql = `SELECT * FROM custom_info_requests WHERE id IN ($1^)`
return db.any(sql, [_.map(pgp.as.text, infoRequestIds).join(',')]).then(res => {
const map = _.groupBy('id', res)
return infoRequestIds.map(id => {
const item = map[id][0] // since id is primary key the array always has 1 element
return {
id: item.id,
enabled: item.enabled,
customRequest: item.custom_request
}
return db
.any(sql, [_.map(pgp.as.text, infoRequestIds).join(',')])
.then(res => {
const map = _.groupBy('id', res)
return infoRequestIds.map(id => {
const item = map[id][0] // since id is primary key the array always has 1 element
return {
id: item.id,
enabled: item.enabled,
customRequest: item.custom_request,
}
})
})
})
}
const setAuthorizedCustomRequest = (customerId, infoRequestId, override, token) => {
const setAuthorizedCustomRequest = (
customerId,
infoRequestId,
override,
token,
) => {
const sql = `UPDATE customers_custom_info_requests SET override = $1, override_by = $2, override_at = now() WHERE customer_id = $3 AND info_request_id = $4`
return db.none(sql, [override, token, customerId, infoRequestId]).then(() => true)
return db
.none(sql, [override, token, customerId, infoRequestId])
.then(() => true)
}
const setCustomerData = (customerId, infoRequestId, data) => {
@ -138,5 +169,5 @@ module.exports = {
batchGetCustomInfoRequest,
setAuthorizedCustomRequest,
setCustomerData,
setCustomerDataViaMachine
setCustomerDataViaMachine,
}

View file

@ -7,55 +7,65 @@ const ticker = require('../../ticker')
const txBatching = require('../../tx-batching')
const { utils: coinUtils } = require('@lamassu/coins')
function computeCrypto (cryptoCode, _balance) {
function computeCrypto(cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return new BN(_balance).shiftedBy(-unitScale).decimalPlaces(5)
}
function computeFiat (rate, cryptoCode, _balance) {
function computeFiat(rate, cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return new BN(_balance).shiftedBy(-unitScale).times(rate).decimalPlaces(5)
}
function getSingleCoinFunding (settings, fiatCode, cryptoCode) {
function getSingleCoinFunding(settings, fiatCode, cryptoCode) {
const promises = [
wallet.newFunding(settings, cryptoCode),
ticker.getRates(settings, fiatCode, cryptoCode),
txBatching.getOpenBatchCryptoValue(cryptoCode)
txBatching.getOpenBatchCryptoValue(cryptoCode),
]
return Promise.all(promises)
.then(([fundingRec, ratesRec, batchRec]) => {
const rates = ratesRec.rates
const rate = (rates.ask.plus(rates.bid)).div(2)
const fundingConfirmedBalance = fundingRec.fundingConfirmedBalance
const fiatConfirmedBalance = computeFiat(rate, cryptoCode, fundingConfirmedBalance)
const pending = fundingRec.fundingPendingBalance.minus(batchRec)
const fiatPending = computeFiat(rate, cryptoCode, pending)
const fundingAddress = fundingRec.fundingAddress
const fundingAddressUrl = coinUtils.buildUrl(cryptoCode, fundingAddress)
return Promise.all(promises).then(([fundingRec, ratesRec, batchRec]) => {
const rates = ratesRec.rates
const rate = rates.ask.plus(rates.bid).div(2)
const fundingConfirmedBalance = fundingRec.fundingConfirmedBalance
const fiatConfirmedBalance = computeFiat(
rate,
cryptoCode,
fundingConfirmedBalance,
)
const pending = fundingRec.fundingPendingBalance.minus(batchRec)
const fiatPending = computeFiat(rate, cryptoCode, pending)
const fundingAddress = fundingRec.fundingAddress
const fundingAddressUrl = coinUtils.buildUrl(cryptoCode, fundingAddress)
return {
return {
cryptoCode,
fundingAddress,
fundingAddressUrl,
confirmedBalance: computeCrypto(
cryptoCode,
fundingAddress,
fundingAddressUrl,
confirmedBalance: computeCrypto(cryptoCode, fundingConfirmedBalance).toFormat(5),
pending: computeCrypto(cryptoCode, pending).toFormat(5),
fiatConfirmedBalance: fiatConfirmedBalance,
fiatPending: fiatPending,
fiatCode
}
})
fundingConfirmedBalance,
).toFormat(5),
pending: computeCrypto(cryptoCode, pending).toFormat(5),
fiatConfirmedBalance: fiatConfirmedBalance,
fiatPending: fiatPending,
fiatCode,
}
})
}
// Promise.allSettled not running on current version of node
const reflect = p => p.then(value => ({ value, status: 'fulfilled' }), error => ({ error: error.toString(), status: 'rejected' }))
const reflect = p =>
p.then(
value => ({ value, status: 'fulfilled' }),
error => ({ error: error.toString(), status: 'rejected' }),
)
function getFunding () {
function getFunding() {
return settingsLoader.loadLatest().then(settings => {
const cryptoCodes = configManager.getAllCryptoCurrencies(settings.config)
const fiatCode = configManager.getGlobalLocale(settings.config).fiatCurrency
@ -63,12 +73,15 @@ function getFunding () {
const cryptoCurrencies = coinUtils.cryptoCurrencies()
const cryptoDisplays = _.filter(pareCoins, cryptoCurrencies)
const promises = cryptoDisplays.map(it => getSingleCoinFunding(settings, fiatCode, it.cryptoCode))
return Promise.all(promises.map(reflect))
.then((response) => {
const mapped = response.map(it => _.merge({ errorMsg: it.error }, it.value))
return _.toArray(_.merge(mapped, cryptoDisplays))
})
const promises = cryptoDisplays.map(it =>
getSingleCoinFunding(settings, fiatCode, it.cryptoCode),
)
return Promise.all(promises.map(reflect)).then(response => {
const mapped = response.map(it =>
_.merge({ errorMsg: it.error }, it.value),
)
return _.toArray(_.merge(mapped, cryptoDisplays))
})
})
}

View file

@ -1,16 +1,23 @@
const db = require('../../db')
function validateUser (username, password) {
function validateUser(username, password) {
return db.tx(t => {
const q1 = t.one('SELECT * FROM users WHERE username=$1 AND password=$2', [username, password])
const q2 = t.none('UPDATE users SET last_accessed = now() WHERE username=$1', [username])
const q1 = t.one('SELECT * FROM users WHERE username=$1 AND password=$2', [
username,
password,
])
const q2 = t.none(
'UPDATE users SET last_accessed = now() WHERE username=$1',
[username],
)
return t.batch([q1, q2])
return t
.batch([q1, q2])
.then(([user]) => user)
.catch(() => false)
})
}
module.exports = {
validateUser
validateUser,
}

View file

@ -1,19 +1,26 @@
const machineLoader = require('../../machine-loader')
const { UserInputError } = require('../graphql/errors')
function getMachine (machineId) {
return machineLoader.getMachines()
function getMachine(machineId) {
return machineLoader
.getMachines()
.then(machines => machines.find(({ deviceId }) => deviceId === machineId))
}
function machineAction ({ deviceId, action, cashUnits, newName }, context) {
function machineAction({ deviceId, action, cashUnits, newName }, context) {
const operatorId = context.res.locals.operatorId
return getMachine(deviceId)
.then(machine => {
if (!machine) throw new UserInputError(`machine:${deviceId} not found`, { deviceId })
if (!machine)
throw new UserInputError(`machine:${deviceId} not found`, { deviceId })
return machine
})
.then(machineLoader.setMachine({ deviceId, action, cashUnits, newName }, operatorId))
.then(
machineLoader.setMachine(
{ deviceId, action, cashUnits, newName },
operatorId,
),
)
.then(getMachine(deviceId))
}

View file

@ -3,7 +3,6 @@ const pify = require('pify')
const readFile = pify(fs.readFile)
const crypto = require('crypto')
const baseX = require('base-x')
const { parse, NIL } = require('uuid')
const db = require('../../db')
const pairing = require('../../pairing')
@ -16,19 +15,23 @@ const HOSTNAME = process.env.HOSTNAME
const unpair = pairing.unpair
function totem (name) {
return readFile(CA_PATH)
.then(data => {
const caHash = crypto.createHash('sha256').update(data).digest()
const token = crypto.randomBytes(32)
const hexToken = token.toString('hex')
const caHexToken = crypto.createHash('sha256').update(hexToken).digest('hex')
const buf = Buffer.concat([caHash, token, Buffer.from(HOSTNAME)])
const sql = 'insert into pairing_tokens (token, name) values ($1, $3), ($2, $3)'
function totem(name) {
return readFile(CA_PATH).then(data => {
const caHash = crypto.createHash('sha256').update(data).digest()
const token = crypto.randomBytes(32)
const hexToken = token.toString('hex')
const caHexToken = crypto
.createHash('sha256')
.update(hexToken)
.digest('hex')
const buf = Buffer.concat([caHash, token, Buffer.from(HOSTNAME)])
const sql =
'insert into pairing_tokens (token, name) values ($1, $3), ($2, $3)'
return db.none(sql, [hexToken, caHexToken, name])
.then(() => bsAlpha.encode(buf))
})
return db
.none(sql, [hexToken, caHexToken, name])
.then(() => bsAlpha.encode(buf))
})
}
module.exports = { totem, unpair }

View file

@ -1,16 +1,21 @@
const _ = require('lodash/fp')
const uuid = require('uuid')
const db = require('../../db')
function getServerLogs (from = new Date(0).toISOString(), until = new Date().toISOString(), limit = null, offset = 0) {
function getServerLogs(
from = new Date(0).toISOString(),
until = new Date().toISOString(),
limit = null,
offset = 0,
) {
const sql = `select id, log_level, timestamp, message from server_logs
where timestamp >= $1 and timestamp <= $2
order by timestamp desc
limit $3
offset $4`
return db.any(sql, [ from, until, limit, offset ])
return db
.any(sql, [from, until, limit, offset])
.then(_.map(_.mapKeys(_.camelCase)))
}

View file

@ -6,8 +6,8 @@ const { promisify } = require('util')
// [inet_http_server]
// port = 127.0.0.1:9001
function getAllProcessInfo () {
const convertStates = (state) => {
function getAllProcessInfo() {
const convertStates = state => {
// From http://supervisord.org/subprocess.html#process-states
switch (state) {
case 'STOPPED':
@ -33,28 +33,30 @@ function getAllProcessInfo () {
const client = xmlrpc.createClient({
host: 'localhost',
port: '9001',
path: '/RPC2'
path: '/RPC2',
})
client.methodCall[promisify.custom] = (method, params) => {
return new Promise((resolve, reject) => client.methodCall(method, params, (err, value) => {
if (err) reject(err)
else resolve(value)
}))
return new Promise((resolve, reject) =>
client.methodCall(method, params, (err, value) => {
if (err) reject(err)
else resolve(value)
}),
)
}
return promisify(client.methodCall)('supervisor.getAllProcessInfo', [])
.then((value) => {
return value.map(process => (
{
name: process.name,
state: convertStates(process.statename),
uptime: (process.statename === 'RUNNING') ? process.now - process.start : 0
}
))
.then(value => {
return value.map(process => ({
name: process.name,
state: convertStates(process.statename),
uptime:
process.statename === 'RUNNING' ? process.now - process.start : 0,
}))
})
.catch((error) => {
if (error.code === 'ECONNREFUSED') logger.error('Failed to connect to supervisord HTTP server.')
.catch(error => {
if (error.code === 'ECONNREFUSED')
logger.error('Failed to connect to supervisord HTTP server.')
else logger.error(error)
})
}

View file

@ -4,14 +4,16 @@ const pgp = require('pg-promise')()
const db = require('../../db')
const BN = require('../../bn')
const { utils: coinUtils } = require('@lamassu/coins')
const machineLoader = require('../../machine-loader')
const tx = require('../../tx')
const cashInTx = require('../../cash-in/cash-in-tx')
const { REDEEMABLE_AGE, CASH_OUT_TRANSACTION_STATES } = require('../../cash-out/cash-out-helper')
const {
REDEEMABLE_AGE,
CASH_OUT_TRANSACTION_STATES,
} = require('../../cash-out/cash-out-helper')
const NUM_RESULTS = 1000
function addProfits (txs) {
function addProfits(txs) {
return _.map(it => {
const profit = getProfit(it).toString()
return _.set('profit', profit, it)
@ -28,7 +30,7 @@ const DEVICE_NAME_QUERY = `
END AS machine_name
`
const DEVICE_NAME_JOINS = `
const DEVICE_NAME_JOINS = `
LEFT JOIN devices d ON txs.device_id = d.device_id
LEFT JOIN (
SELECT device_id, name, unpaired, paired
@ -38,7 +40,7 @@ const DEVICE_NAME_QUERY = `
AND (txs.created >= ud.paired)
`
function batch (
function batch(
from = new Date(0).toISOString(),
until = new Date().toISOString(),
limit = null,
@ -52,20 +54,19 @@ function batch (
status = null,
swept = null,
excludeTestingCustomers = false,
simplified
simplified,
) {
const isCsvExport = _.isBoolean(simplified)
const packager = _.flow(
_.flatten,
_.orderBy(_.property('created'), ['desc']),
_.map(_.flow(
camelize,
_.mapKeys(k =>
k == 'cashInFee' ? 'fixedFee' :
k
)
)),
addProfits
_.map(
_.flow(
camelize,
_.mapKeys(k => (k == 'cashInFee' ? 'fixedFee' : k)),
),
),
addProfits,
)
const cashInSql = `SELECT 'cashIn' AS tx_class, txs.*,
@ -138,46 +139,164 @@ function batch (
let promises
if (hasCashInOnlyFilters && hasCashOutOnlyFilters) {
throw new Error('Trying to filter transactions with mutually exclusive filters')
throw new Error(
'Trying to filter transactions with mutually exclusive filters',
)
}
if (hasCashInOnlyFilters) {
promises = [db.any(cashInSql, [cashInTx.PENDING_INTERVAL, from, until, limit, offset, txClass, deviceId, customerName, fiatCode, cryptoCode, toAddress, status])]
promises = [
db.any(cashInSql, [
cashInTx.PENDING_INTERVAL,
from,
until,
limit,
offset,
txClass,
deviceId,
customerName,
fiatCode,
cryptoCode,
toAddress,
status,
]),
]
} else if (hasCashOutOnlyFilters) {
promises = [db.any(cashOutSql, [REDEEMABLE_AGE, from, until, limit, offset, txClass, deviceId, customerName, fiatCode, cryptoCode, toAddress, status, swept])]
promises = [
db.any(cashOutSql, [
REDEEMABLE_AGE,
from,
until,
limit,
offset,
txClass,
deviceId,
customerName,
fiatCode,
cryptoCode,
toAddress,
status,
swept,
]),
]
} else {
promises = [
db.any(cashInSql, [cashInTx.PENDING_INTERVAL, from, until, limit, offset, txClass, deviceId, customerName, fiatCode, cryptoCode, toAddress, status]),
db.any(cashOutSql, [REDEEMABLE_AGE, from, until, limit, offset, txClass, deviceId, customerName, fiatCode, cryptoCode, toAddress, status, swept])
db.any(cashInSql, [
cashInTx.PENDING_INTERVAL,
from,
until,
limit,
offset,
txClass,
deviceId,
customerName,
fiatCode,
cryptoCode,
toAddress,
status,
]),
db.any(cashOutSql, [
REDEEMABLE_AGE,
from,
until,
limit,
offset,
txClass,
deviceId,
customerName,
fiatCode,
cryptoCode,
toAddress,
status,
swept,
]),
]
}
return Promise.all(promises)
.then(packager)
.then(res =>
!isCsvExport ? res :
// GQL transactions and transactionsCsv both use this function and
// if we don't check for the correct simplified value, the Transactions page polling
// will continuously build a csv in the background
simplified ? simplifiedBatch(res) :
advancedBatch(res)
!isCsvExport
? res
: // GQL transactions and transactionsCsv both use this function and
// if we don't check for the correct simplified value, the Transactions page polling
// will continuously build a csv in the background
simplified
? simplifiedBatch(res)
: advancedBatch(res),
)
}
function advancedBatch (data) {
const fields = ['txClass', 'id', 'deviceId', 'toAddress', 'cryptoAtoms',
'cryptoCode', 'fiat', 'fiatCode', 'fee', 'status', 'fiatProfit', 'cryptoAmount',
'dispense', 'notified', 'redeem', 'phone', 'error', 'fixedFee',
'created', 'confirmedAt', 'hdIndex', 'swept', 'timedout',
'dispenseConfirmed', 'provisioned1', 'provisioned2', 'provisioned3', 'provisioned4',
'provisionedRecycler1', 'provisionedRecycler2', 'provisionedRecycler3', 'provisionedRecycler4', 'provisionedRecycler5', 'provisionedRecycler6',
'denomination1', 'denomination2', 'denomination3', 'denomination4',
'denominationRecycler1', 'denominationRecycler2', 'denominationRecycler3', 'denominationRecycler4', 'denominationRecycler5', 'denominationRecycler6',
'errorCode', 'customerId', 'txVersion', 'publishedAt', 'termsAccepted', 'layer2Address',
'commissionPercentage', 'rawTickerPrice', 'receivedCryptoAtoms',
'discount', 'txHash', 'customerPhone', 'customerEmail', 'customerIdCardDataNumber',
'customerIdCardDataExpiration', 'customerIdCardData', 'customerName', 'sendTime',
'customerFrontCameraPath', 'customerIdCardPhotoPath', 'expired', 'machineName', 'walletScore']
function advancedBatch(data) {
const fields = [
'txClass',
'id',
'deviceId',
'toAddress',
'cryptoAtoms',
'cryptoCode',
'fiat',
'fiatCode',
'fee',
'status',
'fiatProfit',
'cryptoAmount',
'dispense',
'notified',
'redeem',
'phone',
'error',
'fixedFee',
'created',
'confirmedAt',
'hdIndex',
'swept',
'timedout',
'dispenseConfirmed',
'provisioned1',
'provisioned2',
'provisioned3',
'provisioned4',
'provisionedRecycler1',
'provisionedRecycler2',
'provisionedRecycler3',
'provisionedRecycler4',
'provisionedRecycler5',
'provisionedRecycler6',
'denomination1',
'denomination2',
'denomination3',
'denomination4',
'denominationRecycler1',
'denominationRecycler2',
'denominationRecycler3',
'denominationRecycler4',
'denominationRecycler5',
'denominationRecycler6',
'errorCode',
'customerId',
'txVersion',
'publishedAt',
'termsAccepted',
'layer2Address',
'commissionPercentage',
'rawTickerPrice',
'receivedCryptoAtoms',
'discount',
'txHash',
'customerPhone',
'customerEmail',
'customerIdCardDataNumber',
'customerIdCardDataExpiration',
'customerIdCardData',
'customerName',
'sendTime',
'customerFrontCameraPath',
'customerIdCardPhotoPath',
'expired',
'machineName',
'walletScore',
]
const addAdvancedFields = _.map(it => ({
...it,
@ -191,28 +310,48 @@ function advancedBatch (data) {
return _.compose(_.map(_.pick(fields)), addAdvancedFields)(data)
}
function simplifiedBatch (data) {
const fields = ['txClass', 'id', 'created', 'machineName', 'fee',
'cryptoCode', 'cryptoAtoms', 'fiat', 'fiatCode', 'phone', 'email', 'toAddress',
'txHash', 'dispense', 'error', 'status', 'fiatProfit', 'cryptoAmount']
function simplifiedBatch(data) {
const fields = [
'txClass',
'id',
'created',
'machineName',
'fee',
'cryptoCode',
'cryptoAtoms',
'fiat',
'fiatCode',
'phone',
'email',
'toAddress',
'txHash',
'dispense',
'error',
'status',
'fiatProfit',
'cryptoAmount',
]
const addSimplifiedFields = _.map(it => ({
...it,
status: getStatus(it),
fiatProfit: getProfit(it).toString(),
cryptoAmount: getCryptoAmount(it).toString()
cryptoAmount: getCryptoAmount(it).toString(),
}))
return _.compose(_.map(_.pick(fields)), addSimplifiedFields)(data)
}
const getCryptoAmount = it => coinUtils.toUnit(BN(it.cryptoAtoms), it.cryptoCode)
const getCryptoAmount = it =>
coinUtils.toUnit(BN(it.cryptoAtoms), it.cryptoCode)
const getProfit = it => {
/* fiat - crypto*tickerPrice */
const calcCashInProfit = (fiat, crypto, tickerPrice) => fiat.minus(crypto.times(tickerPrice))
const calcCashInProfit = (fiat, crypto, tickerPrice) =>
fiat.minus(crypto.times(tickerPrice))
/* crypto*tickerPrice - fiat */
const calcCashOutProfit = (fiat, crypto, tickerPrice) => crypto.times(tickerPrice).minus(fiat)
const calcCashOutProfit = (fiat, crypto, tickerPrice) =>
crypto.times(tickerPrice).minus(fiat)
const fiat = BN(it.fiat)
const crypto = getCryptoAmount(it)
@ -247,10 +386,15 @@ const getStatus = it => {
return getCashInStatus(it)
}
function getCustomerTransactionsBatch (ids) {
const packager = _.flow(it => {
return it
}, _.flatten, _.orderBy(_.property('created'), ['desc']), _.map(camelize))
function getCustomerTransactionsBatch(ids) {
const packager = _.flow(
it => {
return it
},
_.flatten,
_.orderBy(_.property('created'), ['desc']),
_.map(camelize),
)
const cashInSql = `SELECT 'cashIn' AS tx_class, txs.*,
c.phone AS customer_phone,
@ -292,16 +436,25 @@ function getCustomerTransactionsBatch (ids) {
WHERE c.id IN ($1^)
ORDER BY created DESC limit $2`
return Promise.all([
db.any(cashInSql, [_.map(pgp.as.text, ids).join(','), cashInTx.PENDING_INTERVAL, NUM_RESULTS]),
db.any(cashOutSql, [_.map(pgp.as.text, ids).join(','), NUM_RESULTS, REDEEMABLE_AGE])
db.any(cashInSql, [
_.map(pgp.as.text, ids).join(','),
cashInTx.PENDING_INTERVAL,
NUM_RESULTS,
]),
db.any(cashOutSql, [
_.map(pgp.as.text, ids).join(','),
NUM_RESULTS,
REDEEMABLE_AGE,
]),
])
.then(packager).then(transactions => {
.then(packager)
.then(transactions => {
const transactionMap = _.groupBy('customerId', transactions)
return ids.map(id => transactionMap[id])
})
}
function single (txId) {
function single(txId) {
const packager = _.flow(_.compact, _.map(camelize))
const cashInSql = `SELECT 'cashIn' AS tx_class, txs.*,
@ -344,18 +497,17 @@ function single (txId) {
return Promise.all([
db.oneOrNone(cashInSql, [cashInTx.PENDING_INTERVAL, txId]),
db.oneOrNone(cashOutSql, [txId, REDEEMABLE_AGE])
db.oneOrNone(cashOutSql, [txId, REDEEMABLE_AGE]),
])
.then(packager)
.then(_.head)
}
function cancel (txId) {
return tx.cancel(txId)
.then(() => single(txId))
function cancel(txId) {
return tx.cancel(txId).then(() => single(txId))
}
function getTx (txId, txClass) {
function getTx(txId, txClass) {
const cashInSql = `select 'cashIn' as tx_class, txs.*,
((not txs.send_confirmed) and (txs.created <= now() - interval $1)) as expired
from cash_in_txs as txs
@ -372,7 +524,7 @@ function getTx (txId, txClass) {
: db.oneOrNone(cashOutSql, [txId, REDEEMABLE_AGE])
}
function getTxAssociatedData (txId, txClass) {
function getTxAssociatedData(txId, txClass) {
const billsSql = `select 'bills' as bills, b.* from bills b where cash_in_txs_id = $1`
const actionsSql = `select 'cash_out_actions' as cash_out_actions, actions.* from cash_out_actions actions where tx_id = $1`
@ -381,15 +533,27 @@ function getTxAssociatedData (txId, txClass) {
: db.manyOrNone(actionsSql, [txId])
}
function updateTxCustomerPhoto (customerId, txId, direction, data) {
function updateTxCustomerPhoto(customerId, txId, direction, data) {
const formattedData = _.mapKeys(_.snakeCase, data)
const cashInSql = 'UPDATE cash_in_txs SET tx_customer_photo_at = $1, tx_customer_photo_path = $2 WHERE customer_id=$3 AND id=$4'
const cashInSql =
'UPDATE cash_in_txs SET tx_customer_photo_at = $1, tx_customer_photo_path = $2 WHERE customer_id=$3 AND id=$4'
const cashOutSql = 'UPDATE cash_out_txs SET tx_customer_photo_at = $1, tx_customer_photo_path = $2 WHERE customer_id=$3 AND id=$4'
const cashOutSql =
'UPDATE cash_out_txs SET tx_customer_photo_at = $1, tx_customer_photo_path = $2 WHERE customer_id=$3 AND id=$4'
return direction === 'cashIn'
? db.oneOrNone(cashInSql, [formattedData.tx_customer_photo_at, formattedData.tx_customer_photo_path, customerId, txId])
: db.oneOrNone(cashOutSql, [formattedData.tx_customer_photo_at, formattedData.tx_customer_photo_path, customerId, txId])
? db.oneOrNone(cashInSql, [
formattedData.tx_customer_photo_at,
formattedData.tx_customer_photo_path,
customerId,
txId,
])
: db.oneOrNone(cashOutSql, [
formattedData.tx_customer_photo_at,
formattedData.tx_customer_photo_path,
customerId,
txId,
])
}
module.exports = {
@ -399,5 +563,5 @@ module.exports = {
getCustomerTransactionsBatch,
getTx,
getTxAssociatedData,
updateTxCustomerPhoto
updateTxCustomerPhoto,
}