Files
Craze-Data-check/api/dropbox-sync.js
T

91 lines
3.0 KiB
JavaScript

import { applyCors, isAllowedOrigin } from './_cors.js';
import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = process.env.SUPABASE_URL || 'https://hwithddwaapyhnfwcesj.supabase.co';
const SUPABASE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SERVICE_KEY || 'sb_publishable_fGXkh0bSrAOqSk2jWKAzSg_NJD9YPCv';
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
function setCors(req, res) {
applyCors(req, res, 'POST, OPTIONS');
}
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 && !isAllowedOrigin(origin)) {
return res.status(403).json({ error: 'Forbidden' });
}
try {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { rows } = req.body;
if (!rows || !Array.isArray(rows)) {
return res.status(400).json({ error: 'Missing rows data' });
}
const articleNoIdx = 0;
// Fetch IDs of ALL products that have manual edits so we don't overwrite them
const { data: existingProducts } = await supabase
.from('products')
.select('product_id, status');
// Protect ALL products that are not 'excel' status (i.e. they have manual edits or special status)
const manuallyEditedIds = new Set(
(existingProducts || [])
.filter(p => p.status && p.status !== 'excel')
.map(p => p.product_id)
);
// Also protect any product that has history entries — they were edited at some point.
// If their status was accidentally reset to 'excel', this restores protection.
const { data: historyProducts } = await supabase
.from('products_history')
.select('product_id');
(historyProducts || []).forEach(h => manuallyEditedIds.add(h.product_id));
const productsToUpsert = [];
for (const row of rows) {
const productId = String(row[articleNoIdx]);
// Only add if: new product OR existing but NOT manually edited
if (productId && productId.trim() !== '' && !manuallyEditedIds.has(productId)) {
productsToUpsert.push({
product_id: productId,
data: row,
status: 'excel',
updated_at: new Date().toISOString()
});
}
}
console.log('Upserting', productsToUpsert.length, 'new/updated products to Supabase...');
// We can now use a normal upsert because we filtered out the manual edits
const { error } = await supabase
.from('products')
.upsert(productsToUpsert, { onConflict: 'product_id' });
if (error) {
console.error('Supabase upsert error:', error);
return res.status(500).json({ error: error.message, detail: 'Failed to upsert products' });
}
return res.json({
success: true,
syncedCount: productsToUpsert.length
});
} catch (err) {
console.error('Handler error:', err);
res.status(500).json({ error: err.message });
}
}