From 1269c53959f81babc9ba14b57429cb49c1c0aba2 Mon Sep 17 00:00:00 2001
From: Miqdad <ahmadmiqdad27@gmail.com>
Date: Thu, 28 Aug 2025 09:58:51 +0700
Subject: <Miqdad> push

---
 src/lib/transaction/components/Transactions.jsx | 204 +++++++++---------------
 1 file changed, 75 insertions(+), 129 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 826d88ac..7df1f0ff 100644
--- a/src/lib/transaction/components/Transactions.jsx
+++ b/src/lib/transaction/components/Transactions.jsx
@@ -40,12 +40,10 @@ import { Calendar } from 'lucide-react';
 import { DateRangePicker } from 'react-date-range';
 import 'react-date-range/dist/styles.css';
 import 'react-date-range/dist/theme/default.css';
-// import { fetchPaymentSummary } from '../api/regenerate';
 
 const Transactions = ({ context = '' }) => {
   const auth = useAuth();
   const router = useRouter();
-  const swiperRef = useRef(null);
   const {
     q = '',
     page = 1,
@@ -70,52 +68,9 @@ const Transactions = ({ context = '' }) => {
   const [sortNew, setSortNew] = useState(sort);
   const [contextNew, setcontextNew] = useState(router.query.context || context);
   const [isOpenCalender, setIsOpenCalender] = useState(false);
-  const [cachedAllData, setCachedAllData] = useState(null);
-  const [currentData, setCurrentData] = useState([]);
   const calendarRef = useRef(null);
-  // --- helpers aturan regenerate ---
-  const getApproval = (so) =>
-    (so?.approvalStatus || so?.approval_status || '').toLowerCase();
-
-  const isApprovalPending = (so) =>
-    ['pengajuan1', 'pengajuan2'].includes(getApproval(so));
-
-  const isWebSource = (so) => {
-    const code = (so?.source || so?.sourceCode || '').toLowerCase();
-    const id = so?.sourceId ?? so?.source_id;
-    return code === 'website' || code === 'web' || id === 59; // sesuaikan id sumber web kamu
-  };
-
-  const getPaymentStatus = (so) =>
-    (
-      so?.paymentSummary?.paymentStatus ||
-      so?.paymentSummary?.status ||
-      so?.paymentStatus ||
-      ''
-    ).toLowerCase();
-
-  // kosong | expire | belum settlement → boleh regenerate
-  const isPaymentUnsettled = (so) => {
-    const ps = getPaymentStatus(so);
-    if (!ps) return true; // kosong
-    if (['expire', 'expired'].includes(ps)) return true;
-    // dianggap “belum settlement” jika bukan status paid/settled
-    return !['settlement', 'paid', 'capture', 'success', 'settled'].includes(
-      ps
-    );
-  };
-
-  // WAJIB semua true
-  const canRegeneratePayment = (so) =>
-    isApprovalPending(so) && isWebSource(so) && isPaymentUnsettled(so);
-
-  // Jika backend sudah kirim flag eligibleContinue, tetap wajib lolos aturan front-end
-  const eligibleToShow = (so) => {
-    const backend =
-      typeof so?.eligibleContinue === 'boolean' ? so.eligibleContinue : true;
-    return backend && canRegeneratePayment(so);
-  };
 
+  // loading id utk tombol lanjutkan transaksi
   const [contLoadingId, setContLoadingId] = useState(null);
 
   const parseDate = (date) => {
@@ -191,13 +146,9 @@ const Transactions = ({ context = '' }) => {
     setToCancel(null);
   };
 
-  const pageCount = Math.ceil(transactions?.data?.saleOrderTotal / limitNew);
-  let pageQuery = _.omit(query, ['limit', 'offset', 'context']);
-  pageQuery = _.pickBy(
-    pageQuery,
-    (value, key) => value !== '' && !(key === 'page' && value === '1')
+  const pageCount = Math.ceil(
+    (transactions?.data?.saleOrderTotal || 0) / (limitNew || 1)
   );
-  pageQuery = toQuery(pageQuery);
 
   const handleSubmit = (e) => {
     e.preventDefault();
@@ -227,12 +178,12 @@ const Transactions = ({ context = '' }) => {
     ];
     const rowsToExport = [];
 
-    data.forEach((saleOrder) => {
+    (data || []).forEach((saleOrder) => {
       const row = {
         'No. Transaksi': saleOrder.name,
         'No. PO': saleOrder.purchaseOrderName || '-',
         Tanggal: saleOrder.dateOrder || '-',
-        'Created By': saleOrder.address.customer?.name || '-',
+        'Created By': saleOrder.address?.customer?.name || '-',
         Salesperson: saleOrder.sales,
         Total: currencyFormat(saleOrder.amountTotal),
         Status: contextLabelMap[saleOrder.status] || saleOrder.status,
@@ -251,7 +202,7 @@ const Transactions = ({ context = '' }) => {
   };
 
   const getAllData = async () => {
-    const query = {
+    const qobj = {
       name: q,
       offset: (pageNew - 1) * limitNew,
       limit: limitNew,
@@ -266,7 +217,7 @@ const Transactions = ({ context = '' }) => {
       site:
         siteFilter || (auth?.webRole === null && auth?.site ? auth.site : null),
     };
-    const queryString = toQuery(query);
+    const queryString = toQuery(qobj);
     const data = await transactionsApi({ query: queryString });
     return data;
   };
@@ -289,12 +240,15 @@ const Transactions = ({ context = '' }) => {
           saleOrder.name,
           saleOrder.purchaseOrderName || '-',
           saleOrder.dateOrder || '-',
-          saleOrder.address.customer?.name || '-',
+          saleOrder.address?.customer?.name || '-',
           saleOrder.sales,
           currencyFormat(saleOrder.amountTotal),
-          contextLabelMap[saleOrder.status] || saleOrder.status,
+          (contextLabelMap[saleOrder.status] || saleOrder.status || '').replace(
+            /,/g,
+            ' '
+          ),
         ];
-        if (siteFilter) row.push(siteFilter);
+        if (siteFilter) row.push((siteFilter || '').replace(/,/g, ' '));
         return row.join(',');
       }) || [];
 
@@ -335,7 +289,7 @@ const Transactions = ({ context = '' }) => {
   const startItem = 1 + (pageNew - 1) * limitNew;
   const endItem = Math.min(
     limitNew * pageNew,
-    transactions?.data?.saleOrderTotal
+    transactions?.data?.saleOrderTotal || 0
   );
 
   useEffect(() => {
@@ -345,7 +299,7 @@ const Transactions = ({ context = '' }) => {
   const handleBuyBack = async (products) => {
     try {
       const results = await Promise.all(
-        products.map((product) =>
+        (products || []).map((product) =>
           upsertUserCart({
             userId: auth.id,
             type: 'product',
@@ -358,15 +312,13 @@ const Transactions = ({ context = '' }) => {
         )
       );
 
-      const failedOperations = results.filter((r) => r && r.error);
-      if (failedOperations.length > 0) {
-        toast.error(
-          `${failedOperations.length} produk gagal ditambahkan ke keranjang`
-        );
-        if (failedOperations.length < products.length) {
+      const failed = results.filter((r) => r && r.error);
+      if (failed.length > 0) {
+        toast.error(`${failed.length} produk gagal ditambahkan ke keranjang`);
+        if (failed.length < (products || []).length) {
           toast.success(
             `${
-              products.length - failedOperations.length
+              (products || []).length - failed.length
             } produk berhasil ditambahkan`
           );
           setRefreshCart(true);
@@ -377,26 +329,24 @@ const Transactions = ({ context = '' }) => {
       setRefreshCart(true);
       toast.success('Semua produk berhasil ditambahkan ke keranjang');
       router.push('/shop/cart');
-    } catch (error) {
+    } catch {
       toast.error('Terjadi kesalahan saat menambahkan produk ke keranjang');
     }
   };
 
-  const handleStatusChange = async (status) => {
+  const handleStatusChange = (status) => {
     setStatusNew(status);
     setPageNew(1);
-
-    if (status === 'all' && cachedAllData) {
-      setCurrentData(cachedAllData);
-      return;
-    }
-    const data = await fetchSite(status, 1);
-    if (status === 'all') setCachedAllData(data);
-    setCurrentData(data);
+    // opsional: sinkronkan ke URL
+    router.push({
+      pathname: router.pathname,
+      query: { ...router.query, status },
+    });
   };
 
   useEffect(() => {
-    setCachedAllData([]);
+    // bersihkan cache lama jika perlu (saat first mount)
+    // (sengaja kosong; tidak pakai cached data di versi ini)
   }, []);
 
   const handleReset = () => {
@@ -405,7 +355,6 @@ const Transactions = ({ context = '' }) => {
     router.push(`${router.pathname}`);
   };
 
-
   const formatDate = (dateString) => {
     const months = [
       'Januari',
@@ -421,57 +370,54 @@ const Transactions = ({ context = '' }) => {
       'November',
       'Desember',
     ];
-    const [day, month, year] = dateString.split('/');
+    const [day, month, year] = (dateString || '').split('/');
+    if (!day || !month || !year) return dateString || '-';
     return `${day} ${months[parseInt(month, 10) - 1]} ${year}`;
   };
 
-const handleContinuePayment = async (saleOrder) => {
-  try {
-    if (!canRegeneratePayment(saleOrder)) {
-      toast.error(
-        'Tidak memenuhi syarat: approval belum pengajuan1/2, sumber bukan web, atau pembayaran sudah settle.'
-      );
-      return;
-    }
-    const partnerId =
-      auth?.partnerId || auth?.partner_id || auth?.partner?.id || auth?.id;
-    setContLoadingId(saleOrder.id);
-
-    // pakai URL yang sudah ada dulu
-    const existingUrl =
-      saleOrder?.paymentSummary?.redirectUrl || saleOrder?.paymentLinkMidtrans;
-
-    if (existingUrl) {
-      window.open(existingUrl, '_blank', 'noopener,noreferrer');
-      toast.success('Membuka halaman pembayaran…');
-      return;
-    }
+  // ==== Lanjutkan Transaksi (tanpa endpoint baru) ====
+  const handleContinuePayment = async (saleOrder) => {
+    try {
+      setContLoadingId(saleOrder.id);
 
-    // fallback autogen
-    const res = await fetchPaymentSummary({
-      partnerId,
-      saleOrderId: saleOrder.id,
-      autogen: true,
-    });
-    const redirectUrl = res?.redirect_url || res?.redirectUrl;
-    if (redirectUrl) {
-      window.open(redirectUrl, '_blank', 'noopener,noreferrer');
-      toast.success('Membuka halaman pembayaran…');
-    } else {
-      toast.error('Link pembayaran belum tersedia.');
-    }
-  } catch (e) {
-    const msg =
-      e?.response?.data?.description ||
-      e?.message ||
-      'Gagal melanjutkan transaksi';
-    toast.error(msg);
-  } finally {
-    setContLoadingId(null);
-  }
-};
+      // 1) pakai URL yang dikirim server di list
+      const existingUrl =
+        saleOrder?.paymentSummary?.redirectUrl ||
+        saleOrder?.paymentLinkMidtrans ||
+        '';
 
+      if (existingUrl) {
+        window.open(existingUrl, '_blank', 'noopener,noreferrer');
+        toast.success('Membuka halaman pembayaran…');
+        return;
+      }
 
+      // 2) kalau masih kosong, refetch list (server bisa auto-generate saat list)
+      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.');
+      }
+    } catch (e) {
+      const msg =
+        e?.response?.data?.description ||
+        e?.message ||
+        'Gagal melanjutkan transaksi';
+      toast.error(msg);
+    } finally {
+      setContLoadingId(null);
+    }
+  };
 
   return (
     <>
@@ -681,7 +627,7 @@ const handleContinuePayment = async (saleOrder) => {
                       Beli Lagi
                     </button>
 
-                    {eligibleToShow(saleOrder) && (
+                    {saleOrder?.eligibleContinue && (
                       <button
                         type='button'
                         disabled={contLoadingId === saleOrder.id}
@@ -694,7 +640,7 @@ const handleContinuePayment = async (saleOrder) => {
                       >
                         {contLoadingId === saleOrder.id
                           ? 'Memproses…'
-                          : 'Lanjutkan Pembayaran'}
+                          : 'Lanjutkan Transaksi'}
                       </button>
                     )}
                   </div>
@@ -1175,7 +1121,7 @@ const handleContinuePayment = async (saleOrder) => {
                                 Beli Lagi
                               </button>
 
-                              {eligibleToShow(saleOrder) && (
+                              {saleOrder?.eligibleContinue && (
                                 <button
                                   type='button'
                                   disabled={contLoadingId === saleOrder.id}
@@ -1188,7 +1134,7 @@ const handleContinuePayment = async (saleOrder) => {
                                 >
                                   {contLoadingId === saleOrder.id
                                     ? 'Memproses…'
-                                    : 'Lanjutkan Pembayaran'}
+                                    : 'Lanjutkan Transaksi'}
                                 </button>
                               )}
                             </div>
-- 
cgit v1.2.3

