nhance/app/Views/leads_list.php
2026-03-23 18:33:11 +05:30

2353 lines
100 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.

<style>
.table th,
.table td {
padding: 8px;
}
table.dataTable tbody td {
padding: 4px 4px !important;
}
.col-12 {
max-width: 100% !important;
}
.dataTables_filter {
position: absolute;
}
.highlight {
border: 2px solid red;
background-color: #ffe6e6;
}
.column-header {
margin-right: 10px;
}
.form-section {
border: 1px solid #ccc;
padding: 15px;
margin-bottom: 20px;
}
.row-box {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
.select2-selection__choice {
background-color: #0a8794 !important;
color: white !important;
font-weight: bold;
}
.select2-selection__choice__remove {
color: white !important;
margin-right: 5px;
}
.custom-dropdown-menu {
display: none;
position: absolute;
background-color: #ffffff !important;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 0.25rem;
padding: 0.5rem 0;
min-width: 10rem;
z-index: 9999;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.custom-dropdown-menu .dropdown-item {
display: block !important;
width: 100% !important;
padding: 0.5rem 1rem !important;
color: #212529 !important;
text-decoration: none !important;
background-color: transparent !important;
}
.custom-dropdown-menu .dropdown-item:hover {
background-color: #f8f9fa !important;
color: #16181b !important;
cursor: pointer !important;
}
.addbtnStyle{
margin-left: 20px !important;
}
/* Modeal class */
.modal-content {
border-radius: 4px;
border: 1px solid #dee2e6;
}
.modal-header {
background: #f8f9fa;
border-bottom: 1px solid #dee2e6;
padding: 1rem 1.5rem;
}
.modal-title {
font-size: 1.1rem;
font-weight: 500;
color: #495057;
}
.modal-body {
padding: 1.5rem;
}
.policy-label {
font-weight: 500;
color: #495057;
margin-bottom: 1rem;
}
.radio-option {
border: 1px solid #dee2e6;
border-radius: 4px;
padding: 0.75rem 1rem;
margin-bottom: 0.5rem;
cursor: pointer;
background: #fff;
}
.radio-option:hover {
border-color: #007bff;
background: #f8f9fa;
}
.radio-option.selected {
border-color: #007bff;
background: #e7f3ff;
}
.form-check {
margin-bottom: 0;
}
.form-check-input {
margin-right: 0.5rem;
}
.form-check-label {
cursor: pointer;
font-weight: normal;
margin-bottom: 0;
}
.modal-footer {
border-top: 1px solid #dee2e6;
padding: 1rem 1.5rem;
}
.btn {
font-size: 0.9rem;
padding: 0.5rem 1rem;
}
.dataTables_length label {height: 21px !important;}
/* Modeal class */
.table-responsive {
overflow-x: auto !important;
}
</style>
<div class="row" id="leads_list">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row mb-2">
<!-- <div class="col-sm-12">
<h4 class="page-title">Opportunities List</h4>
</div> -->
<div class="col-3" id="status_change" style="text-align: right; position: relative;top: 56px; left: 291px;">
<!-- <button type="button" id="btnAdd" class="btn btn-primary waves-effect waves-light" onclick="openLeadTypeAskModal();">Add</button> -->
</div>
</div>
<div>
<div class="table-responsive">
<table data-custom-table-css="table" class="table mb-0 nowrap w-100 table-centered" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th><div class="column-header">S.No &nbsp;</div></th>
<th><div class="column-header">Opportunity Type &nbsp;</div></th>
<th><div class="column-header">Issuer &nbsp;</div></th>
<th><div class="column-header">Client Type &nbsp;</div></th>
<th><div class="column-header">Client / Branch &nbsp;</div></th>
<th><div class="column-header">Entity Type &nbsp;</div></th>
<th><div class="column-header">Branch Name &nbsp;</div></th>
<th><div class="column-header">Branch Code &nbsp;</div></th>
<th><div class="column-header">Contact Person Name &nbsp;</div></th>
<th><div class="column-header">Contact Person Mobile &nbsp;</div></th>
<th><div class="column-header">Policy Type &nbsp;</div></th>
<th><div class="column-header">Status &nbsp;</div></th>
<th><div class="column-header">Action &nbsp;</div></th>
</tr>
</thead>
<tbody>
<?php if (isset($lead_data_list)) {?>
<?php foreach ($lead_data_list as $index => $row) {?>
<tr>
<td class="text-center">
<?php echo $index + 1; ?>
<?php if ($row['demography_file_status'] == "failed") {?>
<a href="<?php echo base_url('util/getMemberDataExcelFileErrors?lead_id=') . $row['id'] ?>"
class="mdi mdi-information-outline text-danger"
style="cursor: pointer; font-size: 16px"
data-toggle="tooltip"
data-placement="top"
title="Click to view the Demography File Error data" target="_blank">
</a>
<?php }?>
</td>
<td><?php echo $lead_type[$row['lead_type']] ?? '-'; ?></td>
<td><?php echo $issuer[$row['issuer']] ?? '-'; ?></td>
<td><?php echo $client_type[$row['client_type']] ?? '-'; ?></td>
<td><?php echo $row['client_type'] == 2 ? ($row['client_name'] ?? '-') : (($row['client_short_name'] ?? '-') . ' - ' . ($row['branch_name'] ?? '-')); ?></td>
<td><?php echo $row['entity_type'] ?? '-'; ?></td>
<td><?php echo $row['branch_name'] ?? '-'; ?></td>
<td><?php echo $row['branch_code'] ?? '-'; ?></td>
<td><?php echo $row['contact_person_name'] ?? '-'; ?></td>
<td><?php echo $row['contact_person_mobile'] ?? '-'; ?></td>
<td><?php echo $row['policy_type'] ?? '-'; ?></td>
<td><?php echo $lead_status[$row['status']] ?? '-'; ?></td>
<td>
<div class="btn-group dropdown">
<a href="javascript:void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm"
data-toggle="dropdown"
aria-expanded="false"
data-boundary="window"> <i class="mdi mdi-dots-horizontal"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<?php $isNonEb = isset($row['lead_form_type']) && (int) $row['lead_form_type'] === 2; ?>
<a class="dropdown-item btnEdit" data-id="<?php echo $row['id']; ?>" data-ft="<?php echo $row['lead_form_type']; ?>" onclick="getLeadsDataForEdit('<?php echo htmlspecialchars($row['id'], ENT_QUOTES) ?>', '<?php echo htmlspecialchars($row['lead_form_type'], ENT_QUOTES) ?>')">
<i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit
</a>
<?php if ($isNonEb) {?>
<a href="#" class="dropdown-item btnEdit2 btnRfqSheetList" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-note-text mr-2 text-muted font-18 vertical-middle"></i>RFQ
</a>
<?php if (! in_array($row['status'], ['queued', 'rfq_created', 'rfq_sent'])) {?>
<?php if (in_array(get_role_id(), [1, 5, 2, 3]) || in_array(BUSINESS_SUPPORT_TEAM_ID, user_team())) {?>
<a href="#" class="dropdown-item btnEdit3 btnQcrSheetList" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-note-text mr-2 text-muted font-18 vertical-middle"></i>QCR
</a>
<?php }?>
<?php }?>
<?php if ($row['status'] != 'queued' ){?>
<a href="#" class="dropdown-item btnInternalMailList" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-email mr-2 text-muted font-18 vertical-middle"></i>Send Internal Mail
</a>
<a href="#" class="dropdown-item btnInsurerMailList" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-email-outline mr-2 text-muted font-18 vertical-middle"></i>Send Insurer Mail
</a>
<a href="#" class="dropdown-item btnClientMailList" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-email-open mr-2 text-muted font-18 vertical-middle"></i>Send Client Mail
</a>
<a href="#" class="dropdown-item btnPlacementList" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-briefcase-check mr-2 text-muted font-18 vertical-middle"></i>Placement
</a>
<?php }?>
<?php } else {?>
<a href="<?php echo base_url('/rfq/list/') . $row['id'] . '/' . 1; ?>" class="dropdown-item btnEdit2" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-note-text mr-2 text-muted font-18 vertical-middle"></i>RFQ
</a>
<?php if (! in_array($row['status'], ['queued', 'rfq_created', 'rfq_sent'])) {?>
<?php if (in_array(get_role_id(), [1, 5, 2, 3]) || in_array(BUSINESS_SUPPORT_TEAM_ID, user_team())) {?>
<a href="<?php echo base_url('/rfq/list/') . $row['id'] . '/' . 2; ?>" class="dropdown-item btnEdit3" data-id="<?php echo $row['id']; ?>">
<i class="mdi mdi-note-text mr-2 text-muted font-18 vertical-middle"></i>QCR
</a>
<?php }?>
<?php }?>
<?php }?>
<a class="dropdown-item btnHistory font-color-black"
data-id="<?php echo $row['id']; ?>"
title="Click to view Mail History">
<i class="mdi mdi-history mr-2 text-muted font-18 vertical-middle"></i>Email History
</a>
</div>
</div>
</td>
</tr>
<?php }?>
<?php } else {?>
<tr>
<td colspan="14" class="text-center">No data available</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div><!-- end col -->
</div>
<!-- External CC Disclaimer Confirmation Modal (z-index elevated to appear above other open modals) -->
<div class="modal fade" id="external_cc_disclaimer_modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false" style="z-index: 1070;">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="mdi mdi-alert-outline text-warning mr-2"></i>External Mail Warning</h5>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>This mail will be sent to <strong>external email address(es)</strong>. Please review before proceeding.</p>
<p id="external_cc_disclaimer_list" class="text-muted small mb-0"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="confirm_external_send_btn">Yes, Send Mail</button>
</div>
</div>
</div>
</div>
<!-- Hidden field to hold selected lead id for mail modals -->
<input type="hidden" id="lead_id" value="">
<!-- Sheet creation wait message (shown over loader overlay) -->
<div id="sheet-wait-msg" style="display:none; position:fixed; z-index:99999; left:0; right:0; bottom:calc(50% - 70px); text-align:center; color:#fff; font-size:14px; pointer-events:none;">
Creating RFQ/QCR file, this may take a while, please wait...
</div>
<div class="modal fade" id="New_Lead_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel">Select Opportunity Type</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="radio-option selected" onclick="selectOption(this, 'lead_eb')">
<div class="form-check">
<input class="form-check-input" type="radio" name="lead_form_type" id="lead_eb" value="1" checked>
<label class="form-check-label" for="lead_eb">EB</label>
</div>
</div>
<div class="radio-option" onclick="selectOption(this, 'lead_non_eb')">
<div class="form-check">
<input class="form-check-input" type="radio" name="lead_form_type" id="lead_non_eb" value="2">
<label class="form-check-label" for="lead_non_eb">Non-EB</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="submitToRedirectLeadNewUrl(this)">Submit</button>
</div>
</div>
</div>
</div>
<div class="modal fade " id="EmailModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl" style="max-width: 1140px !important;">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Email History</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body history-container" style="padding:11px !important;">
</div>
</div>
</div>
</div>
<!-- Modal content for Send Placement Mail (Non-EB) -->
<div class="modal fade" id="placement_mail_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="false">
<div class="modal-dialog modal-full-width">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabel">Placement</h4>
<button type="button" id="close_btn" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="form-group col-md-12">
<label><span id="alert_msg" class="text-danger"></span></label>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="policy_start_date">Policy Start Date</label>
<input type="text" class="form-control" id="policy_start_date" name="policy_start_date" placeholder="DD/MM/YYY" value="">
</div>
<div class="form-group col-md-3">
<label for="policy_end_date">Policy End Date</label>
<input type="text" class="form-control" id="policy_end_date" name="policy_end_date" placeholder="DD/MM/YYY" value="">
</div>
<div class="form-group col-md-3">
<label for="placement_date">Placement Date</label>
<input type="text" class="form-control" id="placement_date" name="placement_date" placeholder="DD/MM/YYY" value="">
</div>
<div class="form-group col-md-3">
<label for="is_cd_switch">CD Entry</label>
<input id="is_cd_switch" type="checkbox" name="is_cd" value="1"
data-toggle="toggle" data-on="With CD" data-off="Without CD"
data-onstyle="info" data-offstyle="primary" data-style="border"
data-width="218" checked onchange="toggleCDEntry()">
</div>
<div class="form-group col-md-3">
<label for="premium_amount">Premium Amount</label>
<input type="text" class="form-control" id="premium_amount" name="premium_amount" placeholder="Enter Premium Amount" value="">
</div>
<div class="form-group col-md-3">
<label for="cd_amount">CD Amount</label>
<input type="text" class="form-control" id="cd_amount" name="cd_amount" placeholder="Enter CD Amount" value="">
</div>
<div class="form-group col-md-3">
<label for="total_amount">Total Amount</label>
<input type="text" class="form-control" id="total_amount" name="total_amount" placeholder="Enter Total Amount" value="">
</div>
<div class="form-group col-md-3">
<label for="is_installment_switch">Installemnt </label>
<input id="is_installment_switch" type="checkbox" name="is_installment" value="1"
data-toggle="toggle" data-on="With Installments" data-off="Without Installments"
data-onstyle="info" data-offstyle="primary" data-style="border"
data-width="218" style="height: 37.53px;" onchange="toggleInstallment()">
</div>
<div class="form-group col-md-3" id="no_of_installment_group" style="display: none;">
<label for="no_of_installment">No of Installments</label>
<input type="text" class="form-control" id="no_of_installment" name="no_of_installment" value="1">
</div>
</div>
<div class="row" id="not_installment">
<div class="form-group col-md-3">
<label for="payment_date">Payment Date</label>
<input type="text" class="form-control" id="payment_date" name="payment_date" placeholder="DD/MM/YYY" value="">
</div>
<div class="form-group col-md-3">
<label for="utr_no">UTR No.</label>
<input type="text" class="form-control" id="utr_no" name="utr_no" placeholder="Enter UTR No." value="">
</div>
</div>
<hr>
<div id="installment_form_row">
<!-- Installment rows will be added dynamically if needed -->
</div>
<hr>
<div class="form-row">
<!-- <div class="form-group col-md-6">
<label for="proposals"> Proposal(s) / Insurer(s) <span id="base_danger" class="text-danger">*</span></label>
<select class="form-control" id="proposals" name="proposals" required>
<option value="">Select Proposals</option>
</select>
</div> -->
<div class="form-group col-md-6">
<label for="placement_to"> TO <span id="base_danger" class="text-danger">*</span></label>
<select class="form-control" id="placement_to" name="placement_to" required>
<option value="">Select TO Mail</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="placement_cc">CC </label>
<select class="form-control" id="placement_cc" name="placement_cc" required multiple>
<?php if (isset($userList)) { ?>
<?php foreach ($userList as $user) { ?>
<option value="<?= $user['email']; ?>">
<?= $user['first_name'] . ' - ' . $user['email']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
</div>
<div class="form-group col-md-12">
<label for="placement_subject">Subject</label>
<input type="text" class="form-control" id="placement_subject" name="placement_subject" value="" placeholder="Enter Subject">
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-12">
<label for="placement_mail_content">Mail Content</label>
<textarea id="placement_mail_content" class="form-control" name="placement_mail_content" rows="3"></textarea>
</div>
</div>
</div>
<br>
<h4>Attachments Files</h4>
<hr>
<div class="attachment-upload-wrap" data-attachment-target="#placement_mail_attachment">
<div class="form-row align-items-end">
<div class="form-group col-md-4 mb-2">
<label>Document Label <span class="text-danger">*</span></label>
<input type="text" class="form-control att-docs-name" placeholder="Enter document label">
</div>
<div class="form-group col-md-5 mb-2">
<label>File <span class="text-danger">*</span></label>
<input type="file" class="form-control att-file-input">
</div>
<div class="form-group col-md-3 mb-2">
<label>&nbsp;</label><br>
<button type="button" class="btn btn-secondary btn-sm btn-upload-att">Upload & Add</button>
</div>
</div>
</div>
<div class="form-group" id="placement_mail_attachment"></div>
<div class="form-group" id="external_cc_placement_wrap">
<label for="external_cc_placement">External CC <small class="text-muted">(comma-separated email addresses)</small></label>
<input type="text" class="form-control" id="external_cc_placement" placeholder="e.g. john@external.com, jane@external.com">
</div>
<!-- if status is won disable the button -->
<div class="form-group text-right m-b-0">
<button type="submit" id="placement_mail_btn" class="btn btn-primary" onclick="constructURL(3)">Send Mail</button>
</div>
</div>
</div><!-- /.modal-content -->
</div>
</div><!-- /.modal -->
<!-- Modal content for Send Insurer and Client Mail (Non-EB RFQ/QCR mail) -->
<div class="modal fade" id="list_model" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="false">
<div class="modal-dialog modal-full-width">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myCenterModalLabelForClientAndInsurer">CLIENT&INSURER</h4>
<button type="button" id="close_btn" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="form-row" id="input_for_row">
</div>
</div>
<br>
<h4>Attachments Files</h4>
<hr>
<div class="attachment-upload-wrap" data-attachment-target="#insurer_or_clinet_mail_attachment">
<div class="form-row align-items-end">
<div class="form-group col-md-4 mb-2">
<label>Document Label <span class="text-danger">*</span></label>
<input type="text" class="form-control att-docs-name" placeholder="Enter document label">
</div>
<div class="form-group col-md-5 mb-2">
<label>File <span class="text-danger">*</span></label>
<input type="file" class="form-control att-file-input">
</div>
<div class="form-group col-md-3 mb-2">
<label>&nbsp;</label><br>
<button type="button" class="btn btn-secondary btn-sm btn-upload-att">Upload & Add</button>
</div>
</div>
</div>
<div class="form-group" id="insurer_or_clinet_mail_attachment">
<div class="form-row attachmet_row">
<?php echo isset($attachment_html) && ! empty($attachment_html) ? $attachment_html : ''; ?>
</div>
</div>
<div class="form-group" id="external_cc_client_wrap" style="display:none;">
<label for="external_cc_client">External CC <small class="text-muted">(comma-separated email addresses)</small></label>
<input type="text" class="form-control" id="external_cc_client" placeholder="e.g. john@external.com, jane@external.com">
</div>
<div class="form-group text-right m-b-0" id="hide_smbt_btn">
<button type="submit" class="btn btn-primary" onclick="constructURL(1)">Send Mail</button>
</div>
</div>
</div><!-- /.modal-content -->
</div>
</div><!-- /.modal -->
<!-- Modal content for Send Internal Mail -->
<div class="modal fade" id="internal_mail_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="false">
<div class="modal-dialog modal-full-width">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="internal_mail_modal_label">Send Internal Mail</h4>
<button type="button" id="close_btn" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-4">
<label for="to">TO</label>
<select class="form-control" id="to" name="to" required>
<?php if (isset($userList)) {?>
<?php foreach ($userList as $user) {?>
<option value="<?php echo $user['email'];?>">
<?php echo $user['first_name'].' - '.$user['email'];?>
</option>
<?php }?>
<?php }?>
</select>
</div>
<div class="form-group col-md-4">
<label for="cc">CC </label>
<select class="form-control" id="cc" name="cc" required multiple>
<?php if ($page_name == "RFQ") {$exclusiveUserList = $userList;}?>
<?php if (isset($exclusiveUserList)) {?>
<?php foreach ($exclusiveUserList as $user) {?>
<?php if ($page_name == "RFQ" || in_array($user['role'], [1, 5]) || in_array($user['team_id'], [6, 7])) {?>
<option value="<?php echo $user['id'];?>">
<?php echo $user['first_name'].' - '.$user['email'];?>
</option>
<?php }?>
<?php }?>
<?php }?>
</select>
</div>
<div class="form-group col-md-12">
<label for="subject">Subject</label>
<input id="subject" type="text" class="form-control" name="subject" value="<?php echo isset($subject) ? $subject : " " ?>">
</div>
<div class="form-group col-md-12">
<label for="internal_mail_content">Mail Content</label>
<textarea id="internal_mail_content" class="form-control" name="internal_mail_content" rows="3"><?php echo isset($mail_content) ? $mail_content : " " ?></textarea>
</div>
</div>
</div>
<br>
<h4>Attachments Files</h4>
<hr>
<div class="attachment-upload-wrap" data-attachment-target="#internal_mail_attachment">
<div class="form-row align-items-end">
<div class="form-group col-md-4 mb-2">
<label>Document Label <span class="text-danger">*</span></label>
<input type="text" class="form-control att-docs-name" placeholder="Enter document label">
</div>
<div class="form-group col-md-5 mb-2">
<label>File <span class="text-danger">*</span></label>
<input type="file" class="form-control att-file-input">
</div>
<div class="form-group col-md-3 mb-2">
<label>&nbsp;</label><br>
<button type="button" class="btn btn-secondary btn-sm btn-upload-att">Upload & Add</button>
</div>
</div>
</div>
<div class="form-group" id="internal_mail_attachment">
<div class="form-row attachmet_row">
<?php echo isset($attachment_html) && ! empty($attachment_html) ? $attachment_html : ''; ?>
</div>
</div>
<br>
<div class="form-group text-right m-b-0" id="hide_smbt_btn">
<button type="submit" class="btn btn-primary" onclick="constructURL(2)">Send Mail</button>
</div>
</div>
</div><!-- /.modal-content -->
</div>
</div><!-- /.modal -->
<script>
function toggleCDEntry() {
// alert('NEW');
var switch_status = ($("#is_cd_switch").is(":checked")? "on" : "off");
console.log("CD Switch status",switch_status);
if (switch_status == "on"){
$("#cd_amount").show();
$("#total_amount").show();
$("#cd_amount").closest('.form-group').show();
$("#total_amount").closest('.form-group').show();
}
else {
$("#cd_amount").hide();
$("#total_amount").hide();
$("#cd_amount").closest('.form-group').hide();
$("#total_amount").closest('.form-group').hide();
}
}
function toggleInstallment() {
var switch_status = ($("#is_installment_switch").is(":checked")? "on" : "off");
console.log("Installment Switch status",switch_status);
if (switch_status == "on"){
$("#no_of_installment_group").show();
}
else {
$("#no_of_installment_group").hide();
}
}
// Global Jodit editor config (same as RFQ page)
var editorConfig = {
buttons: [
"bold",
"italic",
"strikethrough",
"|",
"superscript",
"subscript",
"|",
"align",
"fontsize",
"|",
"source"
],
fontsize: ["8px", "10px", "12px", "14px", "16px", "18px", "20px", "22px", "24px"],
showPlaceholder: false,
toolbarButtonSize: "small",
toolbarAdaptive: false,
saveHeightInStorage: true,
minHeight: 400,
height: 400,
defaultMode: "1",
enableDragAndDropFileToEditor: true,
placeholder: "Start typing here...",
};
// New menu
document.addEventListener("DOMContentLoaded", function () {
const table = document.getElementById("tickets-table");
// RFQ_or_QCR: 1 = RFQ (insurer/internal), 2 = QCR (client)
window.RFQ_or_QCR = 1;
// Logged-in user role id (used in mail modal rendering)
window.user_role_id = <?php echo get_role_id(); ?>;
function createCustomDropdown(row) {
const originalDropdown = row.querySelector('.dropdown-menu');
if (!originalDropdown) return null;
const customDropdown = document.createElement('div');
customDropdown.className = 'custom-dropdown-menu';
// Clone the items but remove their original click handlers
const items = originalDropdown.querySelectorAll('.dropdown-item');
items.forEach(item => {
const newItem = item.cloneNode(true);
// Preserve the attributes but remove the onclick
newItem.removeAttribute('onclick');
customDropdown.appendChild(newItem);
});
return customDropdown;
}
let activeDropdown = null;
table.querySelectorAll("tbody tr").forEach(row => {
const customDropdown = createCustomDropdown(row);
if (!customDropdown) return;
document.body.appendChild(customDropdown);
row.addEventListener("click", function(event) {
if (event.target.closest('.dropdown-toggle')) {
event.stopPropagation();
const originalDropdown = event.target.closest('.btn-group').querySelector('.dropdown-menu');
if (originalDropdown) {
if (activeDropdown) {
activeDropdown.style.display = 'none';
}
const rect = event.target.getBoundingClientRect();
customDropdown.style.display = 'block';
customDropdown.style.position = 'fixed';
customDropdown.style.left = `${rect.left}px`;
customDropdown.style.top = `${rect.bottom + 5}px`;
activeDropdown = customDropdown;
}
return;
}
if (event.target.closest('td:last-child')) {
return;
}
if (activeDropdown) {
activeDropdown.style.display = 'none';
}
const rect = event.target.getBoundingClientRect();
customDropdown.style.display = 'block';
customDropdown.style.position = 'fixed';
customDropdown.style.left = `${rect.left}px`;
customDropdown.style.top = `${rect.bottom + 5}px`;
activeDropdown = customDropdown;
event.stopPropagation();
});
customDropdown.querySelectorAll('.dropdown-item').forEach(item => {
item.addEventListener('click', function(e) {
console.log("##############");
e.preventDefault();
e.stopPropagation();
// Get the data-id and other attributes from the original button
const originalItem = row.querySelector(`.dropdown-item[data-id="${this.getAttribute('data-id')}"]`);
// For edit functionality
if (this.classList.contains('btnEdit')) {
const id = this.getAttribute('data-id');
const lead_form_type = this.getAttribute('data-ft');
console.log('second drop lead_form_type', lead_form_type)
if (id) {
getLeadsDataForEdit(id, lead_form_type);
}
}else if (this.classList.contains('btnHistory')) {
let lead_id = this.getAttribute('data-id');
if(lead_id){ console.log("******** Clicked from td lead_id-", lead_id); getLeadsDataForMailHistory(lead_id); }
else{ console.log("******** Clicked from td but i don`t have lead_id"); }
}else if (this.classList.contains('btnRfqSheetList')) {
const leadId = this.getAttribute('data-id');
if (leadId) {
createRfqSheetFromList(leadId);
}
}else if (this.classList.contains('btnQcrSheetList')) {
const leadId = this.getAttribute('data-id');
if (leadId) {
createQcrSheetFromList(leadId);
}
}else if (this.classList.contains('btnInternalMailList')) {
const leadId = this.getAttribute('data-id');
if (leadId) {
openInternalMailFromList(leadId);
}
}else if (this.classList.contains('btnInsurerMailList')) {
const leadId = this.getAttribute('data-id');
if (leadId) {
openInsurerMailFromList(leadId);
}
}else if (this.classList.contains('btnClientMailList')) {
const leadId = this.getAttribute('data-id');
if (leadId) {
openClientMailFromList(leadId);
}
}else if (this.classList.contains('btnPlacementList')) {
const leadId = this.getAttribute('data-id');
if (leadId) {
openPlacementFromList(leadId);
}
}
else{
const onclickAttr = this.getAttribute('onclick');
if (onclickAttr) {
eval(onclickAttr);
}
}
// For RFQ links
const href = this.getAttribute('href');
if (
href &&
href !== '#' &&
!this.classList.contains('btnEdit') &&
!this.classList.contains('btnRfqSheetList') &&
!this.classList.contains('btnQcrSheetList') &&
!this.classList.contains('btnInternalMailList') &&
!this.classList.contains('btnInsurerMailList') &&
!this.classList.contains('btnClientMailList') &&
!this.classList.contains('btnPlacementList')
) {
window.location.href = href;
}
// Close the dropdown
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
});
});
});
// Close dropdown when clicking outside
document.addEventListener("click", function() {
if (activeDropdown) {
activeDropdown.style.display = 'none';
activeDropdown = null;
}
});
document.addEventListener("click", function(e) {
const historyBtn = e.target.closest(".btnHistory");
if (historyBtn && historyBtn.dataset.id) {
let lead_id = historyBtn.dataset.id;
console.log("******** in triple dot id available - " + lead_id);
getLeadsDataForMailHistory(lead_id);
}
});
});
// Datatable document ready
$(document).ready(function() {
var ticketsTable = $('#tickets-table');
if (ticketsTable.length) {
ticketsTable.DataTable({
scrollX: true,
// dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>", // Pagination at the bottom, without page length selector
dom: "<'row'<'col-sm-7'f><'col-sm-5 text-right'B>>" + // Filter left, buttons right
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: '<i class="mdi mdi-filter" ></i><span class=" btn-custom"> Filter </span>',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openOpportunitiesListFilterNav();
}
},
{
text: '<i class="mdi mdi-plus" ></i><span class=" btn-custom"> Add </span>',
className: 'btn app-btn-primary mr-2',
action: function(e, dt, node, config) {
openLeadTypeAskModal();
}
},
{
extend: 'collection',
text: '<span class=" btn-custom"> Export </span><i class="mdi mdi-menu-down"></i>',
className: 'btn app-btn-secondary ',
buttons: [
{
extend: 'csv',
text: '<i class="mdi mdi-file-delimited " ></i><span class=" btn-custom"> CSV </span>',
title: 'Opportunity-List',
className: 'app-btn-primary ',
exportOptions: {
columns: ':not(:last-child)'
},
}
]
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true, // Enable pagination
pageLength: 10, // Set default number of rows per page (optional)
// ordering: false,
});
} else {
console.error("Table not found.");
}
});
function openLeadTypeAskModal(){
var myModal = new bootstrap.Modal(document.getElementById('New_Lead_modal'));
myModal.show();
}
function submitToRedirectLeadNewUrl(){
console.log('function called')
// let Lead_type = $('#openLeadTypeAskModal').val()
let Lead_type = $('input[name="lead_form_type"]:checked').val();
console.log('Lead_type ', Lead_type)
let url = '<?php echo base_url('/util/getLeadNonEB/') ?>' + Lead_type + '/0';
console.log('url ', url)
window.location.href = url;
}
function getLeadsDataForEdit(lead_id, lead_form_type){
console.log('lead_id', lead_id);
console.log('lead_form_type', lead_form_type);
let actual_lead_id = 0; // Hardcoded to 0 since this is an edit operation
//Here After Edit URL: /type / actual_lead_id (0) / lead_id
let url = '<?php echo base_url('/util/getLeadNonEB/') ?>' + lead_form_type + '/' + actual_lead_id + '/' + lead_id;
// old URL
// let url = '<?php echo base_url('/util/getLeadNonEB/') ?>' + lead_form_type + '/' + lead_id
console.log('url ', url)
window.location.href = url;
}
function getLeadsDataForMailHistory(lead_id){
console.log("******** Inside Fnz :", lead_id);
let url = '<?php echo base_url('/util/getLeadEmailHistory/') ?>' + lead_id;
console.log("******** Fetching:", url);
fetch(url, {
method: "GET",
headers: { "Accept": "application/json" }
})
.then(response => response.json())
.then(response => {
let container = document.querySelector(".history-container");
container.innerHTML = "";
if (response.status === "success" && response.data.length > 0) {
console.log("******** 1" + response.status);
let table = `
<div class="table-responsive">
<table data-custom-table-css="table" id="historytable" class="table table-striped mb-0 nowrap" cellspacing="0" id="tickets-table">
<thead class="bg-light">
<tr>
<th><div class="column-header">S.No&nbsp;</div></th>
<th><div class="column-header">From Mail&nbsp;</div></th>
<th><div class="column-header">To Mail&nbsp;</div></th>
<th><div class="column-header">BCC&nbsp;</div></th>
<th><div class="column-header">CC&nbsp;</div></th>
<th><div class="column-header">Type&nbsp;</div></th>
<th><div class="column-header">Status&nbsp;</div></th>
<th><div class="column-header">Date/Time&nbsp;</div></th>
</tr>
</thead>
<tbody>
`;
response.data.forEach((row, index) => {
let formattedDate = "-";
let statusValue = "-";
if (row.received_message) {
if (row.received_message.toLowerCase().includes("error")) {
statusValue = "Failed";
} else {
statusValue = "Success";
}
}
if (row.created_at) {
let dt = new Date(row.created_at);
let dateStr = dt.toLocaleDateString("en-GB", {
day: "2-digit",
month: "long",
year: "numeric"
});
let timeStr = dt.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: true
}).toLowerCase();
formattedDate = `${dateStr} ${timeStr}`;
}
let fromMails = "-";
if (row.from_mail) {
fromMails = row.from_mail
.split(",") // split by comma
.map(m => m.trim().replace(/^"|"$/g, "")) // trim + remove quotes at start/end
.filter(m => m !== "") // remo
.join("<br>"); // join with line break
}
let toMails = "-";
if (row.mail) {
toMails = row.mail
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
let ccMails = "-";
if (row.cc && row.cc.trim() !== "") {
ccMails = row.cc
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
let bccMails = "-";
if (row.bcc && row.bcc.trim() !== "") {
bccMails = row.bcc
.split(",")
.map(m => m.trim().replace(/^"|"$/g, ""))
.filter(m => m !== "")
.join("<br>");
}
table += `
<tr>
<td style="white-space: nowrap !important;">${index + 1}</td>
<td style="white-space: nowrap !important;">${fromMails}</td>
<td style="white-space: nowrap !important;">${toMails}</td>
<td style="white-space: nowrap !important;">${bccMails ? bccMails : '-'}</td>
<td style="white-space: nowrap !important;">${ccMails ? ccMails : '-'}</td>
<td style="white-space: nowrap !important;">${row.mail_type ? row.mail_type.toUpperCase() : '-'}</td>
<td style="white-space: nowrap !important;">${statusValue ? statusValue.toUpperCase() : '-'}</td>
<td style="white-space: nowrap !important;">${formattedDate}</td>
</tr>
`;
});
table += `</tbody></table>`;
container.innerHTML = table;
// show modal (if using Bootstrap 5)
} else {
container.innerHTML = `
<div class="d-flex justify-content-center align-items-center" style="height: 50vh; width:100%;">
<p class="text-center font-color-black"><i>${response.message ?? "No History Available"}</i></p>
</div>
`;
}
// Show modal always
new bootstrap.Modal(document.getElementById("EmailModal")).show();
})
.catch(error => {
console.log("******** 3" + error);
document.querySelector(".history-container").innerHTML = `
<div class="d-flex justify-content-center align-items-center" style="height: 50vh; width:100%;">
<p class="text-center font-color-black"><i>No Data Found</i></p>
</div>
`;
let EmailModal = new bootstrap.Modal(document.getElementById("EmailModal"));
EmailModal.show();
console.error(error);
});
}
</script>
<script>
function showModal(mail_type) {
if (mail_type == 1) {
insurerAndClientMailPopUp();
} else if (mail_type == 2) {
var myModal = new bootstrap.Modal(document.getElementById('internal_mail_modal'));
myModal.show();
// Initialize Jodit for internal mail content when modal opens
if (typeof Jodit !== 'undefined' && $('#internal_mail_content').length) {
Jodit.make("#internal_mail_content", editorConfig);
}
// Initialize select2 for TO / CC when modal opens
if ($('#to').length) {
$('#to').select2({
placeholder: 'Select TO Mail',
});
}
if ($('#cc').length) {
$('#cc').select2({
placeholder: 'Select CC Mail',
});
}
}
}
function insurerAndClientMailPopUp() {
var url = '';
var lead_id = $('#lead_id').val();
var modalTitle = 'Send mail';
console.log('RFQ_or_QCR' + RFQ_or_QCR);
if (RFQ_or_QCR == 2) {
modalTitle = 'Client Mail';
$('#myCenterModalLabelForClientAndInsurer').html(modalTitle);
console.log('modalTitle' + modalTitle);
url = '<?php echo base_url('leads/list/') ?>' + lead_id;
$('#external_cc_client_wrap').show();
$('#external_cc_client').val('');
} else {
modalTitle = 'Insurer Mail';
$('#myCenterModalLabelForClientAndInsurer').html(modalTitle);
console.log('modalTitle' + modalTitle);
url = '<?php echo base_url('util/getLevelContects') ?>';
$('#external_cc_client_wrap').hide();
$('#external_cc_client').val('');
}
ajaxRequestForGetMailData(url);
var myModal = new bootstrap.Modal(document.getElementById('list_model'));
myModal.show();
}
function ajaxRequestForGetMailData(url) {
console.log(url);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: function(res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
appendInput(res.data);
},
error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
}
});
}
function appendInput(data) {
console.log("append data:", data);
var lead_id = $('#lead_id').val();
$('#input_for_row').empty();
let html = '';
if (RFQ_or_QCR == 2) {
const url = '<?php echo base_url('leads/list') ?>?lead_id=' + lead_id;
html += `
<div class="form-group col-md-12">
<label for="contact_mail">Client Contact Mail</label>
<input value="${data.contact_person_email || ''}" type="text" id="contact_mail" class="form-control" placeholder="Contact Mail">
</div>
`;
if (!data.contact_person_email) {
html += `
<div class="form-group col-md-4">
<a href="${url}">Click here to update mail ID</a>
</div>
`;
}
if (user_role_id == 1 || user_role_id == 5) {
html += `
<div class="form-group col-md-6">
<label for="client_cc">CC </label>
<select class="form-control" id="client_cc" name="client_cc" required multiple>
<?php if ($page_name == "RFQ") {$exclusiveUserList = $userList;}?>
<?php if (isset($exclusiveUserList)) {?>
<?php foreach ($exclusiveUserList as $user) {?>
<?php if ($page_name == "RFQ" || in_array($user['role'], [1, 5]) || in_array($user['team_id'], [6, 7])) {?>
<option value="<?php echo $user['id'];?>">
<?php echo $user['first_name'].' - '.$user['email'];?>
</option>
<?php }}?>
<?php }?>
</select>
</div>
<div class="form-group col-md-6">
<label for="client_bcc">BCC </label>
<select class="form-control" id="client_bcc" name="client_bcc" required multiple>
<?php if ($page_name == "RFQ") {$exclusiveUserList = $userList;}?>
<?php if (isset($exclusiveUserList)) {?>
<?php foreach ($exclusiveUserList as $user) {?>
<?php if ($page_name == "RFQ" || in_array($user['role'], [1, 5]) || in_array($user['team_id'], [6, 7])) {?>
<option value="<?php echo $user['id'];?>">
<?php echo $user['first_name'].' - '.$user['email'];?>
</option>
<?php }}?>
<?php }?>
</select>
</div>
`;
}
html += `
<div class="form-group col-md-12">
<label for="mail_subject">Subject</label>
<input type="text" id="mail_subject" class="form-control"
value="${window.preloadedMailSubject || ''}" placeholder="Subject">
</div>
`;
} else {
const contacts = data || {};
html = `
<div class="form-group col-md-4">
<label for="insurerContact">Insurers</label>
<select id="insurerContact" class="form-control" name="insurerContact[]" multiple>
<option></option>
`;
for (const id in contacts) {
const contact = contacts[id];
html += `
<option value="${contact.id}" data-value="${contact.insurer_branch_id}-${contact.insurer_id}" >${contact.insurer_name} - ${contact.branch_code} - ${contact.contact_person_name} - ${contact.contact_person_email}</option>
`;
}
html += `
</select>
</div>
`;
html += `
<div class="form-group col-md-4">
<label for="client_cc">CC </label>
<select class="form-control" id="client_cc" name="client_cc" required multiple>
<?php if ($page_name == "RFQ") {$exclusiveUserList = $userList;}?>
<?php if (isset($exclusiveUserList)) {?>
<?php foreach ($exclusiveUserList as $user) {?>
<?php if ($page_name == "RFQ" || in_array($user['role'], [1, 5]) || in_array($user['team_id'], [6, 7])) {?>
<option value="<?php echo $user['id'];?>">
<?php echo $user['first_name'].' - '.$user['email'];?>
</option>
<?php }?>
<?php }}?>
</select>
</div>
<div class="form-group col-md-4">
<label for="client_bcc">BCC </label>
<select class="form-control" id="client_bcc" name="client_bcc" required multiple>
<?php if ($page_name == "RFQ") {$exclusiveUserList = $userList;}?>
<?php if (isset($exclusiveUserList)) {?>
<?php foreach ($exclusiveUserList as $user) {?>
<?php if ($page_name == "RFQ" || in_array($user['role'], [1, 5]) || in_array($user['team_id'], [6, 7])) {?>
<option value="<?php echo $user['id'];?>">
<?php echo $user['first_name'].' - '.$user['email'];?>
</option>
<?php }}?>
<?php }?>
</select>
</div>
`;
html += `
<div class="form-group col-md-12">
<label for="mail_subject">Subject</label>
<input type="text" id="mail_subject" class="form-control" value="${window.preloadedMailSubject || ''}" placeholder="Subject">
</div>
`;
}
html += `
<div class="form-group col-md-12">
<label for="insurer_and_client_mail_content">Mail Content</label>
<textarea id="insurer_and_client_mail_content" class="form-control" name="insurer_and_client_mail_content" rows="3">${window.preloadedMailContent || ''}</textarea>
</div>
`;
$('#input_for_row').append(html);
// Initialize select2 for the dropdown if insurerContact is present
if ($('#insurerContact').length) {
$('#insurerContact').select2({
placeholder: 'Select an Insurer',
});
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
}
// Initialize select2 for the dropdown if Client is present
if ($('#client_cc').length) {
$('#client_cc').select2({
placeholder: 'Select an CC',
});
$('#client_bcc').select2({
placeholder: 'Select an BCC',
});
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
}
// Initialize the Jodit editor
if (typeof Jodit !== 'undefined') {
Jodit.make("#insurer_and_client_mail_content", editorConfig);
}
}
function validateExternalCC(rawValue) {
if (!rawValue || rawValue.trim() === '') return { valid: true, emails: [] };
var emails = rawValue.split(',').map(function(e) { return e.trim(); }).filter(function(e) { return e !== ''; });
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var invalid = emails.filter(function(e) { return !emailRegex.test(e); });
if (invalid.length > 0) {
return { valid: false, emails: emails, invalid: invalid };
}
return { valid: true, emails: emails };
}
function showExternalCCDisclaimer(emails, onConfirmCallback) {
var listHtml = 'Sending to: <strong>' + emails.join(', ') + '</strong>';
$('#external_cc_disclaimer_list').html(listHtml);
window._externalCCSendCallback = onConfirmCallback;
var disclaimerModalEl = document.getElementById('external_cc_disclaimer_modal');
var disclaimerModal = new bootstrap.Modal(disclaimerModalEl);
disclaimerModal.show();
// Elevate the latest backdrop so it sits above the parent mail modal
setTimeout(function() {
$('.modal-backdrop').last().css('z-index', 1065);
}, 150);
}
$(document).on('click', '#confirm_external_send_btn', function () {
// Close disclaimer modal first
$('#external_cc_disclaimer_modal').modal('hide');
// Execute the pending send callback
if (typeof window._externalCCSendCallback === 'function') {
window._externalCCSendCallback();
window._externalCCSendCallback = null;
}
});
function constructURL(url_type) {
if (url_type == 1) {
var validationStatus = checkMailValidation();
if (!validationStatus) {
toastr.error("All Client Mail ID's Should Contain Same Domain", "Error");
return;
}
if (RFQ_or_QCR == 2) {
var externalCCRaw = $('#external_cc_client').val().trim();
var result = validateExternalCC(externalCCRaw);
if (!result.valid) {
toastr.error('Invalid email(s) in External CC: ' + result.invalid.join(', '), 'Error');
return;
}
if (result.emails.length > 0) {
showExternalCCDisclaimer(result.emails, function() {
constructURL_ForInsurerAndClientMailSend();
});
} else {
constructURL_ForInsurerAndClientMailSend();
}
} else {
constructURL_ForInsurerAndClientMailSend();
}
} else if (url_type == 2) {
constructURL_ForInternalMailSend();
} else if (url_type == 3) {
var externalCCRaw = $('#external_cc_placement').val().trim();
var result = validateExternalCC(externalCCRaw);
if (!result.valid) {
toastr.error('Invalid email(s) in External CC: ' + result.invalid.join(', '), 'Error');
return;
}
if (result.emails.length > 0) {
showExternalCCDisclaimer(result.emails, function() {
constructURL_ForPlacementMailSend();
});
} else {
constructURL_ForPlacementMailSend();
}
}
}
// Insurer and Client Mail
function constructURL_ForInsurerAndClientMailSend() {
var lead_id = $('#lead_id').val();
var mail_content = $('#insurer_and_client_mail_content').val();
var subject = $('#mail_subject').val();
var bcc = $('#client_bcc').val();
var cc = $('#client_cc').val();
var contact_mail = $("#contact_mail").val();
// Convert cc to JSON string
cc = cc.map(Number);
cc = JSON.stringify(cc);
// Convert bcc to JSON string
bcc = bcc.map(Number);
bcc = JSON.stringify(bcc);
var selectedFiles = [];
$('#insurer_or_clinet_mail_attachment .multi_file_attachment:checked').each(function () {
selectedFiles.push($(this).val());
});
// Prepare FormData object
var formData = new FormData();
formData.append('lead_id', lead_id);
formData.append('mail_content', mail_content);
formData.append('subject', subject);
formData.append('cc', cc);
formData.append('bcc', bcc);
formData.append('selected_attachment_files', JSON.stringify(selectedFiles));
if (RFQ_or_QCR == 2) {
var externalCCClient = validateExternalCC($('#external_cc_client').val().trim()).emails;
formData.append('external_cc', JSON.stringify(externalCCClient));
formData.append('contact_mail', contact_mail);
formData.append('file_type', 'qcr');
formData.append('recipient_type', 'client');
formData.append('recipient_mail', '');
} else {
var insurerContact = $('#insurerContact').val();
insurerContact = insurerContact.map(Number);
let insurerIds = [];
$("#insurerContact option:selected").each(function () {
insurerIds.push($(this).data("value"));
});
formData.append('file_type', 'rfq');
formData.append('recipient_type', 'insurer');
formData.append('recipient_mail', JSON.stringify(insurerContact));
formData.append('insurer_ids', JSON.stringify(insurerIds));
}
ajaxRequest(formData);
}
// Internal Mail
function constructURL_ForInternalMailSend() {
var lead_id = $('#lead_id').val();
let to = $('#to').val();
let mail_content = $('#internal_mail_content').val();
let subject = $('#subject').val();
let cc = $('#cc').val();
// Convert cc to JSON string
cc = cc.map(Number);
cc = JSON.stringify(cc);
// Determine file type
var file_type = RFQ_or_QCR == 2 ? 'qcr' : 'rfq';
var selectedFiles = [];
$('#internal_mail_attachment .multi_file_attachment:checked').each(function () {
selectedFiles.push($(this).val());
});
// Create FormData
var formData = new FormData();
formData.append('lead_id', lead_id);
formData.append('file_type', file_type);
formData.append('recipient_type', 'internal');
formData.append('to', to);
formData.append('cc', cc);
formData.append('subject', subject);
formData.append('mail_content', mail_content);
formData.append('recipient_mail', '');
formData.append('selected_attachment_files', JSON.stringify(selectedFiles));
ajaxRequest(formData);
}
// Placement mail (Non-EB)
function constructURL_ForPlacementMailSend() {
var lead_id = $('#lead_id').val();
let to = $('#placement_to').val();
let placement_date = $('#placement_date').val();
let payment_date = $('#payment_date').val();
let utr_no = $('#utr_no').val();
let premium_amount = $('#premium_amount').val();
let total_amount = $('#total_amount').val();
let cd_amount = $('#cd_amount').val();
let subject = $('#placement_subject').val();
let mail_content = $('#placement_mail_content').val();
let proposal_insurer = null;
let insurer_and_branch = null;
let cc = $('#placement_cc').val();
let is_cd = $("#is_cd_switch").is(":checked") ? 1 : 0;
let no_of_installment = $('#no_of_installment').val();
let is_installment = $("#is_installment_switch").is(":checked") ? 1 : 0;
let policy_end_date = $('#policy_end_date').val();
let policy_start_date = $('#policy_start_date').val();
var selectedFiles = [];
$('#placement_mail_attachment .multi_file_attachment:checked').each(function () {
selectedFiles.push($(this).val());
});
let data = [];
$('#installment_form_row .form-row').each(function () {
var lead_id = $('#lead_id').val();
let installment_amount = $(this).find('input[name="installment_amount[]"]').val();
let payment_date = $(this).find('input[name="payment_date[]"]').val();
let utr_no = $(this).find('input[name="utr_no[]"]').val();
let id = $(this).find('input[name="installment_primary_key[]"]').val();
let obj = {
lead_id: lead_id,
installment_amount: installment_amount,
payment_date: payment_date,
utr_no: utr_no
};
if (id != undefined && id != null && id != '') {
obj.id = id;
}
data.push(obj);
});
// Prepare FormData
var formData = new FormData();
formData.append('lead_id', lead_id);
formData.append('file_type', RFQ_or_QCR == 2 ? 'qcr' : 'rfq');
formData.append('recipient_type', 'placement');
formData.append('recipient_mail', JSON.stringify(to));
formData.append('cc', JSON.stringify(cc));
formData.append('subject', subject);
formData.append('proposal_insurer', proposal_insurer);
formData.append('insurer_and_branch', insurer_and_branch);
formData.append('placement_date', placement_date);
formData.append('payment_date', payment_date);
formData.append("is_cd", is_cd);
formData.append('utr_no', utr_no);
formData.append('premium_amount', premium_amount);
formData.append('total_amount', total_amount);
formData.append('cd_amount', cd_amount);
formData.append('mail_content', mail_content);
formData.append('selected_attachment_files', JSON.stringify(selectedFiles));
formData.append('installments', JSON.stringify(data));
formData.append('no_of_installment', no_of_installment);
formData.append('is_installment', is_installment);
formData.append('policy_end_date', policy_end_date);
formData.append('policy_start_date', policy_start_date);
var externalCCPlacement = validateExternalCC($('#external_cc_placement').val().trim()).emails;
var mergedPlacementCC = (cc || []).concat(externalCCPlacement);
formData.set('cc', JSON.stringify(mergedPlacementCC));
ajaxRequest(formData);
}
function createRfqSheetFromList(leadId) {
var apiURL = '<?php echo base_url("leads/createRfqSheet") ?>';
$('#sheet-wait-msg').fadeIn();
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: apiURL,
type: "GET",
data: { lead_id: leadId },
dataType: 'json',
success: function(res) {
$('#sheet-wait-msg').fadeOut();
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (res.status === 'success' && res.code === 200 && res.sheet_url) {
window.open(res.sheet_url, '_blank');
} else {
toastr.error(res.message || 'Failed to create RFQ sheet', 'Error');
}
},
error: function(xhr, status, error) {
$('#sheet-wait-msg').fadeOut();
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
toastr.error('Failed to create RFQ sheet', 'Error');
}
});
}
function createQcrSheetFromList(leadId) {
var apiURL = '<?php echo base_url("leads/createQcrSheet") ?>';
$('#sheet-wait-msg').fadeIn();
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: apiURL,
type: "GET",
data: { lead_id: leadId },
dataType: 'json',
success: function(res) {
$('#sheet-wait-msg').fadeOut();
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (res.status === 'success' && res.code === 200 && res.sheet_url) {
window.open(res.sheet_url, '_blank');
} else {
toastr.error(res.message || 'Failed to create QCR sheet', 'Error');
}
},
error: function(xhr, status, error) {
$('#sheet-wait-msg').fadeOut();
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
toastr.error('Failed to create QCR sheet', 'Error');
}
});
}
// Delegated click handler for all modal upload buttons
$(document).on('click', '.btn-upload-att', function () {
var wrap = $(this).closest('.attachment-upload-wrap');
var attachTarget = wrap.data('attachment-target');
var docsName = wrap.find('.att-docs-name').val().trim();
var fileInput = wrap.find('.att-file-input')[0];
var file = fileInput && fileInput.files[0];
var leadId = $('#lead_id').val();
if (!leadId) {
toastr.error('Lead not selected.', 'Error');
return;
}
if (!docsName) {
toastr.error('Please enter a document label.', 'Error');
return;
}
if (!file) {
toastr.error('Please select a file to upload.', 'Error');
return;
}
var formData = new FormData();
formData.append('lead_id', leadId);
formData.append('docs_name', docsName);
formData.append('attachment_file', file);
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: '<?php echo base_url("leads/uploadLeadAttachment") ?>',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (res.status === 'success') {
$(attachTarget).html(res.attachment_html || '');
wrap.find('.att-docs-name').val('');
wrap.find('.att-file-input').val('');
toastr.success('File uploaded successfully.', 'Success');
} else {
toastr.error(res.message || 'Upload failed.', 'Error');
}
},
error: function (xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText, status, error);
toastr.error('Upload failed.', 'Error');
}
});
});
function fetchPlacementData(leadId, callback) {
var apiURL = '<?php echo base_url("rfq/placementData") ?>/' + leadId;
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: apiURL,
type: "GET",
dataType: 'json',
success: function(res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (res.status === 'success' && res.code === 200) {
if (typeof callback === 'function') {
callback(res.data || {});
}
} else {
toastr.error(res.message || 'Failed to load placement data', 'Error');
}
},
error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
toastr.error('Failed to load placement data', 'Error');
}
});
}
function fetchLeadMailTemplate(leadId, templateType, callback) {
var apiURL = '<?php echo base_url("leads/mailTemplate") ?>';
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: apiURL,
type: "GET",
data: { lead_id: leadId, template_type: templateType },
dataType: 'json',
success: function(res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (res.status === 'success' && res.code === 200) {
if (typeof callback === 'function') {
callback(res.subject || '', res.mail_content || '',res.attachment_html || '');
}
} else {
toastr.error(res.message || 'Failed to load mail template', 'Error');
}
},
error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
toastr.error('Failed to load mail template', 'Error');
}
});
}
function openInternalMailFromList(leadId) {
fetchLeadMailTemplate(leadId, 'rfq', function(subject, content,attachments) {
$('#lead_id').val(leadId);
$('#subject').val(subject);
$('#internal_mail_content').val(content);
$('#internal_mail_attachment').html('');
$('#internal_mail_attachment').html(attachments);
window.RFQ_or_QCR = 1;
showModal(2);
});
}
function openInsurerMailFromList(leadId) {
fetchLeadMailTemplate(leadId, 'rfq', function(subject, content,attachments) {
window.preloadedMailSubject = subject;
window.preloadedMailContent = content;
$('#insurer_or_clinet_mail_attachment').html('');
$('#insurer_or_clinet_mail_attachment').html(attachments);
$('#lead_id').val(leadId);
window.RFQ_or_QCR = 1;
showModal(1);
});
}
function openClientMailFromList(leadId) {
fetchLeadMailTemplate(leadId, 'qcr', function(subject, content,attachments) {
window.preloadedMailSubject = subject;
window.preloadedMailContent = content;
$('#insurer_or_clinet_mail_attachment').html('');
$('#insurer_or_clinet_mail_attachment').html(attachments);
$('#lead_id').val(leadId);
window.RFQ_or_QCR = 2;
showModal(1);
});
}
function openPlacementFromList(leadId) {
fetchPlacementData(leadId, function(data) {
fetchLeadMailTemplate(leadId, 'placement', function(subject, content, attachments) {
$('#lead_id').val(leadId);
$('#policy_start_date').val(data.policy_start_date || '');
$('#policy_end_date').val(data.policy_end_date || '');
$('#placement_date').val(data.placement_date || '');
$('#payment_date').val(data.payment_date || '');
$('#utr_no').val(data.utr_no || '');
$('#premium_amount').val(data.premium_amount || '');
$('#cd_amount').val(data.cd_amount || '');
$('#total_amount').val(data.total_amount || '');
// $('#is_cd_switch').prop('checked', (data.is_cd ?? 1) == 1);
// $('#is_installment_switch').prop('checked', (data.is_installment ?? 0) == 1);
// $('#no_of_installment').val(data.no_of_installment || 1);
$('#placement_subject').val(subject || '');
$('#placement_mail_content').val(content || '');
$('#placement_mail_attachment').html(attachments || '');
if (data.status == 'won') {
$('#placement_mail_btn').prop('disabled', true);
} else {
$('#placement_mail_btn').prop('disabled', false);
}
// Populate TO with client contact from lead data
var $placementTo = $('#placement_to');
$placementTo.empty().append('<option value="">Select TO Mail</option>');
if (data.client_contact && data.client_contact.email) {
var displayText = (data.client_contact.name || '') + ' - ' + data.client_contact.email;
$placementTo.append(
$('<option>', {
value: data.client_contact.email,
text: displayText.replace(/^- /, '')
})
);
// Select by default
$placementTo.val(data.client_contact.email);
}
window.RFQ_or_QCR = 2; // Placement behaves like QCR for file_type
// Apply CD UI based on loaded data without interfering with future toggles
if ((data.is_cd ?? 1) == 1) {
$("#cd_amount").show();
$("#total_amount").show();
$("#cd_amount").closest('.form-group').show();
$("#total_amount").closest('.form-group').show();
} else {
$("#cd_amount").hide();
$("#total_amount").hide();
$("#cd_amount").closest('.form-group').hide();
$("#total_amount").closest('.form-group').hide();
}
// Apply installment UI based on loaded data without triggering change handler
if ((data.is_installment ?? 0) == 1) {
$("#no_of_installment_group").show();
$("#payment_date").hide();
$("#utr_no").hide();
$("#payment_date").closest('.form-group').hide();
$("#utr_no").closest('.form-group').hide();
let $installmentContainer = $('#installment_form_row');
let row_count = $installmentContainer.find('.form-row').length;
if (row_count == 0) {
addInstallmentHTMLForPlacement();
}
} else {
$("#no_of_installment_group").hide();
$("#payment_date").show();
$("#utr_no").show();
$("#payment_date").closest('.form-group').show();
$("#utr_no").closest('.form-group').show();
$('#installment_form_row').empty();
$('#no_of_installment').val("1");
}
// Initialize Jodit for placement mail content when modal opens
if (typeof Jodit !== 'undefined' && $('#placement_mail_content').length) {
Jodit.make("#placement_mail_content", editorConfig);
}
// Initialize select2 for TO / CC when modal opens
if ($('#placement_to').length) {
$('#placement_to').select2({
placeholder: 'Select TO Mail',
});
}
if ($('#placement_cc').length) {
$('#placement_cc').select2({
placeholder: 'Select CC Mail',
});
}
const myModal = new bootstrap.Modal(document.getElementById('placement_mail_modal'));
myModal.show();
});
});
}
function ajaxRequest(formData) {
var apiURL = '<?php echo base_url('leads/sendMail') ?>';
$('.loader').fadeIn();
$('.loader-mask').fadeIn();
$.ajax({
url: apiURL,
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function(res) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
if (res.status == 'success' && res.code == 200) {
toastr.success('Mail send Successfully', 'Success');
} else {
if (res.messgae) {
toastr.error(res.messgae, 'Error');
} else {
toastr.error('Mail send failed', 'Error');
}
}
$('.close').click();
},
error: function(xhr, status, error) {
$('.loader').fadeOut();
$('.loader-mask').delay(350).fadeOut('slow');
console.error(xhr.responseText);
console.error(status, error);
}
});
if ($('#to').length) {
$('#to').select2({
placeholder: 'Select TO Mail',
});
}
if ($('#cc').length) {
$('#cc').val('').select2({
placeholder: 'Select CC Mail'
});
}
$('#mail_subject').val('');
$('#insurer_and_client_mail_content').val('');
if ($('#client_cc').length) {
$('#client_cc').val('').select2({
placeholder: 'Select CC Mail'
});
}
if ($('#client_bcc').length) {
$('#client_bcc').val('').select2({
placeholder: 'Select BCC Mail'
});
}
$("textarea.select2-search__field").attr('rows', '1');
$("textarea.select2-search__field").css('resize', 'none');
}
function checkMailValidation() {
emailString = $("#contact_mail").val();
if (RFQ_or_QCR == 1) {
if (typeof emailString !== 'string' || !emailString.includes(',')) return true;
} else {
if (typeof emailString !== 'string') return false;
}
const invalidChars = /[;|]/;
if (invalidChars.test(emailString)) return false;
const emails = emailString.split(',').map(email => email.trim());
if (emails.length === 0) return false;
const getDomain = email => email.split('@')[1]?.toLowerCase();
const firstDomain = getDomain(emails[0]);
if (!firstDomain) return false;
return emails.every(email => getDomain(email) === firstDomain);
}
// Initialize Flatpickr for placement modal date fields and handle CD/installment toggles
$(document).ready(function () {
if (typeof flatpickr !== 'undefined') {
if ($('#placement_date').length) {
flatpickr("#placement_date", {
dateFormat: "d-m-Y",
allowInput: false,
});
}
if ($('#payment_date').length) {
flatpickr("#payment_date", {
dateFormat: "d-m-Y",
allowInput: false,
});
}
if ($('#policy_start_date').length) {
flatpickr("#policy_start_date", {
dateFormat: "d-m-Y",
allowInput: false,
});
}
if ($('#policy_end_date').length) {
flatpickr("#policy_end_date", {
dateFormat: "d-m-Y",
allowInput: false,
});
}
}
// CD total amount calculation (from view_rfq_non_eb)
$(document).on("input", "#cd_amount, #premium_amount", function() {
var cd_amount = parseInt($("#cd_amount").val()) || 0;
var premium_amount = parseInt($("#premium_amount").val()) || 0;
var total_amount = (cd_amount + premium_amount);
$("#total_amount").val(total_amount);
});
// CD entry toggle (from view_rfq_non_eb)
$('#is_cd_switch') . on('change', function () {
alert('CD');
var switch_status = ($("#is_cd_switch").is(":checked")? "on" : "off");
console.log("CD Switch status",switch_status);
if (switch_status == "on"){
$("#cd_amount").show();
$("#total_amount").show();
$("#cd_amount").closest('.form-group').show();
$("#total_amount").closest('.form-group').show();
}else{
$("#cd_amount").hide();
$("#total_amount").hide();
$("#cd_amount").closest('.form-group').hide();
$("#total_amount").closest('.form-group').hide();
}
});
// Placement installments toggle behaviour (from view_rfq_non_eb, simplified for list view)
$('#is_installment_switch') . on('change', function () {
alert('Installment');
var switch_status = ($(this).is(":checked") ? "on" : "off");
console.log("Switch status", switch_status);
if (switch_status == "on") {
$("#no_of_installment_group").show();
$("#payment_date").hide();
$("#utr_no").hide();
$("#payment_date").closest('.form-group').hide();
$("#utr_no").closest('.form-group').hide();
let $installmentContainer = $('#installment_form_row');
let row_count = $installmentContainer.find('.form-row').length;
if (row_count == 0) {
addInstallmentHTMLForPlacement();
}
} else {
console.log("inside else");
let $installmentContainer = $('#installment_form_row');
let row_count = $installmentContainer.find('.form-row').length;
let remove_count = $("#no_of_installment").val();
if (row_count > 0) {
// Just clear client-side installments in list view
$("#no_of_installment_group").hide();
$("#payment_date").show();
$("#utr_no").show();
$("#payment_date").closest('.form-group').show();
$("#utr_no").closest('.form-group').show();
$('#installment_form_row').empty();
$('#no_of_installment').val("1");
}
}
});
$('#no_of_installment').on('change', function () {
let no_of_installments = parseInt($(this).val());
let $installmentContainer = $('#installment_form_row');
let row_count = $installmentContainer.find('.form-row').length;
console.log("Form row count:", row_count);
if (row_count === 1) {
for (let index = 0; index < no_of_installments - 1; index++) {
addInstallmentHTMLForPlacement();
}
} else if (no_of_installments === row_count) {
console.log('Same row count, no change needed.');
} else if (no_of_installments < row_count) {
// Remove extra rows from the end
let remove_count = row_count - no_of_installments;
$installmentContainer.find('.form-row').slice(-remove_count).remove();
} else if (no_of_installments > row_count) {
// Add extra rows from the end
let add_count = no_of_installments - row_count;
for (let index = 0; index < add_count; index++) {
addInstallmentHTMLForPlacement();
}
}
});
// Ensure dynamic installment dates use flatpickr
setTimeout(function () {
if (typeof flatpickr !== 'undefined') {
$('.payment_date').flatpickr({
dateFormat: 'd-m-Y',
});
}
}, 2000);
});
function addInstallmentHTMLForPlacement() {
let html = `
<div class="form-row align-items-end">
<div class="form-group col-md-3">
<label for="installment_amount">Installment Amount</label>
<input type="text" class="form-control" name="installment_amount[]" placeholder="Enter Amount">
</div>
<div class="form-group col-md-3">
<label for="payment_date">Payment Date</label>
<input type="text" class="form-control payment_date" name="payment_date[]" placeholder="DD/MM/YYYY">
</div>
<div class="form-group col-md-3">
<label for="utr_no">UTR No.</label>
<input type="text" class="form-control" name="utr_no[]" placeholder="Enter UTR No.">
</div>
<div class="form-group col-md-2">
<button type="button" class="btn btn-danger remove-installment">X</button>
</div>
</div>
`;
$('#installment_form_row').append(html);
if (typeof flatpickr !== 'undefined') {
$('.payment_date').flatpickr({
dateFormat: 'd-m-Y',
});
}
}
// Remove installment row
$(document).on('click', '.remove-installment', function () {
let $this = $(this);
let row_count = $('#installment_form_row .form-row').length;
if (row_count > 1) {
$this.closest('.form-row').remove();
let updated_row_count = $('#installment_form_row .form-row').length;
$('#no_of_installment').val(updated_row_count);
console.log("after remove row_count", updated_row_count);
} else {
console.log("Only one row left. Not removing.");
}
});
</script>
<script>
function selectOption(element, radioId) {
// Remove selected class from all options
document.querySelectorAll('.radio-option').forEach(option => {
option.classList.remove('selected');
});
// Add selected class to clicked option
element.classList.add('selected');
// Check the corresponding radio button
document.getElementById(radioId).checked = true;
}
// Add click event to radio inputs directly
document.querySelectorAll('input[name="lead_form_type"]').forEach(radio => {
radio.addEventListener('change', function() {
// Remove selected class from all options
document.querySelectorAll('.radio-option').forEach(option => {
option.classList.remove('selected');
});
// Add selected class to parent of checked radio
this.closest('.radio-option').classList.add('selected');
});
});
</script>
<script>
$(document).ready(function() {
if (typeof openOpportunitiesListFilterNav !== 'function') {
console.log('Developer Notice: The file lead_filter.php must be loaded by the controller for the filters to work, not leads_list.php.');
}
});
</script>