TKK_E32230908/app/Http/Controllers/EspController.php

108 lines
3.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Models\BorrowTransaction;
use App\Models\IotMode;
class EspController extends Controller
{
/* Fungsi ini dipanggil oleh JavaScript Web saat ada Scan RFID.
Sesuai dengan URL di Web Anda: /api/esp/check-member?uid=...
*/
public function checkMember(Request $request)
{
// 1. Ambil UID dan bersihkan (Sama seperti logika scan Anda)
$uid = strtoupper(trim($request->query('uid') ?? ''));
$eventId = time() . rand(100,999);
if (!$uid) {
return response()->json(['status' => 'error', 'message' => 'Kartu tidak terdeteksi'], 400);
}
// 2. Cek Mode IOT (Hanya boleh scan jika mode 'user' atau 'scan_member')
$iot = IotMode::first();
if (!$iot) {
return response()->json(['status' => 'error', 'message' => 'Sistem Belum Siap'], 500);
}
// 3. Cari data Anggota (Sesuai struktur DB Anda: kolom 'uid')
$anggota = DB::table('anggota')
->whereRaw("UPPER(TRIM(uid)) = ?", [$uid])
->first();
if (!$anggota) {
// Kita kirim 404 agar JavaScript masuk ke blok catch "TIDAK TERDAFTAR"
return response()->json([
'status' => 'gagal',
'message' => 'Anggota tidak ditemukan'
], 404);
}
// 4. Proses Transaksi (Jika buku sudah di-scan sebelumnya)
$buku = null;
if ($iot->book_id) {
$buku = DB::table('koleksis')->where('biblio_id', $iot->book_id)->first();
if ($buku) {
// Simpan ke database transaksi asli
$trx = BorrowTransaction::create([
'anggota_id' => $anggota->id,
'koleksi_id' => $buku->biblio_id,
'tanggal_pinjam' => now(),
'tanggal_kembali' => now()->addDays(7),
'status' => 'dipinjam'
]);
// Simpan ke Cache untuk keperluan Polling/Halaman Success
Cache::put('rfid_event', [
'event_id' => $eventId,
'status' => 'berhasil',
'nama' => $anggota->nama,
'judul' => $buku->title ?? $buku->judul_koleksi,
'trx_id' => $trx->id
], now()->addSeconds(60));
}
}
// 5. Reset Mode IOT ke Standby setelah sukses scan
$iot->update([
'mode' => 'standby',
'book_id' => null
]);
// 6. Return Response yang diharapkan JavaScript Web Anda
return response()->json([
'status' => 'berhasil',
'id' => $anggota->id,
'nama' => $anggota->nama,
'judul' => $buku ? ($buku->title ?? $buku->judul_koleksi) : 'Buku tidak terdeteksi'
], 200);
}
/* ================= POLLING & MODE (TETAP SAMA) ================= */
public function mode()
{
$iot = IotMode::first();
if (!$iot) return response()->json(['status' => 'empty']);
$judul = '-';
if ($iot->book_id) {
$buku = DB::table('koleksis')->where('biblio_id', $iot->book_id)->first();
$judul = $buku->title ?? $buku->judul_koleksi ?? 'Judul Tidak Ditemukan';
}
return response()->json([
'status' => 'ok',
'mode' => $iot->mode,
'judul' => $judul,
'barcode' => $iot->book_id ?? '-'
]);
}
}