|
|
require('dotenv').config(); |
|
|
const Redis = require('ioredis'); |
|
|
const { Pool } = require('pg'); |
|
|
|
|
|
const redis = new Redis(process.env.REDIS_URL); |
|
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL }); |
|
|
|
|
|
redis.subscribe('infra:faults:created', (err, count) => { |
|
|
if (err) return console.error(err); |
|
|
console.log('subscribed to infra:faults:created'); |
|
|
}); |
|
|
|
|
|
redis.on('message', async (chan, msg) => { |
|
|
if (chan !== 'infra:faults:created') return; |
|
|
try { |
|
|
const ev = JSON.parse(msg); |
|
|
console.log('verifying', ev.id); |
|
|
|
|
|
const confidence = Math.random(); |
|
|
const confirmed = confidence > 0.45; |
|
|
const q = 'UPDATE objects SET confirmed=$1 WHERE id=$2 RETURNING *'; |
|
|
const r = await pool.query(q, [confirmed, ev.id]); |
|
|
console.log('updated confirmed', ev.id, confirmed); |
|
|
|
|
|
if (confirmed) { |
|
|
const base = 5000; |
|
|
const total = base * (r.rows[0].severity || 1); |
|
|
const insert = 'INSERT INTO payouts (fault_id, amount_minor_units, currency, payee_id, status) VALUES ($1,$2,$3,$4,\'created\') RETURNING *'; |
|
|
const payee = 'local-contractor-001'; |
|
|
const p = await pool.query(insert, [ev.id, total, 'ZAR', payee]); |
|
|
redis.publish('payouts:created', JSON.stringify({ payoutId: p.rows[0].id })); |
|
|
} |
|
|
} catch (e) { |
|
|
console.error('verify error', e); |
|
|
} |
|
|
}); |
|
|
|