Create services/verification-worker/index.js
Browse files
services/verification-worker/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
require('dotenv').config();
|
| 2 |
+
const Redis = require('ioredis');
|
| 3 |
+
const { Pool } = require('pg');
|
| 4 |
+
|
| 5 |
+
const redis = new Redis(process.env.REDIS_URL);
|
| 6 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
| 7 |
+
|
| 8 |
+
redis.subscribe('infra:faults:created', (err, count) => {
|
| 9 |
+
if (err) return console.error(err);
|
| 10 |
+
console.log('subscribed to infra:faults:created');
|
| 11 |
+
});
|
| 12 |
+
|
| 13 |
+
redis.on('message', async (chan, msg) => {
|
| 14 |
+
if (chan !== 'infra:faults:created') return;
|
| 15 |
+
try {
|
| 16 |
+
const ev = JSON.parse(msg);
|
| 17 |
+
console.log('verifying', ev.id);
|
| 18 |
+
// simple verification stub: random confidence
|
| 19 |
+
const confidence = Math.random();
|
| 20 |
+
const confirmed = confidence > 0.45;
|
| 21 |
+
const q = 'UPDATE objects SET confirmed=$1 WHERE id=$2 RETURNING *';
|
| 22 |
+
const r = await pool.query(q, [confirmed, ev.id]);
|
| 23 |
+
console.log('updated confirmed', ev.id, confirmed);
|
| 24 |
+
// if confirmed, create a payout row
|
| 25 |
+
if (confirmed) {
|
| 26 |
+
const base = 5000;
|
| 27 |
+
const total = base * (r.rows[0].severity || 1);
|
| 28 |
+
const insert = 'INSERT INTO payouts (fault_id, amount_minor_units, currency, payee_id, status) VALUES ($1,$2,$3,$4,\'created\') RETURNING *';
|
| 29 |
+
const payee = 'local-contractor-001';
|
| 30 |
+
const p = await pool.query(insert, [ev.id, total, 'ZAR', payee]);
|
| 31 |
+
redis.publish('payouts:created', JSON.stringify({ payoutId: p.rows[0].id }));
|
| 32 |
+
}
|
| 33 |
+
} catch (e) {
|
| 34 |
+
console.error('verify error', e);
|
| 35 |
+
}
|
| 36 |
+
});
|