CrestRoad/laravel/app/Services/SessionCommunicationService...

347 lines
12 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Services;
use App\Models\Session;
use Illuminate\Support\Facades\DB;
class SessionCommunicationService
{
protected static $feedbackTemplateCodes = [
'crest_thankyou_and_feedback',
'crest_feedback_new',
'post_impact_assessment',
'pre_impact_assessment',
];
public function resolveMode($session): string
{
if (!$session) {
return Session::MODE_WHATSAPP;
}
$mode = is_object($session)
? ($session->communication_mode ?? null)
: ($session['communication_mode'] ?? null);
$mode = strtolower(trim((string) $mode));
if (!in_array($mode, [Session::MODE_WHATSAPP, Session::MODE_EMAIL, Session::MODE_BOTH], true)) {
return Session::MODE_WHATSAPP;
}
return $mode;
}
public function shouldSendWhatsApp(string $mode): bool
{
return in_array($mode, [Session::MODE_WHATSAPP, Session::MODE_BOTH], true);
}
public function shouldSendEmail(string $mode): bool
{
return in_array($mode, [Session::MODE_EMAIL, Session::MODE_BOTH], true);
}
public function normalizeModeForSave(?string $mode): string
{
$mode = strtolower(trim((string) $mode));
if (!in_array($mode, [Session::MODE_WHATSAPP, Session::MODE_EMAIL, Session::MODE_BOTH], true)) {
return Session::MODE_WHATSAPP;
}
return $mode;
}
public function buildSessionVariables($session, $sendRow = null): array
{
$session = is_object($session) ? $session : (object) $session;
return [
'SESSION_NAME' => $session->number ?? '',
'SESSION_DATE' => isset($session->start_date)
? date('d M, Y', strtotime($session->start_date))
: '',
'SESSION_TYPE' => strtoupper($session->type ?? ''),
'SESSION_BROCHURE' => 'https://road.xltr.in/brochure/' . ($session->code ?? ''),
'SESSION_CODE' => $session->code ?? '',
];
}
public function applyFeedbackSessionCode(string $sessionCode, $contact, string $templateCode): string
{
if (!in_array($templateCode, self::$feedbackTemplateCodes, true)) {
return $sessionCode;
}
$contactId = is_object($contact) ? ($contact->id ?? '') : ($contact['id'] ?? '');
return $sessionCode . '_' . $contactId;
}
public function buildContactVariables($contact, $session, $sendRow): array
{
$sessionVars = $this->buildSessionVariables($session, $sendRow);
$templateCode = is_object($sendRow)
? ($sendRow->template_code ?? '')
: ($sendRow['template_code'] ?? '');
$sessionCode = $this->applyFeedbackSessionCode(
$sessionVars['SESSION_CODE'],
$contact,
$templateCode
);
$sendId = is_object($sendRow) ? ($sendRow->id ?? 0) : ($sendRow['id'] ?? 0);
return array_merge($sessionVars, [
'SESSION_CODE' => $sessionCode,
'RECIPIENT_NAME' => is_object($contact) ? ($contact->name ?? '') : ($contact['name'] ?? ''),
'CERT_PARAM' => (is_object($contact) ? ($contact->phone ?? '') : ($contact['phone'] ?? '')) . '_' . $sendId,
]);
}
public function substituteParams(?string $pipeList, array $vars): array
{
if ($pipeList === null || $pipeList === '') {
return [];
}
$params = explode('||', $pipeList);
foreach ($params as &$var) {
if (isset($vars[$var]) && $vars[$var] !== '') {
$var = $vars[$var];
}
}
return $params;
}
public function renderTemplateBody(string $body, array $vars): string
{
$rendered = $body;
foreach ($vars as $key => $value) {
$rendered = str_replace('{{' . $key . '}}', $value, $rendered);
$rendered = str_replace('{' . $key . '}', $value, $rendered);
}
return $rendered;
}
public function buildButtonSection(array $buttonValues): string
{
if (empty($buttonValues)) {
return '';
}
$lines = ["\n"];
foreach ($buttonValues as $i => $value) {
$value = trim((string) $value);
if ($value === '') {
continue;
}
if (filter_var($value, FILTER_VALIDATE_URL)) {
$lines[] = 'Link: ' . $value;
} else {
$lines[] = $value;
}
}
return implode("\n", $lines);
}
public function buildInteraktTemplate(array $config, array $vars): array
{
if (!empty($config['header_values']) && is_array($config['header_values'])) {
$headerParams = $config['header_values'];
} else {
$headerParams = $this->substituteParams($config['header_params'] ?? '', $vars);
}
$bodyParams = $this->substituteParams($config['body_params'] ?? '', $vars);
$buttonParams = $this->substituteParams($config['button_params'] ?? '', $vars);
$template = [
'name' => $config['template_code'],
'languageCode' => 'en',
];
if (count($headerParams) > 0) {
$template['headerValues'] = $headerParams;
}
if (count($bodyParams) > 0) {
$template['bodyValues'] = $bodyParams;
}
if (count($buttonParams) > 0) {
$template['buttonValues'] = (object) ['0' => $buttonParams];
}
return $template;
}
public function buildEmailBody(string $templateBody, array $vars, array $buttonValues = [], array $headerValues = []): string
{
$body = $this->renderTemplateBody($templateBody, $vars);
$body .= $this->buildButtonSection($buttonValues);
$imageHtml = '';
foreach ($headerValues as $headerValue) {
if (filter_var($headerValue, FILTER_VALIDATE_URL)) {
$imageHtml .= '<p><img src="' . e($headerValue) . '" alt="Crest" style="max-width:100%;height:auto;" /></p>';
}
}
return $imageHtml . nl2br(e($body));
}
public function buildEmailSubject($session, $sendRow): string
{
$sessionName = is_object($session) ? ($session->number ?? 'Crest Session') : ($session['number'] ?? 'Crest Session');
$title = is_object($sendRow) ? ($sendRow->template_title ?? null) : ($sendRow['template_title'] ?? null);
if (!empty($title)) {
return 'Crest – ' . $title;
}
return 'Crest – ' . $sessionName;
}
public function contactEmail($contact): ?string
{
$email = is_object($contact) ? ($contact->email ?? '') : ($contact['email'] ?? '');
$email = trim((string) $email);
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
return $email;
}
public function queueWhatsApp($contact, int $sessionId, array $interaktPayload): void
{
$phone = is_object($contact) ? ($contact->phone ?? '') : ($contact['phone'] ?? '');
$contactId = is_object($contact) ? ($contact->id ?? null) : ($contact['id'] ?? null);
DB::table('raphiwa_send')->insert([
'to' => $phone,
'text' => json_encode($interaktPayload),
'contact_id' => $contactId,
'session_id' => $sessionId,
'is_sent' => 0,
'status' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
}
public function queueEmail($contact, int $sessionId, string $subject, string $bodyHtml, ?string $templateCode = null): bool
{
$email = $this->contactEmail($contact);
if (!$email) {
return false;
}
$contactId = is_object($contact) ? ($contact->id ?? null) : ($contact['id'] ?? null);
DB::table('email_send')->insert([
'to' => $email,
'subject' => $subject,
'body_html' => $bodyHtml,
'contact_id' => $contactId,
'session_id' => $sessionId,
'template_code' => $templateCode,
'is_sent' => 0,
'status' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
return true;
}
public function queueEmailFromText($session, $contact, string $plainText, ?string $templateCode = null): bool
{
if (!$this->shouldSendEmail($this->resolveMode($session))) {
return false;
}
$sessionId = is_object($session) ? (int) ($session->id ?? 0) : (int) ($session['id'] ?? 0);
$subject = 'Crest – ' . (is_object($session) ? ($session->number ?? 'Message') : ($session['number'] ?? 'Message'));
$bodyHtml = nl2br(e($plainText));
return $this->queueEmail($contact, $sessionId, $subject, $bodyHtml, $templateCode);
}
public function dispatchForContact($session, $contact, array $config): void
{
$mode = $this->resolveMode($session);
$sessionId = is_object($session) ? (int) ($session->id ?? 0) : (int) ($session['id'] ?? 0);
$vars = $this->buildContactVariables($contact, $session, $config);
if (!empty($config['header_values']) && is_array($config['header_values'])) {
$headerParams = $config['header_values'];
} else {
$headerParams = $this->substituteParams($config['header_params'] ?? '', $vars);
}
$bodyParams = $this->substituteParams($config['body_params'] ?? '', $vars);
$buttonParams = $this->substituteParams($config['button_params'] ?? '', $vars);
if ($this->shouldSendWhatsApp($mode)) {
$phone = is_object($contact) ? ($contact->phone ?? '') : ($contact['phone'] ?? '');
$contactId = is_object($contact) ? ($contact->id ?? '') : ($contact['id'] ?? '');
$template = $this->buildInteraktTemplate($config, $vars);
$params = [
'countryCode' => '+91',
'phoneNumber' => $phone,
'callbackData' => $phone . '_' . $contactId,
'type' => 'Template',
'template' => $template,
];
$this->queueWhatsApp($contact, $sessionId, $params);
}
if ($this->shouldSendEmail($mode)) {
$templateBody = $config['template_body'] ?? '';
if ($templateBody !== '') {
$bodyHtml = $this->buildEmailBody($templateBody, $vars, $buttonParams, $headerParams);
$subject = $this->buildEmailSubject($session, $config);
$this->queueEmail(
$contact,
$sessionId,
$subject,
$bodyHtml,
$config['template_code'] ?? null
);
}
}
}
public function dispatchPlainText($session, $contact, string $message, bool $sendWhatsApp = true): void
{
$mode = $this->resolveMode($session);
$sessionId = is_object($session) ? (int) ($session->id ?? 0) : (int) ($session['id'] ?? 0);
if ($sendWhatsApp && $this->shouldSendWhatsApp($mode)) {
$phone = is_object($contact) ? ($contact->phone ?? '') : ($contact['phone'] ?? '');
$params = [
'countryCode' => '+91',
'phoneNumber' => $phone,
'callbackData' => 'email_mirror',
'type' => 'Text',
'data' => ['message' => $message],
];
$this->queueWhatsApp($contact, $sessionId, $params);
}
if ($this->shouldSendEmail($mode)) {
$this->queueEmailFromText($session, $contact, $message);
}
}
}