From 306122977320b7ec7c8516a3cda1978ed2de7060 Mon Sep 17 00:00:00 2001
From: Miqdad <ahmadmiqdad27@gmail.com>
Date: Sat, 6 Sep 2025 20:41:31 +0700
Subject: <Miqdad> fix transactions

---
 src/lib/transaction/components/Transactions.jsx | 142 +++++++++++++++++-------
 1 file changed, 103 insertions(+), 39 deletions(-)

(limited to 'src/lib/transaction/components/Transactions.jsx')

diff --git a/src/lib/transaction/components/Transactions.jsx b/src/lib/transaction/components/Transactions.jsx
index 4572a7b5..cdac4036 100644
--- a/src/lib/transaction/components/Transactions.jsx
+++ b/src/lib/transaction/components/Transactions.jsx
@@ -42,7 +42,6 @@ import { DateRangePicker } from 'react-date-range';
 import 'react-date-range/dist/styles.css';
 import 'react-date-range/dist/theme/default.css';
 
-
 const Transactions = ({ context = '' }) => {
   const auth = useAuth();
   const router = useRouter();
@@ -389,6 +388,7 @@ const Transactions = ({ context = '' }) => {
   const handleContinuePayment = async (saleOrder) => {
     try {
       setContLoadingId(saleOrder.id);
+      console.log('🚀 START PAYMENT PROCESS');
 
       const base = (process.env.NEXT_PUBLIC_ODOO_API_HOST || '').replace(
         /\/$/,
@@ -397,61 +397,125 @@ const Transactions = ({ context = '' }) => {
       const token = auth?.token;
       const partnerId = auth?.partnerId;
 
-      // (1) Minta Odoo ensure (generate hanya jika kosong/expire/cancel)
-      let ensuredUrl = '';
+      // 1. TRIGGER GENERATE + GET URL SEKALIGUS
+      console.log('🔹 Step 1: Trigger generate + get URL');
+      const { data: response } = await axios.get(
+        `${base}/api/v1/partner/${partnerId}/sale_order/${saleOrder.id}`,
+        {
+          params: {
+            ensure_payment_link: 1,
+            ts: Date.now(),
+          },
+          headers: {
+            Token: token,
+            'Cache-Control': 'no-cache',
+          },
+          timeout: 10000, // 10 second timeout
+        }
+      );
+
+      console.log('📦 Full API Response:', response);
+
+      // 2. EKSTRAK URL DENGAN CARA YANG BENAR
+      let paymentUrl = '';
+
+      // Cara 1: Langsung dari response.result
+      if (response?.result?.payment_summary?.redirect_url) {
+        paymentUrl = response.result.payment_summary.redirect_url;
+        console.log('✅ URL found in response.result');
+      }
+      // Cara 2: Mungkin nested di data.result
+      else if (response?.data?.result?.payment_summary?.redirect_url) {
+        paymentUrl = response.data.result.payment_summary.redirect_url;
+        console.log('✅ URL found in response.data.result');
+      }
+      // Cara 3: Coba variasi lain
+      else {
+        console.log(
+          '❌ URL not found in usual places, checking all possibilities...'
+        );
+
+        // Debug: Log semua keys yang ada
+        console.log('🔍 Response keys:', Object.keys(response));
+        if (response.result)
+          console.log('🔍 Result keys:', Object.keys(response.result));
+
+        // Manual search untuk redirect_url
+        const searchForUrl = (obj) => {
+          for (const key in obj) {
+            if (
+              key.toLowerCase().includes('redirect') &&
+              typeof obj[key] === 'string' &&
+              obj[key].includes('http')
+            ) {
+              return obj[key];
+            }
+            if (typeof obj[key] === 'object' && obj[key] !== null) {
+              const found = searchForUrl(obj[key]);
+              if (found) return found;
+            }
+          }
+          return null;
+        };
+
+        paymentUrl = searchForUrl(response);
+        console.log('🔍 Manual search result:', paymentUrl);
+      }
+
+      // 3. JIKA DAPAT URL, BUKA
+      if (paymentUrl) {
+        console.log('🎯 Opening URL:', paymentUrl);
+        window.open(paymentUrl, '_blank', 'noopener,noreferrer');
+        toast.success('Membuka halaman pembayaran…');
+        return;
+      }
+
+      // 4. FALLBACK: COBA LAGI TANPA ensure_payment_link
+      console.log('🔹 Step 2: Fallback - try without ensure');
       try {
-        const { data: resp } = await axios.get(
+        const { data: fallbackResponse } = await axios.get(
           `${base}/api/v1/partner/${partnerId}/sale_order/${saleOrder.id}`,
           {
-            params: { ensure_payment_link: 1, ts: Date.now() },
             headers: { Token: token },
+            timeout: 5000,
           }
         );
-        const payload = resp?.data || resp;
-        ensuredUrl =
-          payload?.payment_summary?.redirect_url ||
-          payload?.paymentLinkMidtrans ||
-          '';
-      } catch (_) {
-        /* biarkan lanjut ke fallback */
+
+        const fallbackUrl =
+          fallbackResponse?.result?.payment_summary?.redirect_url ||
+          fallbackResponse?.data?.result?.payment_summary?.redirect_url;
+
+        if (fallbackUrl) {
+          console.log('✅ Fallback URL found:', fallbackUrl);
+          window.open(fallbackUrl, '_blank', 'noopener,noreferrer');
+          toast.success('Membuka halaman pembayaran…');
+          return;
+        }
+      } catch (fallbackError) {
+        console.error('Fallback error:', fallbackError);
       }
 
-      // (2) Pakai link hasil ensure atau yang sudah ada di list
+      // 5. ULTIMATE FALLBACK: PAKAI URL DARI DATA LAMA
+      console.log('🔹 Step 3: Ultimate fallback - use existing data');
       const existingUrl =
-        ensuredUrl ||
         saleOrder?.paymentSummary?.redirectUrl ||
-        saleOrder?.paymentLinkMidtrans ||
-        '';
+        saleOrder?.payment_summary?.redirect_url;
 
       if (existingUrl) {
+        console.log('✅ Using existing URL:', existingUrl);
         window.open(existingUrl, '_blank', 'noopener,noreferrer');
         toast.success('Membuka halaman pembayaran…');
-        return;
-      }
-
-      // (3) Fallback terakhir: refetch list (agar link yang disimpan Odoo ikut terambil)
-      await transactions.refetch();
-      const updated =
-        transactions?.data?.saleOrders?.find((s) => s.id === saleOrder.id) ||
-        null;
-      const updatedUrl =
-        updated?.paymentSummary?.redirectUrl ||
-        updated?.paymentLinkMidtrans ||
-        '';
-
-      if (updatedUrl) {
-        window.open(updatedUrl, '_blank', 'noopener,noreferrer');
-        toast.success('Membuka halaman pembayaran…');
       } else {
-        toast.error('Link pembayaran belum tersedia.');
+        console.error('❌ No URL found in any method');
+        toast.error('Link pembayaran tidak ditemukan. Silakan coba lagi.');
       }
-    } catch (e) {
-      const msg =
-        e?.response?.data?.description ||
-        e?.message ||
-        'Gagal melanjutkan transaksi';
-      toast.error(msg);
+    } catch (error) {
+      console.error('💥 Payment error:', error);
+      toast.error(
+        error.response?.data?.description || 'Gagal memproses pembayaran'
+      );
     } finally {
+      console.log('🏁 END PAYMENT PROCESS');
       setContLoadingId(null);
     }
   };
-- 
cgit v1.2.3

