Rapport-Laravel/resources/views/form/rapport-lifemankind/1792561624-4466e937-cfb5-46...

1042 lines
58 KiB
PHP

<!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="/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">
<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">TGICS (The Great Indian Cough Study - Dr Enrolment)</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> -->
<button type="button" class="btn btn-primary btn-xs" id="add-camp-btn">Enroll Doctor</button>
@else
<a href="{{ url()->previous() }}" class="float-end pt-1">Back</a>
@endif
</div>
@endif
@php
$history = Formhelper::getMultiformData(
$form->partition,
$form->form_id,
$form->user_id,
);
$tgicsSubmissions = collect($history->data->submissions ?? []);
$doctorsAddedCount = $tgicsSubmissions->count();
$tgicsContactIds = $tgicsSubmissions
->map(function ($countSub) {
return trim((string) ($countSub->formdata->tgics_contact_id ?? ''));
})
->filter()
->unique()
->values()
->all();
$tgicsSurveyData = \App\Helpers\TgicsHelper::getSurveyCounts($tgicsContactIds);
$tgicsSurveyCounts = $tgicsSurveyData['counts'] ?? [];
$totalSurveysDone = (int) ($tgicsSurveyData['total'] ?? 0);
$tgicsWhatsappValidated = \App\Helpers\TgicsHelper::getWhatsappValidationStatus(
$tgicsContactIds,
'lifemankind'
);
$tgicsCommonUserId = trim((string) ($form->user_id ?? ''));
$tgicsCommonLink = $tgicsCommonUserId !== ''
? 'https://tgics.cttr.in/' . $tgicsCommonUserId
: '';
@endphp
<div class="col-12" id="table-wrapper">
@if ($tgicsCommonLink !== '')
<div class="mb-3">
<label class="form-label mb-1">Doctor Survey Link</label>
<div class="input-group input-group-sm">
<input type="text" class="form-control form-control-sm tgics-doctor-link" value="{{ $tgicsCommonLink }}" readonly>
<button type="button" class="btn btn-outline-secondary btn-copy-tgics-link" data-link="{{ $tgicsCommonLink }}" title="Copy to clipboard">
<i class="mdi mdi-content-copy"></i> Copy
</button>
</div>
<small class="text-muted">Common link for all doctors. Doctors enter their WhatsApp number to log in.</small>
</div>
@endif
<div class="row mb-2">
<div class="col-6">
<div class="border rounded p-2">
<small class="text-muted d-block">No. of doctors added</small>
<strong>{{ $doctorsAddedCount }}</strong>
</div>
</div>
<div class="col-6">
<div class="border rounded p-2">
<small class="text-muted d-block">No. of surveys done</small>
<strong>{{ $totalSurveysDone }}</strong>
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-borderless table-nowrap table-hover table-centered m-0">
<thead class="table-light">
<tr>
<th>Action</th>
<th>Workflow Status</th>
<th>Surveys Done</th>
<th>Name of the Practitioner</th>
<th>WFSA Code</th>
<th>WhatsApp Mobile Number</th>
<th>Email ID</th>
</tr>
</thead>
<tbody>
@foreach ($tgicsSubmissions->sortByDesc('formdata.record_date') as $sub)
@php
$sub->formdata->id = $sub->id;
$workflowStatus = strtolower(trim((string) ($sub->workflow_status ?? '')));
$isApproved = $workflowStatus === 'approved';
$whatsappDigits = preg_replace('/\D+/', '', (string) ($sub->formdata->whatsapp_mobile_number ?? ''));
if (strlen($whatsappDigits) === 10) {
$whatsappDigits = '91' . $whatsappDigits;
}
$doctorName = '';
if (isset($sub->formdata->contact_id) && $sub->formdata->contact_id !== '') {
$doctorName = $sub->formdata->contact_id;
} elseif (isset($sub->formdata->doctor_name)) {
$doctorName = $sub->formdata->doctor_name;
}
$tgicsContactId = trim((string) ($sub->formdata->tgics_contact_id ?? ''));
$rowUserId = trim((string) ($sub->formdata->user_id ?? ($sub->user_id ?? ($form->user_id ?? ''))));
$doctorLink = ($rowUserId !== '' && $tgicsContactId !== '')
? 'https://tgics.cttr.in/' . $rowUserId . '/' . $tgicsContactId
: '';
$surveysDone = $tgicsContactId !== ''
? (int) ($tgicsSurveyCounts[$tgicsContactId] ?? 0)
: 0;
$whatsappValidated = $tgicsContactId !== ''
&& !empty($tgicsWhatsappValidated[$tgicsContactId]);
$whatsappText = "Dear Doctor" . ($doctorName !== '' ? ' ' . $doctorName : '') . ",\nThank you for participating in TGICS (The Great Indian Cough Study).\nPlease open the link and enter your WhatsApp mobile number to continue:\n" . $doctorLink;
$whatsappLink = ($whatsappDigits !== '' && $doctorLink !== '')
? 'https://api.whatsapp.com/send?phone=' . $whatsappDigits . '&text=' . rawurlencode($whatsappText)
: '';
$validateToken = $tgicsContactId !== ''
? 'CREST_VERIFY_TGICS_' . $tgicsContactId
: '';
$validateWaUrl = $validateToken !== ''
? 'https://wa.me/918142061298?text=' . rawurlencode($validateToken)
: '';
@endphp
<tr>
<td>
@if ($isApproved)
@if ($doctorLink === '')
<span class="text-muted">Link unavailable</span>
@elseif ($whatsappDigits === '')
<span class="text-muted">No WhatsApp number</span>
@elseif ($whatsappValidated && $whatsappLink !== '')
<a href="{{ $whatsappLink }}" target="_blank" rel="noopener noreferrer"
class="btn btn-xs btn-success">
<i class="mdi mdi-whatsapp"></i> Send
</a>
@elseif ($validateWaUrl !== '')
<button type="button"
class="btn btn-xs btn-warning tgics-validate-wa-btn"
data-contact-id="{{ $tgicsContactId }}"
data-validate-url="{{ $validateWaUrl }}"
data-doctor-name="{{ $doctorName }}">
<i class="mdi mdi-qrcode"></i> Validate
</button>
@else
<span class="text-muted">Validation unavailable</span>
@endif
@else
<button type="button" class="btn btn-xs btn-info edit-btn"
plan_details="{{ json_encode($sub->formdata) }}"><i
class="mdi mdi-pencil"></i> Edit</button>
@endif
</td>
<td>{{ $workflowStatus !== '' ? ucwords($workflowStatus) : '-' }}</td>
<td>{{ $surveysDone }}</td>
<td>{{ $doctorName }}</td>
<td>{{ isset($sub->formdata->wfsa_code) ? $sub->formdata->wfsa_code : '' }}
</td>
<td>{{ isset($sub->formdata->whatsapp_mobile_number) ? $sub->formdata->whatsapp_mobile_number : '' }}
</td>
<td>{{ isset($sub->formdata->email_id) ? $sub->formdata->email_id : '' }}
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
<div id="form-wrapper">
<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
@foreach ($questions as $question)
@if (in_array($question->code, [
'execution_date',
'no_of_attendees',
'total_amount_spent_in_rs',
'upload_photo_1',
'upload_photo_2',
'ziten_m_rx',
'total_camp_rx',
'no_of_strips_left_with_fso',
]))
@continue
@endif
<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="{{ $question->type }}" 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="{{ $question->type }}" 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)
@if($question->code == 'contact_id' && isset($option->contact->type) && $option->contact->type != 'Chemist' )
<option value="{{ $option->value }}"
@if(isset($question->value) && $question->value == $option->value) selected @endif
@if($question->code == 'contact_id')
msl_code="{{ (isset($option->contact->msl_code) ? $option->contact->msl_code : '') }}"
speciality="{{ (isset($option->contact->speciality) ? $option->contact->speciality : '') }}"
@endif
>
{{ $option->display }}
</option>
@elseif($question->code != 'contact_id')
<option value="{{ $option->value }}" {{ isset($question->value) && $question->value == $option->value ? 'selected' : '' }} {{ $question->code == 'contact_id' ? 'pcode= ' . (isset($option->contact->pcode)?$option->contact->pcode:'') . ' ' : '' }} {{ isset($question->value) && $question->value == $option->value ? 'selected' : '' }} {{ $question->code == 'contact_id' ? 'speciality= ' . (isset($option->contact->speciality) ? $option->contact->speciality :'') . ' ' : '' }} >
{{ $option->display }}
</option>
@endif
@endforeach
</select>
@break
@case('checkbox')
@foreach ($question->options as $option)
<div class="form-check mb-2 form-check-primary">
<input class="form-check-input" type="checkbox"
id="field-{{ $question->code }}-{{ $option->value }}"
name="{{ $question->code }}[]" value="{{ $option->value }}"
{{ isset($question->value) && $question->value != '' && in_array($option->value, $question->value) ? 'checked' : '' }}>
<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" value=""
accept="image/jpg, image/jpeg, image/png" required>
@break
@endswitch
</div>
@endforeach
@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>
<div id="execution-form-wrapper">
<form method="POST" action="/form/submit" id="execution-form"
enctype="multipart/form-data">
<input type="hidden" name="form_id" value="{{ $form_id }}">
@csrf
<input type="hidden" name="id" value="" id="execution-id">
<input type="hidden" name="execution_done" value="yes">
@foreach ($questions as $question)
<div class="col-md-12 mb-2">
<label for="execution-{{ $question->code }}"
class="form-label">{{ $question->question }} {!! $question->required == 'yes' ? '<span class="text-danger">*</span>' : '' !!}
</label>
@switch($question->type)
@case('hidden')
<input type="{{ $question->type }}" id="execution-{{ $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="execution-{{ $question->code }}"
name="{{ $question->code }}" class="form-control"
{{ $question->required == 'yes' ? 'required' : '' }}
value="{{ isset($question->value) ? $question->value : '' }}">
@break
@case('number')
<input type="{{ $question->type }}" min="0" max="9999999999"
step="1" id="execution-{{ $question->code }}"
name="{{ $question->code }}" class="form-control"
{{ $question->required == 'yes' ? 'required' : '' }}
value="{{ isset($question->value) ? $question->value : 0 }}">
@break
@case('textarea')
<textarea id="execution-{{ $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="execution-{{ $question->code }}"
name="{{ $question->code }}"
{{ $question->required == 'yes' ? 'required' : '' }}>
<option value=""> -- Select -- </option>
@foreach ($question->options as $option)
@if($question->code == 'contact_id' && isset($option->contact->type) && $option->contact->type != 'Chemist' )
<option value="{{ $option->value }}"
@if(isset($question->value) && $question->value == $option->value) selected @endif
@if($question->code == 'contact_id')
msl_code="{{ (isset($option->contact->msl_code) ? $option->contact->msl_code : '') }}"
speciality="{{ (isset($option->contact->speciality) ? $option->contact->speciality : '') }}"
@endif
>
{{ $option->display }}
</option>
@elseif($question->code != 'contact_id')
<option value="{{ $option->value }}" {{ isset($question->value) && $question->value == $option->value ? 'selected' : '' }} {{ $question->code == 'contact_id' ? 'pcode= ' . (isset($option->contact->pcode)?$option->contact->pcode:'') . ' ' : '' }} {{ isset($question->value) && $question->value == $option->value ? 'selected' : '' }} {{ $question->code == 'contact_id' ? 'speciality= ' . (isset($option->contact->speciality) ? $option->contact->speciality :'') . ' ' : '' }} >
{{ $option->display }}
</option>
@endif
@endforeach
</select>
@break
@case('checkbox')
@foreach ($question->options as $option)
<div class="form-check mb-2 form-check-primary">
<input class="form-check-input" type="checkbox"
id="execution-{{ $question->code }}-{{ $option->value }}"
name="{{ $question->code }}[]" value="{{ $option->value }}"
{{ isset($question->value) && $question->value != '' && in_array($option->value, $question->value) ? 'checked' : '' }}>
<label class="form-check-label"
for="execution-{{ $question->code }}-{{ $option->value }}">{{ $option->display }}</label>
</div>
@endforeach
@break
@case('file')
<input type="file" id="execution-{{ $question->code }}"
name="{{ $question->code }}" class="form-control" value=""
accept="image/jpg, image/jpeg, image/png">
@break
@endswitch
</div>
@endforeach
@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>
</div> <!-- end card-body -->
</div>
<!-- end card -->
<!-- end row -->
</div> <!-- end col -->
</div>
<!-- end row -->
</div>
<!-- end container -->
</div>
<!-- end page -->
<div class="modal fade" id="tgics-validate-wa-modal" tabindex="-1" role="dialog" aria-labelledby="tgics-validate-wa-title" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="tgics-validate-wa-title">Validate WhatsApp</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body text-center">
<p class="mb-2" id="tgics-validate-wa-doctor"></p>
<p class="text-muted small">Ask the doctor to scan this QR with the enrolled WhatsApp number and send the pre-filled message without changing it.</p>
<div id="tgics-validate-wa-qr" class="d-flex justify-content-center my-3"></div>
<p class="small mb-1" id="tgics-validate-wa-status">Waiting for validation…</p>
<a href="#" id="tgics-validate-wa-open" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-outline-success">
Open link instead
</a>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<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%;
}
#tgics-validate-wa-qr canvas,
#tgics-validate-wa-qr img {
max-width: 220px;
height: auto;
}
#tgics-validate-wa-modal {
z-index: 1055;
}
.tgics-validate-backdrop {
z-index: 1050;
}
</style>
@include('layouts.shared/footer-script')
<script src="{{ asset('assets/libs/sweetalert2/sweetalert2.min.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script src="{{ asset('js/tgics-india-geo.js') }}"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#form-wrapper').hide()
$('#execution-form-wrapper').hide()
var indiaGeo = window.TGICS_INDIA_GEO || {};
var indiaStates = Object.keys(indiaGeo).sort();
function fillSelectOptions($sel, values, selected, placeholder) {
$sel.empty();
$sel.append($('<option></option>').attr('value', '').text(placeholder || ' -- Select -- '));
(values || []).forEach(function(v) {
var $opt = $('<option></option>').attr('value', v).text(v);
if (selected && String(selected) === String(v)) {
$opt.prop('selected', true);
}
$sel.append($opt);
});
if (selected && values && values.indexOf(selected) === -1 && String(selected).trim() !== '') {
$sel.append(
$('<option></option>').attr('value', selected).text(selected + ' (current)').prop('selected', true)
);
}
}
function ensureAvgPatientsField(prefix) {
if ($('#' + prefix + '-average_no_of_patients').length) {
return;
}
var $years = $('#' + prefix + '-years_of_practice').closest('.col-md-12.mb-2');
if (!$years.length) {
return;
}
var html =
'<div class="col-md-12 mb-2">' +
'<label for="' + prefix + '-average_no_of_patients" class="form-label">' +
'Average No. of Patients <span class="text-danger">*</span></label>' +
'<input type="number" min="0" max="999999" step="1" id="' + prefix +
'-average_no_of_patients" name="average_no_of_patients" class="form-control" required value="">' +
'</div>';
$years.after(html);
}
function convertTextToSelect(prefix, code, values, placeholder) {
var $input = $('#' + prefix + '-' + code);
if (!$input.length || $input.is('select')) {
return $input;
}
var current = $input.val() || '';
var required = $input.prop('required');
var $sel = $('<select></select>')
.attr('id', prefix + '-' + code)
.attr('name', code)
.addClass('form-control');
if (required) {
$sel.prop('required', true);
}
fillSelectOptions($sel, values, current, placeholder);
$input.replaceWith($sel);
return $sel;
}
function refreshCityOptions(prefix, keepCity) {
var state = $('#' + prefix + '-state').val() || '';
var cities = indiaGeo[state] || [];
var $city = $('#' + prefix + '-city_town');
if (!$city.length) {
return;
}
var current = keepCity != null ? keepCity : ($city.val() || '');
if (!$city.is('select')) {
$city = convertTextToSelect(prefix, 'city_town', cities, ' -- Select City -- ');
}
fillSelectOptions($city, cities, current, ' -- Select City -- ');
}
function setupGeoFields(prefix) {
ensureAvgPatientsField(prefix);
convertTextToSelect(prefix, 'state', indiaStates, ' -- Select State -- ');
convertTextToSelect(prefix, 'city_town', [], ' -- Select City -- ');
refreshCityOptions(prefix);
$('#' + prefix + '-state').off('change.tgicsGeo').on('change.tgicsGeo', function() {
refreshCityOptions(prefix, '');
});
$('#' + prefix + '-average_no_of_patients').off('input.tgicsAvg').on('input.tgicsAvg', function() {
this.value = String(this.value || '').replace(/[^0-9]/g, '');
});
}
setupGeoFields('field');
setupGeoFields('execution');
function copyTgicsLink(text) {
function fallbackCopy() {
return new Promise(function(resolve, reject) {
var textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-9999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var ok = document.execCommand('copy');
document.body.removeChild(textArea);
ok ? resolve() : reject();
} catch (err) {
document.body.removeChild(textArea);
reject(err);
}
});
}
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
return navigator.clipboard.writeText(text).catch(function() {
return fallbackCopy();
});
}
return fallbackCopy();
}
$(document).on('click', '.btn-copy-tgics-link', function() {
var link = $(this).attr('data-link') || '';
var $btn = $(this);
if (!link) {
return;
}
copyTgicsLink(link).then(function() {
var original = $btn.html();
$btn.html('<i class="mdi mdi-check"></i> Copied');
setTimeout(function() {
$btn.html(original);
}, 1500);
}).catch(function() {
var $input = $btn.closest('.input-group').find('.tgics-doctor-link');
if ($input.length) {
$input.trigger('focus');
$input[0].select();
}
Swal.fire({
icon: 'error',
title: 'Unable to copy',
text: 'Please copy the link manually.',
});
});
});
// $('#add-camp-btn').click(function() {
// $('#form-wrapper').show()
// $('#table-wrapper').hide()
// })
$('#add-camp-btn').click(function() {
$('#table-wrapper').hide(0)
$('#form-wrapper').show(100, () => {
$('#add-camp-btn').hide(0);
})
})
$('.edit-btn').click(function() {
$('#execution-form-wrapper').show(100, () => {
$('#add-camp-btn').hide(0);
})
$('#table-wrapper').hide()
$('#execution-speciality').prop('readonly', true)
$('#execution-plan_date').prop('readonly', true)
$('#execution-uid').prop('readonly', true);
//$('#execution-time').prop('disabled', true)
let selected = JSON.parse($(this).attr('plan_details'));
console.log("Plan Detail : ", selected);
if (selected['contact_id']) {
selected['contact_id'] = selected['contact_id'].trim();
}
console.log("Selected Doctor:", selected['contact_id']);
for (let k of Object.keys(selected)) {
//console.log("k",k);
if (selected[k] != '') {
if (k == 'contact_id_') {
//$("#execution-contact_id option:contains(" + selected[k] + ")").prop('selected', true)
// console.log($("#execution-contact_id option:contains(" + selected[k] + ")").attr('value'))
$('#execution-contact_id').val($("#execution-contact_id option:contains(" +
selected[k] + ")").attr('value'));
} else if (k == 'upload_photo_1' || k == 'upload_photo_2' || k == 'city_town' || k == 'state') {
continue;
} else {
$('#execution-' + k).val(selected[k]);
}
}
// if(selected[k] != '')
// $('#execution-'+k).val(selected[k]);
}
if (selected['state']) {
$('#execution-state').val(selected['state']);
if (!$('#execution-state').val() && selected['state']) {
$('#execution-state').append(
$('<option></option>').attr('value', selected['state'])
.text(selected['state'] + ' (current)').prop('selected', true)
);
}
}
refreshCityOptions('execution', selected['city_town'] || '');
if (selected['average_no_of_patients'] != null && selected['average_no_of_patients'] !== '') {
$('#execution-average_no_of_patients').val(selected['average_no_of_patients']);
}
/* let docid = $('#execution-contact_id option').map(function() {
if ($(this).text().trim() == selected['contact_id'] || $(this).val().trim() == selected['cont_id']) return this;
}).attr('value')
$('#execution-contact_id').val(docid) */
$('#execution-id').val(selected['id'])
toggleOtherQualification('execution');
})
$('#report-form').on('submit', function(event) {
event.preventDefault();
$("#pageloader").fadeIn();
$.ajax({
type: "POST",
url: '/form/ajaxsubmit',
data: new FormData($('#report-form')[0]),
processData: false,
contentType: false,
success: function(data) {
$("#pageloader").fadeOut();
if (data.status == 'success') {
Swal.fire({
title: 'Great!',
text: 'Your data is successfully submitted!',
icon: 'success'
}).then(function() {
window.location.reload();
});
} else {
Swal.fire({
icon: 'error',
title: data.message || 'Data not submitted',
text: data.description || data.message || 'Something went wrong, please try again after some time!'
});
}
},
error: function() {
$("#pageloader").fadeOut();
Swal.fire({
icon: 'error',
title: 'Data not submitted',
text: 'Something went wrong, please try again after some time!'
});
}
});
});
function toggleOtherQualification(prefix) {
var $qualification = $('#' + prefix + '-qualification');
var $other = $('#' + prefix + '-other_qualification');
if (!$qualification.length || !$other.length) {
return;
}
if ($qualification.val() === 'Others') {
$other.parent().show();
$other.prop('required', true);
} else {
$other.val('');
$other.prop('required', false);
$other.parent().hide();
}
}
toggleOtherQualification('field');
toggleOtherQualification('execution');
$('#field-qualification, #execution-qualification').on('change', function() {
var prefix = this.id.indexOf('execution-') === 0 ? 'execution' : 'field';
toggleOtherQualification(prefix);
});
$('#field-contact_id,#field-other_qualification').on('input', function () {
this.value = this.value.replace(/[^a-zA-Z\s]/g, '');
});
$('#field-age').attr('max',"105");
$('#field-years_of_practice').attr('max',"85");
$('#field-wfsa_code').on('input', function () {
let value = $(this).val();
// Remove all non-numeric characters
value = value.replace(/[^0-9]/g, '');
// Remove leading zeros
value = value.replace(/^0+/, '');
// Allow maximum 10 digits
value = value.substring(0, 10);
$(this).val(value);
});
$('#field-whatsapp_mobile_number').on('input', function () {
let value = $(this).val();
// Remove non-numeric characters
value = value.replace(/[^0-9]/g, '');
// Allow only 10 digits
value = value.substring(0, 10);
// First digit must be 6, 7, 8 or 9
if (value.length > 0 && !/^[6-9]/.test(value)) {
value = '';
}
$(this).val(value);
});
$(document).ready(function () {
$('#field-contact_id').trigger('change');
});
var tgicsWaPollTimer = null;
var tgicsWaPollStartedAt = 0;
function stopTgicsWaPoll() {
if (tgicsWaPollTimer) {
clearInterval(tgicsWaPollTimer);
tgicsWaPollTimer = null;
}
}
function hideTgicsValidateModal() {
stopTgicsWaPoll();
var $modal = $('#tgics-validate-wa-modal');
if ($.fn.modal && typeof $modal.modal === 'function') {
$modal.modal('hide');
} else if (window.bootstrap && bootstrap.Modal) {
var inst = bootstrap.Modal.getInstance($modal[0]);
if (inst) {
inst.hide();
}
}
$modal.removeClass('show').css('display', 'none').attr('aria-hidden', 'true');
$('.tgics-validate-backdrop').remove();
$('body').removeClass('modal-open').css('overflow', '');
}
function showTgicsValidateModal() {
var $modal = $('#tgics-validate-wa-modal');
if ($.fn.modal && typeof $modal.modal === 'function') {
$modal.modal('show');
return;
}
if (window.bootstrap && bootstrap.Modal) {
bootstrap.Modal.getOrCreateInstance($modal[0]).show();
return;
}
// Manual fallback when Bootstrap modal JS is unavailable
$modal.addClass('show').css('display', 'block').attr('aria-hidden', 'false');
if (!$('.tgics-validate-backdrop').length) {
$('body').append('<div class="modal-backdrop fade show tgics-validate-backdrop"></div>');
}
$('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) {
stopTgicsWaPoll();
tgicsWaPollStartedAt = Date.now();
$('#tgics-validate-wa-status').text('Waiting for validation…');
// Immediate check, then every 2s
checkTgicsWaStatus(contactId);
tgicsWaPollTimer = setInterval(function() {
if (Date.now() - tgicsWaPollStartedAt > 120000) {
stopTgicsWaPoll();
$('#tgics-validate-wa-status').text('Still waiting. Close and try Validate again after the doctor sends the message.');
return;
}
checkTgicsWaStatus(contactId);
}, 2000);
}
$(document).on('click', '.tgics-validate-wa-btn', function(e) {
e.preventDefault();
e.stopPropagation();
var contactId = $(this).attr('data-contact-id') || '';
var validateUrl = $(this).attr('data-validate-url') || '';
var doctorName = $(this).attr('data-doctor-name') || 'Doctor';
if (!contactId || !validateUrl) {
Swal.fire({
icon: 'error',
title: 'Validation unavailable',
text: 'Missing doctor contact link. Please re-enrol or contact support.'
});
return;
}
$('#tgics-validate-wa-doctor').text(doctorName);
$('#tgics-validate-wa-open').attr('href', validateUrl);
$('#tgics-validate-wa-qr').empty();
try {
if (typeof QRCode !== 'undefined') {
new QRCode(document.getElementById('tgics-validate-wa-qr'), {
text: validateUrl,
width: 200,
height: 200
});
} else {
$('#tgics-validate-wa-qr').html(
'<p class="text-muted small mb-2">QR library unavailable. Use the button below.</p>'
);
}
} catch (qrErr) {
console.error(qrErr);
$('#tgics-validate-wa-qr').html(
'<p class="text-muted small mb-2">Unable to render QR. Use the button below.</p>'
);
}
showTgicsValidateModal();
startTgicsWaPoll(contactId);
});
$(document).on('click', '#tgics-validate-wa-modal [data-bs-dismiss="modal"], #tgics-validate-wa-modal .btn-close, #tgics-validate-wa-modal .btn-secondary', function() {
hideTgicsValidateModal();
});
$(document).on('click', '.tgics-validate-backdrop', function() {
hideTgicsValidateModal();
});
$('#tgics-validate-wa-modal').on('hidden.bs.modal hide.bs.modal', function() {
stopTgicsWaPoll();
$('.tgics-validate-backdrop').remove();
});
$('#execution-form').on('submit', function(event) {
event.preventDefault();
$("#pageloader").fadeIn();
$.ajax({
type: "POST",
url: '/form/ajaxsubmit',
data: new FormData($('#execution-form')[0]),
processData: false,
contentType: false,
success: function(data) {
$("#pageloader").fadeOut();
if (data.status == 'success') {
Swal.fire({
title: 'Great!',
text: 'Your data is successfully submitted!',
icon: 'success'
}).then(function() {
location.reload();
});
$('#report-form').trigger("reset");
} else {
Swal.fire({
icon: 'error',
title: data.message || 'Data not submitted',
text: data.description || data.message || 'Something went wrong, please try again after some time!'
});
}
},
error: function() {
$("#pageloader").fadeOut();
Swal.fire({
icon: 'error',
title: 'Data not submitted',
text: 'Something went wrong, please try again after some time!'
});
}
});
});
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 recordDateField = document.getElementById('field-plan_date');
if (recordDateField) {
recordDateField.setAttribute('min', today);
}
var executionDateField = document.getElementById('execution-plan_date');
$('.edit-btn').click(function() {
var executionexeField = document.getElementById('execution-execution_date');
if (executionexeField && executionDateField && executionDateField.value) {
executionexeField.setAttribute('min', executionDateField.value);
}
});
if (executionDateField) {
executionDateField.addEventListener('change', function() {
var executionexeField = document.getElementById('execution-record_date');
if (executionexeField) {
executionexeField.setAttribute('min', executionDateField.value);
}
});
}
});
</script>
</body>
</html>