has('per_page') ? $request->input('per_page') : 10; $results = DB::connection('oldlms')->table('tx_prescriptions') ->join('tx_prescription_orders', 'tx_prescription_orders.nIDPrescription', '=', 'tx_prescriptions.nID') ->join('tm_users', 'tm_users.nID', '=', 'tx_prescriptions.nIDUser') ->when($request->input('search'), function ($query, $search) { $query->where(function ($query) use ($search) { $query->orWhere('tx_prescriptions.sKodeResep', 'like', "%" . $search . "%") ->orWhere('tm_users.sFirstName', 'like', "%" . $search . "%"); }); }) ->when($request->has('orderBy'), function ($query) use ($request) { $orderBy = $request->orderBy; $direction = $request->order ?? 'asc'; if($orderBy == 'apotek') { $orderBy = 'nIDApotek'; } $query->orderBy($orderBy, $direction); }) ->when($request->input('start_date') && !$request->input('end_date'), function ($query, $start_date) { $query->where(function ($query) use ($start_date) { $query->where('tx_prescriptions.dTanggalresep', '<', $start_date); }); }) ->when($request->input('status'), function ($query, $status) { $query->where(function ($query) use ($status) { $query->where('tx_prescription_orders.sStatus', '=', $status); }); }) ->select( 'tx_prescriptions.nID as id', 'tx_prescription_orders.nID as nID_orders', 'tx_prescriptions.nIDUser', 'tx_prescriptions.sKodeResep as no_resep', 'tx_prescriptions.dTanggalResep as tanggal', 'tx_prescription_orders.nIDApotek', 'tx_prescription_orders.sStatus as status', 'tx_prescription_orders.sStatus', DB::raw(' CASE WHEN tx_prescription_orders.sStatus = "waiting_pharmacy" THEN "Diterima" WHEN tx_prescription_orders.sStatus = "order_prepared" THEN "Siap Diambil" WHEN tx_prescription_orders.sStatus = "ready" THEN "Cari Kurir" WHEN tx_prescription_orders.sStatus = "waiting_for_courir" THEN "Kurir Sudah Ambil Pesanan" WHEN tx_prescription_orders.sStatus = "package_picked_up" THEN "Sedang diantar ke Alamat Tujuan" WHEN tx_prescription_orders.sStatus = "package_on_delivery" THEN "Selesai" ELSE "" END AS button_accept'), DB::raw('CONCAT( COALESCE(tm_users.sFirstName, ""), " ", COALESCE(tm_users.sMiddleName, ""), " ", COALESCE(tm_users.sLastName, "") ) as pasien'), DB::raw(' (SELECT CONCAT( COALESCE(u.sFirstName, ""), " ", COALESCE(u.sMiddleName, ""), " ", COALESCE(u.sLastName, "") ) FROM tm_dokter d LEFT JOIN tm_users u ON u.nID = d.nIDUser WHERE d.nID = tx_prescriptions.nIDDokter LIMIT 1) AS nama_dokter '), DB::raw(' (SELECT s.sSpesialis FROM tm_dokter d LEFT JOIN tm_spesialis s ON s.nID = d.nIDSpesialis WHERE d.nID = tx_prescriptions.nIDDokter LIMIT 1) AS spesialis '), DB::raw(' (SELECT t.sSIP FROM tm_dokter d LEFT JOIN tx_jadwal_dokter t ON t.nIDDokter = d.nID WHERE d.nID = tx_prescriptions.nIDDokter LIMIT 1) AS sip '), DB::raw(' (SELECT u.sPhone FROM tm_dokter d LEFT JOIN tm_users u ON u.nID = d.nIDUser WHERE d.nID = tx_prescriptions.nIDDokter LIMIT 1) AS no_ponsel_dokter '), DB::raw(' (SELECT tm_users_detail.dTanggalLahir FROM tm_users_detail WHERE tm_users_detail.nIDUser = tm_users.nID LIMIT 1) AS tgl_lahir_pasien '), DB::raw(' (SELECT CASE WHEN tm_users_detail.nIDJenisKelamin = 1 THEN "Male" ELSE "Female" END FROM tm_users_detail WHERE tm_users_detail.nIDUser = tm_users.nID LIMIT 1) AS jenis_kelamin_pasien '), DB::raw(' (SELECT CONCAT(tm_users_detail.sHeight, "/", tm_users_detail.sWeight) FROM tm_users_detail WHERE tm_users_detail.nIDUser = tm_users.nID LIMIT 1) AS tinggi_berat '), DB::raw(' (SELECT tm_users_insurance.sNoPolis FROM tm_users_insurance LEFT JOIN tm_insurance ON tm_users_insurance.nIDInsurance = tm_insurance.nID WHERE tm_users_insurance.nIDUser = tx_prescriptions.nIDUser LIMIT 1) AS no_polis '), DB::raw(' (SELECT tm_insurance.sInsurance FROM tm_users_insurance LEFT JOIN tm_insurance ON tm_users_insurance.nIDInsurance = tm_insurance.nID WHERE tm_users_insurance.nIDUser = tx_prescriptions.nIDUser LIMIT 1) AS perusahaan_asuransi '), DB::raw(' (SELECT tm_users_insurance.sCorporateName FROM tm_users_insurance LEFT JOIN tm_insurance ON tm_users_insurance.nIDInsurance = tm_insurance.nID WHERE tm_users_insurance.nIDUser = tx_prescriptions.nIDUser LIMIT 1) AS nama_perusahaan '), DB::raw(' (SELECT tm_users_insurance.sProductCode FROM tm_users_insurance LEFT JOIN tm_insurance ON tm_users_insurance.nIDInsurance = tm_insurance.nID WHERE tm_users_insurance.nIDUser = tx_prescriptions.nIDUser LIMIT 1) AS kode_produk '), DB::raw(' ( SELECT CASE WHEN tm_users_insurance.sPlanCode = "A" THEN "Alba" WHEN tm_users_insurance.sPlanCode = "B" THEN "Blue" WHEN tm_users_insurance.sPlanCode = "S" THEN "Silver" WHEN tm_users_insurance.sPlanCode = "G" THEN "Gold" WHEN tm_users_insurance.sPlanCode = "P" THEN "Platinum" WHEN tm_users_insurance.sPlanCode = "D" THEN "Diamond" ELSE "" END AS kelas_asuransi FROM tm_users_insurance LEFT JOIN tm_insurance ON tm_users_insurance.nIDInsurance = tm_insurance.nID WHERE tm_users_insurance.nIDUser = tx_prescriptions.nIDUser LIMIT 1 ) AS kelas_asuransi '), DB::raw(' ( SELECT CASE WHEN tm_hubungan_keluarga.sHubunganKeluarga = "Husband" THEN "S" WHEN tm_hubungan_keluarga.sHubunganKeluarga = "Wife" THEN "I" WHEN tm_hubungan_keluarga.sHubunganKeluarga = "Child" THEN "A" ELSE "P" END AS tipe_member FROM tm_hubungan_keluarga WHERE tm_hubungan_keluarga.nID = tm_users.nIDHubunganKeluarga LIMIT 1 ) AS tipe_member '), 'tx_prescription_orders.sAddress AS alamat_penerima', 'tx_prescription_orders.sDeliveryMethod AS pengiriman', 'tx_prescription_orders.sDeliveryPrice AS total_kirim', 'tx_prescriptions.sNoRefProvider AS noref_dokter', DB::raw('DATE_ADD(tx_prescriptions.dTanggalResep, INTERVAL 1 DAY) as valid_tanggal'), 'tx_prescriptions.sNomorPenjamin AS nomor_penjamin', DB::raw(' (SELECT tx_livechat.dCreateOn FROM tx_livechat WHERE tx_livechat.nID = tx_prescriptions.nIDLivechat LIMIT 1) AS tgl_livechat '), 'tx_prescriptions.sDiagnose as diagnosa', 'tx_prescription_orders.nDeliveryID', 'tx_prescription_orders.sDeliveryStatus' ) ->paginate($limit); // Secret key for generating the token $secret_key = env('SECRET_KEY_LMS'); // Transform the results to include the download link $results->getCollection()->transform(function ($item) use ($secret_key) { // Generate the token with the timestamp $expiry_time = time() + 86400; // Token expiry time (1 day) $token = hash_hmac('sha256', $item->id . $expiry_time, $secret_key); // Construct the download link $path = 'prescription/barcode-print-pdf/' . $item->id . '?token=' . urlencode($token) . '&expiry=' . $expiry_time; $host = $_SERVER['HTTP_HOST']; // This will give you the host like 'linksehat.dev' or 'linksehat.com' $base_url = "https://m.linksehat.dev/"; // Check if the host contains '.dev' if (strpos($host, '.com') !== false) { $base_url = "https://m.linksehat.com/"; } $item->link_download = $base_url.$path; return $item; }); $apotekIds = $results->pluck(value: 'nIDApotek')->unique()->filter(); $organizations = DB::connection('mysql')->table('organizations') ->whereIn('id', $apotekIds) ->pluck('name', 'id'); $results->getCollection()->transform(function ($item) use ($organizations) { $item->apotek = $organizations->get($item->nIDApotek, '-'); // Default to 'Unknown' if not found return $item; }); // Transform results to include allergies $results->getCollection()->transform(function ($item) use ($organizations) { // Get the allergies for each user $allergies = $this->getAllergies($item->nIDUser); // Concatenate the allergy description $alergi_desc = ''; foreach ($allergies as $row) { $alergi_desc .= $row->sAlergi . ' - ' . $row->sKeterangan . ', '; } // Set apotek and allergies data $item->apotek = $organizations->get($item->nIDApotek, '-'); // Default to 'Unknown' if not found $item->alergi_desc = rtrim($alergi_desc, ', '); // Remove the trailing comma return $item; }); // Extract unique Prescription IDs from the results $prescriptionIDs = $results->pluck('id')->unique()->filter(); // Fetch prescription items based on Prescription IDs $items = DB::connection('oldlms')->table('tx_prescription_items') ->whereIn('nIDPrescription', $prescriptionIDs) ->select('nIDPrescription', 'sItemName', 'sSigna', 'sTiming', 'sDuration', 'nQty', 'sNote') ->get() ->groupBy('nIDPrescription'); // Group items by their Prescription ID // Final transformation: Attach prescription items to each prescription $results->getCollection()->transform(function ($item) use ($items) { $item->prescription_items = $items->get($item->id, collect())->map(function ($prescriptionItem) { return [ 'sItemName' => $prescriptionItem->sItemName, 'sSigna' => $prescriptionItem->sSigna, 'sTiming' => $prescriptionItem->sTiming, 'sDuration' => $prescriptionItem->sDuration, 'nQty' => $prescriptionItem->nQty, 'sNote' => $prescriptionItem->sNote, ]; }); return $item; }); return response()->json(Helper::paginateResources($results)); } public function getAllergies($nIDUser) { return DB::connection('oldlms') ->table('tx_alergi_users as txa') ->join('tm_alergi as ta', 'ta.nID', '=', 'txa.nIDAlergi') ->select('ta.sAlergi', 'ta.sKeterangan') ->where('txa.nIDUser', $nIDUser) ->get(); } /** * Show the form for creating a new resource. * @return Renderable */ public function create() { return view('hospitalportal::create'); } /** * Store a newly created resource in storage. * @param Request $request * @return Renderable */ public function store(Request $request) { // } /** * Show the specified resource. * @param int $id * @return Renderable */ public function show($id) { return view('hospitalportal::show'); } /** * Show the form for editing the specified resource. * @param int $id * @return Renderable */ public function edit($id) { return view('hospitalportal::edit'); } /** * Update the specified resource in storage. * @param Request $request * @param int $id * @return Renderable */ public function update(Request $request, $id) { $data = ['sStatus' => $request->sStatus]; $validator = Validator::make($request->all(), [ 'sStatus' => 'required|string|max:255', ], [ 'sStatus.required' => trans('Validation.required',['attribute' => 'Status']), ]); if ($validator->fails()) { return ApiResponse::apiResponse('Bad Request', $data, $validator->errors(), 400); } else { try { // Define the valid transitions $valid_transitions = [ 'waiting_for_payment' => 'waiting_pharmacy', 'waiting_pharmacy' => 'order_prepared', 'order_prepared' => 'ready', 'ready' => 'waiting_for_courir', 'waiting_for_courir' => 'package_picked_up', 'package_picked_up' => 'package_on_delivery', 'package_on_delivery' => 'package_delivered' ]; // Get the current status from the request $inputStatus = $request->sStatus; // Check if the input status has a valid next status in the map if (isset($valid_transitions[$inputStatus])) { // Get the next status $status = $valid_transitions[$inputStatus]; // Start the transaction DB::connection('oldlms')->beginTransaction(); // Update the status in the database DB::connection('oldlms')->table('tx_prescription_orders') ->where('tx_prescription_orders.nID', '=', $id) ->update([ 'sStatus' => $status, 'sUpdateBy' => auth()->user()->id, 'dUpdateOn' => date('Y-m-d H:i:s'), ]); // Commit the transaction DB::connection('oldlms')->commit(); // Return success response return ApiResponse::apiResponse("Success", $data, trans('Message.success'), 200); } else { // If the input status is not valid, return an error return ApiResponse::apiResponse('Invalid Status', $data, 'The input status is not valid.', 400); } } catch (\Exception $e) { // Rollback the transaction if an error occurs DB::connection('oldlms')->rollBack(); // Handle error, could log or return as response return ApiResponse::apiResponse('Server Error', $data, $e->getMessage(), 500); } } } public function getDriver(Request $request, $id) { $data = ['sStatus' => $request->sStatus]; // Validation $validator = Validator::make($request->all(), [ 'sStatus' => 'required|string|max:255', ], [ 'sStatus.required' => trans('Validation.required', ['attribute' => 'Status']), ]); if ($validator->fails()) { return ApiResponse::apiResponse('Bad Request', $data, $validator->errors(), 400); } try { // Fetch prescription data $prescriptions = DB::connection('oldlms')->table('tx_prescription_orders') ->leftJoin('tx_prescriptions', 'tx_prescriptions.nID', '=', 'tx_prescription_orders.nIDPrescription') ->where('tx_prescription_orders.nID', '=', $id) ->select( 'tx_prescriptions.nIDUser', 'tx_prescriptions.nID as id_prescription', 'tx_prescriptions.sKodeResep as merchantOrderID', 'tx_prescription_orders.nIDApotek' ) ->first(); if (!$prescriptions) { return ApiResponse::apiResponse('Not Found', [], 'Prescription not found', 404); } // Fetch prescription items (medicine data) $items = DB::connection('oldlms')->table('tx_prescription_items') ->where('nIDPrescription', $prescriptions->id_prescription) ->select('nIDPrescription', 'sItemName', 'nQty', 'nHarga') ->get(); $packages = []; foreach ($items as $item) { $packages[] = [ 'name' => $item->sItemName, 'description' => $item->sItemName, 'quantity' => (float)$item->nQty, 'price' => (float)$item->nHarga, 'dimensions' => [ 'height' => 0, 'width' => 0, 'depth' => 0, 'weight' => 0, ] ]; } // Fetch pharmacy (apotek) data $apotek = DB::connection('mysql')->table('organizations') ->leftJoin('addresses', 'addresses.id', '=', 'organizations.main_address_id') ->where('organizations.id', '=', $prescriptions->nIDApotek) ->select('organizations.name as nama_apotek', 'addresses.lat', 'addresses.lng') ->first(); // Fetch patient (pasien) data $pasien = DB::connection('oldlms')->table('tm_users') ->leftJoin('tm_users_detail', 'tm_users_detail.nIDuser', '=', 'tm_users.nID') ->where('tm_users.nID', '=', $prescriptions->nIDUser) ->select( DB::raw('CONCAT( COALESCE(tm_users.sFirstName, ""), " ", COALESCE(tm_users.sMiddleName, ""), " ", COALESCE(tm_users.sLastName, "") ) as nama_pasien'), 'tm_users.sFirstName as firstname', 'tm_users.sLastName as lastname', 'tm_users.sEmail as email', 'tm_users.sPhone as phone', 'tm_users_detail.sLatitude as latitude', 'tm_users_detail.sLongitude as longitude', DB::raw('(SELECT tm_provinsi.sProvinsi FROM tm_provinsi WHERE tm_provinsi.nID = tm_users_detail.nIDProvinsi LIMIT 1) AS provinsi'), DB::raw('(SELECT tm_kota.sKota FROM tm_kota WHERE tm_kota.nID = tm_users_detail.nIDKota LIMIT 1) AS kota'), DB::raw('(SELECT tm_kecamatan.sKecamatan FROM tm_kecamatan WHERE tm_kecamatan.nID = tm_users_detail.nIDKecamatan LIMIT 1) AS kecamatan'), DB::raw('(SELECT tm_kelurahan.sKelurahan FROM tm_kelurahan WHERE tm_kelurahan.nID = tm_users_detail.nIDKelurahan LIMIT 1) AS kelurahan'), DB::raw('(SELECT tm_kelurahan.nKodePos FROM tm_kelurahan WHERE tm_kelurahan.nID = tm_users_detail.nIDKelurahan LIMIT 1) AS kode_pos') ) ->first(); if (!$pasien) { return ApiResponse::apiResponse('Not Found', [], 'Patient not found', 404); } if(!$pasien->email) { return ApiResponse::apiResponse('Not Found', [], 'Email Patient not found', 404); } if(!$pasien->phone) { return ApiResponse::apiResponse('Not Found', [], 'Phone Patient not found', 404); } // Use GrabHelper to handle the API calls $grabHelper = new GrabHelper(); $token = $grabHelper->getToken(); $body = json_encode([ "merchantOrderID" => $prescriptions->merchantOrderID, "serviceType" => "INSTANT", "vehicleType" => "BIKE", "codType" => "REGULAR", "paymentMethod" => "CASHLESS", "highValue" => false, "packages" => $packages, "origin" => [ "address" => $apotek->nama_apotek, "coordinates" => [ "latitude" => (float)$apotek->lat, "longitude" => (float)$apotek->lng ] ], "destination" => [ "address" => "{$pasien->provinsi}, {$pasien->kota}, {$pasien->kecamatan}, {$pasien->kelurahan}, {$pasien->kode_pos}", "coordinates" => [ "latitude" => (float)$pasien->latitude, "longitude" => (float)$pasien->longitude ] ], "recipient" => [ "firstName" => $pasien->firstname, "lastName" => $pasien->lastname, "email" => $pasien->email, "phone" => $grabHelper->normalizePhoneNumber($pasien->phone), "smsEnabled" => true ], "sender" => [ "firstName" => env('SENDER_NAME_GRAB'), "companyName" => env('SENDER_COMPANY_NAME_GRAB'), "email" => env('SENDER_EMAIL_GRAB'), "phone" => env('SENDER_PHONE_GRAB'), "smsEnabled" => true ], "schedule" => $grabHelper->getScheduleTimes() ]); // Create the delivery request $response = $grabHelper->createDelivery($token, $body); $data_grab = json_decode($response, true); // Transaction to update status DB::connection('oldlms')->beginTransaction(); DB::connection('oldlms')->table('tx_prescription_orders') ->where('tx_prescription_orders.nID', '=', $id) ->update([ 'nDeliveryID' => $data_grab['deliveryID'], 'sDeliveryStatus' => $data_grab['status'], 'sStatus' => 'waiting_for_courir', 'sUpdateBy' => auth()->user()->id, 'dUpdateOn' => now(), ]); $data_logs = [ 'sType' => 'out', 'sContext' => 'grab', 'sTarget' => 'deliveries/create-grab', 'sRequest' => $body, 'sResponse' => $response, 'sCreateBy' => auth()->user()->id, 'dCreateOn' => now(), ]; DB::connection('oldlms')->table('api_logs') ->insert($data_logs); DB::connection('oldlms')->commit(); // Return success response return ApiResponse::apiResponse("Success", $data_grab, trans('Message.success'), 200); } catch (\Exception $e) { // Rollback transaction on error DB::connection('oldlms')->rollBack(); return ApiResponse::apiResponse('Server Error', [], $e->getMessage(), 500); } } /** * Remove the specified resource from storage. * @param int $id * @return Renderable */ public function destroy($id) { // } }