Files
FloatBackOfffice/application/views/tools/view_pointsofinterest.php
T
dev-chiefworks f76abffdcd first commit
2022-05-31 16:21:53 -04:00

887 lines
32 KiB
PHP

<!-- start alert -->
<?php if ($this->session->flashdata('success')) { ?>
<div class="col-12">
<div class="alert alert-success alert-dismissible bg-success text-white" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<?php echo $this->session->flashdata('success') ?>
</div>
</div>
<?php } ?>
<!-- end alert -->
<div id="overlay" style="display:none;">
<div class="spinner"></div>
<br />
Importing...
</div>
<div class="row">
<div class="col-12">
<form id="local-location" name="local-location" method="post" action="handleGetDataFromOpenTripMap" autocomplete="off" class="local-location-form">
<input type="hidden" id="city-name" name="city_name" />
<div class="form-group">
<label for="city-id">City</label>
<select name="city_id" id="semi-auto-city-id" data-toggle="select2" class="form-control">
<option value="">Select a city</option>
<?php
foreach($city_list as $city) {
$selected = set_value('city_id') == $city->id ? 'selected' : '';
echo '<option value="' . $city->id . '"' . $selected . '>' . $city->city . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="country"> </label>
<button type="button" id="get-location-btn" name="get-location" class="btn btn-info btn-block btn-sm">Get Location</button>
</div>
</form>
</div>
<div class="col-lg-4">
<div class="panel panel-flat">
<div class="jumbotron" style="background-color:#F3DFE5; padding:10px;">
<?php if ($errMsg) { ?>
<div class="col-12">
<div class="alert alert-danger alert-dismissible bg-danger text-white border-0" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<strong>Error</strong> <?php echo $errMsg ? $errMsg : '' ?>
</div>
</div>
<?php } ?>
<?php if ($msg) { ?>
<div class="col-12">
<div class="alert alert-danger alert-dismissible bg-danger text-white border-0" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<?php echo $msg ? $msg : '' ?>
</div>
</div>
<?php } ?>
<font id="message" color=red></font>
<h3>POI Form <span class="label label-primary" style="cursor: pointer" onclick="showAddPOIForm()">New</h3>
<form id="tourist_attraction_form" name="tourist_attraction_form" method="post" action="create" autocomplete="off">
<div class="form-group">
<label for="country">Country</lrbel>
<?= $card_country ?>
</div>
<div class="form-group">
<label for="loc_name">Location Name</lrbel>
<input type="text"
value="<?php echo set_value('loc_name'); ?>"
class="form-control"
name="loc_name"
id="loc_name"
maxlength="35"
placeholder="Location name"/>
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea
class="form-control"
name="address"
id="address"
rows="6"
maxlength="250"
placeholder="Address"><?php echo set_value('address'); ?></textarea>
</div>
<div class="form-group">
<label for="city-id">City</label>
<select name="city_id" id="city-id" data-toggle="select2" class="form-control">
<option value="">Select a city</option>
<?php
foreach($city_list as $city) {
$selected = set_value('city_id') == $city->id ? 'selected' : '';
echo '<option value="' . $city->id . '"' . $selected . '>' . $city->city . '</option>';
}
?>
</select>
</div>
<div class="form-ggetTimezoneComboription">
<label for="postal_code">Description</label>
<textarea
class="form-control"
name="description"
id="description"
rows="6"
maxlength="250"
placeholder="Description"><?php echo set_value('description'); ?></textarea>
</div>
<input type="hidden"
class="form-control"
name="tourist_selected"
id="tourist_selected"
value="<?php echo set_value('tourist_selected'); ?>">
<div class="form-group">
<label for="postal_code">Image URL</label>
<input
type="text"
class="form-control"
name="feature_image"
value="<?php echo set_value('feature_image'); ?>"
placeholder="UniqueId.type"
>
</div>
<a target="_blank" href="" data-popup="lightbox" id="feature_image_preview" style="display: none;">
<img id="image_preview" src="" alt="" class="img-rounded img-preview">
</a>
<br />
<div class="form-group">
<label for="active">Is Pbulic</label>
<input type="checkbox" name="status" />
</div>
<div class="form-group">
<button type="submit" name="go" class="btn btn-info btn-block btn-sm">Add Location</button>
<button type="button" onclick="updatePOI()" name="update" class="btn btn-info btn-block btn-sm" style="display: none;">Update</button>
<button type="button" onclick="return deleteTouristAttraction();" name="delete" class="btn btn-info btn-block btn-sm" style="display: none;">Delete</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-lg-8">
<div class="row">
<div class="col">
<form class="poi-filter-form" autocomplete="off">
<div class="row">
<!-- <div class="form-group col-md-3">
<?php //echo $card_country_filter ?>
</div> -->
<div class="form-group col-md-3">
<select name="city_id[]" id="city_id_filter" class="form-control" multiple></select>
</div>
<div class="form-group col-md-3">
<select name="address_id" id="address_id_filter" class="form-control"></select>
</div>
<div class="form-group col-md-3">
<textarea name="attraction" class="form-control" id="attraction_filter" rows="1" placeholder="Attraction"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-3">
<input type="number" class="form-control m-b-xs" name="latitude" id="latitude_filter" placeholder="Latitude"></input>
<input type="number" class="form-control m-b-xs" name="longitude" id="longitude_filter" placeholder="Longitude"></input>
<input type="number" class="form-control" name="radius" id="radius_filter" value="5000" placeholder="Radius (meter)"></input>
</div>
<div class="form-group col-md-2">
<button type="button" name="search" id="search" class="btn btn-info btn-block btn-sm">Search</button>
<button type="button" data-action="export" id="export" class="btn btn-warning btn-block btn-sm">Export</button>
</div>
</div>
</form>
</div>
</div>
<div id="container">
<div class="import-group">
<form id="form-upload">
<div class="file-upload">
<span id="pickfiles">[Choose files]</span>
<input type="button" id="btn-upload" class="btn btn-success btn-sm" value="Upload">
</div>
</form>
</div>
<div id="filelist"></div>
<div id="import-message"></div>
</div>
<!-- Media library -->
<div class="panel-heading">
<div class="heading-elements">
<div style='margin-top: 10px;' id='pagination'></div>
</div>
</div>
<div class="panel panel-white">
<table id="address-list" class="col-lg-12 table-bordered table-condensed table-hover table-striped table-condensed" style="padding:0px; background-color:lightgreen;">
<thead class="bg-indigo">
<th>Country</th>
<th>ID</th>
<th>City</th>
<th>Attraction</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Address</th>
<th>Plus Code</th>
<th>Actions</th>
</thead>
<tbody></tbody>
</table>
</div>
<!-- /media library -->
</div>
</div>
<div class="modal fade" id="importingModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">Import local attractions from third party - OpenTripMap</h4>
</div>
<div class="modal-body">
<span class="status">Getting data ...</span>
<p class="status-count"></p>
<p class="error-count"></p>
<div id="importProgress">
<div id="importBar"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="/assets/js/plugins/forms/selects/select2.min.js"></script>
<script src="/assets/js/pages/tools/saveOrUpdatePOI.js"></script>
<script>
// hide update and delete button when url contains /tools/update
$(document).ready(function() {
var importCount = 0;
var totalImportCount = 0;
var importPercent = 0;
var errorCount = 0;
let isFetchingData = false;
$('[name="card_country_filter"]').change(function(){
$('#country_filter_form').submit();
});
$('#importingModal button[type="button"][data-dismiss="modal"]').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
if (isFetchingData) {
return;
} else {
$('#importingModal').modal('hide');
}
});
//Load panigation
loadPagination(0);
// Detect pagination click
$('#pagination').on('click', 'a', function(e) {
e.preventDefault();
var pageno = $(this).attr('data-ci-pagination-page');
loadPagination(pageno);
});
// Detect search click
$('#search').on('click', function(e) {
loadPagination(0);
$('#message').html('');
});
// address automation
$('#address_id_filter').select2({
placeholder: "Search by address",
allowClear: true,
maximumSelectionSize: 1,
minimumInputLength: 3,
ajax: {
url: "/addresses/getAddressesAjax",
type: "GET",
dataType: "json",
delay: 250,
data: function(params) {
const query = {
name: params.term,
page: params.page || 1,
per_page: 20,
};
return query;
},
processResults: function(res, params) {
const { data, total } = res;
params.page = params.page || 1;
return {
results: data.map(item => ({ id: item.id, text: item.address })),
pagination: {
more: params.page * 20 < +total
}
};
}
}
});
// city automation
$('#city_id_filter').select2({
placeholder: "Search by city",
allowClear: true,
maximumSelectionSize: 1,
minimumInputLength: 2,
ajax: {
url: "/geofence_area_city/getcityAjax",
type: "GET",
dataType: "json",
delay: 250,
data: function(params) {
const query = {
city_name: params.term,
page: params.page || 1,
per_page: 20,
};
return query;
},
processResults: function(res, params) {
const { data, total } = res;
params.page = params.page || 1;
return {
results: data.map(item => ({ id: item.id, text: item.city })),
pagination: {
more: params.page * 20 < +total
}
};
}
}
});
if (window.location.href.includes('/tools/update')) {
document.getElementsByName('go')[0].style.display = "none";
document.getElementsByName('update')[0].style.display = "block";
document.getElementsByName('delete')[0].style.display = "block";
}
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
if (target && $(target).prop('tagName').toLowerCase() == 'button' && $(target).hasClass('btn-change-status')) {
handleChangeStatusOfPOI(e);
return;
}
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
var featureImage = (cells[12] || {}).innerHTML || null;
const isActive = (cells[13] || {}).innerHTML == 't';
document.getElementsByName('card_country')[0].value = cells[0].innerText;
document.getElementsByName('tourist_selected')[0].value = cells[1].innerText;
document.getElementsByName('loc_name')[0].value = cells[3].innerText;
document.getElementsByName('address')[0].value = cells[6].innerText;
document.getElementsByName('description')[0].value = cells[10].innerText;
document.getElementsByName('city_id')[1].value = cells[11].innerText;
document.getElementsByName('feature_image')[0].value = featureImage || '';
document.getElementsByName('go')[0].style.display = "none";
document.getElementsByName('update')[0].style.display = "block";
document.getElementsByName('delete')[0].style.display = "block";
isActive
? document.getElementsByName('status')[0].setAttribute('checked', isActive)
: document.getElementsByName('status')[0].removeAttribute('checked');
isActive
? $('input[type="checkbox"][name="status"]').prop("checked", true)
: $('input[type="checkbox"][name="status"]').prop("checked", false)
$aElem = document.getElementById('feature_image_preview');
if (featureImage) {
$aElem.style.display = 'unset';
$imgElem = document.getElementById('image_preview');
if (featureImage.includes('http')) {
$aElem.href = `${featureImage}`;
$imgElem.src = `${featureImage}?size=80x80`;
} else {
$aElem.href = `<?= $storage ?>cards/${featureImage}`;
$imgElem.src = `<?= $storage ?>cards/${featureImage}?size=80x80`;
}
} else {
$aElem.style.display = 'none';
}
var element = document.getElementById("underline-location");
if (element !== null) {
element.removeAttribute('id');
}
cells[2].id="underline-location";
}
}
$('#semi-auto-city-id').select2().on('select2:select', function(e) {
const cityName = e.params.data.text;
$('#city-name').val(cityName);
});
$('#get-location-btn').on('click', function(e) {
e.preventDefault();
isFetchingData = true;
const cityInfo = $('#local-location').serializeArray().reduce((result, item) => {
result[item.name] = item.value;
return result;
}, {});
countLocationsByCity(cityInfo.city_id).then(result => {
$('#importingModal').modal({ backdrop: 'static', keyboard: false });
$('#importingModal').modal('show');
const isFetchedData = (result.fetch_status || {}).is_fectched_data === 't';
const count = result.count;
if (isFetchedData) {
$('#importingModal .status-count').text(`Saved: ${count}`);
$('#importingModal .status').text(`Complete: ${count}`);
$('#importingModal #importProgress').css('display', 'none');
isFetchingData = false;
return;
} else {
$('#importingModal #importProgress').css('display', 'block');
$('#importingModal .status').text(`Getting data ...`);
}
$.ajax({
url: '/tools/handleGetDataFromOpenTripMap',
method: 'POST',
data: cityInfo,
}).done(function(results) {
const locations = JSON.parse(results);
const city_id = $('#semi-auto-city-id').val();
totalImportCount = locations.length;
importCount = 0;
importPercent = 0;
errorCount = 0;
$('#importingModal .status-count').text(`Saved: 0 / ${totalImportCount}`);
locations.forEach((location, index) => {
const xid = location.xid;
setTimeout(() => {
getLocalLocationInfo({ xid: xid, city_id: city_id });
}, index * 3000);
});
});
});
});
$('#importingModal').on('hide.bs.modal', function(e) {
$('#importingModal .status-count').text('');
$('#importingModal .status').text('');
});
function handleChangeStatusOfPOI(e) {
e.preventDefault();
const $target = $(e.target);
const id = $target.data('id');
const status = !($target.data('status') == 't');
rowCells = $(e.target).closest('tr').children();
console.log(rowCells);
$.ajax({
url: '/tools/updateAJAX',
method: 'POST',
data: {
id: id,
status: status,
}
}).done(result => {
try {
result = JSON.parse(result);
if (result && result.error) {
alert(`Something went wrong: ${JSON.stringify(result.error)}`);
} else {
if (status) {
$target.data('status', 't');
$target.text('Deactive');
$('input[type="checkbox"][name="status"]').prop("checked", true);
alert('Public successfully.');
} else {
$target.data('status', 'f');
$target.text('Public');
$('input[type="checkbox"][name="status"]').prop("checked", false);
alert('Deactive successfully.');
}
}
} catch(err) {
alert('Something went wrong. Please try again later')
}
}).fail(error => {
alert('Something went wrong. Please try again later');
})
}
function getLocalLocationInfo(params) {
return $.ajax({
url: '/tools/getSingleLocalAttractionFromThirdParty',
method: 'POST',
data: {xid: params.xid},
}).done(function(result) {
const location = JSON.parse(result);
const locationAddress = location.address || null;
const wikipedia_extracts = location.wikipedia_extracts || null;
let locationName = location.name;
if (!locationName) {
locationName = wikipedia_extracts ? (wikipedia_extracts.title || '').substr(3) : '';
}
const createParams = {
'loc_name': locationName || '', // location name
'address': `${locationAddress.house_number} ${locationAddress.road}`,
'description': wikipedia_extracts && wikipedia_extracts.text,
'city_id': params.city_id,
'feature_image': (location.preview || {}).source || null,
'card_country': locationAddress.country_code.toUpperCase(),
};
return createLocalLocation(createParams);
});
}
function createLocalLocation(params) {
return $.ajax({
url: '/tools/createAJAX',
method: 'POST',
data: params
}).done(function(result) {
try {
result = result && JSON.parse(result) ? JSON.parse(result) : null;
if (!result || !result.success) {
errorCount++;
$('#importingModal .error-count').text(`Errors: ${errorCount} / ${totalImportCount}`);
} else {
importCount++;
}
importPercent++;
const width = importPercent * 100 / totalImportCount;
if (importPercent == totalImportCount) {
$('#importingModal .status').text('Completed ');
isFetchingData = false;
const cityId = $('#semi-auto-city-id').val();
updateCityFetchStatus(cityId);
}
$('#importingModal #importBar').css('width', `${width}%`);
$('#importingModal .status-count').text(`Saved: ${importCount} / ${totalImportCount}`);
} catch(error) {
errorCount++;
importPercent++;
const width = importPercent * 100 / totalImportCount;
if (importPercent == totalImportCount) {
$('#importingModal .status').text('Completed ');
isFetchingData = false;
const cityId = $('#semi-auto-city-id').val();
updateCityFetchStatus(cityId);
}
$('#importingModal #importBar').css('width', `${width}%`);
$('#importingModal .error-count').text(`Errors: ${errorCount} / ${totalImportCount}`);
}
}).fail(function(error) {
importPercent++;
errorCount++;
const width = importPercent * 100 / totalImportCount;
$('#importingModal #importBar').css('width', `${width}%`);
$('#importingModal .error-count').text(`Errors: ${errorCount} / ${totalImportCount}`);
if (importPercent == totalImportCount) {
$('#importingModal .status').text('Completed ');
isFetchingData = false;
const cityId = $('#semi-auto-city-id').val();
updateCityFetchStatus(cityId);
}
});
}
function countLocationsByCity(city_id) {
return new Promise((resolve, reject) => $.ajax({
url: '/tools/countLocations',
method: 'GET',
dataType: 'json',
data: {
city_id: city_id,
},
success: function(response) {
return resolve(response);
},
}));
}
function updateCityFetchStatus(city_id) {
return new Promise((resolve, reject) => $.ajax({
url: '/tools/updateFetchStatus',
method: 'GET',
dataType: 'json',
data: {
city_id: city_id,
},
success: function(response) {
return resolve(response);
},
}));
}
$('#export').on('click', function(e) {
$(this).closest('form')
.attr('action', $(this).data('action'))
.submit();
})
});
function updateTouristAttraction() {
document.tourist_attraction_form.action = origin + "/tools/update";
var frm = document.getElementsByName('tourist_attraction_form')[0];
frm.submit(); // Submit the form
}
function deleteTouristAttraction() {
document.tourist_attraction_form.action = origin + "/tools/destroy";
var frm = document.getElementsByName('tourist_attraction_form')[0];
frm.submit(); // Submit the form
return false; // Prevent page refresh
}
function loadPagination(pagno) {
$.ajax({
url: '/tools/loadRecordAddress',
type: 'get',
dataType: 'json',
data : {
'rowno' : pagno,
'address_id' : $('#address_id_filter').val(),
'city_id' : $('#city_id_filter').val(),
'attraction' : $('#attraction_filter').val(),
'latitude' : $('#latitude_filter').val(),
'longitude' : $('#longitude_filter').val(),
'radius' : $('#radius_filter').val(),
},
success: function(response) {
$('#pagination').html(response.pagination);
createTable(response.result, response.row);
},
});
}
function createTable(result) {
$('#address-list tbody').empty();
for (index in result) {
var id = result[index].id;
var address = result[index].address;
var latitude = result[index].latitude;
var longitude = result[index].longitude;
var attraction = result[index].attraction;
var country = result[index].country;
var timezone = result[index].timezone;
var postal = result[index].postal;
var description = (result[index].description || result[index].address_description) || '';
var nameCity = result[index].city;
var cityId = result[index].city_id;
var featureImage = result[index].feature_image;
const isActive = result[index].active;
var plus_code = result[index].plus_code;
var tr = "<tr style='cursor: pointer;'>";
tr += "<td>" + country + "</td>";
tr += "<td>" + id + "</td>";
tr += "<td>" + nameCity + "</td>";
tr += "<td>" + attraction + "</td>";
tr += "<td>" + latitude + "</td>";
tr += "<td>" + longitude + "</td>";
tr += "<td>" + address + "</td>";
tr += "<td>" + plus_code + "</td>";
tr += "<td style='display:none'>" + timezone + "</td>";
tr += "<td style='display:none'>" + postal + "</td>";
tr += "<td style='display:none'>" + description + "</td>";
tr += "<td style='display:none'>" + cityId + "</td>";
tr += "<td style='display:none'>" + featureImage + "</td>";
tr += '<td style="display: none">'+ isActive + "</td>";
if (isActive == 't') {
tr += `<td><button type="button" class="btn btn-primary btn-change-status" data-id="${id}" data-status="${isActive}">Deactive</button></td>`
} else {
tr += `<td><button type="button" class="btn btn-primary btn-change-status" data-id="${id}" data-status="${isActive}">Public</button></td>`
}
tr += "</tr>";
$('#address-list tbody').append(tr);
}
}
</script>
<!-- upload and import file -->
<script src="/assets/js/plupload.full.min.js"></script>
<script>
window.addEventListener("load", function() {
let uploader = new plupload.Uploader({
runtimes: 'html5',
browse_button: 'pickfiles',
container: document.getElementById('container'),
url: '/tools/upload',
chunk_size: '200kb',
max_retries: 2,
filters: {
max_file_size: '50mb',
mime_types: [{
title: "CSV files",
extensions: "csv"
}]
},
init: {
PostInit: function() {
document.getElementById('filelist').innerHTML = '';
},
FilesAdded: function(up, files) {
$("#import-message").text('');
plupload.each(files, function(file) {
document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
});
},
UploadProgress: function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
Error: function(up, err) {
// DO YOUR ERROR HANDLING!
console.log(err);
}
}
})
uploader.bind('FileUploaded', function() {
// After file uploaded , send signal to insert all records
removeFile();
$('#overlay').fadeIn();
$.ajax({
url: '/tools/import_csv',
success: function(data) {
$("#import-message").text(JSON.parse(data).message);
},
error: function(err) {
$("#import-message").text('Something went wrong !!!');
},
complete: function() {
$('#overlay').fadeOut();
}
})
})
uploader.init()
function removeFile() {
$.each(uploader.files, function (i, file) {
if (file) {
uploader.removeFile(file);
}
});
}
$('#btn-upload').on('click', function(e) {
$('#import-message').text('');
if (uploader.files.length === 0) {
$('#import-message').text('Please choose a file !!!');
return;
}
if ( ! uploader.files[0].size) {
$('#import-message').text('File is empty');
removeFile();
return;
}
uploader.start();
})
});
</script>
<style>
#underline-location {text-decoration: underline;}
a {
padding-left: 5px;
padding-right: 5px;
margin-left: 5px;
margin-right: 5px;
}
.local-location-form {
margin-bottom: 30px;
display: flex;
flex-direction: row;
align-items: center;
padding: 0 10px;
}
.local-location-form .form-group {
margin-bottom: 0;
}
.local-location-form .form-group + .form-group {
margin-left: 15px;
}
.local-location-form .form-group label {
margin-bottom: 0;
}
#importingModal .modal-body {
font-size: 38px;
}
#importingModal .modal-body .status-count {
font-size: 24px;
color: green;
}
#importingModal .modal-body .error-count {
font-size: 24px;
color: red;
}
#importProgress {
width: 100%;
background-color: white;
border: 1px solid black;
}
#importBar {
width: 0%;
height: 30px;
background-color: green;
}
#overlay {
background: #ffffff;
color: #666666;
position: fixed;
height: 100%;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
float: left;
text-align: center;
padding-top: 25%;
opacity: .80;
}
.spinner {
margin: 0 auto;
height: 64px;
width: 64px;
animation: rotate 0.8s infinite linear;
border: 5px solid firebrick;
border-right-color: transparent;
border-radius: 50%;
}
@keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>