FEAT_CHATBOT

This commit is contained in:
velz 2025-02-01 10:29:43 +05:30
parent 602eabb54a
commit 941d504413
10 changed files with 562 additions and 0 deletions

View File

@ -0,0 +1,110 @@
<?php
namespace App\Controllers\Chatbot;
use BotMan\BotMan\BotMan;
class BotService
{
public static function sendMainOptions(BotMan $bot)
{
$bot->reply('Welcome! Please choose an option:', [
'reply_markup' => json_encode([
'keyboard' => [
['Card Download'],
['Network Hospital'],
['Reimbursement Claim Process'],
['Reimbursement Claim Status'],
['New Policy'],
['Renew Policy']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
])
]);
}
public static function handleCardDownload(BotMan $bot)
{
$bot->reply('Please choose an option:', [
'reply_markup' => json_encode([
'keyboard' => [
['Download Card'],
['Go Back']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
])
]);
}
public static function handleNetworkHospital(BotMan $bot)
{
$bot->reply('Please choose an option:', [
'reply_markup' => json_encode([
'keyboard' => [
['Find Hospital'],
['Go Back']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
])
]);
}
public static function handleReimbursementClaimProcess(BotMan $bot)
{
$bot->reply('Please choose an option:', [
'reply_markup' => json_encode([
'keyboard' => [
['Submit Claim'],
['Go Back']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
])
]);
}
public static function handleReimbursementClaimStatus(BotMan $bot)
{
$bot->reply('Please choose an option:', [
'reply_markup' => json_encode([
'keyboard' => [
['Check Status'],
['Go Back']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
])
]);
}
public static function handleNewPolicy(BotMan $bot)
{
$bot->reply('Please choose an option:', [
'reply_markup' => json_encode([
'keyboard' => [
['Get Quote'],
['Go Back']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
])
]);
}
public static function handleRenewPolicy(BotMan $bot)
{
$bot->reply('Please choose an option:', [
'reply_markup' => json_encode([
'keyboard' => [
['Renew Now'],
['Go Back']
],
'resize_keyboard' => true,
'one_time_keyboard' => true
])
]);
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Controllers\Chatbot;
use BotMan\BotMan\BotMan;
use BotMan\BotMan\Messages\Outgoing\Actions\ButtonTemplate;
use BotMan\BotMan\Messages\Outgoing\Actions\ElementButton;
class ClaimHandler
{
public static function handle(BotMan $bot, $option)
{
$responses = [
'reimbursement_claim_process' => "Reimbursement Claim Process: Here is a dummy response.",
'reimbursement_claim_status' => "Reimbursement Claim Status: Here is a dummy response."
];
if (isset($responses[$option])) {
$bot->reply($responses[$option]);
} else {
$bot->reply("Unknown claim option.");
}
// Send Back Button
self::sendBackButton($bot);
}
private static function sendBackButton(BotMan $bot)
{
$bot->reply(ButtonTemplate::create("Would you like to return?")
->addButton(ElementButton::create("Go Back")->type('postback')->payload("main_menu"))
);
}
}

View File

@ -0,0 +1,65 @@
<?php
// namespace App\Conversations;
namespace App\Controllers\Chatbot;
use BotMan\BotMan\Messages\Conversations\Conversation;
use BotMan\BotMan\Messages\Outgoing\Question;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
use App\Helpers\ChatbotHelper;
class EcardDownloadConversation extends Conversation
{
public function run()
{
$this->showEcardMenu();
}
protected function showEcardMenu()
{
$policy_list = ChatbotHelper::getListOfPolicies();
$buttons = [];
$question = 'Choose Policy to Download Ecard:';
if(is_array($policy_list) && count($policy_list))
{
foreach($policy_list as $policy)
{
// $question = Question::create("Choose Policy to Download Ecard:")
// ->addButtons([
// Button::create("🔹 $policy['policy_name']")->value("$policy['emp_policy_id']"),
// Button::create("◀️ Go Back")->value("go_back"),
// ]);
$buttons[] = Button::create("🔹 {$policy['policy_name']}")->value($policy['emp_policy_id'].'#'.$policy['rand_string']);
}
}
else
{
$question = 'No policy found';
}
$buttons = array_merge($buttons,[Button::create("◀️ Go Back")->value("go_back")]);
$question = Question::create($question)
->addButtons($buttons);
$this->bot->ask($question, function ($answer) {
// print_r($answer->getValue());die();
switch ($answer->getValue()) {
case "go_back":
$this->bot->startConversation(new MainMenuConversation());
break;
case is_string($answer->getValue()) && is_array(explode('#',$answer->getValue())) && count((explode('#',$answer->getValue()))) == 2:
$link = base_url().'/download-e-card/' . explode('#',$answer->getValue())[1].'/1';
$this->say('Click here to downlad: <a href="'.$link.'" target="_blank">Ecard</a>');
$this->bot->startConversation(new EcardDownloadConversation()); // ✅ Restart the
break;
default:
$this->say("Invalid selection. Please choose an option.");
$this->bot->startConversation(new EcardDownloadConversation()); // ✅ Restart the conversation
break;
}
});
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Controllers\Chatbot;
use BotMan\BotMan\Messages\Conversations\Conversation;
use BotMan\BotMan\Messages\Outgoing\Question;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
class MainMenuConversation extends Conversation
{
public function run()
{
$this->showMainMenu();
}
protected function showMainMenu()
{
$question = Question::create("Please choose")
->addButtons([
Button::create("📄 Ecard Download")->value("ecard_download"),
Button::create("🏥 Network Hospital")->value("network_hospital"),
Button::create("💰 Reimbursement Claim Process")->value("reimbursement_claim"),
Button::create("📑 Reimbursement Claim Status")->value("reimbursement_status"),
Button::create("🆕 New Policy")->value("new_policy"),
Button::create("🔄 Renew Policy")->value("renew_policy"),
]);
$this->bot->ask($question, function ($answer) {
switch ($answer->getValue()) {
case "ecard_download":
$this->say("📄 Ecard Download Menu:");
$this->bot->startConversation(new EcardDownloadConversation());
break;
case "network_hospital":
$this->say("🏥 Network Hospital Menu:");
$this->bot->startConversation(new NetworkHospitalConversation());
break;
case "reimbursement_claim":
$this->say("Reimbursement Claim Process selected. (Dummy Response)");
break;
case "reimbursement_status":
$this->say("Reimbursement Claim Status selected. (Dummy Response)");
break;
case "new_policy":
$this->say("New Policy selected. (Dummy Response)");
break;
case "renew_policy":
$this->say("Renew Policy selected. (Dummy Response)");
break;
default:
$this->say("Invalid selection. Please choose an option.");
$this->showMainMenu();
break;
}
});
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Controllers\Chatbot;
use BotMan\BotMan\BotMan;
use BotMan\BotMan\Messages\Outgoing\Actions\ButtonTemplate;
use BotMan\BotMan\Messages\Outgoing\Actions\ElementButton;
class PolicyHandler
{
public static function handle(BotMan $bot, $option)
{
$responses = [
'ecard_download' => "Ecard Download: Here is a dummy response.",
'network_hospital' => "Network Hospital: Here is a dummy response.",
'new_policy' => "New Policy: Here is a dummy response.",
'renew_policy' => "Renew Policy: Here is a dummy response."
];
if (isset($responses[$option])) {
$bot->reply($responses[$option]);
} else {
$bot->reply("Unknown policy option.");
}
// Send Back Button
self::sendBackButton($bot);
}
private static function sendBackButton(BotMan $bot)
{
$bot->reply(ButtonTemplate::create("Would you like to return?")
->addButton(ElementButton::create("Go Back")->type('postback')->payload("main_menu"))
);
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace App\Controllers;
use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Drivers\DriverManager;
use BotMan\BotMan\Cache\SymfonyCache;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use BotMan\Drivers\Web\WebDriver;
use App\Controllers\Chatbot\MainMenuConversation;
use App\Helpers\ChatbotHelper;
class ChatbotControllerNew extends BaseController
{
protected $myLogger;
protected $session;
protected $botman;
public function __construct()
{
set_session_context('CHATBOT CON');
$this->myLogger = \Config\Services::mylogger();
$this->session = \Config\Services::session();
$this->myLogger->logme('error', 'CALLED');
// Load BotMan driver
DriverManager::loadDriver(WebDriver::class);
// Setup BotMan with cache
$cache = new SymfonyCache(new FilesystemAdapter());
$this->botman = BotManFactory::create([], $cache);
// Retrieve user ID from session or request
$extras = request()->getGet('conf');
$extras = json_decode($extras);
$router = service('router');
$method = $router->methodName();
$this->myLogger->logme('error', $method);
if (isset($extras) && $method == 'widget') {
$extras = $extras->parameters;
$this->session->set('CHATBOT_USER_ID', $extras->employee_id);
}
$this->myLogger->logme('error', $this->session->get('CHATBOT_USER_ID'));
// print_rr(ChatbotHelper::getListOfPolicies());die();
}
public function index()
{
// Start the Main Menu when user says "hi" or "start"
$this->botman->hears('start|hi|hello', function (BotMan $bot) {
$bot->reply('How how can i assit?');
$bot->startConversation(new MainMenuConversation());
});
// $this->botman->hears('main_menu', function (BotMan $bot) {
// BotService::sendMainOptions($bot);
// });
// // Register Option Handlers
// $this->registerHandlers();
// Listen for Messages
$this->botman->listen();
}
private function registerHandlers()
{
// Handling Policy and Claims
$this->botman->hears('group:policy:{option}', [\App\Controllers\Chatbot\PolicyHandler::class, 'handle']);
$this->botman->hears('group:claim:{option}', [\App\Libraries\Chatbot\ClaimHandler::class, 'handle']);
}
public function chatbot()
{
$this->loadLayout('chatbot.php');
}
public function widget()
{
echo view('widget.php');
}
}

View File

@ -0,0 +1,28 @@
<?php
// File: App\Helpers\DepositHelper.php
namespace App\Helpers;
use App\Models\EmployeeModel;
use App\Models\CDMasterModel;
class ChatbotHelper
{
//get list of policies againest an employee_id
public static function getListOfPolicies()
{
$emp_id = 12288;
$emp_code = 'HTL-007';
$client_id = 159;
$policy_id = 0;
$client_branch_id = 126;
$relationship ='Father';
$EmployeeModel = new EmployeeModel();
return $EmployeeModel->getEmpFamilybyEmpCode(emp_code: $emp_code,client_id: $client_id,emp_status: ['draft'],policy_status:['draft'],client_branch_id:[ $client_branch_id ],relationship:[$relationship]);
}
}
?>

View File

@ -0,0 +1,44 @@
<?php
// namespace App\Conversations;
namespace App\Controllers\Chatbot;
use BotMan\BotMan\Messages\Conversations\Conversation;
use BotMan\BotMan\Messages\Outgoing\Question;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
class NetworkHospitalConversation extends Conversation
{
public function run()
{
$this->showHospitalMenu();
}
protected function showHospitalMenu()
{
$question = Question::create("Choose your Network Hospital option:")
->addButtons([
Button::create("🔹 Search by City")->value("search_city"),
Button::create("🔹 Search by Pincode")->value("search_pincode"),
Button::create("◀️ Go Back")->value("go_back"),
]);
$this->bot->ask($question, function ($answer) {
switch ($answer->getValue()) {
case "search_city":
$this->say("Searching by City... (Dummy Response)");
break;
case "search_pincode":
$this->say("Searching by Pincode... (Dummy Response)");
break;
case "go_back":
$this->bot->startConversation(new MainMenuConversation());
break;
default:
$this->say("Invalid selection. Please choose an option.");
$this->showHospitalMenu();
break;
}
});
}
}

83
app/Views/chatbot.php Normal file
View File

@ -0,0 +1,83 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insurance ChatBot</title>
</head>
<style type="text/css">
</style>
<body>
<h1>Welcome to Insurance ChatBot </h1>
<script>
// var botmanWidget = {
// frameEndpoint: 'https://localhost/PHP828APPS/ruc/nhance/chat', // This should match your CI4 route
// introMessage: "Hi! I am your Insurance Bot. How can I assist you today?",
// placeholderText: "Type your message here...",
// title: "Insurance Bot",
// mainColor: "#5C6BC0",
// bubbleBackground: "#673AB7"
// };
var uid = Math.floor(100000 + Math.random() * 900000);
console.log('CURRENT_USER' + uid);
var botmanWidget = {
chatServer: "https://localhost/PHP828APPS/ruc/nhance/chat", // Make sure this URL is correct
frameEndpoint: 'https://localhost/PHP828APPS/ruc/nhance/widget', // This should match your CI4
title: "Ask ஆதிரை",
introMessage: "",
bubbleBackground: "#007bff",
mainColor: "#007bff",
placeholderText: "Type your message here...",
aboutText: "Insurance AI Assistant ஆதிரை",
enableAttachments: false,
// Add extra parameters
parameters: {
employee_id: '1234655', //PK of emp
session_id: "XYZ789", // token
origin: "mobile", // origin
emp_code:"EMP001",
client_id:10,
client_branch_id:12
}
};
// Send a first load request when the chat widget opens
// window.addEventListener("load", function () {
// setTimeout(function () {
// fetch("https://localhost/PHP828APPS/ruc/nhance/chat", {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify({ first_load: "true", user_id: "12345" })
// });
// }, 2000); // Slight delay to ensure the widget is ready
// });
window.addEventListener("load", function () {
setTimeout(function () {
if (window.botmanWidget) {
botmanChatWidget.open();
setTimeout(function(){
botmanChatWidget.sayAsBot('hi user '+ uid +' , this is ஆதிரை your Insurance AI Assistant, plz choose the following options')
botmanChatWidget.whisper('hi');
},2000);
}
}, 3000); // Delay to ensure widget is initialized
});
</script>
<!-- <script src="https://cdn.jsdelivr.net/npm/botman-web-widget@latest"></script> -->
<!-- <script id="botmanWidget" src='https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/js/chat.js'></script> -->
<!-- <script src='https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/js/widget.js'></script> -->
<script src='https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/js/widget.js'></script>
</body>
</html>

15
app/Views/widget.php Normal file
View File

@ -0,0 +1,15 @@
<!doctype html>
<html>
<head>
<title>BotMan Widget</title>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,500,700,800" rel="stylesheet">
<link rel="stylesheet" type="text/css" href=" https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/assets/css/chat.min.css">
</head>
<body>
<script id="botmanWidget" src=' https://cdn.jsdelivr.net/npm/botman-web-widget@0/build/js/chat.js'></script>
</body>
</html>