update komponen

This commit is contained in:
bagus-arie05
2025-10-17 15:12:20 +07:00
parent f3a5e8935e
commit fa2d439ea4
15 changed files with 746 additions and 306 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

+49 -40
View File
@@ -83,11 +83,7 @@
@error="onVideoError"
></iframe>
<div
v-else
class="video-thumbnail"
@click="playVideo(index)"
>
<div v-else class="video-thumbnail" @click="playVideo(index)">
<img
:src="`https://img.youtube.com/vi/${item.videoId}/maxresdefault.jpg`"
alt="Video thumbnail"
@@ -112,7 +108,7 @@
</div>
</div>
<div class="cta-section-contact">
<!-- <div class="cta-section-contact">
<v-btn
@click="startDebugPayment"
color="#808080"
@@ -121,7 +117,7 @@
>
<span class="button-text">SIMULASI PEMBAYARAN</span>
</v-btn>
</div>
</div> -->
</div>
<div class="orange-background-contact">
@@ -175,7 +171,7 @@ const carouselItems = ref([
isImage: false,
},
{
src: "https://scontent.fcgk22-2.fna.fbcdn.net/v/t39.30808-6/481267190_3904366386504845_1409667601717073976_n.jpg?stp=dst-jpg_s960x960_tt6&_nc_cat=110&ccb=1-7&_nc_sid=cc71e4&_nc_ohc=w6wAp5Df1lAQ7kNvwHL8Snq&_nc_oc=Adnq0LOV2vro6n7DGZu9GfUYGx3iBXzZ7LlUk7oWYi_lZ_OYDD7LVYe5zogYKxEEJdU&_nc_zt=23&_nc_ht=scontent.fcgk22-2.fna&_nc_gid=Dir3R7zaEbm2b0HPtrmGiQ&oh=00_AfaERSA1GyvNKkfajBF5yIv_JrijpizdmUqgy9528oAszQ&oe=68D12398",
src: "https://rsusaifulanwar.jatimprov.go.id/wp-content/uploads/2023/08/siam-2-scaled.jpg",
alt: "Medical Services",
title: "Pelayanan Terbaik",
description: "Tim medis profesional siap melayani 24 jam",
@@ -184,31 +180,30 @@ const carouselItems = ref([
]);
const getYouTubeEmbedUrl = (videoId) => {
const baseUrl = 'https://www.youtube.com/embed/';
const baseUrl = "https://www.youtube.com/embed/";
const params = new URLSearchParams({
autoplay: '1',
mute: '0',
controls: '1',
modestbranding: '1',
rel: '0',
showinfo: '0',
fs: '1',
cc_load_policy: '0',
iv_load_policy: '3',
autohide: '0'
autoplay: "1",
mute: "0",
controls: "1",
modestbranding: "1",
rel: "0",
showinfo: "0",
fs: "1",
cc_load_policy: "0",
iv_load_policy: "3",
autohide: "0",
});
return `${baseUrl}${videoId}?${params.toString()}`;
};
const onVideoLoad = () => {
console.log('Video iframe loaded successfully');
console.log("Video iframe loaded successfully");
};
const onVideoError = (error) => {
console.error('Video iframe error:', error);
console.error("Video iframe error:", error);
};
// Fungsi untuk memulai carousel otomatis
const startCarousel = () => {
if (carouselInterval.value) {
clearInterval(carouselInterval.value);
@@ -216,10 +211,9 @@ const startCarousel = () => {
carouselInterval.value = setInterval(() => {
const nextSlide = (currentSlide.value + 1) % carouselItems.value.length;
currentSlide.value = nextSlide;
}, 10000); // Ganti gambar setiap 10 detik
}, 10000);
};
// Fungsi untuk menghentikan carousel otomatis
const stopCarousel = () => {
if (carouselInterval.value) {
clearInterval(carouselInterval.value);
@@ -227,40 +221,33 @@ const stopCarousel = () => {
}
};
// Fungsi untuk memutar video (menghentikan carousel)
const playVideo = (index) => {
currentSlide.value = index;
stopCarousel(); // Hentikan carousel saat video diputar
stopCarousel();
};
// Tonton perubahan slide
watch(currentSlide, (newSlide) => {
const currentItem = carouselItems.value[newSlide];
if (currentItem && !currentItem.isImage) {
// Jika slide adalah video, hentikan carousel
console.log('Video detected, stopping carousel');
console.log("Video detected, stopping carousel");
stopCarousel();
} else {
// Jika slide adalah gambar, mulai kembali carousel
console.log('Image detected, starting carousel');
console.log("Image detected, starting carousel");
startCarousel();
}
});
onMounted(() => {
// Mulai carousel saat komponen dimuat
startCarousel();
});
onUnmounted(() => {
// Hentikan carousel saat komponen dihancurkan
stopCarousel();
});
// Fungsi untuk simulasi pembayaran debug
const startDebugPayment = () => {
console.log("Simulasi Pembayaran (Debug) dimulai.");
// Mengisi data dummy untuk simulasi
const dummyData = {
posdevice: "GRANDPAV",
invoice_number: "000000000000012000615",
@@ -268,14 +255,15 @@ const startDebugPayment = () => {
created_at: "2024-11-21T11:52:25.805965+07:00",
display_name: "KASIH",
id: "1",
status: "1", // Status awal untuk simulasi
status: "1",
display_amount: "90",
qrvalue: "000201010212262710019ID.CO.BANKJATIM.WWW01189360011400001347728215ID02400134529083038ES1459015ID.OR.GPMQR.MM0215ID202431094996960309ES2049939530536054029605802D5923-RSUD SAIFUL ANWAR MLG-100000MALANG0556111622901250000000000000000000000000000012800061563040C9B",
qrvalue:
"000201010212262710019ID.CO.BANKJATIM.WWW01189360011400001347728215ID02400134529083038ES1459015ID.OR.GPMQR.MM0215ID202431094996960309ES2049939530536054029605802D5923-RSUD SAIFUL ANWAR MLG-100000MALANG0556111622901250000000000000000000000000000012800061563040C9B",
ip: "10.10.150.106",
display_nobill: "24072579/10000675",
};
paymentStore.updatePayment({ data: [dummyData] });
paymentStore.currentStep = 2; // Pindah ke QRISPayment
paymentStore.currentStep = 2;
};
</script>
@@ -388,10 +376,13 @@ const startDebugPayment = () => {
width: 100%;
height: 100%;
position: relative;
background: #000;
background: white;
display: flex;
align-items: center;
justify-content: center;
/* PASTIKAN INI ADA untuk membatasi iframe */
overflow: hidden;
}
.youtube-iframe {
@@ -399,8 +390,26 @@ const startDebugPayment = () => {
height: 100%;
border: none;
border-radius: 15px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
min-width: 100%;
min-height: 100%;
aspect-ratio: 16 / 9;
}
.thumbnail-img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 15px;
}
.video-thumbnail {
width: 100%;
height: 100%;
@@ -558,4 +567,4 @@ const startDebugPayment = () => {
:deep(.v-carousel__controls--bottom) {
bottom: 40px !important;
}
</style>
</style>
+20 -3
View File
@@ -12,6 +12,19 @@
<p class="failure-message mb-8">
Terjadi kesalahan saat memproses<br />pembayaran Anda.
</p>
<div class="action-section">
<v-btn
color="primary"
size="x-large"
variant="flat"
rounded="xl"
class="success-btn"
@click="paymentStore.reset"
>
<v-icon class="mr-2" >mdi-home</v-icon>
Kembali ke Awal
</v-btn>
</div>
<!-- Uncomment jika butuh buttons -->
<!-- <div class="button-group">
@@ -54,7 +67,7 @@ const retryPayment = () => {
<style scoped>
.payment-step {
background: linear-gradient(135deg, #f8f9ff 0%, #e8f2ff 100%);
background: #ff9248;
min-height: 100vh;
height: auto;
display: flex;
@@ -75,10 +88,10 @@ const retryPayment = () => {
border-radius: 24px;
backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow:
/* box-shadow:
0 20px 60px rgba(0, 0, 0, 0.08),
0 8px 32px rgba(0, 0, 0, 0.04),
inset 0 1px 0 rgba(255, 255, 255, 0.8);
inset 0 1px 0 rgba(255, 255, 255, 0.8); */
padding: 3rem 2rem !important;
}
@@ -139,6 +152,10 @@ const retryPayment = () => {
max-width: 300px;
}
.action-section {
margin-top: 2rem;
}
.action-btn {
font-weight: 600 !important;
text-transform: none !important;
+17 -18
View File
@@ -1,7 +1,6 @@
<!-- eslint-disable vue/multi-word-component-names -->
<template>
<div class="payment-step">
<div class="success-wrapper">
<div class="success-wrapper">
<div class="success-container">
<!-- Success Icon with Animation -->
<div class="success-icon-container mb-6">
@@ -12,14 +11,14 @@
class="success-icon"
/>
</div>
<div class="success-checkmark">
<!-- <div class="success-checkmark">
<div class="check-icon">
<span class="icon-line line-tip"></span>
<span class="icon-line line-long"></span>
<div class="icon-circle"></div>
<div class="icon-fix"></div>
</div>
</div>
</div> -->
</div>
<!-- Success Content -->
@@ -71,7 +70,6 @@
</div>
</div>
</div>
</div>
</template>
<script setup>
@@ -93,30 +91,31 @@ const formatCurrency = (amount) => {
background: linear-gradient(135deg, #f8f9ff 0%, #e8f2ff 100%);
min-height: 100vh;
height: auto;
padding: 2rem 0;
padding: 1rem;
display: flex;
margin: 80px;
align-items: center;
justify-content: center;
}
.success-wrapper {
width: 100%;
max-width: 600px;
margin: 0 auto;
padding: 0 1rem;
max-width: 800px;
margin: 0;
padding: 0rem;
}
.success-container {
background: rgba(255, 255, 255, 0.95);
background: rgb(255, 255, 255);
border-radius: 24px;
padding: 3rem 2rem;
padding: 0.5rem 0.5rem;
text-align: center;
backdrop-filter: blur(20px);
/* backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.08),
0 8px 32px rgba(0, 0, 0, 0.04),
inset 0 1px 0 rgba(255, 255, 255, 0.8);
inset 0 1px 0 rgba(255, 255, 255, 0.8); */
}
/* Success Icon Animation */
@@ -221,14 +220,14 @@ const formatCurrency = (amount) => {
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 1rem;
line-height: 1.2;
line-height: 1.5;
}
.success-message {
color: #666;
font-size: 1.2rem;
font-size: 1rem;
font-weight: 500;
line-height: 1.4;
line-height: 2;
}
.message-line {
@@ -238,13 +237,13 @@ const formatCurrency = (amount) => {
/* Payment Summary */
.payment-summary {
margin: 2rem 0;
margin: 1rem 0;
}
.summary-card {
background: rgba(76, 175, 80, 0.06);
border-radius: 16px;
padding: 1.5rem;
padding: 2rem;
border: 1px solid rgba(76, 175, 80, 0.2);
}
+185 -38
View File
@@ -1,7 +1,6 @@
<template>
<div class="payment-step">
<v-card-text class="pa-6">
<!-- Header Section -->
<v-card-text class="main-content pa-4">
<div class="header-section text-center mb-8">
<h2 class="payment-title">Pindai Kode QR untuk Pembayaran</h2>
<p class="payment-subtitle">
@@ -9,15 +8,19 @@
</p>
</div>
<!-- Main Content Section - QR & Details Side by Side -->
<div class="main-content-section mb-8">
<div class="content-grid">
<!-- QR Code Section -->
<div class="qr-section">
<div class="qr-container">
<div class="qris-logo-container mb-0">
<v-img
src="https://iconlogovector.com/uploads/images/2024/03/lg-65ffda68a47ee-QRIS.webp"
src="https://static.wikia.nocookie.net/logopedia/images/1/15/Rumah_Sakit_Umum_Daerah_Dr._Saiful_Anwar.png"
height="60"
class="RSSA-logo"
contain
/>
<v-img
src="https://ottocash.id/wp-content/uploads/2022/08/qris.png"
height="60"
class="qris-logo"
contain
@@ -44,11 +47,9 @@
</div>
</div>
<!-- Scanning Animation -->
<div class="scan-line" v-if="qrLoaded"></div>
</div>
<!-- QR Instructions -->
<div class="qr-instructions text-center mt-4">
<v-icon size="20" color="primary" class="mb-2"
>mdi-qrcode-scan</v-icon
@@ -57,7 +58,6 @@
</div>
</div>
<!-- Payment Details Section -->
<div class="details-section">
<div class="payment-details-card">
<div class="details-header">
@@ -111,11 +111,12 @@
>
Berlaku Sampai
</div>
<div class="detail-value expired">Tidak terbatas</div>
<div class="detail-value expired">
{{ expiryDisplayTime }}
</div>
</div>
</div>
<!-- Status in Details Card -->
<div class="payment-status mt-4">
<div class="status-row">
<div class="status-indicator-inline">
@@ -133,7 +134,6 @@
</div>
</div>
<!-- Action Buttons -->
<div class="action-buttons">
<v-btn
color="grey-lighten-1"
@@ -150,32 +150,106 @@
color="success"
variant="flat"
size="large"
class="action-btn simulate-btn"
@click="paymentStore.nextStep"
class="action-btn"
@click="simulateSuccess"
>
<v-icon class="mr-2">mdi-play-circle-outline</v-icon>
Simulasi Pembayaran
<v-icon class="mr-2">mdi-check-circle-outline</v-icon>
Simulasi Sukses
</v-btn>
<v-btn
color="error"
variant="flat"
size="large"
class="action-btn"
@click="simulateFailure"
>
<v-icon class="mr-2">mdi-close-circle-outline</v-icon>
Simulasi Gagal
</v-btn>
</div>
<!-- Help Text -->
<div class="help-text text-center mt-6">
<!-- <div class="help-text text-center mt-6">
<v-icon size="16" class="mr-1">mdi-information-outline</v-icon>
<span>Scan QR code menggunakan aplikasi pembayaran digital Anda</span>
</div>
</div> -->
</v-card-text>
</div>
</template>
<script setup>
import { usePaymentStore } from "~/stores/payment";
import QRCode from "qrcode";
import { ref, onMounted, watch } from "vue";
import { ref, onMounted, watch, onBeforeUnmount } from "vue";
const paymentStore = usePaymentStore();
const qrCodeImage = ref(null);
const qrLoaded = ref(false);
const EXPIRY_MINUTES = 1440;
const expiryDisplayTime = ref("Menghitung...");
let countdownInterval = null;
const calculateExpiryDate = (createdAt) => {
if (!createdAt) return null;
try {
const createdDate = new Date(createdAt);
if (isNaN(createdDate.getTime())) return null;
return new Date(createdDate.getTime() + EXPIRY_MINUTES * 60000);
} catch (e) {
console.error("Error calculating expiry time:", e);
return null;
}
};
const formatTimeLeft = (seconds) => {
if (seconds <= 0) {
clearInterval(countdownInterval);
return "KEDALUWARSA";
}
const h = String(Math.floor(seconds / 3600)).padStart(2, "0");
const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, "0");
const s = String(seconds % 60).padStart(2, "0");
return `${h}:${m}:${s}`;
};
// Memulai fungsi hitung mundur
const startCountdown = (expiryDate) => {
if (!expiryDate) {
expiryDisplayTime.value = "Waktu tidak valid";
return;
}
// Hentikan interval sebelumnya jika ada
if (countdownInterval) {
clearInterval(countdownInterval);
}
const updateCountdown = () => {
const now = new Date().getTime();
const timeRemainingMs = expiryDate.getTime() - now;
const timeRemainingSeconds = Math.max(
0,
Math.floor(timeRemainingMs / 1000)
);
expiryDisplayTime.value = formatTimeLeft(timeRemainingSeconds);
};
updateCountdown();
countdownInterval = setInterval(updateCountdown, 1000);
};
// Membersihkan interval saat komponen dihancurkan
onBeforeUnmount(() => {
if (countdownInterval) {
clearInterval(countdownInterval);
}
});
const formatCurrency = (amount) => {
return new Intl.NumberFormat("id-ID", {
style: "currency",
@@ -210,51 +284,122 @@ const generateQRCode = async () => {
}
};
const simulateSuccess = () => {
console.log("--- DEBUG: SIMULASI SUKSES ---");
const currentData = paymentStore.qrData;
// Simulasikan data status SUKSES (status "2")
const successData = {
data: [
{
...currentData,
status: "2",
transaction_id: `TRX-SIM-SUKSES-${Date.now()}`,
},
],
};
paymentStore.updatePayment(successData);
};
const simulateFailure = () => {
console.log("--- DEBUG: SIMULASI GAGAL ---");
const currentData = paymentStore.qrData;
// Simulasikan data status GAGAL (status "0")
const failureData = {
data: [
{
...currentData,
status: "0",
reason: "SIMULASI: Transaksi dibatalkan atau kedaluwarsa.",
},
],
};
// Update store Pinia. Watcher di index.vue akan memicu transisi ke Step 4.
paymentStore.updatePayment(failureData);
};
// ------------------------------------
onMounted(() => {
generateQRCode();
// Hitung tanggal kedaluwarsa awal dan mulai hitung mundur
const createdAt = paymentStore.qrData.created_at;
if (createdAt) {
const expiryDate = calculateExpiryDate(createdAt);
startCountdown(expiryDate);
}
});
watch(
() => paymentStore.qrData,
() => {
(newQrData) => {
generateQRCode();
}
// LOGIKA PERHITUNGAN WAKTU KEDALUWARSA
const createdAt = newQrData.created_at;
if (createdAt) {
const expiryDate = calculateExpiryDate(createdAt);
startCountdown(expiryDate); // Mulai hitung mundur setiap kali data QR berubah
console.log(`[QRISPayment] Waktu kedaluwarsa diperbarui.`);
} else {
expiryDisplayTime.value = "Data Waktu Tidak Tersedia";
}
},
{ deep: true }
);
</script>
<style scoped>
.payment-step {
background: #ff9248;
}
.main-content {
background: linear-gradient(135deg, #f8f9ff 0%, #e8f2ff 100%);
min-height: 100vh;
height: auto;
padding: 1rem 0;
/* min-height: 100vh; */
margin-top: 10px;
margin-bottom: 10px;
border-radius: 16px;
height: fit-content;
}
/* Header Section */
.header-section {
padding-top: 8px;
padding-top: 0px;
}
.qris-logo-container {
position: center;
/* display: inline-block; */
display: flex;
gap: 0rem;
align-items: center;
flex-wrap: wrap;
justify-content: center;
}
.qris-logo {
filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
transition: transform 0.3s ease;
align-items: baseline;
margin-right: 25px;
}
.RSSA-logo {
filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
transition: transform 0.3s ease;
align-items: end;
margin-right: -50px !important;
}
.qris-logo:hover {
transform: scale(1.05);
transform: scale(1);
}
.payment-title {
font-size: 1.5rem;
font-weight: 700;
color: #1a1a1a;
margin-top: 1rem;
margin-bottom: 0.5rem;
margin-top: 0;
margin-bottom: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
@@ -275,7 +420,7 @@ watch(
.content-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3rem;
gap: 0.5rem;
align-items: start;
max-width: 1000px;
margin: 0 auto;
@@ -394,6 +539,8 @@ watch(
/* QR Instructions */
.qr-instructions {
margin-top: 1rem;
display: flex;
gap: 8px;
}
.instruction-text {
@@ -407,7 +554,7 @@ watch(
.payment-details-card {
background: rgba(255, 255, 255, 0.95);
border-radius: 20px;
padding: 2rem;
padding: 1.5rem;
backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow:
@@ -420,8 +567,8 @@ watch(
.details-header {
display: flex;
align-items: center;
margin-bottom: 1.5rem;
padding-bottom: 1rem;
margin-bottom: 1rem;
padding-bottom: 0.5rem;
border-bottom: 2px solid rgba(0, 0, 0, 0.06);
}
@@ -434,7 +581,7 @@ watch(
.details-content {
display: flex;
flex-direction: column;
gap: 0.5rem;
gap: 0.4rem;
}
.detail-row {
+79
View File
@@ -0,0 +1,79 @@
import { ref, onUnmounted } from 'vue';
/**
* Komposable untuk mengelola koneksi WebSocket.
* @param {string} url - URL WebSocket lengkap.
*/
export function useWebSocket(url) {
const ws = ref(null);
const data = ref(null);
const isConnected = ref(false);
const error = ref(null);
let reconnectTimer = null;
const connect = () => {
if (ws.value && ws.value.readyState === WebSocket.OPEN) {
console.log('[WS] Already connected.');
return;
}
error.value = null;
console.log(`[WS] Attempting to connect to: ${url}`);
ws.value = new WebSocket(url);
ws.value.onopen = () => {
isConnected.value = true;
console.log('✅ [WS] Connection established.');
clearTimeout(reconnectTimer);
};
ws.value.onmessage = (event) => {
// LOGIC PENTING: Menerima data dan memicu watcher di index.vue
console.log('🔔 [WS] Message received. Parsing data...');
try {
const parsedData = JSON.parse(event.data);
data.value = parsedData;
} catch (e) {
error.value = new Error('Gagal memproses pesan WebSocket.');
console.error('❌ [WS] Data parsing error:', e);
data.value = null;
}
};
ws.value.onerror = (e) => {
console.error('❌ [WS] WebSocket error:', e);
error.value = e;
};
ws.value.onclose = (event) => {
isConnected.value = false;
if (event.code !== 1000) {
console.log('🛑 [WS] Connection closed unexpectedly. Reconnecting in 5s...');
reconnectTimer = setTimeout(connect, 5000); // Reconnect setelah 5 detik
} else {
console.log('🛑 [WS] Connection closed normally.');
}
};
};
const disconnect = () => {
if (ws.value) {
ws.value.close(1000, "Component unmounted");
ws.value = null;
}
clearTimeout(reconnectTimer);
};
onUnmounted(() => {
disconnect();
});
return {
wsData: data,
isConnected,
error,
connect,
disconnect,
};
}
-43
View File
@@ -1,43 +0,0 @@
import { io } from 'socket.io-client';
import { usePaymentStore } from '~/stores/payment1';
// Fungsi untuk mendapatkan IP Address lokal (ini butuh bantuan backend/API eksternal)
async function getLocalIpAddress() {
// Anda bisa menggunakan API eksternal atau endpoint di backend Anda sendiri.
// Contoh menggunakan API eksternal:
// const response = await fetch('https://api.ipify.org?format=json');
// const data = await response.json();
// return data.ip;
// ATAU, jika IP address diatur secara statis pada tablet:
return '192.168.1.101'; // Ganti dengan IP Address loket yang sesungguhnya
}
export async function setupSocket() {
const paymentStore = usePaymentStore();
const socket = io('https://your-backend-api.com'); // Ganti dengan URL backend Anda
const localIp = await getLocalIpAddress();
socket.on('connect', () => {
console.log('Connected to backend WebSocket');
// Mengirim IP Address tablet ke backend untuk identifikasi loket.
socket.emit('register-kiosk', { ipAddress: localIp });
});
socket.on('payment-data-ready', (data) => {
console.log('Payment data received:', data);
// Panggil action Pinia untuk memperbarui state dan pindah step
paymentStore.updatePayment(data);
});
socket.on('disconnect', () => {
console.log('Disconnected from backend');
});
// Tambahkan error handling
socket.on('error', (error) => {
console.error('Socket error:', error);
});
}
+185
View File
@@ -0,0 +1,185 @@
// ~/config/websocket.js
// Helper function untuk mendeteksi environment
const detectEnvironment = () => {
// Jika ada environment variable NODE_ENV
if (process.env.NODE_ENV) {
return process.env.NODE_ENV;
}
// Deteksi berdasarkan hostname/URL jika di browser
if (typeof window !== 'undefined') {
const hostname = window.location.hostname;
// Local development
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return 'development';
}
// Server di jaringan lokal (IP private)
if (hostname.match(/^192\.168\./) ||
hostname.match(/^10\./) ||
hostname.match(/^172\.(1[6-9]|2[0-9]|3[0-1])\./)) {
return 'staging';
}
// Production (domain atau IP public)
return 'production';
}
// Default fallback
return 'development';
};
export const websocketConfig = {
// Local Development (localhost)
development: {
url: 'ws://localhost:8084/api/v1/ws',
// Alternative untuk development
// url: 'ws://localhost:8084/api/v1/ws',
queryParams: {
user_id: 'QRIS',
room: 'BANKJATIM'
},
options: {
transports: ['websocket', 'polling'],
timeout: 15000,
reconnection: true,
reconnectionAttempts: 3,
reconnectionDelay: 1000,
reconnectionDelayMax: 3000,
}
},
// Staging/Network Server (IP jaringan)
staging: {
url: 'ws://10.10.150.68:8084/api/v1/ws',
queryParams: {
user_id: 'QRIS',
room: 'BANKJATIM'
},
options: {
transports: ['websocket', 'polling'],
timeout: 20000,
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
}
},
// Production (domain atau IP public)
production: {
url: 'wss://your-production-server.com/api/v1/ws',
queryParams: {
user_id: 'QRIS',
room: 'BANKJATIM'
},
options: {
transports: ['websocket', 'polling'],
timeout: 30000,
reconnection: true,
reconnectionAttempts: 10,
reconnectionDelay: 2000,
reconnectionDelayMax: 10000,
// Additional production settings
secure: true,
rejectUnauthorized: true,
}
},
// Testing Environment
test: {
url: 'ws://test-server:8084/api/v1/ws',
queryParams: {
user_id: 'QRIS_TEST',
room: 'BANKJATIM_TEST'
},
options: {
transports: ['websocket'],
timeout: 10000,
reconnection: false,
}
}
};
// Helper function untuk build URL dengan query parameters
export const buildWebSocketUrl = (baseUrl, queryParams = {}) => {
const url = new URL(baseUrl);
Object.entries(queryParams).forEach(([key, value]) => {
url.searchParams.append(key, value);
});
return url.toString();
};
// Helper function untuk mendapatkan config berdasarkan environment
export const getWebSocketConfig = () => {
const env = detectEnvironment();
const config = websocketConfig[env] || websocketConfig.development;
// Build URL dengan query parameters
const fullUrl = buildWebSocketUrl(config.url, config.queryParams);
console.log(`🌍 Detected environment: ${env}`);
console.log(`🔗 WebSocket URL: ${fullUrl}`);
return {
...config,
fullUrl,
environment: env
};
};
// Helper untuk override manual dengan custom query params
export const getCustomWebSocketConfig = (customUrl, customQueryParams = {}, customOptions = {}) => {
const baseConfig = getWebSocketConfig();
const mergedQueryParams = {
...baseConfig.queryParams,
...customQueryParams
};
const fullUrl = buildWebSocketUrl(customUrl, mergedQueryParams);
return {
...baseConfig,
url: customUrl,
queryParams: mergedQueryParams,
fullUrl,
options: {
...baseConfig.options,
...customOptions
},
environment: 'custom'
};
};
// Environment detection helpers
export const isProduction = () => detectEnvironment() === 'production';
export const isDevelopment = () => detectEnvironment() === 'development';
export const isStaging = () => detectEnvironment() === 'staging';
// Advanced configuration berdasarkan kondisi khusus
export const getAdvancedConfig = () => {
const baseConfig = getWebSocketConfig();
// Tambah konfigurasi khusus berdasarkan browser atau device
if (typeof window !== 'undefined') {
// Mobile device adjustments
if (navigator.userAgent.match(/Mobile|Android|iPhone|iPad/)) {
baseConfig.options.timeout = Math.min(baseConfig.options.timeout, 15000);
baseConfig.options.reconnectionDelay = 2000;
}
// Connection type adjustments
if ('connection' in navigator) {
const connection = navigator.connection;
if (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g') {
baseConfig.options.timeout = 30000;
baseConfig.options.reconnectionDelay = 3000;
}
}
}
return baseConfig;
};
+7 -3
View File
@@ -3,7 +3,7 @@ import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
devtools: { enabled: true },
ssr:false,
modules: [
'@nuxt/content',
'@nuxt/eslint',
@@ -20,14 +20,13 @@ export default defineNuxtConfig({
config.plugins.push(vuetify({ autoImport: true }))
})
},
//...
],
css: [
'vuetify/lib/styles/main.sass',
'@mdi/font/css/materialdesignicons.min.css',
],
build: {
transpile: ['vuetify'],
transpile: ['vuetify', 'socket.io-client'],
},
devServer: {
host: "10.10.150.114",
@@ -38,5 +37,10 @@ export default defineNuxtConfig({
viewport: 'width=device-width,initial-scale=1',
charset: 'utf-8'
}
},
nitro: {
experimental: {
wasm: true
}
}
})
+1
View File
@@ -20,6 +20,7 @@
"nuxt": "^3.19.0",
"pinia": "^3.0.3",
"qrcode": "^1.5.4",
"socket.io-client": "^4.8.1",
"typescript": "^5.9.2",
"vue": "^3.5.20",
"vue-router": "^4.5.1",
+1
View File
@@ -23,6 +23,7 @@
"nuxt": "^3.19.0",
"pinia": "^3.0.3",
"qrcode": "^1.5.4",
"socket.io-client": "^4.8.1",
"typescript": "^5.9.2",
"vue": "^3.5.20",
"vue-router": "^4.5.1",
+1 -1
View File
@@ -30,7 +30,7 @@
</v-card-text>
<v-card-actions class="justify-center">
<v-btn
color="primary"
color="white"
@click="saveIpAddress"
:disabled="!isValidIp"
variant="flat"
+135 -138
View File
@@ -8,13 +8,25 @@
elevation="0"
:class="{
'contact-fullscreen': paymentStore.currentStep === 1,
'payment-centered': paymentStore.currentStep !== 1,
'payment-centered': paymentStore.currentStep === 2,
'status-centered':
paymentStore.currentStep === 3 ||
paymentStore.currentStep === 4,
}"
>
<component :is="activeComponent" v-if="hasIpAddress" />
<div v-else class="text-center pa-10">
<v-progress-circular indeterminate color="primary"></v-progress-circular>
<p class="mt-4">Memeriksa konfigurasi...</p>
<v-progress-circular
indeterminate
color="primary"
></v-progress-circular>
<p class="mt-4">Memeriksa konfigurasi dan koneksi data...</p>
<p v-if="hasIpAddress && wsIsConnected" class="mt-2 text-success">
Koneksi WS: **Terhubung** (Siap menerima data 30s)
</p>
<p v-else-if="hasIpAddress" class="mt-2 text-warning">
Koneksi WS: Menunggu/Terputus...
</p>
</div>
</v-card>
</v-col>
@@ -22,22 +34,33 @@
</v-container>
</div>
</template>
<script setup>
import { usePaymentStore } from '~/stores/payment';
import Home from '~/components/Home.vue';
import QRISPayment from '~/components/QRISPayment.vue';
import Success from '~/components/PembayaranSukses.vue';
import Gagal from '~/components/PembayaranGagal.vue';
import { onMounted, onUnmounted, ref, computed, watch } from 'vue';
import { usePaymentStore } from "~/stores/payment";
import Home from "~/components/Home.vue";
import QRISPayment from "~/components/QRISPayment.vue";
import Success from "~/components/PembayaranSukses.vue";
import Gagal from "~/components/PembayaranGagal.vue";
import { onMounted, onUnmounted, ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { useWebSocket } from "~/composables/useWebSocket";
const paymentStore = usePaymentStore();
const router = useRouter();
const localIpAddress = ref(null);
const pollingInterval = ref(null);
// **WEB SOCKET CONFIGURATION**
const WS_URL_BASE = "ws://10.10.150.45:8084/api/v1/ws";
const WS_QUERY = "user_id=QRIS&room=BANKJATIM";
const fullWsUrl = `${WS_URL_BASE}?${WS_QUERY}`;
const {
wsData,
isConnected: wsIsConnected,
connect: wsConnect,
disconnect: wsDisconnect,
} = useWebSocket(fullWsUrl);
const hasIpAddress = computed(() => !!localIpAddress.value);
const apiURL = 'http://10.10.150.67:8084/api/v1/qris/allstatus';
const paymentSteps = {
1: Home,
@@ -50,147 +73,92 @@ const activeComponent = computed(() => {
return paymentSteps[paymentStore.currentStep] || Home;
});
// Watch untuk debugging perubahan step
watch(() => paymentStore.currentStep, (newStep, oldStep) => {
console.log(`Step berubah dari ${oldStep} ke ${newStep}`);
}, { immediate: true });
watch(
() => paymentStore.currentStep,
(newStep, oldStep) => {
console.log(`Step berubah dari ${oldStep} ke ${newStep}`);
},
{ immediate: true }
);
const startPolling = () => {
if (pollingInterval.value) {
clearInterval(pollingInterval.value);
console.log('🛑 Stopping previous polling');
}
watch(
wsData,
(newStatus) => {
const payloadData = newStatus?.data?.data; // Ambil array data transaksi
pollingInterval.value = setInterval(async () => {
try {
console.log(`🔄 POLLING - Step: ${paymentStore.currentStep}`);
const response = await $fetch(apiURL);
if (response?.data?.length > 0) {
if (paymentStore.currentStep === 1) {
// Step 1: Find data by IP address (original logic)
console.log('🔍 Step 1: Looking for IP:', localIpAddress.value);
const relevantData = response.data.find(item => item.ip === localIpAddress.value);
if (relevantData) {
console.log('✅ Data found for IP:', relevantData);
paymentStore.updatePayment({ data: [relevantData] });
paymentStore.currentStep = 2;
} else {
console.log('⏳ No data found for IP:', localIpAddress.value);
}
}
else if (paymentStore.currentStep === 2) {
// Step 2: Monitor payment status for THE SAME PATIENT
console.log('🔍 Step 2: Monitoring payment status...');
// Get patient identifiers from store (data yang sudah di-load di step 1)
const currentPatientBill = paymentStore.qrData.display_nobill;
const currentPatientName = paymentStore.qrData.display_name;
console.log('👤 Current patient:', {
name: currentPatientName,
bill: currentPatientBill
});
if (!currentPatientBill || !currentPatientName) {
console.warn('⚠️ Patient data incomplete in store');
return;
}
// Find ALL records for this same patient (same name + bill)
const samePatientRecords = response.data.filter(item => {
const sameBill = item.display_nobill === currentPatientBill;
const sameName = item.display_name === currentPatientName;
console.log(`🔄 Checking record: ${item.display_name} (${item.display_nobill}) status=${item.status}`);
console.log(` → Same patient? ${sameBill && sameName}`);
return sameBill && sameName;
});
console.log(`📊 Found ${samePatientRecords.length} records for same patient:`,
samePatientRecords.map(r => `status: ${r.status}`));
const successRecord = samePatientRecords.find(record => record.status === "2");
const failRecord = samePatientRecords.find(record => record.status === "0");
if (successRecord) {
console.log('🎉 SUCCESS STATUS FOUND!', successRecord);
paymentStore.updatePayment({ data: [successRecord] });
paymentStore.currentStep = 3;
clearInterval(pollingInterval.value);
setTimeout(() => {
console.log('🏠 Auto return to home');
paymentStore.reset();
startPolling();
}, 20000);
} else if (failRecord) {
console.log('❌ FAIL STATUS FOUND!', failRecord);
paymentStore.updatePayment({ data: [failRecord] });
paymentStore.currentStep = 4;
clearInterval(pollingInterval.value);
setTimeout(() => {
console.log('🏠 Auto return to home');
paymentStore.reset();
startPolling();
}, 20000);
} else {
console.log('⏳ Still waiting for final status...');
console.log('Current statuses for this patient:',
samePatientRecords.map(r => r.status));
}
}
} else {
console.log('📭 No data in API response');
}
} catch (error) {
console.error("❌ Polling error:", error);
if (!newStatus || !payloadData || payloadData.length === 0) {
console.log(
"📭 WS: No valid payload data (newStatus.data.data) in message. Skipping state change."
);
return;
}
}, 20000);
console.log(`🚀 Polling started - IP-based patient detection`);
};
console.log(
`[WS] Menerima update data di Step ${paymentStore.currentStep}. Total records: ${payloadData.length}`
);
const allRecords = payloadData;
if (paymentStore.currentStep === 1) {
console.log("🔍 Step 1 (WS): Looking for IP:", localIpAddress.value);
const relevantData = allRecords.find(
(item) => item.ip === localIpAddress.value && item.status === "1"
);
if (relevantData) {
console.log(
"✅ WS Data found for IP (New Transaction). Moving to Step 2."
);
paymentStore.updatePayment({ data: [relevantData] });
paymentStore.setStep(2);
} else {
console.log(
`⏳ No relevant data found for IP ${localIpAddress.value} in this broadcast.`
);
}
} else if (paymentStore.currentStep === 2) {
const relevantData = allRecords.find(
(item) =>
item.ip === localIpAddress.value &&
item.display_nobill === paymentStore.qrData.display_nobill
);
if (relevantData) {
console.log(
"🔄 WS Update received for current patient in Step 2. Updating store..."
);
paymentStore.updatePayment({ data: [relevantData] });
}
}
},
{ deep: true }
);
const checkAndRedirect = () => {
const savedIp = localStorage.getItem('loketIp');
const savedIp = localStorage.getItem("loketIp");
if (!savedIp) {
console.warn('IP Address belum diatur. Mengarahkan ke halaman setup.');
router.push('/setupip');
router.push("/setupip");
} else {
localIpAddress.value = savedIp;
console.log('IP Address ditemukan:', savedIp);
startPolling();
wsConnect();
}
};
onMounted(() => {
console.log('Component mounted, step saat ini:', paymentStore.currentStep);
checkAndRedirect();
});
onUnmounted(() => {
if (pollingInterval.value) {
clearInterval(pollingInterval.value);
console.log('Polling dihentikan saat unmount.');
}
wsDisconnect();
});
</script>
>
<style scoped>
.medical-payment-app {
background: linear-gradient(135deg, #ff9248 20%, #ff9248 100%);
background: #ff9248;
min-height: 100vh;
height: auto;
height: fit-content;
}
.full-height {
@@ -206,18 +174,35 @@ onUnmounted(() => {
}
.payment-centered {
background: #ff9248 !important;
max-width: 1200px !important;
width: 100% !important;
width: fit-content !important;
margin: 1rem auto !important;
border-radius: 16px !important;
height: auto !important;
height: fit-content !important;
min-height: calc(100vh - 2rem);
}
.payment-card {
background: rgb(224, 224, 224);
background: #ff9248;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
height: auto !important;
height: fit-content !important;
min-height: inherit;
}
.status-centered {
max-width: 1200px !important;
width: 100% !important;
margin: 1rem auto !important;
border-radius: 16px !important;
height: fit-content !important;
min-height: calc(100vh - 2rem);
}
.status-card {
background: #ff9248;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
height: fit-content !important;
min-height: inherit;
}
@@ -227,6 +212,11 @@ onUnmounted(() => {
max-width: 500px !important;
margin: 1rem !important;
}
.status-centered {
max-width: 800px !important;
margin: 1rem !important;
}
}
@media (orientation: landscape) and (min-width: 768px) {
@@ -235,16 +225,23 @@ onUnmounted(() => {
margin: 0.5rem auto !important;
min-height: calc(100vh - 1rem);
}
.status-centered {
max-width: 700px !important;
margin: 0.5rem auto !important;
min-height: calc(100vh - 1rem);
}
}
@media (orientation: landscape) and (max-height: 600px) {
.medical-payment-app {
min-height: 600px;
}
.contact-fullscreen,
.payment-centered {
.payment-centered,
.status-centered {
min-height: 600px;
}
}
</style>
</style>
+66 -22
View File
@@ -1,21 +1,26 @@
// src/stores/payment.js
import { defineStore } from 'pinia';
// Variabel di luar store untuk menyimpan timer, agar persistensi di luar state Pinia
let autoResetTimer = null;
export const usePaymentStore = defineStore('payment', {
state: () => ({
currentStep: 1,
currentStep: 1, // 1: Menunggu Data, 2: Tampilkan QRIS, 3: Sukses, 4: Gagal
patientInfo: {
name: '',
amount: '',
expiry: '',
expiry: '', // Dibiarkan kosong, waktu kedaluwarsa dihitung dari qrData.created_at
},
qrData: {
qrvalue: null,
display_nobill: null,
display_name: null,
display_amount: null,
status: null, // Tambahkan status untuk tracking
ip: null, // Tambahkan IP untuk reference
status: null, // Status pembayaran: "1" (Pending), "2" (Sukses), "0" (Gagal/Expired)
ip: null,
created_at: null, // Tambahkan ini agar properti ada secara eksplisit
// ... properti lain dari API akan ditambahkan melalui spread operator
},
}),
@@ -23,12 +28,12 @@ export const usePaymentStore = defineStore('payment', {
hasQrData: (state) => state.qrData && state.qrData.qrvalue,
safeQrValue: (state) => state.qrData?.qrvalue || 'https://www.google.com',
// Getter untuk cek apakah data siap untuk polling status
// Getter untuk cek apakah data siap
isReadyForStatusCheck: (state) => {
return state.qrData.display_nobill && state.qrData.display_name;
},
// Getter untuk informasi debug
// Getter untuk debug
debugInfo: (state) => ({
step: state.currentStep,
hasIdentifiers: !!(state.qrData.display_nobill && state.qrData.display_name),
@@ -46,12 +51,29 @@ export const usePaymentStore = defineStore('payment', {
},
setStep(step) {
console.log(`Setting step from ${this.currentStep} to ${step}`);
console.log(`[STORE] Setting step from ${this.currentStep} to ${step}`);
this.currentStep = step;
},
/**
* @description Memulai timer untuk reset state kembali ke Step 1 (Home) setelah 20 detik
*/
startAutoReset() {
if (autoResetTimer) {
clearTimeout(autoResetTimer);
}
console.log('🏠 [STORE] Starting auto return timer (20s) for reset.');
autoResetTimer = setTimeout(() => {
console.log('🏠 [STORE] Auto return to home triggered');
this.reset();
}, 20000);
},
reset() {
console.log('Resetting payment store');
console.log('--- [STORE] Resetting payment store ---');
this.currentStep = 1;
this.patientInfo = {
name: '',
@@ -65,25 +87,26 @@ export const usePaymentStore = defineStore('payment', {
display_amount: null,
status: null,
ip: null,
created_at: null,
};
if (autoResetTimer) {
clearTimeout(autoResetTimer);
autoResetTimer = null;
}
},
updatePayment(apiResponse) {
console.log("=== UPDATE PAYMENT ===");
console.log("API Response:", apiResponse);
console.log("=== [STORE] UPDATE PAYMENT ===");
// Validasi response
if (!apiResponse?.data || !Array.isArray(apiResponse.data) || apiResponse.data.length === 0) {
console.error("Invalid API response structure");
console.error("Invalid API response structure or empty data array");
return;
}
const apiData = apiResponse.data[0];
console.log("API Data:", apiData);
// Simpan data lama untuk comparison
const oldQrData = { ...this.qrData };
const oldStatus = this.qrData.status; // Simpan status lama
// Update qrData dengan semua properti dari API
this.qrData = {
qrvalue: apiData.qrvalue || apiData.qr_code || this.qrData.qrvalue,
@@ -92,22 +115,43 @@ export const usePaymentStore = defineStore('payment', {
display_amount: apiData.display_amount || apiData.nominal || this.qrData.display_amount,
status: apiData.status || this.qrData.status,
ip: apiData.ip || this.qrData.ip,
// Spread untuk properti lain yang mungkin ada
created_at: apiData.created_at || this.qrData.created_at, // Ambil 'created_at'
// Spread untuk properti lain yang mungkin ada (misal: transaction_id, reason)
...apiData
};
// Update patientInfo
this.patientInfo = {
name: apiData.display_name || this.patientInfo.name || 'Unknown',
amount: apiData.display_amount || apiData.nominal || this.patientInfo.amount || '0',
name: this.qrData.display_name || this.patientInfo.name || 'Unknown',
amount: this.qrData.display_amount || this.patientInfo.amount || '0',
expiry: this.patientInfo.expiry,
};
// Log changes
if (oldQrData.status !== this.qrData.status) {
console.log(`Status changed: ${oldQrData.status} -> ${this.qrData.status}`);
// --- LOGIKA TRANSISI STATUS OTOMATIS (SUCCESS/FAIL) ---
const newStatus = this.qrData.status;
// Log perubahan status (jika ada)
if (oldStatus !== newStatus) {
console.log(`[STORE] Status changed: ${oldStatus} -> ${newStatus}`);
}
// Proses transisi hanya jika kita berada di Step 2 (Menunggu Pembayaran)
// DAN status yang diterima berbeda dari status sebelumnya
if (this.currentStep === 2 && oldStatus !== newStatus) {
if (newStatus === "2") {
// Status Sukses
console.log('🎉 [STORE] Status 2 (SUKSES) diterima. Pindah ke Step 3.');
this.currentStep = 3;
this.startAutoReset();
} else if (newStatus === "0") {
// Status Gagal
console.log('❌ [STORE] Status 0 (GAGAL) diterima. Pindah ke Step 4.');
this.currentStep = 4;
this.startAutoReset();
}
}
// ------------------------------------------------------
console.log("Updated qrData:", this.qrData);
console.log("Updated patientInfo:", this.patientInfo);
console.log("===================");