Feat: change column "detail" in database to use jsonb

This commit is contained in:
Cesar 2020-12-21 18:16:41 +00:00 committed by Josh Harvey
parent 82916388a0
commit c16e47af96
3 changed files with 73 additions and 51 deletions

View file

@ -125,7 +125,6 @@ function updateCassettes (t, tx) {
] ]
return t.one(sql, values).then(r => { return t.one(sql, values).then(r => {
notifier.cashCassettesNotify(r, tx.deviceId)
return socket.emit(_.assign(r, {op: 'cassetteUpdate', deviceId: tx.deviceId})) return socket.emit(_.assign(r, {op: 'cassetteUpdate', deviceId: tx.deviceId}))
}) })
} }

View file

@ -361,12 +361,12 @@ const clearOldCryptoNotifications = (balances) => {
// first, for each DB notification, if it doesn't exist in balances then it is old and should not be valid anymore // first, for each DB notification, if it doesn't exist in balances then it is old and should not be valid anymore
// if it exists in balances, add the index of it in balances to the array of duplicates // if it exists in balances, add the index of it in balances to the array of duplicates
// return the array of duplicates so that balancesNotify doesn't add them // return the array of duplicates so that balancesNotify doesn't add them
return queries.getAllValidNotifications('cryptoBalance').then(res => { return queries.getAllValidNotifications(CRYPTO_BALANCE).then(res => {
const notifications = _.map(it => { const notifications = _.map(it => {
return { return {
id: it.id, id: it.id,
cryptoCode: it.detail.split('_')[0], cryptoCode: it.detail.cryptoCode,
code: it.detail.split('_').splice(1).join('_') code: it.detail.code
} }
}, res) }, res)
const duplicateIndexes = [] const duplicateIndexes = []
@ -398,18 +398,19 @@ const cryptoBalancesNotify = (cryptoWarnings) => {
const fiat = utils.formatCurrency(balance.fiatBalance.balance, balance.fiatCode) const fiat = utils.formatCurrency(balance.fiatBalance.balance, balance.fiatCode)
const message = `${balance.code === 'HIGH_CRYPTO_BALANCE' ? 'High' : 'Low'} balance in ${balance.cryptoCode} [${fiat}]` const message = `${balance.code === 'HIGH_CRYPTO_BALANCE' ? 'High' : 'Low'} balance in ${balance.cryptoCode} [${fiat}]`
console.log(`Adding ${balance.code === 'HIGH_CRYPTO_BALANCE' ? 'high' : 'low'} balance notification for ${balance.cryptoCode}`) console.log(`Adding ${balance.code === 'HIGH_CRYPTO_BALANCE' ? 'high' : 'low'} balance notification for ${balance.cryptoCode}`)
return queries.addCryptoBalanceWarning(`${balance.cryptoCode}_${balance.code}`, message) const detailB = utils.buildDetail({cryptoCode: balance.cryptoCode, code: balance.code})
return queries.addNotification(CRYPTO_BALANCE, message, detailB)
}) })
}) })
} }
const clearOldFiatNotifications = (balances) => { const clearOldFiatNotifications = (balances) => {
return queries.getAllValidNotifications('fiatBalance').then(notifications => { return queries.getAllValidNotifications(FIAT_BALANCE).then(notifications => {
const duplicateIndexes = [] const duplicateIndexes = []
const idsToInvalidate = [] const idsToInvalidate = []
_.forEach(notification => { _.forEach(notification => {
const idx = _.findIndex(balance => { const idx = _.findIndex(balance => {
return notification.device_id === balance.deviceId && notification.detail === `${balance.cassette}` return notification.detail.deviceId === balance.deviceId && notification.detail.cassette === balance.cassette
}, balances) }, balances)
if (idx === -1) { if (idx === -1) {
@ -433,7 +434,8 @@ const fiatBalancesNotify = (fiatWarnings) => {
} }
console.log(`Adding low cash balance notification for cassette ${balance.cassette} at ${balance.machineName}`) console.log(`Adding low cash balance notification for cassette ${balance.cassette} at ${balance.machineName}`)
const message = `Cash-out cassette ${balance.cassette} almost empty!` const message = `Cash-out cassette ${balance.cassette} almost empty!`
return queries.addCashCassetteWarning(balance.cassette, balance.deviceId, message) const detailB = utils.buildDetail({deviceId: balance.deviceId, cassette: balance.cassette})
return queries.addNotification(FIAT_BALANCE, message, detailB)
}) })
}) })
} }
@ -446,19 +448,22 @@ const balancesNotify = (balances) => {
return Promise.all([cryptoBalancesNotify(cryptoWarnings), fiatBalancesNotify(fiatWarnings)]).catch(console.error) return Promise.all([cryptoBalancesNotify(cryptoWarnings), fiatBalancesNotify(fiatWarnings)]).catch(console.error)
} }
const clearOldErrorNotifications = (alerts) => { const clearOldErrorNotifications = (alerts) => {
queries.getAllValidNotifications('error').then(res => { return queries.getAllValidNotifications(ERROR).then(res => {
const indexesToInvalidate = []
_.forEach(notification => { _.forEach(notification => {
const idx = _.findIndex(alert => { const idx = _.findIndex(alert => {
return alert.code === notification.detail.split('_')[0] && alert.deviceId === notification.device_id return alert.code === notification.detail.code && alert.deviceId === notification.detail.deviceId
}, alerts) }, alerts)
if(idx !== -1) { if(idx !== -1) {
return return
} }
// if the notification doesn't exist, then it is outdated and is not valid anymore // if the notification doesn't exist, then it is outdated and is not valid anymore
return queries.invalidateNotification(notification.id) indexesToInvalidate.push(notification.id)
}, res) }, res)
}) return indexesToInvalidate.length > 0 ? queries.batchInvalidate(indexesToInvalidate) : null
}).catch(console.log)
} }
const errorAlertsNotify = (alertRec) => { const errorAlertsNotify = (alertRec) => {
@ -477,71 +482,79 @@ const errorAlertsNotify = (alertRec) => {
// that alert should be considered invalid // that alert should be considered invalid
// after that, for the alerts array, we have to see if there is a valid alert of // after that, for the alerts array, we have to see if there is a valid alert of
// the sorts already on the DB // the sorts already on the DB
clearOldErrorNotifications(alerts) return clearOldErrorNotifications(alerts).then(() => {
_.forEach(alert => {
_.forEach(alert => { switch(alert.code) {
switch(alert.code) { case PING: {
case PING: const detailB = utils.buildDetail({code: PING, age: alert.age ? alert.age : -1, deviceId: alert.deviceId})
return queries.getValidNotifications('error', PING, alert.deviceId).then(res => { return queries.getValidNotifications(ERROR, _.omit(['age'], detailB)).then(res => {
if(res.length > 0) { if(res.length > 0) {
return Promise.resolve() return Promise.resolve()
} }
console.log("Adding PING alert on database for " + alert.machineName) console.log("Adding PING alert on database for " + alert.machineName)
const message = `Machine down` const message = `Machine down`
return queries.addErrorNotification(`${PING}_${alert.age ? alert.age : '-1'}`, message, alert.deviceId) return queries.addNotification(ERROR, message, detailB)
}) })
case STALE: }
return queries.getValidNotifications('error', STALE, alert.deviceId).then(res => { case STALE: {
if(res.length > 0) { const detailB = utils.buildDetail({code: STALE, deviceId: alert.deviceId})
return Promise.resolve() return queries.getValidNotifications(ERROR, detailB).then(res => {
} if(res.length > 0) {
console.log("Adding STALE alert on database for " + alert.machineName) return Promise.resolve()
const message = `Machine is stuck on ${alert.state} screen` }
return queries.addErrorNotification(STALE, message, alert.deviceId) console.log("Adding STALE alert on database for " + alert.machineName)
}) const message = `Machine is stuck on ${alert.state} screen`
default: return queries.addNotification(ERROR, message, detailB)
return })
} }
}, alerts) default:
return
}
}, alerts)
}).catch(console.error)
} }
const blacklistNotify = (tx, isAddressReuse) => { const blacklistNotify = (tx, isAddressReuse) => {
let detail = ''
let message = '' let message = ''
let detailB = {}
if(isAddressReuse) { if(isAddressReuse) {
detail = `${tx.cryptoCode}_REUSED_${tx.toAddress}` detail = `${tx.cryptoCode}_REUSED_${tx.toAddress}`
detailB = utils.buildDetail({cryptoCode: tx.cryptoCode, code: 'REUSED', cryptoAddress: tx.toAddress})
message = `Blocked reused address: ${tx.cryptoCode} ${tx.toAddress.substr(0,10)}...` message = `Blocked reused address: ${tx.cryptoCode} ${tx.toAddress.substr(0,10)}...`
} else { } else {
detail = `${tx.cryptoCode}_BLOCKED_${tx.toAddress}` detail = `${tx.cryptoCode}_BLOCKED_${tx.toAddress}`
detailB = utils.buildDetail({cryptoCode: tx.cryptoCode, code: 'BLOCKED', cryptoAddress: tx.toAddress})
message = `Blocked blacklisted address: ${tx.cryptoCode} ${tx.toAddress.substr(0,10)}...` message = `Blocked blacklisted address: ${tx.cryptoCode} ${tx.toAddress.substr(0,10)}...`
} }
return queries.addNotification(COMPLIANCE, message, detailB)
}
return queries.addComplianceNotification(tx.deviceId, detail, message) const clearBlacklistNotification = (cryptoCode, cryptoAddress) => {
return queries.clearBlacklistNotification(cryptoCode, cryptoAddress).catch(console.error)
} }
const clearOldCustomerSuspendedNotifications = (customerId, deviceId) => { const clearOldCustomerSuspendedNotifications = (customerId, deviceId) => {
const detail = `SUSPENDED_${customerId}` const detailB = utils.buildDetail({code: 'SUSPENDED', customerId, deviceId})
return queries.invalidateNotification(null, detail, deviceId) return queries.invalidateNotification(detailB, 'compliance')
} }
const customerComplianceNotify = (customer, deviceId, prefix, days = null) => { const customerComplianceNotify = (customer, deviceId, code, days = null) => {
// prefix can be "BLOCKED", "SUSPENDED", etc // code for now can be "BLOCKED", "SUSPENDED"
const detail = `${prefix}_${customer.id}` const detailB = utils.buildDetail({customerId: customer.id, code, deviceId})
const date = new Date() const date = new Date()
if (days) { if (days) {
date.setDate(date.getDate() + days) date.setDate(date.getDate() + days)
} }
const message = prefix === "SUSPENDED" ? `Customer suspended until ${date.toLocaleString()}` : `Customer blocked` const message = code === "SUSPENDED" ? `Customer suspended until ${date.toLocaleString()}` : `Customer blocked`
// we have to clear every notification for this user where the suspension ended before the current date return clearOldCustomerSuspendedNotifications(customer.id, deviceId).then(() => {
clearOldCustomerSuspendedNotifications(customer.id, deviceId).then(() => { return queries.getValidNotifications(COMPLIANCE, detailB)
return queries.getValidNotifications('compliance', detail, deviceId)
}).then(res => { }).then(res => {
if (res.length > 0) { if (res.length > 0) {
return Promise.resolve() return Promise.resolve()
} }
return queries.addComplianceNotification(deviceId, detail, message) return queries.addNotification(COMPLIANCE, message, detailB)
}) }).catch(console.error)
} }
module.exports = { module.exports = {

View file

@ -77,6 +77,16 @@ const batchInvalidate = (ids) => {
return db.none(sql, [formattedIds]) return db.none(sql, [formattedIds])
} }
const clearBlacklistNotification = (cryptoCode, cryptoAddress) => {
const sql = `UPDATE notifications SET valid = 'f', read = 't' WHERE type = 'compliance' AND detail->>'cryptoCode' = $1 AND detail->>'cryptoAddress' = $2 AND (detail->>'code' = 'BLOCKED' OR detail->>'code' = 'REUSED')`
return db.none(sql, [cryptoCode, cryptoAddress])
}
const getValidNotifications = (type, detail) => {
const sql = `SELECT * FROM notifications where type = $1 AND valid = 't' AND detail @> $2`
return db.any(sql, [type, detail])
}
module.exports = { module.exports = {
machineEvents: dbm.machineEvents, machineEvents: dbm.machineEvents,
addNotification, addNotification,