Browse Source

fix: resolve store_sync_config query issue in WooCommerce scheduled sync #75

- Changed from PostgREST nested select to separate queries for stores and configs
- Create a Map for efficient config lookup by store_id
- Fixed config filtering logic to properly check sync_frequency
- Resolved 'has_config: false' issue where configs were not being found
- Now properly fetches and joins sync configs for scheduled syncs
Claude 5 months ago
parent
commit
6f6f150ed3
1 changed files with 55 additions and 23 deletions
  1. 55 23
      supabase/functions/woocommerce-scheduled-sync/index.ts

+ 55 - 23
supabase/functions/woocommerce-scheduled-sync/index.ts

@@ -50,8 +50,8 @@ serve(wrapHandler('woocommerce-scheduled-sync', async (req) => {
     const body = await req.json().catch(() => ({}))
     const body = await req.json().catch(() => ({}))
     const frequency = body.frequency || 'all' // Default to all frequencies
     const frequency = body.frequency || 'all' // Default to all frequencies
 
 
-    // Build query to get WooCommerce stores that need syncing
-    let query = supabaseAdmin
+    // Get all active WooCommerce stores
+    const { data: stores, error: storesError } = await supabaseAdmin
       .from('stores')
       .from('stores')
       .select(`
       .select(`
         id,
         id,
@@ -59,25 +59,11 @@ serve(wrapHandler('woocommerce-scheduled-sync', async (req) => {
         store_name,
         store_name,
         store_url,
         store_url,
         alt_data,
         alt_data,
-        data_access_permissions,
-        store_sync_config (
-          enabled,
-          sync_frequency,
-          sync_products,
-          last_sync_at,
-          next_sync_at
-        )
+        data_access_permissions
       `)
       `)
       .eq('platform_name', 'woocommerce')
       .eq('platform_name', 'woocommerce')
       .eq('is_active', true)
       .eq('is_active', true)
 
 
-    // If specific frequency requested, filter by it
-    if (frequency !== 'all') {
-      query = query.eq('store_sync_config.sync_frequency', frequency)
-    }
-
-    const { data: stores, error: storesError } = await query
-
     if (storesError) {
     if (storesError) {
       console.error('[WooCommerce Scheduled Sync] Error fetching stores:', storesError)
       console.error('[WooCommerce Scheduled Sync] Error fetching stores:', storesError)
       return new Response(
       return new Response(
@@ -88,18 +74,53 @@ serve(wrapHandler('woocommerce-scheduled-sync', async (req) => {
 
 
     console.log(`[WooCommerce Scheduled Sync] Fetched ${stores?.length || 0} WooCommerce stores from database`)
     console.log(`[WooCommerce Scheduled Sync] Fetched ${stores?.length || 0} WooCommerce stores from database`)
 
 
+    if (!stores || stores.length === 0) {
+      console.log('[WooCommerce Scheduled Sync] No WooCommerce stores found')
+      return new Response(
+        JSON.stringify({
+          success: true,
+          message: 'No WooCommerce stores found',
+          stores_processed: 0
+        }),
+        { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
+      )
+    }
+
+    // Get sync configs for all stores
+    const storeIds = stores.map(s => s.id)
+    const { data: syncConfigs, error: configError } = await supabaseAdmin
+      .from('store_sync_config')
+      .select('*')
+      .in('store_id', storeIds)
+
+    if (configError) {
+      console.error('[WooCommerce Scheduled Sync] Error fetching sync configs:', configError)
+      return new Response(
+        JSON.stringify({ error: 'Failed to fetch sync configs', details: configError.message }),
+        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
+      )
+    }
+
+    console.log(`[WooCommerce Scheduled Sync] Fetched ${syncConfigs?.length || 0} sync configs`)
+
+    // Create a map of store_id -> config for easy lookup
+    const configMap = new Map()
+    syncConfigs?.forEach(config => {
+      configMap.set(config.store_id, config)
+    })
+
     // Filter stores that have sync enabled and are due for sync
     // Filter stores that have sync enabled and are due for sync
     const now = new Date()
     const now = new Date()
-    const storesToSync = stores?.filter(store => {
-      const config = store.store_sync_config?.[0]
+    const storesToSync = stores.filter(store => {
+      const config = configMap.get(store.id)
 
 
       // Debug logging
       // Debug logging
       console.log(`[WooCommerce Scheduled Sync] Checking store ${store.id}:`, {
       console.log(`[WooCommerce Scheduled Sync] Checking store ${store.id}:`, {
         has_config: !!config,
         has_config: !!config,
         enabled: config?.enabled,
         enabled: config?.enabled,
+        sync_frequency: config?.sync_frequency,
         next_sync_at: config?.next_sync_at,
         next_sync_at: config?.next_sync_at,
-        is_array: Array.isArray(store.store_sync_config),
-        config_length: store.store_sync_config?.length
+        frequency_filter: frequency
       })
       })
 
 
       if (!config || !config.enabled) {
       if (!config || !config.enabled) {
@@ -107,6 +128,12 @@ serve(wrapHandler('woocommerce-scheduled-sync', async (req) => {
         return false
         return false
       }
       }
 
 
+      // If specific frequency requested, filter by it
+      if (frequency !== 'all' && config.sync_frequency !== frequency) {
+        console.log(`[WooCommerce Scheduled Sync] Store ${store.id} filtered out: frequency mismatch (${config.sync_frequency} !== ${frequency})`)
+        return false
+      }
+
       // Check if sync is due
       // Check if sync is due
       if (config.next_sync_at) {
       if (config.next_sync_at) {
         const nextSync = new Date(config.next_sync_at)
         const nextSync = new Date(config.next_sync_at)
@@ -118,7 +145,12 @@ serve(wrapHandler('woocommerce-scheduled-sync', async (req) => {
       // If no next_sync_at, sync is due
       // If no next_sync_at, sync is due
       console.log(`[WooCommerce Scheduled Sync] Store ${store.id} has no next_sync_at, sync is due`)
       console.log(`[WooCommerce Scheduled Sync] Store ${store.id} has no next_sync_at, sync is due`)
       return true
       return true
-    }) || []
+    })
+
+    // Add config to store objects for later use
+    storesToSync.forEach(store => {
+      store.store_sync_config = configMap.get(store.id)
+    })
 
 
     if (storesToSync.length === 0) {
     if (storesToSync.length === 0) {
       console.log('[WooCommerce Scheduled Sync] No WooCommerce stores due for sync')
       console.log('[WooCommerce Scheduled Sync] No WooCommerce stores due for sync')
@@ -140,7 +172,7 @@ serve(wrapHandler('woocommerce-scheduled-sync', async (req) => {
     // Sync each store by calling the woocommerce-sync function
     // Sync each store by calling the woocommerce-sync function
     for (const store of storesToSync) {
     for (const store of storesToSync) {
       const storeId = store.id
       const storeId = store.id
-      const config = store.store_sync_config?.[0]
+      const config = store.store_sync_config
       console.log(`[WooCommerce Scheduled Sync] Starting sync for store ${storeId} (${store.store_name})`)
       console.log(`[WooCommerce Scheduled Sync] Starting sync for store ${storeId} (${store.store_name})`)
 
 
       const syncStats = {
       const syncStats = {