mirror of
https://github.com/christianvidalwolf-prog/Craze-Data-check.git
synced 2026-08-03 15:05:23 +02:00
57 lines
1.9 KiB
JavaScript
57 lines
1.9 KiB
JavaScript
import * as XLSX from 'xlsx';
|
|||
|
|
import { getBcConfig, getBCToken, fetchAllItems, buildWorkbook } from '../bc-runtime.js';
|
||
|
|
|
||
|
|
const ALLOWED_ORIGINS = [
|
||
|
|
'http://localhost:3000',
|
||
|
|
'http://localhost:4173',
|
||
|
|
'http://localhost:5173',
|
||
|
|
'https://craze-data-check.vercel.app',
|
||
|
|
];
|
||
|
|
|
||
|
|
function setCors(req, res) {
|
||
|
|
const origin = req.headers.origin;
|
||
|
|
if (origin && ALLOWED_ORIGINS.includes(origin)) {
|
||
|
|
res.setHeader('Access-Control-Allow-Origin', origin);
|
||
|
|
}
|
||
|
|
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
|
||
|
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
||
|
|
res.setHeader('Vary', 'Origin');
|
||
|
|
}
|
||
|
|
|
||
|
|
export default async function handler(req, res) {
|
||
|
|
setCors(req, res);
|
||
|
|
|
||
|
|
if (req.method === 'OPTIONS') return res.status(204).end();
|
||
|
|
|
||
|
|
const origin = req.headers.origin;
|
||
|
|
if (origin && !ALLOWED_ORIGINS.includes(origin)) {
|
||
|
|
return res.status(403).json({ error: 'Forbidden' });
|
||
|
|
}
|
||
|
|
|
||
|
|
if (req.method !== 'GET') {
|
||
|
|
return res.status(405).json({ error: 'Method not allowed' });
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const config = getBcConfig();
|
||
|
|
const token = await getBCToken(config);
|
||
|
|
const items = await fetchAllItems(config, token);
|
||
|
|
|
||
|
|
if (req.query?.format === 'json') {
|
||
|
|
return res.json({ success: true, count: items.length, items });
|
||
|
|
}
|
||
|
|
|
||
|
|
const workbook = buildWorkbook(items);
|
||
|
|
const buffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
|
||
|
|
const dateStr = new Date().toISOString().split('T')[0];
|
||
|
|
|
||
|
|
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||
|
|
res.setHeader('Content-Disposition', `attachment; filename="BusinessCentral_Items_${dateStr}.xlsx"`);
|
||
|
|
res.setHeader('Cache-Control', 'no-store');
|
||
|
|
return res.status(200).send(buffer);
|
||
|
|
} catch (err) {
|
||
|
|
console.error('[bc-export] error:', err?.message || err);
|
||
|
|
return res.status(500).json({ success: false, error: err?.message || String(err) });
|
||
|
|
}
|
||
|
|
}
|