sms-extension-1777535448/server/routes/brand.js
2026-03-26 14:19:26 +05:30

87 lines
2.9 KiB
JavaScript

const express = require('express');
const router = express.Router();
const { scrape } = require('../services/firecrawl');
const { parseBrandContext } = require('../services/openai2');
const { uploadImageFromUrl, uploadJSON, fetchJSON, deleteAllBrandFiles } = require('../services/pixelbin');
const DEFAULT_EVENTS = require('../config/defaultEvents');
// POST /api/brand/register
router.post('/register', async (req, res) => {
try {
const { websiteUrl } = req.body;
if (!websiteUrl) return res.status(400).json({ error: 'websiteUrl is required' });
const merchantId = process.env.MERCHANT_ID;
const merchantFolder = `brands/${merchantId}`;
const imagesFolder = `${merchantFolder}/images`;
// 409 if brand already registered
const existing = await fetchJSON(merchantFolder, 'context');
if (existing) {
return res.status(409).json({ error: 'Brand already registered. Delete the current brand first to re-register.' });
}
// 1. Scrape
const scrapedData = await scrape(websiteUrl);
// 2. Parse brand context
const brandContext = await parseBrandContext(scrapedData);
// 3. Upload relevant images to Pixelbin
const imagePaths = [];
for (let i = 0; i < Math.min((brandContext.relevantImageUrls || []).length, 5); i++) {
const url = await uploadImageFromUrl(brandContext.relevantImageUrls[i], imagesFolder, `image_${i + 1}`);
if (url) imagePaths.push(url);
}
// 4. Build and upload context.json
let domain = '';
try { domain = new URL(websiteUrl).hostname; } catch { }
const contextJson = {
merchantId,
domain,
brandName: brandContext.brandName || 'Unknown Brand',
tone: brandContext.tone || 'professional',
taglines: brandContext.taglines || [],
colors: brandContext.colors || [],
relevantImagePaths: imagePaths,
scrapedAt: new Date().toISOString(),
};
await uploadJSON(merchantFolder, 'context', contextJson);
// 5. Init events.json
await uploadJSON(merchantFolder, 'events', { events: DEFAULT_EVENTS });
res.json(contextJson);
} catch (err) {
console.error('Brand register error:', err.message);
res.status(500).json({ error: err.message });
}
});
// GET /api/brand
router.get('/', async (req, res) => {
try {
const context = await fetchJSON(`brands/${process.env.MERCHANT_ID}`, 'context');
if (!context) return res.status(404).json({ error: 'No brand registered.' });
res.json(context);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// DELETE /api/brand — wipe all brand files from Pixelbin
router.delete('/', async (req, res) => {
try {
const merchantId = process.env.MERCHANT_ID;
await deleteAllBrandFiles(merchantId);
res.json({ ok: true });
} catch (err) {
console.error('Brand delete error:', err.message);
res.status(500).json({ error: err.message });
}
});
module.exports = router;