mirror of
https://github.com/christianvidalwolf-prog/Craze-Data-check.git
synced 2026-08-03 11:05:24 +02:00
fix(dropbox): use direct raw fallback
This commit is contained in:
+38
-13
@@ -1,23 +1,47 @@
|
|||||||
import { applyCors, isAllowedOrigin } from './_cors.js';
|
import { applyCors, isAllowedOrigin } from './_cors.js';
|
||||||
|
|
||||||
const DROPBOX_APP_KEY = process.env.DROPBOX_APP_KEY;
|
const DEFAULT_DROPBOX_SHARED_URL = 'https://www.dropbox.com/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0';
|
||||||
const DROPBOX_APP_SECRET = process.env.DROPBOX_APP_SECRET;
|
|
||||||
const DROPBOX_REFRESH_TOKEN = process.env.DROPBOX_REFRESH_TOKEN;
|
function getDropboxConfig() {
|
||||||
const DROPBOX_SHARED_URL = 'https://www.dropbox.com/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0';
|
return {
|
||||||
|
appKey: process.env.DROPBOX_APP_KEY,
|
||||||
|
appSecret: process.env.DROPBOX_APP_SECRET,
|
||||||
|
refreshToken: process.env.DROPBOX_REFRESH_TOKEN,
|
||||||
|
sharedUrl: process.env.DROPBOX_SHARED_URL || DEFAULT_DROPBOX_SHARED_URL,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeDropboxSharedUrl(sharedUrl) {
|
||||||
|
const url = new URL(sharedUrl);
|
||||||
|
url.searchParams.delete('dl');
|
||||||
|
url.searchParams.delete('raw');
|
||||||
|
url.searchParams.delete('st');
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildDropboxDownloadUrl(sharedUrl) {
|
||||||
|
const url = new URL(normalizeDropboxSharedUrl(sharedUrl));
|
||||||
|
url.searchParams.set('raw', '1');
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
function setCors(req, res) {
|
function setCors(req, res) {
|
||||||
applyCors(req, res, 'GET, OPTIONS');
|
applyCors(req, res, 'GET, OPTIONS');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getAccessToken() {
|
async function getAccessToken() {
|
||||||
|
const { appKey, appSecret, refreshToken } = getDropboxConfig();
|
||||||
|
if (!appKey || !appSecret || !refreshToken) {
|
||||||
|
throw new Error('Dropbox auth env vars are not configured.');
|
||||||
|
}
|
||||||
const response = await fetch('https://api.dropboxapi.com/oauth2/token', {
|
const response = await fetch('https://api.dropboxapi.com/oauth2/token', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
body: new URLSearchParams({
|
body: new URLSearchParams({
|
||||||
grant_type: 'refresh_token',
|
grant_type: 'refresh_token',
|
||||||
refresh_token: DROPBOX_REFRESH_TOKEN,
|
refresh_token: refreshToken,
|
||||||
client_id: DROPBOX_APP_KEY,
|
client_id: appKey,
|
||||||
client_secret: DROPBOX_APP_SECRET,
|
client_secret: appSecret,
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
@@ -46,11 +70,12 @@ export default async function handler(req, res) {
|
|||||||
return res.json({ rev: 'new-url-v1', size: 0, server_modified: new Date().toISOString() });
|
return res.json({ rev: 'new-url-v1', size: 0, server_modified: new Date().toISOString() });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip dl=1 for the authenticated API call (browser-redirect hint, not needed for API).
|
const { sharedUrl } = getDropboxConfig();
|
||||||
const sharingUrlForApi = DROPBOX_SHARED_URL.replace(/[&?]dl=1/, '');
|
const sharingUrlForApi = normalizeDropboxSharedUrl(sharedUrl);
|
||||||
|
const downloadUrl = buildDropboxDownloadUrl(sharedUrl);
|
||||||
|
|
||||||
// Try authenticated Dropbox API first — bypasses CDN cache so we always get the latest version.
|
// Try authenticated Dropbox API first — bypasses CDN cache so we always get the latest version.
|
||||||
// Falls back to DROPBOX_SHARED_URL if credentials are not configured.
|
// Falls back to the shared URL if credentials are not configured.
|
||||||
let upstream = null;
|
let upstream = null;
|
||||||
let usedAuth = false;
|
let usedAuth = false;
|
||||||
|
|
||||||
@@ -73,12 +98,12 @@ export default async function handler(req, res) {
|
|||||||
console.warn('Dropbox API download failed, falling back to sharing link:', apiRes.status, errText.substring(0, 200));
|
console.warn('Dropbox API download failed, falling back to sharing link:', apiRes.status, errText.substring(0, 200));
|
||||||
}
|
}
|
||||||
} catch (authErr) {
|
} catch (authErr) {
|
||||||
console.warn('Dropbox auth unavailable, falling back to sharing link:', authErr.message);
|
console.warn('Dropbox auth unavailable, falling back to sharing link:', authErr?.message || String(authErr));
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!upstream) {
|
if (!upstream) {
|
||||||
upstream = await fetch(DROPBOX_SHARED_URL, {
|
upstream = await fetch(downloadUrl, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
'Cache-Control': 'no-cache',
|
'Cache-Control': 'no-cache',
|
||||||
@@ -110,6 +135,6 @@ export default async function handler(req, res) {
|
|||||||
res.send(Buffer.from(buffer));
|
res.send(Buffer.from(buffer));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Dropbox proxy error:', err);
|
console.error('Dropbox proxy error:', err);
|
||||||
res.status(500).send('Proxy error: ' + err.message);
|
res.status(500).send('Proxy error: ' + (err?.message || String(err)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-9
@@ -56,6 +56,8 @@ const FORCED_ZERO_STOCK_SKUS = new Set([
|
|||||||
|
|
||||||
const BC_SYNC_QUEUE_STORAGE_KEY = 'craze_bc_sync_queue';
|
const BC_SYNC_QUEUE_STORAGE_KEY = 'craze_bc_sync_queue';
|
||||||
const LEGACY_CPNP_INDEX = 77;
|
const LEGACY_CPNP_INDEX = 77;
|
||||||
|
const DROPBOX_PROXY_URL = '/api/dropbox-proxy';
|
||||||
|
const DROPBOX_FILE_URL = '/dropbox-file/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0';
|
||||||
|
|
||||||
type BcSyncStatus = 'queued' | 'previewed' | 'preview_only' | 'syncing' | 'synced' | 'failed';
|
type BcSyncStatus = 'queued' | 'previewed' | 'preview_only' | 'syncing' | 'synced' | 'failed';
|
||||||
|
|
||||||
@@ -216,19 +218,15 @@ export default function App() {
|
|||||||
return arrayBuffer.byteLength;
|
return arrayBuffer.byteLength;
|
||||||
};
|
};
|
||||||
|
|
||||||
const dropboxSources = import.meta.env.DEV
|
const dropboxSources = [
|
||||||
? [
|
DROPBOX_PROXY_URL,
|
||||||
'/api/dropbox-proxy',
|
`${DROPBOX_FILE_URL}&t=${Date.now()}`
|
||||||
`/dropbox-file/scl/fi/usa8me7ywgylrij2bt6hj/Data-Matrix.xlsx?rlkey=tsec8csrhye54u1fdvk15ped1&st=qbxxs4cn&dl=0&t=${Date.now()}`
|
];
|
||||||
]
|
|
||||||
: [
|
|
||||||
'/api/dropbox-proxy'
|
|
||||||
];
|
|
||||||
|
|
||||||
let lastError: unknown = null;
|
let lastError: unknown = null;
|
||||||
for (const source of dropboxSources) {
|
for (const source of dropboxSources) {
|
||||||
try {
|
try {
|
||||||
console.log(`Fetching Data-Matrix.xlsx from ${source.includes('/api/') ? 'proxy' : 'Dropbox'}...`);
|
console.log(`Fetching Data-Matrix.xlsx from ${source}...`);
|
||||||
const size = await loadWorkbookFromUrl(source);
|
const size = await loadWorkbookFromUrl(source);
|
||||||
fileMeta = { rev: source, size };
|
fileMeta = { rev: source, size };
|
||||||
lastError = null;
|
lastError = null;
|
||||||
|
|||||||
+142
-132
@@ -29,9 +29,147 @@ async function readJsonBody(req: any): Promise<any> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createLocalApiMiddleware(env: Record<string, string>, prodEnv: Record<string, string>) {
|
||||||
|
return async (req: any, res: any, next: any) => {
|
||||||
|
try {
|
||||||
|
const url = new URL(req.url || '/', 'http://localhost');
|
||||||
|
const config = getBcConfig(env);
|
||||||
|
|
||||||
|
// Populate process.env with loaded env variables for serverless handlers.
|
||||||
|
// The Dropbox proxy reads env at request time so preview/dev/production
|
||||||
|
// can share the same handler implementation.
|
||||||
|
Object.assign(process.env, prodEnv, env);
|
||||||
|
|
||||||
|
// Helper to adapt Node.js req/res to Vercel signature.
|
||||||
|
const adaptVercelHandler = async (handler: any) => {
|
||||||
|
(req as any).query = Object.fromEntries(url.searchParams.entries());
|
||||||
|
try {
|
||||||
|
(req as any).body = await readJsonBody(req);
|
||||||
|
} catch {
|
||||||
|
(req as any).body = {};
|
||||||
|
}
|
||||||
|
(res as any).status = (code: number) => {
|
||||||
|
res.statusCode = code;
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
(res as any).json = (data: any) => {
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify(data));
|
||||||
|
};
|
||||||
|
(res as any).send = (data: any) => {
|
||||||
|
if (data instanceof Buffer) {
|
||||||
|
res.end(data);
|
||||||
|
} else if (typeof data === 'object') {
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify(data));
|
||||||
|
} else {
|
||||||
|
res.end(data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
await handler(req, res);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (url.pathname === '/api/dropbox-proxy') {
|
||||||
|
await adaptVercelHandler(dropboxProxyHandler);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/dropbox-sync') {
|
||||||
|
await adaptVercelHandler(dropboxSyncHandler);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/backup') {
|
||||||
|
await adaptVercelHandler(backupHandler);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/users-admin') {
|
||||||
|
await adaptVercelHandler(usersAdminHandler);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/bc-proxy') {
|
||||||
|
if (req.method === 'OPTIONS') {
|
||||||
|
res.statusCode = 204;
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method !== 'POST') {
|
||||||
|
res.statusCode = 405;
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify({ error: 'Method not allowed' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await readJsonBody(req);
|
||||||
|
const { articleNo, cpnpNo } = body || {};
|
||||||
|
if (!articleNo || cpnpNo === undefined) {
|
||||||
|
res.statusCode = 400;
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify({ error: 'Missing articleNo or cpnpNo' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await getBCToken(config);
|
||||||
|
const item = await findItem(config, token, articleNo);
|
||||||
|
await patchItemCpnpNo(config, token, item, String(cpnpNo));
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify({ success: true, articleNo, cpnpNo }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === '/api/bc-export') {
|
||||||
|
if (req.method === 'OPTIONS') {
|
||||||
|
res.statusCode = 204;
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method !== 'GET') {
|
||||||
|
res.statusCode = 405;
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify({ error: 'Method not allowed' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await getBCToken(config);
|
||||||
|
const items = await fetchAllItems(config, token);
|
||||||
|
|
||||||
|
if (url.searchParams.get('format') === 'json') {
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify({ success: true, count: items.length, items }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const workbook = buildWorkbook(items);
|
||||||
|
const buffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
|
||||||
|
const dateStr = new Date().toISOString().split('T')[0];
|
||||||
|
res.statusCode = 200;
|
||||||
|
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');
|
||||||
|
res.end(buffer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
const message = err?.message || String(err);
|
||||||
|
if ((req.url || '').startsWith('/api/bc-')) {
|
||||||
|
res.statusCode = 500;
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.end(JSON.stringify({ success: false, error: message }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('[bc-local-api]', message);
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export default defineConfig(({mode}) => {
|
export default defineConfig(({mode}) => {
|
||||||
const env = loadEnv(mode, '.', '');
|
const env = loadEnv(mode, '.', '');
|
||||||
const prodEnv = loadEnv('production', '.', '');
|
const prodEnv = loadEnv('production', '.', '');
|
||||||
|
const localApiMiddleware = createLocalApiMiddleware(env, prodEnv);
|
||||||
return {
|
return {
|
||||||
plugins: [
|
plugins: [
|
||||||
react(),
|
react(),
|
||||||
@@ -39,138 +177,10 @@ export default defineConfig(({mode}) => {
|
|||||||
{
|
{
|
||||||
name: 'bc-local-api',
|
name: 'bc-local-api',
|
||||||
configureServer(server) {
|
configureServer(server) {
|
||||||
server.middlewares.use(async (req, res, next) => {
|
server.middlewares.use(localApiMiddleware);
|
||||||
try {
|
},
|
||||||
const url = new URL(req.url || '/', 'http://localhost');
|
configurePreviewServer(server) {
|
||||||
const config = getBcConfig(env);
|
server.middlewares.use(localApiMiddleware);
|
||||||
|
|
||||||
// Populate process.env with loaded env variables for serverless handlers
|
|
||||||
Object.assign(process.env, prodEnv, env);
|
|
||||||
|
|
||||||
// Helper to adapt Node.js req/res to Vercel signature
|
|
||||||
const adaptVercelHandler = async (handler: any) => {
|
|
||||||
(req as any).query = Object.fromEntries(url.searchParams.entries());
|
|
||||||
try {
|
|
||||||
(req as any).body = await readJsonBody(req);
|
|
||||||
} catch {
|
|
||||||
(req as any).body = {};
|
|
||||||
}
|
|
||||||
(res as any).status = (code: number) => {
|
|
||||||
res.statusCode = code;
|
|
||||||
return res;
|
|
||||||
};
|
|
||||||
(res as any).json = (data: any) => {
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify(data));
|
|
||||||
};
|
|
||||||
(res as any).send = (data: any) => {
|
|
||||||
if (data instanceof Buffer) {
|
|
||||||
res.end(data);
|
|
||||||
} else if (typeof data === 'object') {
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify(data));
|
|
||||||
} else {
|
|
||||||
res.end(data);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
await handler(req, res);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (url.pathname === '/api/dropbox-proxy') {
|
|
||||||
await adaptVercelHandler(dropboxProxyHandler);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.pathname === '/api/dropbox-sync') {
|
|
||||||
await adaptVercelHandler(dropboxSyncHandler);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.pathname === '/api/backup') {
|
|
||||||
await adaptVercelHandler(backupHandler);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.pathname === '/api/users-admin') {
|
|
||||||
await adaptVercelHandler(usersAdminHandler);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.pathname === '/api/bc-proxy') {
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
res.statusCode = 204;
|
|
||||||
res.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (req.method !== 'POST') {
|
|
||||||
res.statusCode = 405;
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify({ error: 'Method not allowed' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await readJsonBody(req);
|
|
||||||
const { articleNo, cpnpNo } = body || {};
|
|
||||||
if (!articleNo || cpnpNo === undefined) {
|
|
||||||
res.statusCode = 400;
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify({ error: 'Missing articleNo or cpnpNo' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = await getBCToken(config);
|
|
||||||
const item = await findItem(config, token, articleNo);
|
|
||||||
await patchItemCpnpNo(config, token, item, String(cpnpNo));
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify({ success: true, articleNo, cpnpNo }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.pathname === '/api/bc-export') {
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
res.statusCode = 204;
|
|
||||||
res.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (req.method !== 'GET') {
|
|
||||||
res.statusCode = 405;
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify({ error: 'Method not allowed' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = await getBCToken(config);
|
|
||||||
const items = await fetchAllItems(config, token);
|
|
||||||
|
|
||||||
if (url.searchParams.get('format') === 'json') {
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify({ success: true, count: items.length, items }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const workbook = buildWorkbook(items);
|
|
||||||
const buffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
|
|
||||||
const dateStr = new Date().toISOString().split('T')[0];
|
|
||||||
res.statusCode = 200;
|
|
||||||
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');
|
|
||||||
res.end(buffer);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (err: any) {
|
|
||||||
const message = err?.message || String(err);
|
|
||||||
if ((req.url || '').startsWith('/api/bc-')) {
|
|
||||||
res.statusCode = 500;
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
res.end(JSON.stringify({ success: false, error: message }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
console.error('[bc-local-api]', message);
|
|
||||||
}
|
|
||||||
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
Reference in New Issue
Block a user