← back to Handbag Authentication
scripts/check-deals.js
114 lines
#!/usr/bin/env node
/**
* Deal Checker - Runs every 5 minutes via cron
* Checks for new high-value deals and sends Slack alerts to Steve Abrams (DW)
*/
require('dotenv').config();
const Database = require('../db/schema');
const SlackNotifier = require('../ai/slack-notifier');
const db = new Database(process.env.DATABASE_PATH);
const slackNotifier = new SlackNotifier();
// Track sent deals to avoid duplicates
const sentDealsPath = '/tmp/luxarb-sent-deals.json';
const fs = require('fs');
function loadSentDeals() {
try {
if (fs.existsSync(sentDealsPath)) {
const data = fs.readFileSync(sentDealsPath, 'utf8');
return new Set(JSON.parse(data));
}
} catch (err) {
console.error('Error loading sent deals:', err);
}
return new Set();
}
function saveSentDeals(sentDeals) {
try {
fs.writeFileSync(sentDealsPath, JSON.stringify([...sentDeals]));
} catch (err) {
console.error('Error saving sent deals:', err);
}
}
async function checkNewDeals() {
console.log(`\n🔍 Checking for new deals at ${new Date().toLocaleString()}...`);
const sentDeals = loadSentDeals();
// Get all deals with 20%+ profit margin
const query = `
SELECT
l.*,
da.deal_percentage,
da.avg_us_price,
da.is_deal,
da.confidence_score,
da.ai_notes
FROM listings l
JOIN deal_analysis da ON l.id = da.listing_id
WHERE da.is_deal = 1
AND da.deal_percentage >= 20
AND l.is_active = 1
ORDER BY da.deal_percentage DESC
LIMIT 50
`;
db.db.all(query, [], async (err, deals) => {
if (err) {
console.error('Error querying deals:', err);
return;
}
console.log(`Found ${deals.length} active deals`);
let newDealsCount = 0;
for (const deal of deals) {
const dealKey = `${deal.source}-${deal.external_id}`;
// Skip if already sent
if (sentDeals.has(dealKey)) {
continue;
}
// Send Slack notification to Steve
console.log(`🔥 NEW DEAL: ${deal.brand} - ${deal.deal_percentage.toFixed(1)}% off - $${deal.price_usd}`);
await slackNotifier.notifyDeal(deal, {
deal_percentage: deal.deal_percentage,
avg_us_price: deal.avg_us_price,
confidence_score: deal.confidence_score,
ai_notes: deal.ai_notes
});
// Mark as sent
sentDeals.add(dealKey);
newDealsCount++;
// Rate limit: wait 2 seconds between Slack messages
await new Promise(resolve => setTimeout(resolve, 2000));
}
if (newDealsCount > 0) {
console.log(`✅ Sent ${newDealsCount} new deal alerts to Steve Abrams (DW)!`);
saveSentDeals(sentDeals);
} else {
console.log('✓ No new deals to report');
}
db.close();
});
}
// Run the check
checkNewDeals().catch(err => {
console.error('Fatal error:', err);
process.exit(1);
});