Merge branch 'main' of http://192.168.1.200:3000/Stratawiz/Rapport-Laravel
Specific Folder FTP Upload / ftp-deploy (push) Successful in 28s Details

This commit is contained in:
zeeshan 2026-11-04 15:31:25 +05:30
commit bdf93ddaa1
5 changed files with 1004 additions and 29 deletions

View File

@ -95,6 +95,22 @@ class TgicsHelper
return strtolower(trim((string) $value)) === 'yes'; return strtolower(trim((string) $value)) === 'yes';
} }
/**
* Read validation flag from a contact object (supports attribute_ prefix).
*/
public static function contactHasWhatsappValidated($item): bool
{
if (!$item) {
return false;
}
$direct = $item->tgics_whatsapp_validated ?? null;
if (self::isWhatsappValidatedFlag($direct)) {
return true;
}
$prefixed = $item->attribute_tgics_whatsapp_validated ?? null;
return self::isWhatsappValidatedFlag($prefixed);
}
/** /**
* Map contact_id => whether WhatsApp is validated for TGICS. * Map contact_id => whether WhatsApp is validated for TGICS.
* *
@ -122,11 +138,16 @@ class TgicsHelper
try { try {
$resp = LambdaRequest::getrequest('contact', 'contact/get_one', ['id' => $id], $accessToken); $resp = LambdaRequest::getrequest('contact', 'contact/get_one', ['id' => $id], $accessToken);
$item = $resp->data->item ?? null; $item = $resp->data->item ?? null;
if ($item && self::isWhatsappValidatedFlag($item->tgics_whatsapp_validated ?? '')) { $validated = self::contactHasWhatsappValidated($item);
$status[$id] = true; $status[$id] = $validated;
} Log::info('[TGICS_WA_STATUS] contact lookup', [
'contact_id' => $id,
'validated' => $validated,
'flag' => $item->tgics_whatsapp_validated ?? ($item->attribute_tgics_whatsapp_validated ?? null),
'api_status' => $resp->status ?? null,
]);
} catch (\Throwable $e) { } catch (\Throwable $e) {
Log::warning('TGICS WhatsApp validation lookup failed for '.$id.': '.$e->getMessage()); Log::warning('[TGICS_WA_STATUS] lookup failed for '.$id.': '.$e->getMessage());
} }
} }

View File

@ -1705,6 +1705,43 @@ class FormController extends Controller
} }
} }
// Team3 doctor tagging (single submit): mark attribute = Yes on selected doctor(s)
$team3DrTagAttributes = [
'1793772514-e8e67206-8dba-471e-b08f-deece5d36d11' => 'levoswitch_drs',
'1793767249-069bf040-1469-4117-b364-e4851e1f4bdf' => 'toba_titans_drs',
];
if (isset($team3DrTagAttributes[$formdata->form_id])) {
$tagAttribute = $team3DrTagAttributes[$formdata->form_id];
$rawContactIds = $post['contact_id'] ?? [];
if (!is_array($rawContactIds)) {
$rawContactIds = [$rawContactIds];
}
$contactIds = [];
foreach ($rawContactIds as $contactId) {
$contactId = trim((string) $contactId);
if ($contactId !== '' && strcasecmp($contactId, 'others') !== 0) {
$contactIds[] = $contactId;
}
}
$contactIds = array_values(array_unique($contactIds));
if ($contactIds !== [] && !empty($formdata->partition)) {
list($application, $domain) = explode('-', $formdata->partition);
$token = DB::table('users')->select('access_token')->where('domain', $domain)->where('permissions', 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
$userId = trim((string) ($post['user_id'] ?? ($formdata->user_id ?? '')));
if ($token->isNotEmpty() && $userId !== '') {
foreach ($contactIds as $contactId) {
LambdaRequest::postrequest('contact', 'contact/update', [
'domain' => $domain,
'application' => $application,
'user_id' => $userId,
'id' => $contactId,
$tagAttribute => 'Yes',
], $token[0]->access_token);
}
}
}
}
if($formdata->form_id == '1757055046-ba0eff4e-0d4a-4e90-b190-c59f12ef6edd') { if($formdata->form_id == '1757055046-ba0eff4e-0d4a-4e90-b190-c59f12ef6edd') {
// if(isset($post['cresar_bs_launched']) && $post['cresar_bs_launched'] == 'Yes' ) { // if(isset($post['cresar_bs_launched']) && $post['cresar_bs_launched'] == 'Yes' ) {
list($application, $domain) = explode("-", $formdata->partition); list($application, $domain) = explode("-", $formdata->partition);
@ -8104,6 +8141,40 @@ class FormController extends Controller
]); ]);
} }
// Team3 doctor tagging: mark attribute = Yes on each selected doctor
$team3DrTagAttributes = [
'1793772514-e8e67206-8dba-471e-b08f-deece5d36d11' => 'levoswitch_drs',
'1793767249-069bf040-1469-4117-b364-e4851e1f4bdf' => 'toba_titans_drs',
];
if (isset($team3DrTagAttributes[$formdata->form_id])) {
$tagAttribute = $team3DrTagAttributes[$formdata->form_id];
$contactIds = [];
if (!empty($post['contact_id']) && is_array($post['contact_id'])) {
foreach ($post['contact_id'] as $contactId) {
$contactId = trim((string) $contactId);
if ($contactId !== '' && strcasecmp($contactId, 'others') !== 0) {
$contactIds[] = $contactId;
}
}
}
$contactIds = array_values(array_unique($contactIds));
if ($contactIds !== [] && !empty($formdata->partition)) {
list($application, $domain) = explode('-', $formdata->partition);
$token = DB::table('users')->select('access_token')->where('domain', $domain)->where('permissions', 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
$userId = trim((string) ($post['user_id'] ?? ($formdata->user_id ?? '')));
if ($token->isNotEmpty() && $userId !== '') {
foreach ($contactIds as $contactId) {
LambdaRequest::postrequest('contact', 'contact/update', [
'domain' => $domain,
'application' => $application,
'user_id' => $userId,
'id' => $contactId,
$tagAttribute => 'Yes',
], $token[0]->access_token);
}
}
}
}
if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') { if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') {
$post = $this->applyPobAmounts($post); $post = $this->applyPobAmounts($post);
@ -13550,6 +13621,11 @@ class FormController extends Controller
} }
$validated = \App\Helpers\TgicsHelper::isContactWhatsappValidated($contactId, $domain); $validated = \App\Helpers\TgicsHelper::isContactWhatsappValidated($contactId, $domain);
\Log::info('[TGICS_WA_STATUS] poll', [
'contact_id' => $contactId,
'domain' => $domain,
'validated' => $validated,
]);
return response()->json([ return response()->json([
'status' => 'success', 'status' => 'success',

View File

@ -866,41 +866,50 @@
$('body').addClass('modal-open'); $('body').addClass('modal-open');
} }
function checkTgicsWaStatus(contactId) {
return $.ajax({
type: 'GET',
url: '/form/tgicswhatsappstatus',
data: {
contact_id: contactId,
partition: 'rapport-lifemankind'
}
}).then(function(res) {
if (res && res.status === 'success' && res.data && res.data.validated) {
stopTgicsWaPoll();
$('#tgics-validate-wa-status').text('Validated!');
Swal.fire({
icon: 'success',
title: 'WhatsApp validated',
text: 'You can now send the survey link to this doctor.',
timer: 1800,
showConfirmButton: false
}).then(function() {
window.location.reload();
});
return true;
}
return false;
}, function(err) {
console.warn('[TGICS_WA_STATUS] poll failed', err);
return false;
});
}
function startTgicsWaPoll(contactId) { function startTgicsWaPoll(contactId) {
stopTgicsWaPoll(); stopTgicsWaPoll();
tgicsWaPollStartedAt = Date.now(); tgicsWaPollStartedAt = Date.now();
$('#tgics-validate-wa-status').text('Waiting for validation…'); $('#tgics-validate-wa-status').text('Waiting for validation…');
// Immediate check, then every 2s
checkTgicsWaStatus(contactId);
tgicsWaPollTimer = setInterval(function() { tgicsWaPollTimer = setInterval(function() {
if (Date.now() - tgicsWaPollStartedAt > 120000) { if (Date.now() - tgicsWaPollStartedAt > 120000) {
stopTgicsWaPoll(); stopTgicsWaPoll();
$('#tgics-validate-wa-status').text('Still waiting. Close and try Validate again after the doctor sends the message.'); $('#tgics-validate-wa-status').text('Still waiting. Close and try Validate again after the doctor sends the message.');
return; return;
} }
$.ajax({ checkTgicsWaStatus(contactId);
type: 'GET', }, 2000);
url: '/form/tgicswhatsappstatus',
data: {
contact_id: contactId,
partition: 'rapport-lifemankind'
},
success: function(res) {
if (res && res.status === 'success' && res.data && res.data.validated) {
stopTgicsWaPoll();
$('#tgics-validate-wa-status').text('Validated!');
Swal.fire({
icon: 'success',
title: 'WhatsApp validated',
text: 'You can now send the survey link to this doctor.',
timer: 1800,
showConfirmButton: false
}).then(function() {
window.location.reload();
});
}
}
});
}, 3000);
} }
$(document).on('click', '.tgics-validate-wa-btn', function(e) { $(document).on('click', '.tgics-validate-wa-btn', function(e) {

View File

@ -0,0 +1,267 @@
@php
$multiDoctorFormId = '1793767249-069bf040-1469-4117-b364-e4851e1f4bdf';
$isMultiDoctorForm = isset($form->form_id)
&& $form->form_id == $multiDoctorFormId;
$doctorFieldCodes = [
'contact_id',
'legacy_code',
'msl_code',
'speciality'
];
$doctorFieldLabels = [
'contact_id' => 'HCP Name',
'legacy_code' => 'MSL Code',
'msl_code' => 'Pcode',
'speciality' => 'Speciality'
];
@endphp
<!DOCTYPE html>
<html lang="en">
<head>
@include('layouts.shared/title-meta', ['title' => "History"])
@include('layouts.shared/head-css', ["mode" => $mode ?? '', "demo" => $demo ?? ''])
</head>
<body class="loading">
<div class="account-pages">
<div class="container">
<!-- start page title -->
<div class="row">
<div class="col-8 p-2">
<h4 class="page-title">{{$formname}}</h4>
</div>
<div class="col-4 p-2">
<a href="/form/show" class="float-end pt-1">New Submission</a>
</div>
</div>
<!-- end page title -->
@if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
@endif
@if(session()->has('error'))
<div class="alert alert-danger">
{{ session()->get('error') }}
</div>
@endif
<div class="row">
<div class="col-12 p-0">
<div class="card">
<div class="card-body">
<div class="responsive-table-plugin">
<div class="table-rep-plugin">
<div class="table-responsive" data-pattern="priority-columns">
<table id="tech-companies-1" class="table table-striped">
<thead>
<tr>
<th data-priority="1">Submission Date</th>
@if($isMultiDoctorForm)
@for($i = 1; $i <= 5; $i++)
@foreach($doctorFieldLabels as $code => $label)
<th data-priority="1">
{{ $label }} {{ $i }}
</th>
@endforeach
@endfor
@else
@foreach($questions as $code => $question)
@if($question->type == 'hidden')
@continue
@endif
@if($question->type == 'multitextbox')
@foreach($question->options as $k => $v)
<th data-priority="1">
{{ is_object($v) ? ($v->display ?? $v->label ?? $k) : $v }}
({{ $question->label }})
</th>
@endforeach
@else
<th data-priority="1">{{ $question->label }}</th>
@endif
@endforeach
@endif
<th data-priority="1">Actions</th>
</tr>
</thead>
<tbody>
@foreach($submissions as $submission)
<tr>
<th>
{{ date("d M Y", strtotime($submission->updatedAt)) }}
</th>
@if($isMultiDoctorForm)
@php
$doctorData = [];
foreach ($doctorFieldCodes as $code) {
$rawValue = $submission->formdata->{$code} ?? [];
if (is_string($rawValue)) {
$values = explode(',', $rawValue);
} elseif (is_array($rawValue)) {
$values = $rawValue;
} elseif (is_object($rawValue)) {
$values = (array) $rawValue;
} else {
$values = [];
}
$doctorData[$code] = array_map(
fn($value) => trim((string) $value),
array_values($values)
);
}
@endphp
@for($i = 0; $i < 5; $i++)
@foreach($doctorFieldCodes as $code)
<td>
{{ $doctorData[$code][$i] ?? '-' }}
</td>
@endforeach
@endfor
@else
@foreach(($userAttrs ?? []) as $attr)
@php
$uaUser = $submission->user_info ?? null;
$uaVal = '-';
if ($uaUser) {
if (isset($uaUser->{$attr}) && $uaUser->{$attr} !== '') {
$uaVal = $uaUser->{$attr};
} elseif (isset($uaUser->{'attribute_'.$attr}) && $uaUser->{'attribute_'.$attr} !== '') {
$uaVal = $uaUser->{'attribute_'.$attr};
}
}
@endphp
<td>{{ $uaVal }}</td>
@endforeach
@foreach($questions as $code => $question)
@if($question->type == 'hidden')
@continue
@endif
@if($question->type == 'file')
<td>
<a target="_blank"
href="{{ isset($submission->formdata->{$code}) ? (is_array($submission->formdata->{$code}) ? implode(', ', $submission->formdata->{$code}) : (is_string($submission->formdata->{$code}) ? $submission->formdata->{$code} : '')) : $code }}"
download
class="btn btn-dark btn-xs">
<i class="mdi mdi-cloud-download me-1"></i> Download
</a>
</td>
@elseif($question->type == 'radiometrix' && isset($submission->formdata->{$code}) && is_object($submission->formdata->{$code}))
<td>
{{ collect((array)$submission->formdata->{$code})->map(function($val, $key) {
return "$key: $val";
})->implode(', ') }}
</td>
@elseif($question->type == 'multitextbox')
@foreach($question->options as $k => $v)
@php
$optKey = is_object($v) ? ($v->value ?? $k) : $k;
$optVal = '';
if (isset($submission->formdata->{$optKey})) {
$raw = $submission->formdata->{$optKey};
$optVal = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
} elseif (isset($submission->formdata->{$code}) && (is_object($submission->formdata->{$code}) || is_array($submission->formdata->{$code}))) {
$box = (array) $submission->formdata->{$code};
if (array_key_exists($optKey, $box)) {
$raw = $box[$optKey];
$optVal = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
}
}
@endphp
<td>{{ $optVal }}</td>
@endforeach
@else
<td>
{{ isset($submission->formdata->{$code})
? (is_array($submission->formdata->{$code})
? implode(', ', $submission->formdata->{$code})
: (is_object($submission->formdata->{$code})
? collect((array)$submission->formdata->{$code})->map(function($val, $key) {
return "$key: $val";
})->implode(', ')
: $submission->formdata->{$code}))
: '' }}
</td>
@endif
@endforeach
@endif
<th>
@php
$isApproved = ($submission->workflow ?? '') == 'yes'
&& ($submission->workflow_status ?? '') == 'approved';
$showFieldDelete = isset($form->allow_delete_by_user)
&& $form->allow_delete_by_user == 'yes'
&& !$isApproved;
@endphp
@if($showFieldDelete || !empty($can_delete_submission))
<a href="/form/delete?form_id={{$submission->formdata->form_id}}&id={{$submission->id}}"
onclick="return confirm('Are you sure you want to delete this submission? This is not recoverable!');"
class="btn btn-danger btn-xs mt-1">Delete</a>
@endif
</th>
</tr>
@endforeach
</tbody>
</table>
</div> <!-- end .table-responsive -->
</div> <!-- end .table-rep-plugin-->
</div> <!-- end .responsive-table-plugin-->
</div> <!-- end card body-->
</div> <!-- end card -->
</div><!-- end col-->
</div>
<!-- end row-->
</div> <!-- container -->
</div>
<!-- end page -->
@include('layouts.shared/footer-script')
</body>
</html>

View File

@ -0,0 +1,602 @@
<!DOCTYPE html>
<html lang="en">
<head>
@include('layouts.shared/title-meta', ['title' => "Form"])
@include('layouts.shared/head-css', ["mode" => $mode ?? '', "demo" => $demo ?? ''])
<link href="{{asset('assets/libs/sweetalert2/sweetalert2.min.css')}}" rel="stylesheet" type="text/css" />
</head>
<div id="pageloader">
<img src="http://cdnjs.cloudflare.com/ajax/libs/semantic-ui/0.16.1/images/loader-large.gif" alt="processing..." />
</div>
<body class="loading">
<div class="account-pages">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8 col-lg-6 col-xl-5 p-0">
<div class="card bg-pattern">
<div class="card-body p-3 row">
@if(Session::has('error'))<div class="alert alert-danger">{{Session::get('error')}}</div>
<br>@endif
@if(session('success'))<div class=" alert alert-success">{{ session('success') }}
</div>
<br>@endif
<div class="col-8">
<h4 class="page-title">{{$form->title}}</h4>
</div>
@if(!isset($form->is_approval) || (isset($form->is_approval) && $form->is_approval != 'yes' ) )
<div class="col-4">
@if($form->link_type == 'form')
<a href="/form/history" class="float-end pt-1">View History</a>
@else
<a href="{{url()->previous()}}" class="float-end pt-1">Back</a>
@endif
</div>
@endif
@if(isset($form->user_info))
<div class="col-12">
<h6>Submitted By: {{$form->user_info->name}}</h6>
</div>
@endif
<form method="POST" action="/form/submit" id="report-form" enctype="multipart/form-data">
<input type="hidden" name="form_id" value="{{$form_id}}">
@csrf
@if($id)
<input type="hidden" name="id" value="{{$id}}">
@endif
@if(isset($form->manager_can_submit) && $form->manager_can_submit == true)
<div class="col-md-12 mb-2">
<label for="field-user_id" class="form-label"> Select User / Territory <span class="text-danger">*</span> </label>
<select class="form-control" id="field-user_id" name="user_id" required>
<option value=""> -- Select -- </option>
@foreach($form->users as $option)
<option value="{{$option->value}}" hierarchy="{{$option->hierarchy_id}}" {{isset($question->value) && $question->value == $option->value ? 'selected':''}}>{{$option->display}}</option>
@endforeach
</select>
<input type="hidden" id="field-hierarchy_id" name="hierarchy_id" value="">
</div>
@endif
@php
$multiDoctorFormId = '1793767249-069bf040-1469-4117-b364-e4851e1f4bdf';
$doctorFieldCodes = [
'contact_id',
'legacy_code',
'msl_code',
'speciality'
];
$doctorQuestions = collect($questions)->keyBy('code');
@endphp
@if($form_id == $multiDoctorFormId)
<div class="col-md-12 mb-3" id="doctor-section">
<div id="doctor-wrapper-1" class="doctor-wrapper border rounded p-3 mb-3">
<h5>Doctor 1</h5>
<div class="mb-2">
<label class="form-label">HCP Name <span class="text-danger">*</span></label>
<select name="contact_id[]" class="form-control doctor-contact" required>
<option value="">-- Select Doctor --</option>
</select>
</div>
<div class="mb-2">
<label class="form-label">MSL Code</label>
<input type="text" name="legacy_code[]" class="form-control doctor-legacy-code" readonly>
</div>
<div class="mb-2">
<label class="form-label">Pcode</label>
<input type="text" name="msl_code[]" class="form-control doctor-msl-code" readonly>
</div>
<div class="mb-2">
<label class="form-label">Speciality</label>
<input type="text" name="speciality[]" class="form-control doctor-speciality" readonly>
</div>
</div>
@for($i = 2; $i <= 5; $i++)
<div id="doctor-wrapper-{{ $i }}"
class="doctor-wrapper border rounded p-3 mb-3"
style="display:none;">
<h5>Doctor {{ $i }}</h5>
<div class="mb-2">
<label class="form-label">HCP Name <span class="text-danger">*</span></label>
<select name="contact_id[]" class="form-control doctor-contact">
<option value="">-- Select Doctor --</option>
</select>
</div>
<div class="mb-2">
<label class="form-label">MSL Code</label>
<input type="text" name="legacy_code[]" class="form-control doctor-legacy-code" readonly>
</div>
<div class="mb-2">
<label class="form-label">Pcode</label>
<input type="text" name="msl_code[]" class="form-control doctor-msl-code" readonly>
</div>
<div class="mb-2">
<label class="form-label">Speciality</label>
<input type="text" name="speciality[]" class="form-control doctor-speciality" readonly>
</div>
</div>
@endfor
<button type="button" class="btn btn-secondary" id="add-doctor-btn">
Add Doctor
</button>
</div>
{{-- Render all other questions normally --}}
@foreach($questions as $question)
@if(!in_array($question->code, $doctorFieldCodes))
<div class="col-md-12 mb-2">
<label for="field-{{$question->code}}" class="form-label">
{{$question->question}}
{!!$question->required == 'yes' ? '<span class="text-danger">*</span>':''!!}
</label>
@switch($question->type)
@case('hidden')
<input type="hidden"
id="field-{{$question->code}}"
name="{{$question->code}}"
value="{{isset($question->value)?$question->value:''}}">
@break
@case('text')
@case('email')
@case('tel')
@case('date')
<input type="{{$question->type}}"
id="field-{{$question->code}}"
name="{{$question->code}}"
class="form-control"
{{$question->required == 'yes'?'required':''}}
value="{{isset($question->value)?$question->value:''}}">
@break
@case('number')
<input type="number"
min="0"
max="9999999999"
step="1"
id="field-{{$question->code}}"
name="{{$question->code}}"
class="form-control"
{{$question->required == 'yes'?'required':''}}
value="{{isset($question->value)?$question->value:0}}">
@break
@case('textarea')
<textarea id="field-{{$question->code}}"
name="{{$question->code}}"
class="form-control"
{{$question->required == 'yes'?'required':''}}>{{isset($question->value)?$question->value:''}}</textarea>
@break
@case('dropdown')
<select class="form-control"
id="field-{{$question->code}}"
name="{{$question->code}}"
{{$question->required == 'yes'?'required':''}}>
<option value="">-- Select --</option>
@foreach($question->options as $option)
<option value="{{$option->value}}"
{{isset($question->value) && $question->value == $option->value ? 'selected':''}}>
{{$option->display}}
</option>
@endforeach
</select>
@break
@case('radio')
@foreach($question->options as $option)
<div class="form-check mb-2 form-check-success">
<input class="form-check-input"
type="radio"
name="{{$question->code}}"
id="field-{{$question->code}}_{{$option->value}}"
value="{{$option->value}}">
<label class="form-check-label"
for="field-{{$question->code}}_{{$option->value}}">
{{$option->display}}
</label>
</div>
@endforeach
@break
@case('checkbox')
@foreach($question->options as $option)
<div class="form-check mb-2 form-check-primary ms-2">
<input class="form-check-input"
type="checkbox"
id="field-{{$question->code}}-{{$option->value}}"
name="{{$question->code}}[]"
value="{{$option->value}}">
<label class="form-check-label"
for="field-{{$question->code}}-{{$option->value}}">
{{$option->display}}
</label>
</div>
@endforeach
@break
@case('file')
<input type="file"
id="field-{{$question->code}}"
name="{{$question->code}}"
class="form-control"
{{$question->required == 'yes'?'required':''}}>
@break
@endswitch
</div>
@endif
@endforeach
@else
{{-- Keep your existing question-rendering code here for all other forms. --}}
@endif
@if(!isset($form->is_approval) || (isset($form->is_approval) && $form->is_approval != 'yes' ) )
<div class="text-center d-grid mt-3">
<button class="btn btn-primary" type="submit" id="submit-btn"> Submit </button>
</div>
@endif
</form>
</div> <!-- end card-body -->
</div>
<!-- end card -->
<!-- end row -->
</div> <!-- end col -->
</div>
<!-- end row -->
</div>
<!-- end container -->
</div>
<!-- end page -->
<style type="text/css">
#pageloader {
background: rgba( 255, 255, 255, 0.8 );
display: none;
height: 100%;
position: fixed;
width: 100%;
z-index: 9999;
}
#pageloader img {
left: 50%;
margin-left: -32px;
margin-top: -32px;
position: absolute;
top: 50%;
}
.form-label {
font-weight:bold;
font-size:16px;
}
</style>
@include('layouts.shared/footer-script')
<script src="{{asset('assets/libs/sweetalert2/sweetalert2.min.js')}}"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
// Store all doctors returned by the API
let allDoctors = [];
// Load doctors using the current form hierarchy
function loadDoctorList(hierarchy) {
if (!hierarchy) {
console.error('Hierarchy is missing');
return;
}
$("#pageloader").fadeIn();
$.ajax({
type: "GET",
url: '/form/getdoctorlist',
data: {
partition: @json($form->partition),
hierarchy: hierarchy
},
success: function(data) {
$("#pageloader").fadeOut();
console.log('Doctors received:', data);
allDoctors = data;
// Populate every doctor dropdown
$('.doctor-contact').each(function() {
let dropdown = $(this);
dropdown.empty();
dropdown.append(
$('<option></option>')
.val('')
.text('-- Select Doctor --')
);
$.each(allDoctors, function(index, itm) {
let contact = itm.contact || {};
let option = $('<option></option>')
.val(itm.value)
.text(itm.display)
.attr('msl_code', contact.msl_code || '')
.attr('legacy_code', contact.legacy_code || '')
.attr('speciality', contact.speciality || '');
dropdown.append(option);
});
});
},
error: function(xhr) {
$("#pageloader").fadeOut();
console.error('Doctor API error:', xhr.responseText);
Swal.fire(
'Error',
'Unable to load doctor list.',
'error'
);
}
});
}
// Load automatically when the form opens
loadDoctorList(@json($form->hierarchy_id ?? ''));
$(document).on('change', '.doctor-contact', function() {
let selectedOption = $(this).find('option:selected');
let wrapper = $(this).closest('.doctor-wrapper');
let mslCode = selectedOption.attr('msl_code') || '';
let legacyCode = selectedOption.attr('legacy_code') || '';
let speciality = selectedOption.attr('speciality') || '';
wrapper.find('.doctor-msl-code').val(mslCode);
wrapper.find('.doctor-legacy-code').val(legacyCode);
wrapper.find('.doctor-speciality').val(speciality);
console.log('Doctor:', selectedOption.text());
console.log('MSL Code:', mslCode);
console.log('Legacy Code:', legacyCode);
console.log('Speciality:', speciality);
});
// If the form has a User/Territory dropdown, load when it changes.
$('#field-user_id').on('change', function () {
let hierarchy = $(this).find(':selected').attr('hierarchy');
$('#field-hierarchy_id').val(hierarchy || '');
if (hierarchy) {
loadDoctorList(hierarchy);
}
});
$(document).on('change', '.doctor-contact', function () {
let selectedOption = $(this).find('option:selected');
let wrapper = $(this).closest('.doctor-wrapper');
let legacyCode = selectedOption.attr('legacy_code') || '';
let mslCode = selectedOption.attr('msl_code') || '';
let speciality = selectedOption.attr('speciality') || '';
wrapper.find('.doctor-legacy-code').val(legacyCode);
wrapper.find('.doctor-msl-code').val(mslCode);
wrapper.find('.doctor-speciality').val(speciality);
console.log('Selected doctor:', selectedOption.text());
console.log('Legacy Code:', legacyCode);
console.log('MSL Code:', mslCode);
console.log('Speciality:', speciality);
});
// Add doctor wrappers one by one
let visibleDoctors = 1;
$('#add-doctor-btn').on('click', function() {
if (visibleDoctors >= 5) {
return;
}
visibleDoctors++;
let wrapper = $('#doctor-wrapper-' + visibleDoctors);
wrapper.slideDown();
if (visibleDoctors === 5) {
$('#add-doctor-btn').hide();
}
});
// Make a newly selected doctor required
$(document).on('change', '.doctor-contact', function () {
let wrapper = $(this).closest('.doctor-wrapper');
$(this).prop('required', true);
if ($(this).val() === '') {
$(this).prop('required', false);
}
});
$(document).on('change', '.doctor-contact', function () {
let selectedValue = $(this).val();
let currentSelect = this;
let isDuplicate = false;
if (!selectedValue) {
return;
}
$('.doctor-contact').not(currentSelect).each(function () {
if ($(this).val() === selectedValue) {
isDuplicate = true;
return false;
}
});
if (isDuplicate) {
Swal.fire(
'Duplicate Doctor',
'This doctor has already been selected. Please select another doctor.',
'warning'
);
$(this).val('').trigger('change');
}
});
$('#report-form').on('submit', function(event) {
event.preventDefault();
let selectedDoctors = [];
$('.doctor-contact').each(function() {
let doctorId = $(this).val();
if (doctorId) {
selectedDoctors.push(doctorId);
}
});
// Exactly 5 doctors must be selected.
if (selectedDoctors.length !== 5) {
Swal.fire({
title: 'Warning',
text: 'Please select all 5 doctors before submitting the form.',
icon: 'warning',
confirmButtonText: 'OK'
});
return false;
}
// Continue with your existing AJAX submission below.
$("#pageloader").fadeIn();
let formData = new FormData(this);
console.log('Submitting form data:');
for (let [key, value] of formData.entries()) {
console.log(key, value);
}
$.ajax({
type: "POST",
url: '/form/ajaxsubmitmultiple',
data: formData,
processData: false,
contentType: false,
success: function(data) {
$("#pageloader").fadeOut();
console.log('Submission response:', data);
if (data.status === 'success') {
Swal.fire({
title: 'Great!',
text: 'Your data is successfully submitted!',
icon: 'success'
}).then(() => {
window.location.reload();
});
} else {
Swal.fire({
icon: 'error',
title: 'Data not submitted',
text: data.message || 'Something went wrong. Please try again.'
});
}
},
error: function(xhr) {
$("#pageloader").fadeOut();
console.error('Submission error:', xhr.responseText);
Swal.fire(
'Error',
'Submission failed. Check the browser console and Network response.',
'error'
);
}
});
});
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
today = yyyy + '-' + mm + '-' + dd;
var plandateField = document.getElementById('field-record_date');
plandateField.setAttribute('max', today);
});
</script>
</body>
</html>