2026-04-23 12:37:04 +02:00
|
|
|
import { refreshSession, getStoredSession } from './auth';
|
|
|
|
|
|
2026-03-27 12:23:35 +01:00
|
|
|
const SUPABASE_URL = 'https://hwithddwaapyhnfwcesj.supabase.co';
|
2026-04-23 09:59:46 +02:00
|
|
|
const SUPABASE_ANON_KEY = 'sb_publishable_fGXkh0bSrAOqSk2jWKAzSg_NJD9YPCv';
|
|
|
|
|
|
2026-04-23 12:37:04 +02:00
|
|
|
async function safeFetch(url: string, options: RequestInit = {}): Promise<Response> {
|
|
|
|
|
const session = getStoredSession();
|
|
|
|
|
const token = session?.access_token || SUPABASE_ANON_KEY;
|
|
|
|
|
|
|
|
|
|
const headers = {
|
|
|
|
|
...options.headers,
|
2026-04-23 09:59:46 +02:00
|
|
|
'apikey': SUPABASE_ANON_KEY,
|
2026-04-23 12:37:04 +02:00
|
|
|
'Authorization': `Bearer ${token}`,
|
2026-04-23 09:59:46 +02:00
|
|
|
};
|
2026-04-23 12:37:04 +02:00
|
|
|
|
|
|
|
|
let response = await fetch(url, { ...options, headers });
|
2026-04-23 19:23:29 +02:00
|
|
|
console.log('[safeFetch] URL:', url.split('?')[0]);
|
|
|
|
|
console.log('[safeFetch] Status:', response.status, '| OK:', response.ok);
|
|
|
|
|
console.log('[safeFetch] Session token:', !!session, '| Token length:', token?.length);
|
2026-04-23 12:37:04 +02:00
|
|
|
|
|
|
|
|
if (response.status === 401 && session?.refresh_token) {
|
2026-04-23 19:23:29 +02:00
|
|
|
console.log('[safeFetch] 401 - refreshing session...');
|
2026-04-23 12:37:04 +02:00
|
|
|
try {
|
|
|
|
|
const newSession = await refreshSession(session.refresh_token);
|
|
|
|
|
const newHeaders = {
|
|
|
|
|
...options.headers,
|
|
|
|
|
'apikey': SUPABASE_ANON_KEY,
|
|
|
|
|
'Authorization': `Bearer ${newSession.access_token}`,
|
|
|
|
|
};
|
|
|
|
|
response = await fetch(url, { ...options, headers: newHeaders });
|
2026-04-23 19:23:29 +02:00
|
|
|
console.log('[safeFetch] After refresh - Status:', response.status);
|
2026-04-23 12:37:04 +02:00
|
|
|
} catch (refreshError) {
|
2026-04-23 19:23:29 +02:00
|
|
|
console.error('[safeFetch] Session refresh failed:', refreshError);
|
2026-04-23 12:37:04 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return response;
|
2026-04-23 09:59:46 +02:00
|
|
|
}
|
2026-03-27 12:23:35 +01:00
|
|
|
|
2026-04-10 09:47:35 +02:00
|
|
|
export interface ExcelRow extends Array<any> {}
|
|
|
|
|
|
|
|
|
|
export interface SyncedRow {
|
|
|
|
|
data: ExcelRow;
|
2026-04-23 16:22:35 +02:00
|
|
|
status?: 'pending' | 'edited' | 'synced' | 'excel';
|
2026-04-10 09:47:35 +02:00
|
|
|
}
|
|
|
|
|
|
2026-04-23 12:37:04 +02:00
|
|
|
export async function getAllSyncedRows(): Promise<Record<string, SyncedRow>> {
|
2026-04-23 16:56:54 +02:00
|
|
|
const PAGE_SIZE = 1000;
|
|
|
|
|
const result: Record<string, SyncedRow> = {};
|
2026-04-10 09:47:35 +02:00
|
|
|
try {
|
2026-04-23 16:56:54 +02:00
|
|
|
let offset = 0;
|
|
|
|
|
// Paginate until Supabase returns fewer rows than PAGE_SIZE (no more pages).
|
|
|
|
|
// Supabase REST caps a single response at 1000 rows, so we must page.
|
|
|
|
|
// Safety cap at 20 pages (20k products) to avoid infinite loops.
|
|
|
|
|
for (let page = 0; page < 20; page++) {
|
|
|
|
|
const response = await safeFetch(
|
|
|
|
|
`${SUPABASE_URL}/rest/v1/products?select=product_id,data,status&order=product_id.asc&limit=${PAGE_SIZE}&offset=${offset}`,
|
|
|
|
|
{ cache: 'no-store' }
|
|
|
|
|
);
|
2026-04-10 09:47:35 +02:00
|
|
|
|
2026-04-23 16:56:54 +02:00
|
|
|
if (!response.ok) {
|
|
|
|
|
const errText = await response.text();
|
|
|
|
|
console.error('getAllSyncedRows failed:', response.status, errText);
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
const rows = await response.json();
|
|
|
|
|
for (const row of rows) {
|
|
|
|
|
result[row.product_id] = { data: row.data, status: row.status };
|
|
|
|
|
}
|
|
|
|
|
if (rows.length < PAGE_SIZE) break;
|
|
|
|
|
offset += PAGE_SIZE;
|
2026-04-09 08:22:58 +02:00
|
|
|
}
|
2026-04-10 09:47:35 +02:00
|
|
|
return result;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error fetching synced rows from Supabase:', error);
|
2026-04-23 16:56:54 +02:00
|
|
|
return result;
|
2026-04-09 08:22:58 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 12:37:04 +02:00
|
|
|
export async function saveRowToSupabase(articleNo: string, rowData: ExcelRow): Promise<{ success: boolean; error?: string }> {
|
2026-03-27 12:23:35 +01:00
|
|
|
try {
|
2026-04-23 12:37:04 +02:00
|
|
|
const response = await safeFetch(
|
2026-04-10 10:48:05 +02:00
|
|
|
`${SUPABASE_URL}/rest/v1/products`,
|
2026-04-10 09:47:35 +02:00
|
|
|
{
|
2026-04-10 10:48:05 +02:00
|
|
|
method: 'POST',
|
2026-04-10 09:47:35 +02:00
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
2026-04-23 09:59:46 +02:00
|
|
|
'Prefer': 'resolution=merge-duplicates',
|
2026-04-10 09:47:35 +02:00
|
|
|
},
|
|
|
|
|
body: JSON.stringify({
|
|
|
|
|
product_id: articleNo,
|
|
|
|
|
data: rowData,
|
2026-04-23 15:04:43 +02:00
|
|
|
status: 'edited',
|
2026-04-10 09:47:35 +02:00
|
|
|
updated_at: new Date().toISOString()
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
);
|
2026-03-27 12:23:35 +01:00
|
|
|
|
2026-04-10 12:06:16 +02:00
|
|
|
if (!response.ok) {
|
|
|
|
|
const err = await response.json().catch(() => ({}));
|
2026-04-23 09:59:46 +02:00
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
error: `${response.status} ${response.statusText}: ${err.message || err.error_description || 'Unknown error'}`
|
2026-04-10 12:06:16 +02:00
|
|
|
};
|
|
|
|
|
}
|
2026-04-23 09:59:46 +02:00
|
|
|
|
2026-04-10 12:06:16 +02:00
|
|
|
return { success: true };
|
|
|
|
|
} catch (error: any) {
|
2026-03-27 12:23:35 +01:00
|
|
|
console.error('Error saving to Supabase:', error);
|
2026-04-10 12:06:16 +02:00
|
|
|
return { success: false, error: error.message || 'Network error' };
|
2026-03-27 12:23:35 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-09 09:24:17 +02:00
|
|
|
export interface HistoryEntry {
|
2026-04-23 18:58:52 +02:00
|
|
|
id?: string;
|
2026-04-09 09:24:17 +02:00
|
|
|
product_id: string;
|
|
|
|
|
article_name: string;
|
|
|
|
|
old_data: ExcelRow;
|
|
|
|
|
new_data: ExcelRow;
|
|
|
|
|
changed_by: string;
|
2026-04-10 09:47:35 +02:00
|
|
|
changed_at: string;
|
2026-04-09 09:24:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function saveHistoryEntry(
|
2026-04-10 09:47:35 +02:00
|
|
|
productId: string,
|
2026-04-09 09:24:17 +02:00
|
|
|
articleName: string,
|
|
|
|
|
oldData: ExcelRow,
|
|
|
|
|
newData: ExcelRow,
|
2026-04-23 12:37:04 +02:00
|
|
|
changedBy: string
|
2026-04-10 12:06:16 +02:00
|
|
|
): Promise<{ success: boolean; error?: string }> {
|
2026-04-09 09:24:17 +02:00
|
|
|
try {
|
2026-04-23 12:37:04 +02:00
|
|
|
const response = await safeFetch(
|
2026-04-10 09:47:35 +02:00
|
|
|
`${SUPABASE_URL}/rest/v1/products_history`,
|
|
|
|
|
{
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
2026-04-23 09:59:46 +02:00
|
|
|
'Prefer': 'return=minimal',
|
2026-04-10 09:47:35 +02:00
|
|
|
},
|
|
|
|
|
body: JSON.stringify({
|
|
|
|
|
product_id: productId,
|
|
|
|
|
article_name: articleName,
|
|
|
|
|
old_data: oldData,
|
|
|
|
|
new_data: newData,
|
|
|
|
|
changed_by: changedBy,
|
|
|
|
|
changed_at: new Date().toISOString()
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
);
|
2026-04-09 09:24:17 +02:00
|
|
|
|
2026-04-10 12:06:16 +02:00
|
|
|
if (!response.ok) {
|
|
|
|
|
const err = await response.json().catch(() => ({}));
|
2026-04-23 09:59:46 +02:00
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
error: `History ${response.status}: ${err.message || 'Unknown error'}`
|
2026-04-10 12:06:16 +02:00
|
|
|
};
|
|
|
|
|
}
|
2026-04-23 09:59:46 +02:00
|
|
|
|
2026-04-10 12:06:16 +02:00
|
|
|
return { success: true };
|
|
|
|
|
} catch (error: any) {
|
2026-04-09 09:24:17 +02:00
|
|
|
console.error('Error saving history to Supabase:', error);
|
2026-04-10 12:06:16 +02:00
|
|
|
return { success: false, error: error.message || 'Network error' };
|
2026-04-09 09:24:17 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 12:37:04 +02:00
|
|
|
export async function getHistory(): Promise<HistoryEntry[]> {
|
2026-04-09 09:24:17 +02:00
|
|
|
try {
|
2026-04-23 18:58:52 +02:00
|
|
|
const response = await safeFetch(
|
|
|
|
|
`${SUPABASE_URL}/rest/v1/products_history?select=*&order=changed_at.desc&limit=500`,
|
|
|
|
|
{ cache: 'no-store' }
|
|
|
|
|
);
|
2026-04-09 09:24:17 +02:00
|
|
|
|
2026-04-10 19:48:33 +02:00
|
|
|
if (!response.ok) {
|
2026-04-23 18:51:07 +02:00
|
|
|
const errText = await response.text();
|
2026-04-23 18:58:52 +02:00
|
|
|
console.error('[getHistory] Error:', response.status, errText.substring(0, 200));
|
2026-04-10 19:48:33 +02:00
|
|
|
return [{
|
2026-04-23 18:58:52 +02:00
|
|
|
id: 'ERROR',
|
2026-04-10 19:48:33 +02:00
|
|
|
product_id: 'ERROR',
|
2026-04-23 18:51:07 +02:00
|
|
|
article_name: `Failed: ${response.status} ${errText.substring(0, 200)}`,
|
2026-04-10 19:48:33 +02:00
|
|
|
old_data: [],
|
|
|
|
|
new_data: [],
|
|
|
|
|
changed_at: new Date().toISOString(),
|
|
|
|
|
changed_by: 'system'
|
|
|
|
|
}];
|
|
|
|
|
}
|
2026-04-23 18:58:52 +02:00
|
|
|
return await response.json();
|
2026-04-10 19:48:33 +02:00
|
|
|
} catch (error: any) {
|
2026-04-23 18:51:07 +02:00
|
|
|
console.error('[getHistory] Exception:', error.message);
|
2026-04-10 19:48:33 +02:00
|
|
|
return [{
|
2026-04-23 18:58:52 +02:00
|
|
|
id: 'EXCEPTION',
|
2026-04-23 09:59:46 +02:00
|
|
|
product_id: 'EXCEPTION',
|
|
|
|
|
article_name: `Message: ${error.message}`,
|
|
|
|
|
old_data: [],
|
|
|
|
|
new_data: [],
|
|
|
|
|
changed_at: new Date().toISOString(),
|
|
|
|
|
changed_by: 'system'
|
2026-04-10 19:48:33 +02:00
|
|
|
}];
|
2026-04-09 09:24:17 +02:00
|
|
|
}
|
|
|
|
|
}
|
2026-04-10 09:47:35 +02:00
|
|
|
|
2026-04-23 19:07:38 +02:00
|
|
|
export async function getHistoryDataForMerge(): Promise<Record<string, ExcelRow>> {
|
|
|
|
|
try {
|
|
|
|
|
const response = await safeFetch(
|
|
|
|
|
`${SUPABASE_URL}/rest/v1/products_history?select=product_id,new_data&order=changed_at.desc`,
|
|
|
|
|
{ cache: 'no-store' }
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
console.error('[getHistoryDataForMerge] Error:', response.status);
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
const entries: Array<{ product_id: string; new_data: ExcelRow }> = await response.json();
|
2026-04-23 19:23:29 +02:00
|
|
|
console.log('[getHistoryDataForMerge] Raw entries count:', entries.length);
|
|
|
|
|
const entry_59272 = entries.find(e => e.product_id === '59272EN');
|
|
|
|
|
console.log('[getHistoryDataForMerge] 59272EN entry found:', !!entry_59272);
|
|
|
|
|
if (entry_59272) {
|
|
|
|
|
console.log('[getHistoryDataForMerge] 59272EN new_data length:', entry_59272.new_data?.length);
|
|
|
|
|
console.log('[getHistoryDataForMerge] 59272EN new_data[103]:', entry_59272.new_data?.[103]);
|
|
|
|
|
console.log('[getHistoryDataForMerge] 59272EN new_data type:', typeof entry_59272.new_data);
|
|
|
|
|
}
|
2026-04-23 19:07:38 +02:00
|
|
|
|
|
|
|
|
const result: Record<string, ExcelRow> = {};
|
|
|
|
|
const seen = new Set<string>();
|
|
|
|
|
for (const entry of entries) {
|
|
|
|
|
if (seen.has(entry.product_id)) continue;
|
|
|
|
|
seen.add(entry.product_id);
|
|
|
|
|
if (entry.new_data && entry.new_data.length > 0) {
|
|
|
|
|
result[entry.product_id] = entry.new_data;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return result;
|
|
|
|
|
} catch (error: any) {
|
|
|
|
|
console.error('[getHistoryDataForMerge] Exception:', error.message);
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 12:37:04 +02:00
|
|
|
export async function deleteHistoryEntry(id: string): Promise<boolean> {
|
2026-04-10 09:47:35 +02:00
|
|
|
try {
|
2026-04-23 12:37:04 +02:00
|
|
|
const response = await safeFetch(
|
2026-04-23 18:58:52 +02:00
|
|
|
`${SUPABASE_URL}/rest/v1/products_history?id=eq.${encodeURIComponent(String(id))}`,
|
2026-04-23 12:37:04 +02:00
|
|
|
{ method: 'DELETE' }
|
2026-04-10 09:47:35 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return response.ok;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error deleting history from Supabase:', error);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 12:37:04 +02:00
|
|
|
export async function resetAllPendingRows(): Promise<boolean> {
|
2026-04-10 09:47:35 +02:00
|
|
|
try {
|
2026-04-23 12:37:04 +02:00
|
|
|
const response = await safeFetch(
|
2026-04-10 09:47:35 +02:00
|
|
|
`${SUPABASE_URL}/rest/v1/products?status=eq.pending`,
|
|
|
|
|
{
|
|
|
|
|
method: 'PATCH',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
2026-04-23 09:59:46 +02:00
|
|
|
'Prefer': 'return=minimal',
|
2026-04-10 09:47:35 +02:00
|
|
|
},
|
2026-04-23 16:22:35 +02:00
|
|
|
body: JSON.stringify({ status: 'edited' })
|
2026-04-10 09:47:35 +02:00
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return response.ok;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error resetting pending rows in Supabase:', error);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2026-04-23 09:59:46 +02:00
|
|
|
}
|