|
|
|
|
|
const Redis = require('ioredis'); |
|
|
const fetch = require('node-fetch'); |
|
|
const { Pool } = require('pg'); |
|
|
|
|
|
const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379'); |
|
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL || 'postgresql://localhost/integral' }); |
|
|
|
|
|
redis.subscribe('infra:faults:created', (err, count) => { |
|
|
if (err) return console.error(err); |
|
|
console.log('subscribed to faults created'); |
|
|
}); |
|
|
|
|
|
redis.on('message', async (channel, message) => { |
|
|
if (channel !== 'infra:faults:created') return; |
|
|
try { |
|
|
const ev = JSON.parse(message); |
|
|
console.log('verifying', ev.id); |
|
|
|
|
|
|
|
|
|
|
|
const fakeConfidence = Math.random(); |
|
|
const confirmed = fakeConfidence > 0.45; |
|
|
|
|
|
const q = `UPDATE objects SET confirmed = $1 WHERE id = $2 RETURNING *`; |
|
|
const r = await pool.query(q, [confirmed, ev.id]); |
|
|
const obj = r.rows[0]; |
|
|
|
|
|
|
|
|
await redis.publish('infra:faults:confirmed', JSON.stringify({ id: obj.id, confirmed })); |
|
|
|
|
|
|
|
|
if (confirmed) { |
|
|
|
|
|
const baseAmount = 5000; |
|
|
const total = baseAmount * (obj.severity || 1); |
|
|
const insert = `INSERT INTO payouts (fault_id, amount_minor_units, currency, payee_id, status) |
|
|
VALUES ($1,$2,$3,$4,'created') RETURNING *`; |
|
|
const payeeId = 'local-contractor-123'; |
|
|
const pay = await pool.query(insert, [obj.id, total, 'ZAR', payeeId]); |
|
|
await redis.publish('payouts:created', JSON.stringify({ payoutId: pay.rows[0].id })); |
|
|
} |
|
|
|
|
|
} catch (err) { |
|
|
console.error('verify error', err); |
|
|
} |
|
|
}); |
|
|
|