Răsfoiți Sursa

fix: enable orders and customers sync in shoprenter scheduled sync #90

- Updated shoprenter-scheduled-sync to call shoprenter-sync for full data sync
- Added sync_orders and sync_customers flags to query
- Now syncs orders and customers to Qdrant when enabled
- Respects data_access_permissions and store_sync_config flags
- Fixed bug where scheduled sync only synced products
Claude 5 luni în urmă
părinte
comite
9281553b95
1 a modificat fișierele cu 63 adăugiri și 7 ștergeri
  1. 63 7
      supabase/functions/shoprenter-scheduled-sync/index.ts

+ 63 - 7
supabase/functions/shoprenter-scheduled-sync/index.ts

@@ -1,7 +1,7 @@
 import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
 import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
 import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
 import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
 import { wrapHandler, logError } from '../_shared/error-handler.ts'
 import { wrapHandler, logError } from '../_shared/error-handler.ts'
-import { fetchProducts } from '../_shared/shoprenter-client.ts'
+import { fetchProducts, fetchOrders, fetchCustomers } from '../_shared/shoprenter-client.ts'
 import { detectCountryCode } from '../_shared/phone-formatter.ts'
 import { detectCountryCode } from '../_shared/phone-formatter.ts'
 
 
 const corsHeaders = {
 const corsHeaders = {
@@ -57,10 +57,14 @@ serve(wrapHandler('shoprenter-scheduled-sync', async (req) => {
         store_name,
         store_name,
         store_url,
         store_url,
         alt_data,
         alt_data,
+        qdrant_sync_enabled,
+        data_access_permissions,
         store_sync_config (
         store_sync_config (
           enabled,
           enabled,
           sync_frequency,
           sync_frequency,
           sync_products,
           sync_products,
+          sync_orders,
+          sync_customers,
           last_sync_at,
           last_sync_at,
           next_sync_at
           next_sync_at
         )
         )
@@ -123,7 +127,8 @@ serve(wrapHandler('shoprenter-scheduled-sync', async (req) => {
         store_id: storeId,
         store_id: storeId,
         store_name: store.store_name,
         store_name: store.store_name,
         products: { synced: 0, errors: 0 },
         products: { synced: 0, errors: 0 },
-        // Note: customer_access and order_access removed for GDPR compliance (migration 20251031_160300)
+        orders: { synced: 0, errors: 0 },
+        customers: { synced: 0, errors: 0 },
         started_at: new Date().toISOString(),
         started_at: new Date().toISOString(),
         completed_at: null as string | null,
         completed_at: null as string | null,
         status: 'success' as 'success' | 'partial' | 'failed',
         status: 'success' as 'success' | 'partial' | 'failed',
@@ -192,9 +197,59 @@ serve(wrapHandler('shoprenter-scheduled-sync', async (req) => {
           }
           }
         }
         }
 
 
-        // Note: Customer and Order testing removed for GDPR compliance (migration 20251031_160300)
-        // Customer/order data is now accessed in real-time via webshop-data-api endpoint
-        console.log(`[ShopRenter Scheduled Sync] Skipping customer/order testing (GDPR compliance - use real-time API access)`)
+        // Sync Orders and Customers to Qdrant (if enabled)
+        // Note: Orders/customers are NOT cached to database for GDPR compliance
+        // They are only synced to Qdrant for AI access when flags are enabled
+        const qdrantEnabled = store.qdrant_sync_enabled !== false
+        const permissions = store.data_access_permissions || {}
+        const canSyncOrders = permissions.allow_order_access !== false
+        const canSyncCustomers = permissions.allow_customer_access !== false
+        const shouldSyncOrders = config?.sync_orders === true
+        const shouldSyncCustomers = config?.sync_customers === true
+
+        // Call shoprenter-sync to handle full sync (products + orders + customers)
+        // This ensures orders and customers are synced to Qdrant
+        if (qdrantEnabled && (shouldSyncOrders || shouldSyncCustomers)) {
+          try {
+            console.log(`[ShopRenter Scheduled Sync] Calling shoprenter-sync for full sync on store ${storeId}`)
+            const syncResponse = await fetch(`${supabaseUrl}/functions/v1/shoprenter-sync/${storeId}`, {
+              method: 'POST',
+              headers: {
+                'Authorization': `Bearer ${supabaseServiceKey}`,
+                'Content-Type': 'application/json'
+              }
+            })
+
+            if (syncResponse.ok) {
+              const syncResult = await syncResponse.json()
+              if (syncResult.success && syncResult.stats) {
+                // Update with results from full sync
+                syncStats.orders = syncResult.stats.orders || { synced: 0, errors: 0 }
+                syncStats.customers = syncResult.stats.customers || { synced: 0, errors: 0 }
+                console.log(`[ShopRenter Scheduled Sync] Full sync completed: orders=${syncStats.orders.synced}, customers=${syncStats.customers.synced}`)
+              } else {
+                console.error(`[ShopRenter Scheduled Sync] Full sync failed:`, syncResult.error || syncResult.message)
+                syncStats.status = 'partial'
+              }
+            } else {
+              console.error(`[ShopRenter Scheduled Sync] Full sync HTTP error: ${syncResponse.status}`)
+              syncStats.status = 'partial'
+            }
+          } catch (error) {
+            console.error(`[ShopRenter Scheduled Sync] Full sync error for store ${storeId}:`, error)
+            syncStats.orders.errors++
+            syncStats.customers.errors++
+            syncStats.status = 'partial'
+          }
+        } else {
+          console.log(`[ShopRenter Scheduled Sync] Orders/customers sync skipped:`, {
+            qdrantEnabled,
+            shouldSyncOrders,
+            shouldSyncCustomers,
+            canSyncOrders,
+            canSyncCustomers
+          })
+        }
 
 
         // Update BOTH stores table and store_sync_config to maintain consistency
         // Update BOTH stores table and store_sync_config to maintain consistency
         const syncCompletedAt = new Date().toISOString()
         const syncCompletedAt = new Date().toISOString()
@@ -204,8 +259,9 @@ serve(wrapHandler('shoprenter-scheduled-sync', async (req) => {
           ...(store.alt_data || {}),
           ...(store.alt_data || {}),
           last_sync_at: syncCompletedAt,
           last_sync_at: syncCompletedAt,
           last_sync_stats: {
           last_sync_stats: {
-            products: syncStats.products
-            // Note: customer_access and order_access removed for GDPR compliance
+            products: syncStats.products,
+            orders: syncStats.orders,
+            customers: syncStats.customers
           },
           },
           last_sync_type: 'scheduled'
           last_sync_type: 'scheduled'
         }
         }