Files

77 lines
2.7 KiB
JavaScript
Raw Permalink Normal View History

import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = process.env.SUPABASE_URL || process.env.VITE_SUPABASE_URL || 'https://hwithddwaapyhnfwcesj.supabase.co';
const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY || process.env.SUPABASE_SERVICE_ROLE_KEY || 'sb_publishable_fGXkh0bSrAOqSk2jWKAzSg_NJD9YPCv';
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
export default async function handler(req, res) {
try {
2026-04-23 15:46:54 +02:00
console.log('Starting migration v3...');
// 1. Fetch products
const { data: products, error: pErr } = await supabase
.from('products')
.select('product_id, data')
2026-04-23 15:46:54 +02:00
.in('status', ['edited', 'synced', 'pending']);
2026-04-23 15:46:54 +02:00
if (pErr) return res.status(500).json({ error: 'Fetch products failed', details: pErr });
let pCount = 0;
if (products && products.length > 0) {
2026-04-23 15:46:54 +02:00
for (const p of products) {
const oldData = p.data;
2026-04-23 15:46:54 +02:00
if (!oldData || oldData.length < 13) continue;
const valAt12 = oldData[12];
const isOld = typeof valAt12 === 'number' || (typeof valAt12 === 'string' && /^[0-9.]+$/.test(valAt12));
2026-04-23 15:46:54 +02:00
if (isOld && oldData.length < 110) {
const newData = [...oldData];
2026-04-23 15:46:54 +02:00
newData.splice(12, 0, '');
const { error: updateErr } = await supabase.from('products').update({ data: newData }).eq('product_id', p.product_id);
if (!updateErr) pCount++;
}
2026-04-23 15:46:54 +02:00
}
}
// 2. History
const { data: history, error: hErr } = await supabase.from('products_history').select('*');
2026-04-23 15:46:54 +02:00
if (hErr) return res.status(500).json({ error: 'Fetch history failed', details: hErr });
let hCount = 0;
if (history && history.length > 0) {
2026-04-23 15:46:54 +02:00
for (const h of history) {
let changed = false;
let nOld = h.old_data;
let nNew = h.new_data;
if (nOld && nOld.length >= 13 && (typeof nOld[12] === 'number' || (typeof nOld[12] === 'string' && /^[0-9.]+$/.test(nOld[12])))) {
nOld = [...nOld];
nOld.splice(12, 0, '');
changed = true;
}
if (nNew && nNew.length >= 13 && (typeof nNew[12] === 'number' || (typeof nNew[12] === 'string' && /^[0-9.]+$/.test(nNew[12])))) {
nNew = [...nNew];
nNew.splice(12, 0, '');
changed = true;
}
if (changed) {
2026-04-23 15:46:54 +02:00
const { error: histErr } = await supabase.from('products_history').update({ old_data: nOld, new_data: nNew }).eq('id', h.id);
if (!histErr) hCount++;
}
2026-04-23 15:46:54 +02:00
}
}
return res.json({
success: true,
productsMigrated: pCount,
historyMigrated: hCount,
2026-04-23 15:46:54 +02:00
message: 'Migration v3 finished.'
});
} catch (err) {
2026-04-23 15:46:54 +02:00
return res.status(500).json({ error: err.message });
}
}