Files
web-antrean/stores/queueStore.js
T
2026-02-10 12:18:02 +07:00

2604 lines
99 KiB
JavaScript

// stores/queueStore.js
import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { useClinicStore } from './clinicStore';
import { usePenunjangStore } from './penunjangStore';
import { useLoketStore } from './loketStore';
import { useWebSocket } from '@/composables/useWebSocket';
export const useQueueStore = defineStore('queue', () => {
const clinicStore = useClinicStore();
const penunjangStore = usePenunjangStore();
const loketStore = useLoketStore();
// ============================================
// API INTEGRATION FOR LOKET PATIENTS
// ============================================
// State untuk API patient data per loket
const apiPatientsPerLoket = ref({});
const isLoadingPatients = ref(false);
const apiPatientsError = ref(null);
// Throttle mechanism: track last fetch time per loket
const lastFetchTime = ref({});
// Synchronization Guard: track last update time to break loops across tabs
const lastUpdated = ref(Date.now());
// synchronization guard (moved lower)
// ============================================
// WEBSOCKET INTEGRATION (CENTRALIZED)
// ============================================
const wsInstance = ref(null);
const isWsConnected = ref(false);
const wsClientId = ref(`client-${Math.random().toString(36).substring(7)}`);
/**
* Initialize Global WebSocket
*/
const initWebSocket = (customClientId = null) => {
if (wsInstance.value && isWsConnected.value) {
console.log('🔌 [queueStore] WebSocket already connected.');
return;
}
if (customClientId) {
wsClientId.value = customClientId;
}
const config = useRuntimeConfig();
const wsBaseUrl = config.public?.wsBaseUrl || "ws://10.10.150.100:8084/api/v1/ws";
console.log(`🔌 [queueStore] Connecting to WebSocket: ${wsBaseUrl} as ${wsClientId.value}`);
wsInstance.value = useWebSocket({
url: wsBaseUrl,
clientId: wsClientId.value,
onOpen: () => {
console.log('✅ [queueStore] WebSocket connected');
isWsConnected.value = true;
},
onClose: () => {
console.log('❌ [queueStore] WebSocket disconnected');
isWsConnected.value = false;
},
onError: (err) => {
console.error('⚠️ [queueStore] WebSocket error:', err);
isWsConnected.value = false;
},
onMessage: (data) => {
console.log('📨 [queueStore] Global WS Message:', data);
// TRIGGER STRATEGIC REFRESHES
// 1. Refetch patients for all active lokets in the store
Object.keys(apiPatientsPerLoket.value).forEach(loketId => {
fetchPatientsForLoket(loketId);
});
// 2. Refetch clinics to update quotas/availability
clinicStore.fetchRegulerClinics();
// 3. Ensure base data is synced
ensureInitialData();
}
});
wsInstance.value.connect();
};
/**
* Disconnect Global WebSocket
*/
const disconnectWebSocket = () => {
if (wsInstance.value) {
wsInstance.value.disconnect();
wsInstance.value = null;
isWsConnected.value = false;
}
};
/**
* Sync patient status to apiPatientsPerLoket for reactivity
*/
const syncApiPatientStatus = (patient, newStatus) => {
if (!patient) return;
// Allow syncing if strictly 'api' OR if we can find a matching ID in the API store
// This handles cases where we have an 'onsite' patient locally that corresponds to an API patient
const loketId = patient.loketId;
if (loketId && apiPatientsPerLoket.value[loketId]) {
// Try to find patient in the API list
const index = apiPatientsPerLoket.value[loketId].findIndex(p => {
if (patient.registrationType === 'api' && p.no === patient.no) return true;
// Fallback matching for 'onsite' patients
if (patient.idtiket && p.idtiket && String(patient.idtiket) === String(p.idtiket)) return true;
if (patient.barcode && p.barcode && String(patient.barcode) === String(p.barcode)) return true;
return false;
});
if (index !== -1) {
const updated = [...apiPatientsPerLoket.value[loketId]];
updated[index] = { ...updated[index], status: newStatus };
apiPatientsPerLoket.value[loketId] = updated;
}
}
};
/**
* Reference mapping for patient status from API idvisit
* idvisit 1, 2 = menunggu (CT ANJUNGAN, RT ANJUNGAN)
* idvisit 3, 4 = anjungan (PG ANJUNGAN, RT CHECK-IN)
* idvisit 5, 6 = di-loket (PS CHECK-IN, TP LOKET)
*/
const PATIENT_STATUS_MAP = {
1: 'menunggu',
2: 'menunggu',
3: 'anjungan',
4: 'anjungan',
5: 'di-loket',
6: 'di-loket',
"1": 'menunggu',
"2": 'menunggu',
"3": 'anjungan',
"4": 'anjungan',
"5": 'di-loket',
"6": 'di-loket'
};
/**
* Map status from idvisit API
*/
const mapStatusFromIdVisit = (idvisit) => {
return PATIENT_STATUS_MAP[idvisit] || 'menunggu';
};
/**
* Map status dari deskripsi API ke status internal
* menunggu (id 1, 2): "Cetak Tiket Antrian" atau "Ruang Tunggu Anjungan"
* anjungan (id 3, 4): "Panggilan loket ke Anjungan" atau "Tunggu Pasien Check-In"
* di-loket (id 5, 6): "Pasien Sudah Check-In" atau "Tunggu Panggilan Loket"
*/
const mapStatusFromDeskripsi = (deskripsi) => {
if (!deskripsi) return 'menunggu';
const desc = deskripsi.toString().trim().toUpperCase();
// di-loket (id 5, 6): PS CHECK-IN (Pasien Sudah Check-In), RT PENDAFTARAN (Tunggu Panggilan Loket)
if (desc.includes('PASIEN SUDAH CHECK-IN') || desc.includes('TUNGGU PANGGILAN LOKET') || desc.includes('PS CHECK-IN') || desc.includes('RT PENDAFTARAN')) {
return 'di-loket';
}
// anjungan (id 3, 4): PG ANJUNGAN (Panggilan loket ke Anjungan), RT CHECK-IN (Tunggu Pasien Check-In)
if (desc.includes('PANGGILAN LOKET KE ANJUNGAN') || desc.includes('TUNGGU PASIEN CHECK-IN') || desc.includes('PG ANJUNGAN') || desc.includes('RT CHECK-IN')) {
return 'anjungan';
}
// menunggu (id 1, 2): CT ANJUNGAN (Cetak Tiket Antrian), RT ANJUNGAN (Ruang Tunggu Anjungan)
if (desc.includes('CETAK TIKET') || desc.includes('RUANG TUNGGU ANJUNGAN') || desc.includes('CT ANJUNGAN') || desc.includes('RT ANJUNGAN')) {
return 'menunggu';
}
// Default: menunggu
return 'menunggu';
};
/**
* Map patient data dari API format ke store format
*/
const mapApiPatientToStoreFormat = (apiPatient, index) => {
// Use idtiket as unique patient number to avoid conflicts with seed data
// Seed data uses sequential numbers 1-20, so we use idtiket + 10000 offset
const uniqueNo = apiPatient.idtiket ? parseInt(apiPatient.idtiket) + 10000 : 10000 + index;
// Handle nested positions to find the best status
let status = 'menunggu';
let posisiStr = apiPatient.posisi || '';
let idvisit = apiPatient.idvisit;
if (apiPatient.posisi && Array.isArray(apiPatient.posisi) && apiPatient.posisi.length > 0) {
// Find the "best" status among all positions
// Priority: di-loket > anjungan > menunggu
const statusPriority = { 'di-loket': 3, 'anjungan': 2, 'menunggu': 1 };
let bestPriority = 0;
apiPatient.posisi.forEach(pos => {
const pStatus = pos.idvisit
? mapStatusFromIdVisit(pos.idvisit)
: mapStatusFromDeskripsi(pos.deskripsi);
const pPrio = statusPriority[pStatus] || 0;
if (pPrio > bestPriority) {
bestPriority = pPrio;
status = pStatus;
posisiStr = pos.posisi || pos.deskripsi || '';
idvisit = pos.idvisit || idvisit;
}
});
} else {
// Standard top-level status
status = apiPatient.idvisit
? mapStatusFromIdVisit(apiPatient.idvisit)
: mapStatusFromDeskripsi(apiPatient.deskripsi);
}
const mapped = {
no: uniqueNo,
jamPanggil: apiPatient.waktu || '',
barcode: apiPatient.barcode || '',
noAntrian: `${apiPatient.ticket || ''} | ${posisiStr}`,
shift: apiPatient.shift ? `Shift ${apiPatient.shift}` : '',
klinik: apiPatient.klinik || '',
kodeKlinik: apiPatient.klinik || '', // Will be mapped later
fastTrack: "TIDAK",
pembayaran: apiPatient.pembayaran || '',
status: status,
processStage: 'loket',
createdAt: apiPatient.tanggal || new Date().toISOString(),
registrationType: 'api',
visitType: 'Onsite',
visitDate: apiPatient.tanggal ? apiPatient.tanggal.split('T')[0] : new Date().toISOString().substring(0, 10),
namaDokter: null,
noRM: null,
penanggungJawab: null,
alasanFastTrack: null,
idvisit: idvisit,
idtiket: apiPatient.idtiket,
ticket: apiPatient.ticket,
posisi: apiPatient.posisi,
deskripsi: apiPatient.deskripsi,
};
// Map klinik name to code using clinicStore
const clinic = clinicStore.clinics.find(c =>
c.name && apiPatient.klinik &&
(c.name.toUpperCase().includes(apiPatient.klinik.toUpperCase()) ||
apiPatient.klinik.toUpperCase().includes(c.name.toUpperCase()))
);
if (clinic) {
mapped.kodeKlinik = clinic.kode;
} else {
// Fallback: Use raw clinic ID if it looks like a code (e.g. numeric ID from API)
mapped.kodeKlinik = apiPatient.idklinik || apiPatient.klinik || '';
}
return mapped;
};
/**
* Fetch patient data untuk loket tertentu dari API
*/
const fetchPatientsForLoket = async (loketId) => {
if (!loketId) {
console.error('loketId required for fetchPatientsForLoket');
return { success: false, message: 'ID Loket diperlukan' };
}
isLoadingPatients.value = true;
apiPatientsError.value = null;
// THROTTLE: Check if we recently fetched (within last 5 seconds)
const now = Date.now();
const lastFetch = lastFetchTime.value[loketId] || 0;
const timeSinceLastFetch = now - lastFetch;
if (timeSinceLastFetch < 5000 && apiPatientsPerLoket.value[loketId]) {
console.log(`⏭️ [queueStore] Skipping fetch for loket ${loketId} (last fetched ${Math.round(timeSinceLastFetch/1000)}s ago)`);
isLoadingPatients.value = false;
return {
success: true,
message: 'Using cached data',
data: apiPatientsPerLoket.value[loketId]
};
}
// Update last fetch time
lastFetchTime.value[loketId] = now;
// Check for daily reset before fetching
checkAndResetDaily();
try {
console.log(`🔄 [queueStore] Fetching patients for loket ${loketId}...`);
const response = await fetch(`http://10.10.150.131:8089/api/v1/loket/${loketId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const rawData = await response.json();
// Check response structure
if (rawData.metadata && rawData.metadata.code !== 200) {
throw new Error(rawData.message || 'API returned error status');
}
const patientsRaw = rawData.data || [];
// Map API data to store format
const mappedPatients = patientsRaw.map((apiPatient, index) =>
mapApiPatientToStoreFormat(apiPatient, index)
).filter(p => isTodayPatient(p));
// Deduplicate patients by idtiket
// API returns multiple entries if patient is at multiple positions
const deduplicatedMap = new Map();
mappedPatients.forEach(p => {
const id = p.idtiket || p.barcode || p.no;
const existing = deduplicatedMap.get(id);
if (!existing) {
deduplicatedMap.set(id, p);
} else {
// Priority: di-loket > anjungan > menunggu
const statusPriority = { 'di-loket': 3, 'anjungan': 2, 'menunggu': 1 };
const pPrio = statusPriority[p.status] || 0;
const ePrio = statusPriority[existing.status] || 0;
if (pPrio > ePrio) {
deduplicatedMap.set(id, p);
}
}
});
const finalPatients = Array.from(deduplicatedMap.values());
// Store in API-specific state
apiPatientsPerLoket.value[loketId] = finalPatients;
// IMPORTANT: Also merge into allPatients so callMultiplePatients can find them
// Prepare list of new API patients with loketId assigned
const patientsWithLoketId = finalPatients.map(p => ({
...p,
loketId: parseInt(loketId),
registrationType: 'api'
}));
// ROBUST DEDUPLICATION & STATUS MERGE
// 1. Identify matches between existing allPatients and new API patients
const newPatientMap = new Map();
patientsWithLoketId.forEach(p => {
const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
newPatientMap.set(key, p);
});
// 2. Iterate existing patients to find matches and preserve status
const preservedStatuses = new Map();
allPatients.value.forEach(p => {
const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
if (newPatientMap.has(key)) {
// If existing patient has more advanced status (anjungan/di-loket), preserve it!
// This handles cases where we updated status locally ('onsite' or 'api') but API is lagging
const statusPriority = { 'di-loket': 3, 'anjungan': 2, 'menunggu': 1 };
const existingPrio = statusPriority[p.status] || 0;
const newPatient = newPatientMap.get(key);
const newPrio = statusPriority[newPatient.status] || 0;
if (existingPrio > newPrio) {
preservedStatuses.set(key, p.status);
// Also preserve lastCalledAt/calledByAdmin if available
if (p.lastCalledAt) newPatient.lastCalledAt = p.lastCalledAt;
if (p.calledByAdmin) newPatient.calledByAdmin = p.calledByAdmin;
}
}
});
// 3. Update new patients with preserved status
patientsWithLoketId.forEach(p => {
const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
if (preservedStatuses.has(key)) {
p.status = preservedStatuses.get(key);
}
});
// 4. Remove existing patients that collide with new ones (to be replaced)
// This ensures API data ALWAYS takes precedence over local/seed data
// Remove ANY patient (local, seed, or api) with matching barcode/idtiket
allPatients.value = allPatients.value.filter(p => {
const key = p.idtiket ? `id-${p.idtiket}` : `bc-${p.barcode}`;
// Remove if it's being replaced by new API batch (matches by barcode or idtiket)
if (newPatientMap.has(key)) return false;
// Also check if barcode matches any new API patient (for cases where local has no idtiket)
// This prevents duplicates like barcode "2602050017" appearing as both BPJS (local) and JKN (API)
if (p.barcode) {
const barcodeMatches = patientsWithLoketId.some(newP => newP.barcode === p.barcode);
if (barcodeMatches) return false;
}
// Remove if it's a stale 'api' patient for this loket (that wasn't in the new batch)
if (p.registrationType === 'api' && String(p.loketId) === String(loketId)) return false;
return true;
});
// 5. Add merged patients
allPatients.value.push(...patientsWithLoketId);
console.log(`✅ [queueStore] Successfully fetched ${finalPatients.length} unique patients for loket ${loketId} (Original: ${mappedPatients.length})`);
console.log(`📊 [queueStore] Total patients in allPatients: ${allPatients.value.length}`);
return {
success: true,
message: `${mappedPatients.length} pasien berhasil dimuat`,
data: mappedPatients
};
} catch (error) {
console.error(`❌ [queueStore] Error fetching patients for loket ${loketId}:`, error);
apiPatientsError.value = error.message;
// Return empty array on error
apiPatientsPerLoket.value[loketId] = [];
return {
success: false,
message: `Gagal memuat data pasien: ${error.message}`,
data: []
};
} finally {
isLoadingPatients.value = false;
}
};
/**
* Global fetcher for all patients across all available lokets
*/
const fetchAllPatients = async () => {
console.log('🔄 [queueStore] Fetching all patients for all lokets...');
const allLokets = loketStore.lokets || [];
if (allLokets.length === 0) {
console.warn('⚠️ [queueStore] No lokets available for fetchAllPatients');
return;
}
// Use Promise.all for faster fetching
await Promise.all(allLokets.map(l => fetchPatientsForLoket(l.id)));
console.log(`✅ [queueStore] All patients fetched. Total: ${allPatients.value.length}`);
};
/**
* Get patients for a specific loket (from API or seed data based on loket type)
*/
const getPatientsForLoket = (loketId) => {
return computed(() => {
const loket = loketStore.getLoketById(parseInt(loketId));
// If loket is EKSEKUTIF, use seed data
const isEksekutif = loket?.tipeloket === 'EKSEKUTIF' ||
loket?.tipeLoket === 'EKSEKUTIF' ||
(loket?.namaLoket || '').toUpperCase().includes('EKSEKUTIF');
if (isEksekutif) {
// Return EKSEKUTIF patients from seed data
return allPatients.value.filter(p => {
const isPembayaranEksekutif = (p.pembayaran || '').toUpperCase().includes('EKSEKUTIF') ||
(p.pembayaran || '').toUpperCase().includes('VIP');
return isPembayaranEksekutif && p.processStage === 'loket';
});
}
// For REGULER loket, return API data
return apiPatientsPerLoket.value[loketId] || [];
});
};
// Helper function untuk mendapatkan loket default (Loket A)
const getDefaultLoket = () => {
const allLokets = loketStore.loketData?.value || loketStore.loketData || [];
const loket1 = allLokets.find(l => l.id === 1 || l.no === 1);
return loket1 ? loket1.namaLoket : 'Loket A';
};
// Helper function untuk increment barcode counter setelah barcode digunakan
const incrementBarcodeCounter = () => {
if (typeof window === 'undefined' || typeof localStorage === 'undefined') return;
const now = new Date();
const year = String(now.getFullYear()).slice(-2);
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const datePrefix = `${year}${month}${day}`;
const STORAGE_KEY = `barcode_counter_${datePrefix}`;
const LAST_DATE_KEY = 'barcode_last_date';
const storedCounter = localStorage.getItem(STORAGE_KEY);
if (storedCounter) {
const currentCounter = parseInt(storedCounter, 10) || 1;
localStorage.setItem(STORAGE_KEY, String(currentCounter + 1));
localStorage.setItem(LAST_DATE_KEY, datePrefix);
}
};
// Helper function untuk generate barcode dengan format: YYMMDD + 5 digit sequential
// Format: YY (tahun 2 digit terakhir) + MM (bulan 2 digit) + DD (tanggal 2 digit) + XXXXX (5 digit sequential)
// Contoh: 26011400001, 26011400002, dst
// Counter akan reset setiap ganti tanggal (mulai dari 00001 lagi)
// IMPORTANT: Memastikan barcode selalu UNIQUE dan sequential per tanggal
// NOTE: allPatientsRef adalah optional parameter untuk menghindari TDZ error saat seed initialization
const generateBarcode = (existingBarcodes = [], allPatientsRef = null) => {
const now = new Date();
const year = String(now.getFullYear()).slice(-2); // 2 digit tahun terakhir
const month = String(now.getMonth() + 1).padStart(2, '0'); // 2 digit bulan
const day = String(now.getDate()).padStart(2, '0'); // 2 digit tanggal
const datePrefix = `${year}${month}${day}`; // YYMMDD
// Check if localStorage is available (browser environment)
if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
// Key untuk localStorage berdasarkan tanggal
const STORAGE_KEY = `barcode_counter_${datePrefix}`;
const LAST_DATE_KEY = 'barcode_last_date';
// Cek apakah tanggal sudah berubah (reset counter)
const lastDate = localStorage.getItem(LAST_DATE_KEY);
const currentDate = datePrefix;
let counter = 1; // Default mulai dari 1
if (lastDate === currentDate) {
// Tanggal sama, lanjutkan counter dari localStorage
const storedCounter = localStorage.getItem(STORAGE_KEY);
if (storedCounter) {
counter = parseInt(storedCounter, 10) || 1;
}
} else {
// Tanggal berbeda, reset counter ke 1
counter = 1;
// Hapus counter lama untuk tanggal sebelumnya (cleanup)
if (lastDate) {
localStorage.removeItem(`barcode_counter_${lastDate}`);
}
}
// Generate barcode dengan counter saat ini
let barcode = `${datePrefix}${String(counter).padStart(5, '0')}`;
// Cek apakah barcode sudah ada di existingBarcodes atau allPatientsRef
const checkExists = (b) => {
if (existingBarcodes.includes(b)) return true;
// Hanya cek allPatientsRef jika diberikan (tidak null/undefined)
if (allPatientsRef && allPatientsRef.value && allPatientsRef.value.some(p => p.barcode === b)) return true;
return false;
};
let attempts = 0;
const maxAttempts = 1000; // Maksimal 1000 pasien per hari
// Cek uniqueness dan increment jika duplikat
while (checkExists(barcode) && attempts < maxAttempts) {
counter++;
barcode = `${datePrefix}${String(counter).padStart(5, '0')}`;
attempts++;
}
// IMPORTANT: JANGAN tulis counter ke localStorage di sini!
// Counter hanya di-increment dan di-save setelah barcode benar-benar digunakan
// Ini mencegah counter naik meskipun barcode tidak digunakan (misalnya saat refresh)
// Counter akan di-increment oleh incrementBarcodeCounter() setelah pasien dibuat
// Hanya update LAST_DATE_KEY untuk tracking tanggal
localStorage.setItem(LAST_DATE_KEY, currentDate);
return barcode;
} else {
// Fallback untuk SSR atau environment tanpa localStorage
// Gunakan counter berdasarkan existing barcodes atau allPatientsRef
const existingCount = existingBarcodes.filter(b => b && b.startsWith(datePrefix)).length;
const allCount = allPatientsRef && allPatientsRef.value
? allPatientsRef.value.filter(p => p.barcode && p.barcode.startsWith(datePrefix)).length
: 0;
const counter = Math.max(existingCount, allCount) + 1;
const counterCode = String(counter).padStart(5, '0');
return `${datePrefix}${counterCode}`;
}
};
// Seed data for easy reset during dev
// IMPORTANT: Setiap pasien HARUS memiliki barcode UNIK untuk menghindari konflik
// Format barcode menggunakan generateBarcode() untuk konsistensi dengan format baru
// Generate barcode dengan memastikan uniqueness menggunakan existingBarcodes array
// NOTE: Seed data menggunakan barcode statis untuk menghindari increment counter saat refresh
// Counter hanya di-increment ketika pasien baru benar-benar dibuat dari Anjungan
// Gunakan barcode statis untuk seed data (tidak memanggil generateBarcode)
// Format: YYMMDD + 5 digit sequential dimulai dari 00001
// Ini mencegah counter naik setiap kali halaman di-refresh
const getSeedBarcode = (index) => {
if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
const now = new Date();
const year = String(now.getFullYear()).slice(-2);
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const datePrefix = `${year}${month}${day}`;
// Gunakan barcode statis berdasarkan index (1-16)
// Format: YYMMDD + 5 digit (contoh: 26011500001, 26011500002, dst)
return `${datePrefix}${String(index).padStart(5, '0')}`;
}
// Fallback untuk SSR
const now = new Date();
const year = String(now.getFullYear()).slice(-2);
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const datePrefix = `${year}${month}${day}`;
return `${datePrefix}${String(index).padStart(5, '0')}`;
};
const seedBarcode1 = getSeedBarcode(1);
const seedBarcode2 = getSeedBarcode(2);
const seedBarcode3 = getSeedBarcode(3);
const seedBarcode4 = getSeedBarcode(4);
const seedBarcode5 = getSeedBarcode(5);
// Barcode untuk pasien Eksekutif only (REGULER akan dari API)
const seedBarcodeE1 = getSeedBarcode(1);
const seedBarcodeE2 = getSeedBarcode(2);
const seedBarcodeE3 = getSeedBarcode(3);
const seedBarcodeE4 = getSeedBarcode(4);
// IMPORTANT: Set counter ke nilai yang sesuai dengan jumlah seed data
// Ini mencegah counter naik tidak terkendali saat seed data di-generate
// Counter akan di-set ke jumlah seed data (16) + 1 untuk next barcode
// Hanya set jika counter belum ada atau lebih kecil dari jumlah seed data
if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
const now = new Date();
const year = String(now.getFullYear()).slice(-2);
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const datePrefix = `${year}${month}${day}`;
const STORAGE_KEY = `barcode_counter_${datePrefix}`;
const LAST_DATE_KEY = 'barcode_last_date';
const storedCounter = localStorage.getItem(STORAGE_KEY);
const seedDataCount = 4; // Jumlah seed data (EKSEKUTIF only)
// Hanya set counter jika belum ada atau lebih kecil dari jumlah seed data
// Jangan overwrite counter yang sudah lebih besar (berarti sudah ada pasien baru)
if (!storedCounter || parseInt(storedCounter, 10) < seedDataCount) {
localStorage.setItem(STORAGE_KEY, String(seedDataCount + 1));
localStorage.setItem(LAST_DATE_KEY, datePrefix);
}
}
// SEED DATA: ONLY EKSEKUTIF PATIENTS
// All REGULER patients will come from API
const seedPatients = [
// {
// no: 1,
// jamPanggil: "11:20",
// barcode: seedBarcodeE1,
// noAntrian: `EA001 | Online - ${seedBarcodeE1}`,
// shift: "Shift 1",
// klinik: "KANDUNGAN",
// kodeKlinik: "KD",
// fastTrack: "TIDAK",
// pembayaran: "Eksekutif",
// status: "anjungan",
// processStage: "loket",
// createdAt: new Date().toISOString(),
// registrationType: 'online',
// visitType: 'SEKARANG',
// visitDate: new Date().toISOString().substring(0, 10),
// namaDokter: "Dr. Ahmad Wijaya, Sp.OG",
// noRM: "RM-E001",
// penanggungJawab: null,
// alasanFastTrack: null,
// },
// {
// no: 2,
// jamPanggil: "13:45",
// barcode: seedBarcodeE2,
// noAntrian: `EA002 | Online - ${seedBarcodeE2}`,
// shift: "Shift 1",
// klinik: "IPD",
// kodeKlinik: "IP",
// fastTrack: "TIDAK",
// pembayaran: "Eksekutif",
// status: "anjungan",
// processStage: "loket",
// createdAt: new Date().toISOString(),
// registrationType: 'online',
// visitType: 'SEKARANG',
// visitDate: new Date().toISOString().substring(0, 10),
// namaDokter: "Dr. Budi Santoso, Sp.PD",
// noRM: "RM-E002",
// penanggungJawab: null,
// alasanFastTrack: null,
// },
// {
// no: 3,
// jamPanggil: "15:10",
// barcode: seedBarcodeE3,
// noAntrian: `F-EA003 | Online - ${seedBarcodeE3}`,
// shift: "Shift 2",
// klinik: "SARAF",
// kodeKlinik: "SR",
// fastTrack: "YA",
// pembayaran: "Eksekutif",
// status: "anjungan",
// processStage: "loket",
// createdAt: new Date().toISOString(),
// registrationType: 'online',
// visitType: 'SEKARANG',
// visitDate: new Date().toISOString().substring(0, 10),
// namaDokter: "Dr. Citra Dewi, Sp.S",
// noRM: "RM-E003",
// penanggungJawab: "Dr. Citra Dewi",
// alasanFastTrack: "Pasien Eksekutif prioritas",
// },
// {
// no: 4,
// jamPanggil: "16:30",
// barcode: seedBarcodeE4,
// noAntrian: `EA004 | Online - ${seedBarcodeE4}`,
// shift: "Shift 2",
// klinik: "THT",
// kodeKlinik: "TH",
// fastTrack: "TIDAK",
// pembayaran: "VIP",
// status: "anjungan",
// processStage: "loket",
// createdAt: new Date().toISOString(),
// registrationType: 'online',
// visitType: 'SEKARANG',
// visitDate: new Date().toISOString().substring(0, 10),
// namaDokter: "Dr. Eka Putri, Sp.THT",
// noRM: "RM-E004",
// penanggungJawab: null,
// alasanFastTrack: null,
// },
];
const cloneSeed = () => seedPatients.map(p => ({ ...p }));
// Initialize counters from seed data to ensure numbering continues correctly
// Counter SHARED untuk semua payment group dan semua jenis pasien
// Calculate max queue number from seeds or existing patients
const syncCountersWithState = () => {
if (typeof window === 'undefined') return;
const today = new Date().toISOString().split('T')[0];
const STORAGE_KEY_BARCODE = `barcode_counter_${today.replace(/-/g, '').substring(2)}`;
// Determine the source of patients (prefer current state, fallback to seeds)
const sourcePatients = allPatients.value.length > 0 ? allPatients.value : seedPatients;
// Find max barcode counter
let maxBarcodeCounter = 0;
sourcePatients.forEach(patient => {
const barcode = patient.barcode || '';
if (barcode.length > 5) {
const counterStr = barcode.substring(barcode.length - 5);
const counter = parseInt(counterStr, 10);
if (!isNaN(counter) && counter > maxBarcodeCounter) {
maxBarcodeCounter = counter;
}
}
});
// Initialize barcode counter if not exists or smaller
const existingBarcode = localStorage.getItem(STORAGE_KEY_BARCODE);
if (!existingBarcode || parseInt(existingBarcode, 10) < maxBarcodeCounter) {
localStorage.setItem(STORAGE_KEY_BARCODE, maxBarcodeCounter.toString());
}
// Existing queue counter logic...
const counterKeyQueue = `queue_counter_loket_shared_${today}`;
// Calculate max queue number from seeds dynamically
const maxQueueCounter = sourcePatients.length > 0
? Math.max(...sourcePatients.map(p => p.no))
: 0;
const existingQueue = localStorage.getItem(counterKeyQueue);
// Always update if current max in memory is larger than stored
if (!existingQueue || parseInt(existingQueue) < maxQueueCounter) {
localStorage.setItem(counterKeyQueue, maxQueueCounter.toString());
}
};
// Initial state - START EMPTY to avoid clashing with hydration
const allPatients = ref([]);
const quotaUsed = ref(5);
// State - currentProcessingPatient is now an object mapping 'stage-id' to patient
// For example: { 'loket-1': patient, 'loket-2': patient, 'klinik-3': patient }
const currentProcessingPatient = ref({});
// Daftar klinik untuk dropdown diambil 1 pintu dari clinicStore
const kliniks = ref(clinicStore.clinics || []);
// Penunjang data - reference dari penunjangStore
const penunjangs = ref(penunjangStore.penunjangs || []);
const RESET_HOUR = 2; // 2 AM reset threshold
/**
* Get logical reset threshold date object
* If current time is before 2 AM, the threshold is yesterday at 2 AM.
* If current time is after 2 AM, the threshold is today at 2 AM.
*/
const getResetThreshold = () => {
const now = new Date();
const threshold = new Date(now);
threshold.setHours(RESET_HOUR, 0, 0, 0);
if (now.getHours() < RESET_HOUR) {
threshold.setDate(threshold.getDate() - 1);
}
return threshold;
};
/**
* Check if data needs to be reset (passed 2 AM of a new day)
*/
const checkAndResetDaily = () => {
const threshold = getResetThreshold();
const thresholdTS = threshold.getTime();
// Use localStorage to persist last reset time across sessions/tabs
const lastResetStr = localStorage.getItem('queue_last_reset_time');
const lastResetTS = lastResetStr ? parseInt(lastResetStr, 10) : 0;
if (lastResetTS < thresholdTS) {
console.log(`🕒 [queueStore] Daily reset triggered. Threshold: ${threshold.toLocaleString()}`);
// Clear data
allPatients.value = [];
apiPatientsPerLoket.value = {};
currentProcessingPatient.value = {};
// Update reset timestamp
localStorage.setItem('queue_last_reset_time', thresholdTS.toString());
// Re-sync counters for the new day
syncCountersWithState();
return true;
}
return false;
};
/**
* Filter strictly to only show today's patients (after 2 AM)
*/
const isTodayPatient = (patient) => {
if (!patient) return false;
// Status processing overrides filter (always show if currently processing)
const isProcessing = Object.values(currentProcessingPatient.value).some(p => p && p.no === patient.no);
if (isProcessing) return true;
const threshold = getResetThreshold();
// Get YYYY-MM-DD for the logical "today" (based on 2 AM threshold)
const year = threshold.getFullYear();
const month = String(threshold.getMonth() + 1).padStart(2, '0');
const day = String(threshold.getDate()).padStart(2, '0');
const logicalTodayStr = `${year}-${month}-${day}`;
// 1. If visitDate (YYYY-MM-DD) matches logical today's date, it's a "today" patient
// This correctly includes API patients with midnight timestamps (00:00:00)
if (patient.visitDate) {
if (patient.visitDate === logicalTodayStr) return true;
if (patient.visitDate < logicalTodayStr) return false;
}
// 2. Fallback: check createdAt timestamp (critical for seed/manual tickets)
// Tickets created before today's 2 AM are stale
const createdAt = patient.createdAt ? new Date(patient.createdAt) : null;
if (createdAt && createdAt < threshold) {
return false;
}
return true;
};
/**
* Ensures initial data exists.
* Only seeds if the store is empty (not hydrated from storage)
*/
const ensureInitialData = () => {
// 1. Check for daily reset first
checkAndResetDaily();
if (allPatients.value.length === 0) {
console.log('🌱 Seeding queueStore with initial data...');
allPatients.value = cloneSeed();
}
// ALWAYS sync counters with state (hydrated or seeded) to ensure next number is correct
syncCountersWithState();
};
// Synchronization Guard: track if we are currently hydrating from another tab
let isSyncing = false;
// CROSS-TAB SYNC: Listen for storage events to update store across tabs
if (typeof window !== 'undefined') {
window.addEventListener('storage', (event) => {
if (event.key === 'queue-store-state') {
if (!event.newValue) return;
try {
const newState = JSON.parse(event.newValue);
// BREAK THE LOOP: Only re-hydrate if the incoming data is strictly newer than ours
// Defensive check: Handle cases where lastUpdated might be undefined or missing
const incomingVersion = Number(newState?.lastUpdated || 0);
const currentVersion = Number(lastUpdated.value || 0);
if (incomingVersion === 0 || incomingVersion <= currentVersion) {
// Already up to date, older, or corrupted data. Skip hydration.
return;
}
console.log(`🔄 Syncing state to version: ${incomingVersion}`);
if (newState) {
isSyncing = true; // Block local watch from updating timestamp
try {
if (newState.allPatients) allPatients.value = newState.allPatients;
if (newState.quotaUsed !== undefined) quotaUsed.value = newState.quotaUsed;
if (newState.currentProcessingPatient) currentProcessingPatient.value = newState.currentProcessingPatient;
if (newState.apiPatientsPerLoket) apiPatientsPerLoket.value = newState.apiPatientsPerLoket;
// Set local timestamp to match the source
lastUpdated.value = incomingVersion;
syncCountersWithState();
} finally {
// Ensure we release the lock
setTimeout(() => { isSyncing = false; }, 50);
}
}
} catch (e) {
console.error('Error hydrating from storage event:', e);
isSyncing = false;
}
}
});
}
// Automatic timestamp update for local changes
// This ensures lastUpdated changes whenever state changes LOCALLY
// but skips updates coming from isSyncing = true
watch([allPatients, quotaUsed, currentProcessingPatient, apiPatientsPerLoket], () => {
if (!isSyncing) {
lastUpdated.value = Date.now();
// console.log('✨ Local state updated, version:', lastUpdated.value);
}
}, { deep: true });
// Computed - Filter berdasarkan process stage dan status
const getPatientsByStage = (stage) => {
return computed(() => {
// Filter by stage AND date (today only)
// optimization: filter all once, then sub-filter
const patients = allPatients.value.filter(p => p && p.processStage === stage && isTodayPatient(p));
// Debug log (limited to avoid spam)
if (patients.length > 0) {
// console.log(`getPatientsByStage(${stage}):`, patients.length, 'patients (Today)');
}
return {
all: patients,
anjungan: patients.filter(p => p.status === 'anjungan'),
menunggu: patients.filter(p => p.status === 'menunggu'),
diLoket: patients.filter(p => p.status === 'di-loket'),
terlambat: patients.filter(p => p.status === 'terlambat'),
pending: patients.filter(p => p.status === 'pending'),
};
});
};
// Total pasien per stage - strictly today
const getTotalPasienByStage = (stage) => {
return computed(() =>
allPatients.value.filter(p => p.processStage === stage && isTodayPatient(p)).length
);
};
const totalPasien = computed(() => allPatients.value.length);
const resetPatients = () => {
allPatients.value = cloneSeed();
quotaUsed.value = 5;
currentProcessingPatient.value = { loket: null, klinik: null, penunjang: null };
syncCountersWithState(); // Re-initialize counters after reset
};
/**
* Helper to sort patients for calling/process selection
* Priority: Fast Track ("YA") first, then by sequence number (no)
*/
const sortPatientsForCalling = (patients) => {
if (!patients || !Array.isArray(patients)) return [];
return [...patients].sort((a, b) => {
const aFT = (a.fastTrack ?? "").toString().trim().toUpperCase() === "YA";
const bFT = (b.fastTrack ?? "").toString().trim().toUpperCase() === "YA";
if (aFT && !bFT) return -1;
if (!aFT && bFT) return 1;
const numA = parseInt(a.no) || 0;
const numB = parseInt(b.no) || 0;
return numA - numB;
});
};
/**
* Check if patient's payment type is compatible with loket's accepted payments
* Maps various payment names to standardized categories
* Handles complex names like "UMUM / JKMM / SPM / DLL"
*/
const isPaymentCompatible = (patientPayment, loketPayments) => {
if (!loketPayments || loketPayments.length === 0) return true; // No restriction
if (!patientPayment) return false;
const normalizedPatient = String(patientPayment).toUpperCase().trim();
// Map patient payment to category
const patientCategory =
(normalizedPatient.includes('JKN') || normalizedPatient.includes('BPJS')) ? 'JKN' :
normalizedPatient.includes('EKSEKUTIF') || normalizedPatient.includes('VIP') ? 'EKSEKUTIF' :
'UMUM'; // Default to UMUM for non-JKN, non-EKSEKUTIF
// Check if loket accepts this category
return loketPayments.some(lp => {
const normalized = String(lp).toUpperCase().trim();
// Handle exact match
if (normalized === patientCategory) return true;
// Handle partial matches for complex payment types like "UMUM / JKMM / SPM / DLL"
if (patientCategory === 'UMUM' && normalized.includes('UMUM')) return true;
if (patientCategory === 'JKN' && (normalized.includes('JKN') || normalized.includes('BPJS'))) return true;
if (patientCategory === 'EKSEKUTIF' && (normalized.includes('EKSEKUTIF') || normalized.includes('VIP'))) return true;
// Handle alias: BPJS = JKN (only this alias is allowed)
if (normalized === 'BPJS' && patientCategory === 'JKN') return true;
return false;
});
};
// Action: Ambil Antrean Masuk dari Anjungan (Reservoir -> Waiting Room)
// "fungsi ini juga sesuaikan dengan idloket dan klinik id"
// "hanya memanggil tiket dari loket lain harus tiket menunggu yang sesuai id loket dan id kliniknya"
const callNext = (adminType = 'loket', specificId = null) => {
const stageMap = {
'loket': 'loket',
'klinik': 'klinik',
'penunjang': 'penunjang'
};
const targetStage = stageMap[adminType];
const targetId = specificId;
// Filter list by stage AND relevance to this specific loket/clinic/penunjang
const eligiblePatients = allPatients.value.filter(p => {
// 1. Stage Check
if (p.processStage !== targetStage) return false;
// 2. Relevance Check based on adminType
if (targetId) {
if (adminType === 'loket') {
// Fix: Prioritaskan loketId match. Jika loketId cocok, abaikan check pelayanan (karena bisa jadi data API beda mapping)
const isLoketMatch = p.loketId && String(p.loketId) === String(targetId);
if (isLoketMatch) return true;
const thisLoket = loketStore.getLoketById(parseInt(targetId));
// Enforce clinic mapping (pelayanan)
if (thisLoket && thisLoket.pelayanan && Array.isArray(thisLoket.pelayanan)) {
if (thisLoket.pelayanan.includes(p.kodeKlinik)) {
// NEW: Check payment compatibility
if (!isPaymentCompatible(p.pembayaran, thisLoket.pembayaran)) {
return false;
}
return true;
}
}
return false;
}
else if (adminType === 'klinik') {
// Clinic ID match
if (String(p.kodeKlinik) !== String(targetId) && String(p.klinik) !== String(targetId)) return false;
}
else if (adminType === 'penunjang') {
// Penunjang match
if (String(p.klinik) !== String(targetId) && String(p.kodeKlinik) !== String(targetId)) return false;
}
}
return true;
});
// PRIORITAS: Hanya ambil pasien dengan status 'menunggu' (Antrean Baru dari Anjungan)
// "bukan untuk memanggil pasien tapi tiket baru dari anjungan yang statusnya menunggu"
// SEQUENTIAL: Sort by Fast Track and Queue No before picking the first matching patient
const waitingPatients = eligiblePatients.filter(p => p.status === 'menunggu');
const sortedWaiting = sortPatientsForCalling(waitingPatients);
const nextPatient = sortedWaiting[0];
if (!nextPatient) {
return { success: false, message: `Tidak ada antrean baru yang sesuai untuk ${adminType} ${targetId || ''}` };
}
// Hitung kuota yang tersedia (khusus loket ini)
const currentLoket = loketStore.getLoketById(parseInt(targetId));
const targetQuota = currentLoket?.kuota || 150;
const diLoketCount = allPatients.value.filter(p =>
p.status === 'di-loket' &&
p.processStage === targetStage &&
(targetId && adminType === 'loket' ? String(p.loketId) === String(targetId) : true)
).length;
const availableQuota = targetQuota - diLoketCount;
if (availableQuota <= 0) {
return { success: false, message: "Kuota sudah penuh" };
}
// Update status menjadi 'anjungan' (Masuk ke antrean aktif)
const callTimestamp = new Date().toISOString();
const index = allPatients.value.findIndex(p => p.no === nextPatient.no);
if (index !== -1) {
allPatients.value[index] = {
...allPatients.value[index],
status: "anjungan",
// Assign to this specific loket if it was unassigned
loketId: (adminType === 'loket' && targetId) ? parseInt(targetId) : allPatients.value[index].loketId,
lastCalledAt: callTimestamp
};
// SYNC to apiPatientsPerLoket if it's an API patient
syncApiPatientStatus(allPatients.value[index], "anjungan");
// POST to external API when patient is called
try {
fetch('http://10.10.150.131:8089/api/v1/tiket/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
barcode: nextPatient.barcode || "",
statuspasien: "3",
statuspasien2: "4",
idklinikstatus: "1",
idklinikstatus2: "1"
})
}).then(response => {
if (response.ok) {
console.log(`✅ Successfully posted status update for patient ${nextPatient.barcode}`);
} else {
console.error(`⚠️ Failed to post status update for patient ${nextPatient.barcode}:`, response.status);
}
}).catch(error => {
console.error(`❌ Error posting status update for patient ${nextPatient.barcode}:`, error);
});
} catch (error) {
console.error(`❌ Error initiating status update for patient ${nextPatient.barcode}:`, error);
}
}
return {
success: true,
message: `Berhasil mengambil antrean ${nextPatient.noAntrian.split(" |")[0]} ke daftar tunggu`,
};
};
const callMultiplePatients = (count, adminType = 'loket', specificId = null) => {
const stageMap = { 'loket': 'loket', 'klinik': 'klinik', 'penunjang': 'penunjang' };
const targetStage = stageMap[adminType];
const targetId = specificId;
const eligiblePatients = allPatients.value.filter(p => {
if (p.processStage !== targetStage) return false;
if (targetId) {
if (adminType === 'loket') {
// Fix: Prioritaskan loketId match. Jika loketId cocok, abaikan check pelayanan (karena bisa jadi data API beda mapping)
const isLoketMatch = p.loketId && String(p.loketId) === String(targetId);
if (isLoketMatch) return true;
const thisLoket = loketStore.getLoketById(parseInt(targetId));
if (thisLoket && thisLoket.pelayanan && Array.isArray(thisLoket.pelayanan)) {
if (thisLoket.pelayanan.includes(p.kodeKlinik)) {
// NEW: Check payment compatibility
if (!isPaymentCompatible(p.pembayaran, thisLoket.pembayaran)) {
return false;
}
return true;
}
}
return false;
} else if (adminType === 'klinik' || adminType === 'penunjang') {
if (String(p.kodeKlinik) !== String(targetId) && String(p.klinik) !== String(targetId)) return false;
}
}
return true;
});
// Hanya ambil pasien status 'menunggu'
// SEQUENTIAL: Sort by Fast Track and Queue No
const menungguList = sortPatientsForCalling(eligiblePatients.filter(p => p.status === 'menunggu'));
if (menungguList.length === 0) {
return { success: false, message: `Tidak ada antrean baru yang sesuai untuk ${adminType} ${targetId || ''}` };
}
// Hitung kuota yang tersedia
const currentLoket = loketStore.getLoketById(parseInt(targetId));
const targetQuota = currentLoket?.kuota || 150;
const diLoketCount = allPatients.value.filter(p =>
p.status === 'di-loket' &&
p.processStage === targetStage &&
(targetId && adminType === 'loket' ? String(p.loketId) === String(targetId) : true)
).length;
const availableQuota = targetQuota - diLoketCount;
const maxCallable = Math.min(count, menungguList.length, availableQuota);
if (maxCallable <= 0) {
if (availableQuota <= 0) return { success: false, message: "Kuota sudah penuh" };
return { success: false, message: "Tidak ada antrean yang bisa diambil" };
}
const patientsToCall = menungguList.slice(0, maxCallable);
const callTimestamp = new Date().toISOString();
patientsToCall.forEach(async (patient) => {
const index = allPatients.value.findIndex(p => p.no === patient.no);
if (index !== -1) {
const newStatus = "anjungan";
const newLoketId = (adminType === 'loket' && targetId) ? targetId : allPatients.value[index].loketId;
allPatients.value[index] = {
...allPatients.value[index],
status: newStatus,
loketId: newLoketId,
lastCalledAt: callTimestamp
};
// SYNC to apiPatientsPerLoket if it's an API patient
syncApiPatientStatus(allPatients.value[index], newStatus);
// POST to external API when patient is called
try {
const response = await fetch('http://10.10.150.131:8089/api/v1/tiket/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
barcode: patient.barcode || "",
statuspasien: "3",
statuspasien2: "4",
idklinikstatus: "1",
idklinikstatus2: "1"
})
});
if (response.ok) {
console.log(`✅ Successfully posted status update for patient ${patient.barcode}`);
} else {
console.error(`⚠️ Failed to post status update for patient ${patient.barcode}:`, response.status);
}
} catch (error) {
console.error(`❌ Error posting status update for patient ${patient.barcode}:`, error);
}
}
});
return {
success: true,
message: `Berhasil mengambil ${patientsToCall.length} antrean ke daftar tunggu`,
};
};
const processPatient = (patient, action, adminType = 'loket', specificId = null) => {
const storageKey = specificId ? `${adminType}-${specificId}` : adminType;
const patientCode = patient.noAntrian.split(" |")[0];
let message = "";
// Find patient index for reactive update
const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
if (patientIndex === -1) {
return { success: false, message: "Pasien tidak ditemukan" };
}
switch (action) {
case "check-in":
// Jika check-in di loket, pindahkan ke klinik dengan status di-loket
if (adminType === 'loket') {
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
status: "di-loket",
processStage: "klinik",
calledByAdmin: false // Reset flag saat pindah stage
};
syncApiPatientStatus(allPatients.value[patientIndex], "di-loket");
message = `Pasien ${patientCode} berhasil check in dan masuk ke Tabel Loket Klinik`;
// POST to external API when patient finishes at loket
try {
fetch('http://10.10.150.131:8089/api/v1/tiket/selesai', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
idloket: String(patient.loketId || specificId || ""),
barcode: patient.barcode || "",
statuspasien: "9",
idklinikstatus: "2"
})
}).then(response => {
if (response.ok) {
console.log(`✅ [queueStore] Successfully posted selesai status for patient ${patient.barcode}`);
} else {
console.error(`⚠️ [queueStore] Failed to post selesai status for patient ${patient.barcode}:`, response.status);
}
}).catch(error => {
console.error(`❌ [queueStore] Error posting selesai status for patient ${patient.barcode}:`, error);
});
} catch (error) {
console.error(`❌ [queueStore] Error initiating selesai status update for patient ${patient.barcode}:`, error);
}
}
// Jika check-in di klinik, selesai
else if (adminType === 'klinik') {
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
status: "processed"
};
syncApiPatientStatus(allPatients.value[patientIndex], "processed");
message = `Pasien ${patientCode} berhasil check in di Klinik`;
}
// Jika check-in di penunjang, selesai
else if (adminType === 'penunjang') {
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
status: "processed"
};
syncApiPatientStatus(allPatients.value[patientIndex], "processed");
message = `Pasien ${patientCode} berhasil check in di Penunjang`;
}
// Clear current processing di admin yang melakukan check-in
if (currentProcessingPatient.value[storageKey]?.no === patient.no) {
currentProcessingPatient.value[storageKey] = null;
}
break;
case "terlambat":
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
status: "terlambat",
calledByAdmin: false // Reset flag
};
if (currentProcessingPatient.value[storageKey]?.no === patient.no) {
currentProcessingPatient.value[storageKey] = null;
}
message = `Pasien ${patientCode} ditandai terlambat`;
break;
case "pending":
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
status: "pending",
calledByAdmin: false // Reset flag
};
if (currentProcessingPatient.value[storageKey]?.no === patient.no) {
currentProcessingPatient.value[storageKey] = null;
}
message = `Pasien ${patientCode} di-pending`;
break;
case "aktifkan": {
const currentStatus = allPatients.value[patientIndex].status;
if (currentStatus === "terlambat" || currentStatus === "pending") {
// PERBAIKAN: Update dengan cara yang Vue reactive
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
status: "di-loket"
};
message = `Pasien ${patientCode} diaktifkan kembali dan masuk ke tabel Di Loket`;
} else {
message = `Pasien ${patientCode} tidak dapat diaktifkan (status: ${currentStatus})`;
}
break;
}
case "proses": {
// Ambil data terbaru dari array
const patient = allPatients.value[patientIndex];
// Jika pasien memiliki status "pending" atau "terlambat", ubah menjadi "di-loket"
// agar pasien masuk ke kategori diLoketPatients dan ditampilkan sebagai "diproses"
const currentStatus = patient.status;
const shouldUpdateStatus = currentStatus === "pending" || currentStatus === "terlambat";
// Jika adminType adalah 'loket', pastikan ada loket assignment
if (adminType === 'loket') {
// Pastikan antrian yang diproses memiliki loket assignment
const currentLoket = patient.loket || getDefaultLoket();
const currentLoketId = patient.loketId || 1;
// Update patient dengan loket assignment dan status (jika perlu)
const updatedPatient = {
...patient,
loket: patient.loket || currentLoket,
loketId: patient.loketId || currentLoketId,
// Ubah status menjadi "di-loket" jika sebelumnya "pending" atau "terlambat"
...(shouldUpdateStatus && { status: "di-loket" })
};
allPatients.value[patientIndex] = updatedPatient;
// Set currentProcessingPatient with isolated key
currentProcessingPatient.value[storageKey] = updatedPatient;
} else {
// Untuk adminType selain loket, update status jika perlu
if (shouldUpdateStatus) {
const updatedPatient = {
...patient,
status: "di-loket"
};
allPatients.value[patientIndex] = updatedPatient;
currentProcessingPatient.value[storageKey] = updatedPatient;
} else {
currentProcessingPatient.value[storageKey] = patient;
}
}
message = `Memproses pasien ${patientCode}`;
break;
}
}
return { success: true, message };
};
const callProcessingPatient = (adminType = 'loket', specificId = null) => {
// Panggil pasien yang sedang diproses untuk ditampilkan di layar anjungan
const storageKey = specificId ? `${adminType}-${specificId}` : adminType;
const processingPatient = currentProcessingPatient.value[storageKey];
if (!processingPatient) {
return { success: false, message: "Tidak ada pasien yang sedang diproses" };
}
// Update flag calledByAdmin
const patientIndex = allPatients.value.findIndex(p => p.no === processingPatient.no);
if (patientIndex !== -1) {
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
calledByAdmin: true,
lastCalledAt: new Date().toISOString()
};
// Update currentProcessingPatient with the new data
currentProcessingPatient.value[storageKey] = allPatients.value[patientIndex];
return {
success: true,
message: `Memanggil pasien ${processingPatient.noAntrian.split(" |")[0]}`
};
}
return { success: false, message: "Gagal memanggil pasien" };
};
const createAntreanKlinik = (klinik, patient = null, adminType = 'loket') => {
const newNo = allPatients.value.length + 1;
const timestamp = new Date();
const barcode = patient ? patient.barcode : generateBarcode([], allPatients);
const newPatient = {
no: newNo,
jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
timestamp.getMinutes()
).padStart(2, "0")}`,
barcode: barcode,
noAntrian: `KL${String(newNo).padStart(4, "0")} | Klinik - ${barcode}`,
shift: "Shift 1",
klinik: klinik.name,
fastTrack: "TIDAK",
pembayaran: patient ? patient.pembayaran : "UMUM",
noRM: patient ? (patient.noRM || `RM-SCAN-${barcode.slice(-6)}`) : `RM-SCAN-${barcode.slice(-6)}`,
kodeKlinik: klinik.kode || klinik.id, // Ensure kodeKlinik is saved
status: "di-loket",
processStage: "klinik",
createdAt: timestamp.toISOString(),
referencePatient: patient ? patient.noAntrian : null,
loketId: null, // Initial check
};
// Auto-assign Loket ID based on Clinic Mapping
// "menyesuaikan loketnya berdasar loket id tergantung dari create tiket itu di klinik"
if (newPatient.kodeKlinik) {
const allLokets = loketStore.lokets || [];
const targetLoket = allLokets.find(l =>
l.pelayanan && Array.isArray(l.pelayanan) && l.pelayanan.includes(newPatient.kodeKlinik)
);
if (targetLoket) {
newPatient.loketId = targetLoket.id;
newPatient.loket = targetLoket.namaLoket;
console.log(`✅ Auto-assigned Ticket ${newPatient.noAntrian} to Loket ${targetLoket.id} (${targetLoket.namaLoket})`);
} else {
console.log(`⚠️ No specific Loket found for Clinic ${newPatient.kodeKlinik}, defaulting to general pool.`);
}
}
allPatients.value.push(newPatient);
// Increment counter setelah barcode digunakan
if (!patient) {
incrementBarcodeCounter();
}
return {
success: true,
message: `Antrean klinik ${klinik.name} berhasil dibuat dan masuk ke Tabel Loket Klinik`,
patient: newPatient,
};
};
const createAntreanPenunjang = (penunjang, patient = null, adminType = 'loket') => {
const newNo = allPatients.value.length + 1;
const timestamp = new Date();
const barcode = patient ? patient.barcode : generateBarcode([], allPatients);
const newPatient = {
no: newNo,
jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
timestamp.getMinutes()
).padStart(2, "0")}`,
barcode: barcode,
noAntrian: `PN${String(newNo).padStart(4, "0")} | Penunjang - ${barcode}`,
shift: "Shift 1",
klinik: penunjang.name,
fastTrack: "TIDAK",
pembayaran: patient ? patient.pembayaran : "UMUM",
noRM: patient ? patient.noRM : `RM-SCAN-${barcode.slice(-6)}`,
status: "di-loket",
processStage: "penunjang",
createdAt: timestamp.toISOString(),
referencePatient: patient ? patient.noAntrian : null,
};
allPatients.value.push(newPatient);
// Increment counter setelah barcode digunakan
if (!patient) {
incrementBarcodeCounter();
}
return {
success: true,
message: `Antrean penunjang ${penunjang.name} berhasil dibuat dan masuk ke Tabel Loket Penunjang`,
patient: newPatient,
};
};
const createAntreanKlinikRuang = (klinikRuang, ruang, patient = null, adminType = 'klinik', apiTicketNumber = null) => {
const newNo = allPatients.value.length + 1;
const timestamp = new Date();
const barcode = patient ? patient.barcode : generateBarcode([], allPatients);
// Generate nomor antrian baru dengan format: [huruf pertama poli + urutan abjad ruang + nomor antrian ruang]
// Contoh: "Anak" ruang 1 = "AA001" (A dari Anak, A dari ruang 1, 001 nomor antrian)
let newNoAntrian;
// Use API ticket number if available, otherwise generate locally
if (apiTicketNumber) {
newNoAntrian = apiTicketNumber; // Use ticket from API (e.g., "PK001")
console.log('🎫 Using API ticket number:', newNoAntrian);
} else {
// 1. Ambil huruf pertama dari nama klinik/poli
const firstLetter = klinikRuang.namaKlinik.charAt(0).toUpperCase();
// 2. Konversi nomor ruang ke abjad (1 = A, 2 = B, 3 = C, dst)
const ruangNumber = parseInt(ruang.nomorRuang) || 1;
const ruangLetter = String.fromCharCode(64 + ruangNumber); // 64 = '@', 65 = 'A', 66 = 'B', dst
// 3. Hitung nomor antrian ruang (dimulai dari 1, maksimal 3 digit)
const roomQueues = allPatients.value.filter(p =>
p.kodeKlinik === klinikRuang.kodeKlinik &&
p.nomorRuang === ruang.nomorRuang &&
p.processStage === 'klinik-ruang'
);
const queueNumber = roomQueues.length + 1;
const queueNumberStr = String(queueNumber).padStart(3, "0");
// 4. Format nomor antrian: AA001, AB002, dst
newNoAntrian = `${firstLetter}${ruangLetter}${queueNumberStr}`;
}
const newPatient = {
no: newNo,
jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
timestamp.getMinutes()
).padStart(2, "0")}`,
barcode: barcode,
noAntrian: `${newNoAntrian} | ${klinikRuang.namaKlinik} - ${ruang.namaRuang}`,
noAntrianRuang: `${klinikRuang.namaKlinik} - ${ruang.namaRuang} | ${newNoAntrian}`,
shift: patient ? (patient.shift || "Shift 1") : "Shift 1",
klinik: klinikRuang.namaKlinik,
ruang: ruang.namaRuang,
kodeKlinik: klinikRuang.kodeKlinik,
nomorRuang: ruang.nomorRuang,
nomorScreen: ruang.nomorScreen,
fastTrack: patient ? (patient.fastTrack || "TIDAK") : "TIDAK",
pembayaran: patient ? patient.pembayaran : "UMUM",
noRM: patient ? patient.noRM : null,
status: "pemeriksaan", // Patients from loket to klinik ruang start as "pemeriksaan"
processStage: "klinik-ruang", // Set ke klinik-ruang langsung
createdAt: timestamp.toISOString(),
referencePatient: patient ? patient.noAntrian : null,
sourcePatientNo: patient ? patient.no : null,
// Tracking panggilan
calledPemeriksaanAwal: false,
calledTindakan: false,
lastCalledAt: null,
lastCalledTipeLayanan: null,
calledByAdmin: false, // Flag untuk tracking apakah sudah dipanggil oleh admin
};
allPatients.value.push(newPatient);
// Increment counter setelah barcode digunakan
if (!patient) {
incrementBarcodeCounter();
}
return {
success: true,
message: `Antrean ${klinikRuang.namaKlinik} Ruang ${ruang.nomorRuang} berhasil dibuat: ${newNoAntrian}`,
patient: newPatient,
};
};
// Pindah pasien ke klinik ruang lain dengan nomor antrian tetap
const pindahKlinikRuang = (patient, targetKlinikRuang, targetRuang) => {
if (patientIndex === -1) {
return { success: false, message: "Pasien tidak ditemukan" };
}
const currentPatient = allPatients.value[patientIndex];
// Jika pasien sudah punya antrean klinik ruang, update antreannya
if (currentPatient.processStage === 'klinik-ruang' && currentPatient.tipeLayanan) {
const baseNoAntrian = currentPatient.noAntrian?.split(" |")[0] || currentPatient.barcode || '';
// Update dengan klinik dan ruang baru, tapi nomor antrian tetap sama
allPatients.value[patientIndex] = {
...currentPatient,
klinik: targetKlinikRuang.namaKlinik,
ruang: targetRuang.namaRuang,
kodeKlinik: targetKlinikRuang.kodeKlinik,
nomorRuang: targetRuang.nomorRuang,
nomorScreen: targetRuang.nomorScreen,
// Nomor antrian tetap sama
noAntrian: `${baseNoAntrian} | ${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} - ${currentPatient.tipeLayanan}`,
noAntrianRuang: `${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} | ${baseNoAntrian}`
};
// Clear current processing dari ruang lama jika ada
const oldKey = `klinik-ruang-${currentPatient.kodeKlinik}-${currentPatient.nomorRuang}`;
if (currentProcessingPatient.value[oldKey]?.no === currentPatient.no) {
currentProcessingPatient.value[oldKey] = null;
}
} else {
// Pasien belum digenerate tiket, hanya update ruang
allPatients.value[patientIndex] = {
...currentPatient,
klinik: targetKlinikRuang.namaKlinik,
ruang: targetRuang.namaRuang,
kodeKlinik: targetKlinikRuang.kodeKlinik,
nomorRuang: targetRuang.nomorRuang,
nomorScreen: targetRuang.nomorScreen
};
}
return {
success: true,
message: `Pasien berhasil dipindah ke ${targetKlinikRuang.namaKlinik} Ruang ${targetRuang.nomorRuang}`,
patient: allPatients.value[patientIndex]
};
};
// Konsultasi: pindah pasien ke klinik ruang lain dengan nomor antrian baru (prefix K- atau KF-)
const konsultasiKlinikRuang = (patient, targetKlinikRuang, targetRuang, tipeLayanan = 'Pemeriksaan Awal') => {
const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
if (patientIndex === -1) {
return { success: false, message: "Pasien tidak ditemukan" };
}
const sourcePatient = allPatients.value[patientIndex];
// Cek apakah sudah ada antrean konsultasi di ruang tujuan
const existingKonsultasi = allPatients.value.find(p =>
p.referencePatient === sourcePatient.noAntrian &&
p.kodeKlinik === targetKlinikRuang.kodeKlinik &&
p.nomorRuang === targetRuang.nomorRuang &&
p.processStage === 'klinik-ruang' &&
(p.noAntrian?.startsWith('K-') || p.noAntrian?.startsWith('KF-'))
);
if (existingKonsultasi) {
return {
success: false,
message: `Pasien sudah memiliki antrean konsultasi di ${targetKlinikRuang.namaKlinik} Ruang ${targetRuang.nomorRuang}`
};
}
// Generate queue number untuk konsultasi
const roomQueues = allPatients.value.filter(p =>
p.kodeKlinik === targetKlinikRuang.kodeKlinik &&
p.nomorRuang === targetRuang.nomorRuang &&
p.tipeLayanan === tipeLayanan &&
p.processStage === 'klinik-ruang' &&
(p.noAntrian?.startsWith('K-') || p.noAntrian?.startsWith('KF-'))
);
const queueNumber = roomQueues.length + 1;
const prefix = tipeLayanan === 'Pemeriksaan Awal' ? 'PA' : 'TD';
// Tentukan prefix konsultasi: KF- untuk Fast Track, K- untuk normal
const isFastTrack = sourcePatient.fastTrack === "YA";
const konsultasiPrefix = isFastTrack ? 'KF-' : 'K-';
const queueNumberStr = String(queueNumber).padStart(3, "0");
const newNoAntrian = `${konsultasiPrefix}${prefix}${queueNumberStr}`;
const newNo = allPatients.value.length + 1;
const timestamp = new Date();
const newPatient = {
no: newNo,
jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
timestamp.getMinutes()
).padStart(2, "0")}`,
barcode: sourcePatient.barcode,
noAntrian: `${newNoAntrian} | ${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} - ${tipeLayanan}`,
noAntrianRuang: `${targetKlinikRuang.namaKlinik} - ${targetRuang.namaRuang} | ${newNoAntrian}`,
shift: sourcePatient.shift || "Shift 1",
klinik: targetKlinikRuang.namaKlinik,
ruang: targetRuang.namaRuang,
kodeKlinik: targetKlinikRuang.kodeKlinik,
nomorRuang: targetRuang.nomorRuang,
nomorScreen: targetRuang.nomorScreen,
tipeLayanan: tipeLayanan,
fastTrack: sourcePatient.fastTrack || "TIDAK",
pembayaran: sourcePatient.pembayaran || "UMUM",
status: "anjungan",
processStage: "klinik-ruang",
createdAt: sourcePatient.createdAt || timestamp.toISOString(), // Gunakan createdAt dari pasien awal
referencePatient: sourcePatient.noAntrian,
sourcePatientNo: sourcePatient.no,
isKonsultasi: true, // Flag untuk konsultasi
};
allPatients.value.push(newPatient);
return {
success: true,
message: `Antrean konsultasi berhasil dibuat: ${newNoAntrian} untuk ${targetKlinikRuang.namaKlinik} Ruang ${targetRuang.nomorRuang}`,
patient: newPatient,
};
};
// Scan barcode dan generate antrean klinik ruang baru
const scanAndCreateAntreanKlinikRuang = (barcodeInput, klinikRuang, ruang, tipeLayanan = 'Pemeriksaan Awal') => {
// Clean input - remove whitespace and handle prefix letters
const cleanInput = String(barcodeInput).trim().toUpperCase();
// Remove leading letters if any (e.g., "J200730100005" -> "200730100005")
const numericInput = cleanInput.replace(/^[A-Z]+/, '');
// Find patient by barcode or noAntrian
const sourcePatient = allPatients.value.find(p => {
// Exact barcode match
if (p.barcode === cleanInput || p.barcode === numericInput) return true;
// Check if noAntrian includes the input
const noAntrianUpper = (p.noAntrian || '').toUpperCase();
if (noAntrianUpper.includes(cleanInput) || noAntrianUpper.includes(numericInput)) return true;
// Try extracting number from noAntrian
const noAntrianNumber = noAntrianUpper.match(/([A-Z]+)(\d+)/);
if (noAntrianNumber) {
const extractedNumber = noAntrianNumber[2];
if (extractedNumber.includes(numericInput) || numericInput.includes(extractedNumber)) return true;
}
return false;
});
if (!sourcePatient) {
return { success: false, message: "Pasien tidak ditemukan. Pastikan barcode/nomor antrian benar." };
}
// Check if patient already has antrean klinik ruang for this room
const existingAntrean = allPatients.value.find(p =>
p.referencePatient === sourcePatient.noAntrian &&
p.kodeKlinik === klinikRuang.kodeKlinik &&
p.nomorRuang === ruang.nomorRuang &&
p.processStage === 'klinik-ruang'
);
if (existingAntrean) {
return {
success: false,
message: `Pasien sudah memiliki antrean di ${klinikRuang.namaKlinik} Ruang ${ruang.nomorRuang}`
};
}
// Generate queue number for this specific room and tipeLayanan
const roomQueues = allPatients.value.filter(p =>
p.kodeKlinik === klinikRuang.kodeKlinik &&
p.nomorRuang === ruang.nomorRuang &&
p.tipeLayanan === tipeLayanan &&
p.processStage === 'klinik-ruang' &&
!p.noAntrian?.startsWith('K-') && // Exclude konsultasi
!p.noAntrian?.startsWith('KF-') // Exclude konsultasi Fast Track
);
const queueNumber = roomQueues.length + 1;
const prefix = tipeLayanan === 'Pemeriksaan Awal' ? 'PA' : 'TD';
// Tentukan prefix untuk Fast Track: F- untuk Fast Track
const isFastTrack = sourcePatient.fastTrack === "YA";
const fastTrackPrefix = isFastTrack ? 'F-' : '';
const queueNumberStr = String(queueNumber).padStart(3, "0");
const newNoAntrian = `${fastTrackPrefix}${prefix}${queueNumberStr}`;
const newNo = allPatients.value.length + 1;
const timestamp = new Date();
const newPatient = {
no: newNo,
jamPanggil: `${String(timestamp.getHours()).padStart(2, "0")}:${String(
timestamp.getMinutes()
).padStart(2, "0")}`,
barcode: sourcePatient.barcode,
noAntrian: `${newNoAntrian} | ${klinikRuang.namaKlinik} - ${ruang.namaRuang} - ${tipeLayanan}`,
noAntrianRuang: `${klinikRuang.namaKlinik} - ${ruang.namaRuang} | ${newNoAntrian}`,
shift: sourcePatient.shift || "Shift 1",
klinik: klinikRuang.namaKlinik,
ruang: ruang.namaRuang,
kodeKlinik: klinikRuang.kodeKlinik,
nomorRuang: ruang.nomorRuang,
nomorScreen: ruang.nomorScreen,
tipeLayanan: tipeLayanan,
fastTrack: sourcePatient.fastTrack || "TIDAK",
pembayaran: sourcePatient.pembayaran || "UMUM",
status: "anjungan",
processStage: "klinik-ruang",
createdAt: sourcePatient.createdAt || timestamp.toISOString(), // Gunakan createdAt dari pasien awal
referencePatient: sourcePatient.noAntrian,
sourcePatientNo: sourcePatient.no,
};
allPatients.value.push(newPatient);
return {
success: true,
message: `Antrean ${tipeLayanan} berhasil dibuat: ${newPatient.noAntrian.split(" |")[0]} untuk ${klinikRuang.namaKlinik} Ruang ${ruang.nomorRuang}`,
patient: newPatient,
};
};
// Get patients by klinik and ruang
const getPatientsByKlinikRuang = (kodeKlinik, nomorRuang, tipeLayanan = null) => {
return computed(() => {
let patients = allPatients.value.filter(p =>
p.kodeKlinik === kodeKlinik &&
p.nomorRuang === nomorRuang &&
p.processStage === 'klinik-ruang'
);
if (tipeLayanan) {
patients = patients.filter(p => p.tipeLayanan === tipeLayanan);
}
return {
all: patients,
anjungan: patients.filter(p => p.status === 'anjungan'),
diLoket: patients.filter(p => p.status === 'di-loket'),
terlambat: patients.filter(p => p.status === 'terlambat'),
pending: patients.filter(p => p.status === 'pending'),
};
});
};
// Call next patient for a specific room and tipeLayanan
const callNextKlinikRuang = (kodeKlinik, nomorRuang, tipeLayanan, allowMultiple = false) => {
const patients = allPatients.value.filter(p =>
p.kodeKlinik === kodeKlinik &&
p.nomorRuang === nomorRuang &&
p.tipeLayanan === tipeLayanan &&
p.processStage === 'klinik-ruang' &&
(p.status === 'anjungan' || (allowMultiple && p.status === 'di-loket'))
).sort((a, b) => {
// Sort by status priority first: anjungan=1, di-loket=2
const statusPriority = { 'anjungan': 1, 'di-loket': 2 };
const priorityDiff = (statusPriority[a.status] || 99) - (statusPriority[b.status] || 99);
if (priorityDiff !== 0) return priorityDiff;
const numA = parseInt(a.noAntrian?.match(/\d+/)?.[0] || '999');
const numB = parseInt(b.noAntrian?.match(/\d+/)?.[0] || '999');
return numA - numB;
});
if (patients.length === 0) {
return { success: false, message: `Tidak ada antrian ${tipeLayanan} yang menunggu` };
}
const nextPatient = patients[0];
const index = allPatients.value.findIndex(p => p.no === nextPatient.no);
if (index !== -1) {
allPatients.value[index] = {
...allPatients.value[index],
status: "di-loket",
lastCalledAt: new Date().toISOString()
};
}
return {
success: true,
message: `Memanggil ${nextPatient.noAntrian.split(" |")[0]}`,
patient: allPatients.value[index]
};
};
// Process patient in klinik ruang (set as current processing)
const processPatientKlinikRuang = (patient, action, kodeKlinik, nomorRuang) => {
const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
if (patientIndex === -1) return { success: false, message: "Pasien tidak ditemukan" };
const specificId = `${kodeKlinik}-${nomorRuang}`;
const storageKey = `klinik-ruang-${specificId}`;
const pCode = patient.noAntrian.split(" |")[0];
let message = "";
switch (action) {
case "proses":
currentProcessingPatient.value[storageKey] = allPatients.value[patientIndex];
message = `Memproses ${pCode}`;
break;
case "selesai":
allPatients.value[patientIndex] = { ...allPatients.value[patientIndex], status: "processed" };
currentProcessingPatient.value[storageKey] = null;
message = `Pasien ${pCode} selesai diproses`;
break;
case "terlambat":
allPatients.value[patientIndex] = { ...allPatients.value[patientIndex], status: "terlambat" };
currentProcessingPatient.value[storageKey] = null;
message = `Pasien ${pCode} ditandai terlambat`;
break;
case "pending":
allPatients.value[patientIndex] = { ...allPatients.value[patientIndex], status: "pending" };
currentProcessingPatient.value[storageKey] = null;
message = `Pasien ${pCode} di-pending`;
break;
}
return { success: true, message };
};
const changeKlinik = (patient, newKlinik, adminType = 'loket', specificId = null) => {
const patientIndex = allPatients.value.findIndex(p => p.no === patient.no);
if (patientIndex === -1) return { success: false, message: "Pasien tidak ditemukan" };
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
klinik: newKlinik.name,
kodeKlinik: newKlinik.kode
};
const key = specificId ? `${adminType}-${specificId}` : adminType;
if (currentProcessingPatient.value[key]?.no === patient.no) {
currentProcessingPatient.value[key] = {
...currentProcessingPatient.value[key],
klinik: newKlinik.name,
kodeKlinik: newKlinik.kode
};
}
return { success: true, message: `Klinik berhasil diubah ke ${newKlinik.name}` };
};
const getCurrentProcessing = (adminType, id = null) => {
const key = id ? `${adminType}-${id}` : adminType;
return computed(() => currentProcessingPatient.value[key] || null);
};
const setCurrentProcessing = (patient, adminType, id = null) => {
const key = id ? `${adminType}-${id}` : adminType;
currentProcessingPatient.value[key] = patient;
};
const generateQueueNumber = (clinic, paymentType, isEksekutif = false) => {
const serviceType = isEksekutif ? 'E' : 'R';
const today = new Date().toISOString().split('T')[0];
// FIXED: Use the same key as initializeCountersFromSeed
const counterKey = `queue_counter_loket_shared_${today}`;
let counter = 0;
if (typeof window !== 'undefined') {
const stored = localStorage.getItem(counterKey);
counter = stored ? parseInt(stored, 10) : 0;
}
counter = counter + 1;
const loketIndex = Math.floor((counter - 1) / 999);
if (loketIndex > 13) {
counter = 1;
if (typeof window !== 'undefined') localStorage.setItem(counterKey, '1');
return `${serviceType}A001`;
}
const loketLetter = String.fromCharCode(65 + loketIndex);
const numberInLoket = ((counter - 1) % 999) + 1;
const numberPart = String(numberInLoket).padStart(3, '0');
if (typeof window !== 'undefined') localStorage.setItem(counterKey, counter.toString());
return `${serviceType}${loketLetter}${numberPart}`;
};
// Register patient from Anjungan (onsite registration)
const registerPatientFromAnjungan = (clinic, paymentType, visitType = 'SEKARANG', visitDate = null, shift = 'Shift 1', namaDokter = null, isFastTrack = false, fastTrackData = null, loketId = null, loket = null) => {
// 1. Validasi keberadaan (prevent duplicates)
// Gunakan date today untuk check-in sync
const timestamp = new Date();
// Generate barcode FIRST to check for existence
const barcode = generateBarcode([], allPatients);
// Check EXACT barcode match prevent duplicate submission
const duplicate = allPatients.value.find(p => p.barcode === barcode);
if (duplicate) {
return {
success: false,
message: "Pasien dengan barcode ini sudah terdaftar untuk hari ini.",
patient: duplicate
};
}
const newNo = allPatients.value.length > 0
? Math.max(...allPatients.value.map(p => p.no)) + 1
: 1;
const visitDateTime = visitDate ? new Date(visitDate) : timestamp;
const jamPanggil = visitDate
? `${String(visitDateTime.getHours()).padStart(2, "0")}:${String(visitDateTime.getMinutes()).padStart(2, "0")}`
: `${String(timestamp.getHours()).padStart(2, "0")}:${String(timestamp.getMinutes()).padStart(2, "0")}`;
// Tentukan apakah pasien Eksekutif/Grand Pavilion (jika ada namaDokter, berarti Eksekutif)
const isEksekutif = namaDokter !== null && namaDokter !== undefined && namaDokter !== '';
// Generate nomor antrean dengan format baru: R/E + Loket (A-N) + 3 digit
const queueNumber = generateQueueNumber(clinic, paymentType, isEksekutif);
const finalQueueNumber = isFastTrack ? `F-${queueNumber}` : queueNumber;
const noAntrian = `${finalQueueNumber} | Onsite - ${barcode}`;
const status = 'menunggu';
const newPatient = {
no: newNo,
jamPanggil: jamPanggil,
barcode: barcode,
noAntrian: noAntrian,
shift: shift,
klinik: clinic.name || clinic,
kodeKlinik: clinic.kode || null, // Essential for filtering
fastTrack: isFastTrack ? "YA" : "TIDAK",
pembayaran: paymentType,
noRM: `RM-${barcode.slice(-6)}`,
status: status,
processStage: "loket",
createdAt: timestamp.toISOString(),
registrationType: 'onsite',
visitType: visitType,
visitDate: visitDate || timestamp.toISOString().substring(0, 10),
namaDokter: namaDokter || null,
loketId: loketId, // Optional loketId
loket: loket, // Optional loket name
calledByAdmin: false,
penanggungJawab: (isFastTrack && fastTrackData) ? fastTrackData.penanggungJawab : null,
alasanFastTrack: (isFastTrack && fastTrackData) ? fastTrackData.alasanFastTrack : null,
};
// Auto-assign Loket ID if not provided, based on Clinic Mapping
// fulfill requirement: "adjust based on loket id depending on creation"
if (!newPatient.loketId && newPatient.kodeKlinik) {
const allLokets = loketStore.lokets || [];
const targetLoket = allLokets.find(l =>
l.pelayanan && Array.isArray(l.pelayanan) && l.pelayanan.includes(newPatient.kodeKlinik)
);
if (targetLoket) {
newPatient.loketId = targetLoket.id;
if (!newPatient.loket) newPatient.loket = targetLoket.namaLoket;
console.log(`✅ Auto-assigned Onsite Ticket ${newPatient.noAntrian} to Loket ${targetLoket.id} (${targetLoket.namaLoket})`);
}
}
allPatients.value.push(newPatient);
incrementBarcodeCounter();
return {
success: true,
message: `Pendaftaran ${clinic.name || clinic} berhasil diproses.`,
patient: newPatient,
};
};
/**
* Register REGULER patient via API
* POST to http://10.10.150.131:8089/api/v1/tiket/generate
*/
const registerRegulerPatientViaApi = async (clinic, paymentType, visitType = 'SEKARANG', isFastTrack = false, fastTrackData = null) => {
try {
console.log('🔄 [queueStore] Generating ticket via API for REGULER patient...');
console.log('📋 [queueStore] Payment Type:', paymentType, '| Clinic:', clinic.name, '| Clinic Code:', clinic.kode);
// 1. Find appropriate idloket based on BOTH clinic code AND payment type
const allLokets = loketStore.lokets || [];
// Determine payment type for matching (normalize BPJS to JKN for API compatibility)
const paymentTypeForMatching = paymentType === "BPJS" ? "JKN" : paymentType;
console.log('🔍 [queueStore] Searching lokets...');
console.log(' Total lokets:', allLokets.length);
console.log(' API lokets (id < 1000):', allLokets.filter(l => l.source === 'api' && l.id < 1000).length);
console.log(' Looking for clinic:', clinic.kode, 'payment:', paymentTypeForMatching);
// Find loket that handles BOTH the clinic AND the payment type
const targetLoket = allLokets.find(l => {
// Check source: only use API lokets (id < 1000), not local eksekutif
if (l.source !== 'api' || l.id >= 1000) return false;
// Check if loket handles the clinic
const handlesClinic = l.pelayanan && Array.isArray(l.pelayanan) && l.pelayanan.includes(clinic.kode);
if (handlesClinic) {
// Debug: This loket handles the clinic, now check payment
console.log(` ✓ Loket ${l.id} (${l.namaLoket}) handles clinic ${clinic.kode}`);
console.log(` Pembayaran array:`, l.pembayaran);
// NEW: Use isPaymentCompatible helper for robust payment matching
const acceptsPayment = isPaymentCompatible(paymentTypeForMatching, l.pembayaran);
console.log(` Accepts payment ${paymentTypeForMatching}:`, acceptsPayment);
if (acceptsPayment) {
console.log(` ✅ MATCH FOUND: Loket ${l.id}`);
return true;
}
}
return false;
});
// BLOCK REGISTRATION: No fallback to loket 2
if (!targetLoket) {
console.error(`❌ [queueStore] No loket found for clinic ${clinic.kode} (${clinic.name}) with payment ${paymentTypeForMatching}`);
console.warn(`⚠️ [queueStore] Available lokets:`, allLokets.filter(l => l.source === 'api').map(l => ({
id: l.id,
nama: l.namaLoket,
pelayanan: l.pelayanan,
pembayaran: l.pembayaran
})));
return {
success: false,
message: `Maaf, klinik "${clinic.name}" dengan pembayaran "${paymentTypeForMatching}" belum tersedia. Silakan hubungi petugas pendaftaran.`
};
}
console.log('🎯 [queueStore] Target Loket:', `${targetLoket.namaLoket} (ID: ${targetLoket.id})`, '| Accepts Payment:', targetLoket.pembayaran);
// 2. Determine idpembayaran based on paymentType
const idloket = String(targetLoket.id);
// BPJS (JKN) = "2", UMUM and others = "1"
const idpembayaran = paymentType === "BPJS" ? "2" : "1";
// 3. Prepare API Body
const body = {
idloket: idloket,
dokter: "",
idklinik: String(clinic.id),
namaklinik: clinic.name,
idpembayaran: idpembayaran,
statuspasien: "1",
statuspasien2: "2",
idklinikstatus: "1"
};
console.log('📤 [queueStore] API Body:', body);
// 3. Call API
const response = await fetch('http://10.10.150.131:8089/api/v1/tiket/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
if (!response.ok) {
throw new Error(`API error! status: ${response.status}`);
}
const result = await response.json();
console.log('📥 [queueStore] API Response:', result);
if (result.metadata && result.metadata.code !== 200) {
return { success: false, message: result.message || 'Gagal generate barcode via API' };
}
const apiData = result.data;
if (!apiData || !apiData.barcode) {
return { success: false, message: 'Data barcode tidak valid dari API' };
}
// 4. Map API response to Store Format
const timestamp = new Date();
const newNo = allPatients.value.length > 0
? Math.max(...allPatients.value.map(p => p.no)) + 1
: 1;
// Gunakan waktu dari API jika tersedia
const jamPanggil = apiData.waktutiket ||
`${String(timestamp.getHours()).padStart(2, "0")}:${String(timestamp.getMinutes()).padStart(2, "0")}`;
const barcode = apiData.barcode;
// Penomoran tiket menggunakan "ticket" dari API
const queueNumber = apiData.ticket || apiData.barcode;
const finalQueueNumber = isFastTrack ? `F-${queueNumber}` : queueNumber;
const noAntrian = `${finalQueueNumber} | Onsite - ${barcode}`;
const newPatient = {
no: newNo,
jamPanggil: jamPanggil,
barcode: barcode,
noAntrian: noAntrian,
shift: apiData.shift || 'Shift 1',
klinik: clinic.name,
kodeKlinik: clinic.kode,
fastTrack: isFastTrack ? "YA" : "TIDAK",
pembayaran: paymentType,
noRM: `RM-${barcode.slice(-6)}`,
status: 'menunggu',
processStage: "loket",
createdAt: apiData.tangaltiket ? `${apiData.tangaltiket}T${apiData.waktutiket || '00:00:00'}` : timestamp.toISOString(),
registrationType: 'onsite',
visitType: visitType,
visitDate: apiData.tangaltiket || timestamp.toISOString().substring(0, 10),
namaDokter: null,
loketId: parseInt(idloket),
loket: targetLoket ? targetLoket.namaLoket : null,
calledByAdmin: false,
penanggungJawab: (isFastTrack && fastTrackData) ? fastTrackData.penanggungJawab : null,
alasanFastTrack: (isFastTrack && fastTrackData) ? fastTrackData.alasanFastTrack : null,
// Additional API fields
idvisit: 1, // Default menunggu
idtiket: apiData.id
};
allPatients.value.push(newPatient);
// NOTE: Kita tidak perlu incrementBarcodeCounter() di sini karena barcode berasal dari API
console.log(`✅ [queueStore] Successfully registered REGULER patient via API: ${noAntrian}`);
return {
success: true,
message: `Pendaftaran ${clinic.name} berhasil via API.`,
patient: newPatient
};
} catch (error) {
console.error('❌ [queueStore] Error generating ticket via API:', error);
return {
success: false,
message: `Gagal pendaftaran API: ${error.message}`
};
}
};
/**
* Check-in patient via API
* POST to http://10.10.150.131:8089/api/v1/tiket/checkin
*/
const checkInPatientViaApi = async (barcode) => {
try {
console.log(`🔄 [queueStore] Syncing check-in via API for barcode: ${barcode}...`);
const body = {
barcode: barcode,
statuspasien: "5",
statuspasien2: "6",
idklinikstatus: "1",
idklinikstatus2: "2"
};
console.log('📤 [queueStore] Check-in API Body:', body);
const response = await fetch('http://10.10.150.131:8089/api/v1/tiket/checkin', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
if (!response.ok) {
throw new Error(`API error! status: ${response.status}`);
}
const result = await response.json();
console.log('📥 [queueStore] Check-in API Response:', result);
return {
success: true,
data: result
};
} catch (error) {
console.error('❌ [queueStore] Error syncing check-in via API:', error);
return {
success: false,
message: `Gagal sync check-in API: ${error.message}`
};
}
};
// Check-in patient (update status from anjungan to di-loket)
// IMPORTANT: Hanya menggunakan EXACT barcode match untuk menghindari false positive
// Format barcode: YYMMDD + 5 digit (contoh: 26011500001)
// Jangan gunakan fallback ke noAntrian atau no karena bisa menyebabkan false positive
const checkInPatient = async (patientIdOrBarcode) => {
console.log('🔍 checkInPatient called with:', patientIdOrBarcode);
console.log('📊 Total patients in store:', allPatients.value.length);
// Clean input - remove whitespace and normalize
const cleanInput = String(patientIdOrBarcode).trim();
// PRIORITAS: Hanya cari dengan EXACT barcode match (case-insensitive, whitespace-insensitive)
// Format barcode: YYMMDD + 5 digit (contoh: 26011500001)
// Jangan gunakan fallback ke noAntrian atau no karena bisa menyebabkan false positive
const patientIndex = allPatients.value.findIndex(p => {
// Normalize barcode untuk comparison
const patientBarcode = String(p.barcode || '').trim();
// EXACT barcode match (case-insensitive, whitespace-insensitive)
// Ini adalah satu-satunya cara yang aman untuk match pasien
if (patientBarcode === cleanInput ||
patientBarcode.toLowerCase() === cleanInput.toLowerCase()) {
console.log('✅ Found by exact barcode match:', patientBarcode, '===', cleanInput);
return true;
}
return false;
});
if (patientIndex === -1) {
console.log('❌ Patient not found. Searched for barcode:', cleanInput);
console.log('📋 Available barcodes (first 10):', allPatients.value.slice(0, 10).map(p => ({
no: p.no,
barcode: p.barcode,
noAntrian: p.noAntrian?.split(' |')[0]
})));
return { success: false, message: `Pasien dengan barcode ${cleanInput} tidak ditemukan. Pastikan barcode benar (format: YYMMDD + 5 digit, contoh: 26011500001).` };
}
// IMPORTANT: Get fresh patient data from array to avoid stale data
// Use the patientIndex we found earlier, but get fresh data from array
const patient = allPatients.value[patientIndex];
console.log('✅ Patient found (fresh):', {
no: patient.no,
barcode: patient.barcode,
noAntrian: patient.noAntrian,
status: patient.status,
processStage: patient.processStage
});
// Only allow check-in if status is anjungan (sudah dipanggil) or pending
// Pasien dengan status "menunggu" belum bisa check-in (belum dipanggil)
if (patient.status === 'menunggu') {
console.log('⚠️ Patient status is menunggu (belum dipanggil):', patient.status);
return {
success: false,
message: `Pasien belum dipanggil oleh admin loket. Mohon menunggu hingga nomor antrean Anda dipanggil.`
};
}
// Check if already checked in
if (patient.status === 'di-loket') {
console.log('⚠️ Patient already checked in:', patient.status);
return {
success: false,
message: `Pasien sudah melakukan check-in sebelumnya. Status saat ini: ${patient.status}`
};
}
if (patient.status !== 'anjungan' && patient.status !== 'pending') {
console.log('⚠️ Patient status is not anjungan/pending:', patient.status);
return {
success: false,
message: `Pasien tidak dapat check-in. Status saat ini: ${patient.status}`
};
}
// Update status to di-loket using the patientIndex
allPatients.value[patientIndex] = {
...allPatients.value[patientIndex],
status: "di-loket",
};
syncApiPatientStatus(allPatients.value[patientIndex], "di-loket");
console.log('✅ Check-in successful locally, patient status updated to di-loket');
// Sync to API
const apiSyncResult = await checkInPatientViaApi(allPatients.value[patientIndex].barcode);
if (!apiSyncResult.success) {
console.warn('⚠️ Check-in API sync failed:', apiSyncResult.message);
// We still return true because local state is updated, but we could also return failure if critical
}
return {
success: true,
message: `Check-in berhasil. Pasien ${patient.noAntrian.split(" |")[0]} siap diproses di loket.`,
patient: allPatients.value[patientIndex],
};
};
// FIX: Explicit implementation of processNextQueue to target ONLY 'di-loket' patients
const processNextQueueCorrected = (adminType = 'loket', specificId = null) => {
// 1. Determine target stage and key
const stageMap = { 'loket': 'loket', 'klinik': 'klinik', 'penunjang': 'penunjang' };
const targetStage = stageMap[adminType];
const key = specificId ? `${adminType}-${specificId}` : adminType;
console.log(`🚀 [processNextQueue] Processing for ${key} (Stage: ${targetStage})`);
// 2. Find next patient ONLY from 'di-loket' status
// These are patients who have already checked in or been moved to 'di-loket'
const eligiblePatients = allPatients.value.filter(p =>
p.status === 'di-loket' &&
p.processStage === targetStage &&
(adminType !== 'loket' || String(p.loketId) === String(specificId))
);
// Exclude the current processing patient to find the TRULY next one
const currentNum = currentProcessingPatient.value[key]?.no;
const waitingDiLoket = eligiblePatients.filter(p => p.no !== currentNum);
// 3. Sort by priority (Fast Track, then No)
const sorted = sortPatientsForCalling(waitingDiLoket);
const nextPatient = sorted[0];
if (!nextPatient) {
return { success: false, message: "Tidak ada antrean 'Di Loket' yang menunggu untuk diproses." };
}
// 4. Update Current Processing ISOLATED by key
// We don't change status because it's already 'di-loket'
// But we update the lastCalledAt and set it as current
const index = allPatients.value.findIndex(p => p.no === nextPatient.no);
if (index !== -1) {
const updatedPatient = {
...allPatients.value[index],
lastCalledAt: new Date().toISOString()
};
allPatients.value[index] = updatedPatient;
currentProcessingPatient.value[key] = updatedPatient;
return {
success: true,
message: `Memproses ${nextPatient.noAntrian.split(" |")[0]}`,
patient: updatedPatient
};
}
return { success: false, message: "Gagal memproses antrean." };
};
return {
// State
allPatients,
resetPatients,
ensureInitialData,
quotaUsed,
currentProcessingPatient,
kliniks,
penunjangs,
// API Patient State
apiPatientsPerLoket,
isLoadingPatients,
apiPatientsError,
// Computed
totalPasien,
// Actions
callNext,
callMultiplePatients,
processPatient,
callProcessingPatient,
createAntreanKlinik,
createAntreanPenunjang,
createAntreanKlinikRuang,
scanAndCreateAntreanKlinikRuang,
getPatientsByKlinikRuang,
callNextKlinikRuang,
processPatientKlinikRuang,
changeKlinik,
pindahKlinikRuang,
konsultasiKlinikRuang,
processNextQueue: processNextQueueCorrected,
getPatientsByStage,
getTotalPasienByStage,
getCurrentProcessing,
setCurrentProcessing,
registerPatientFromAnjungan,
checkInPatient,
generateQueueNumber,
generateBarcode,
incrementBarcodeCounter,
syncCountersWithState,
// API Patient Actions
fetchPatientsForLoket,
fetchAllPatients,
getPatientsForLoket,
mapStatusFromDeskripsi,
mapApiPatientToStoreFormat,
registerRegulerPatientViaApi,
checkInPatientViaApi,
checkAndResetDaily,
isTodayPatient,
getResetThreshold,
initWebSocket,
disconnectWebSocket,
isWsConnected,
};
}, {
persist: {
key: 'queue-store-state',
storage: typeof window !== 'undefined' ? localStorage : undefined,
paths: ['allPatients', 'quotaUsed', 'currentProcessingPatient', 'apiPatientsPerLoket', 'lastUpdated'],
serializer: {
deserialize: JSON.parse,
serialize: JSON.stringify,
},
restore: (value) => {
// Ensure allPatients is always an array
if (value && value.allPatients && !Array.isArray(value.allPatients)) {
value.allPatients = [];
}
return value;
},
},
});