[go: nahoru, domu]

Skip to content

Commit

Permalink
[fixed] currently available rooms not loading when going back (#335)
Browse files Browse the repository at this point in the history
-created an ajax call to load currently available rooms
-created a less intrusive UI for loading results in the card
  • Loading branch information
dynamic11 authored Nov 14, 2019
1 parent a6c1a1a commit 58ce3a5
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 90 deletions.
2 changes: 1 addition & 1 deletion app/Controllers/Http/BookingController.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ class BookingController {
*
* @param {Object} Context The context object.
*/
async cancelBooking ({ session, params, response, view }) {
async cancelBooking ({ session, params, response }) {
try {
// fetch booking
const result = await Booking
Expand Down
78 changes: 1 addition & 77 deletions app/Controllers/Http/HomeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const RoomStatus = use('App/Models/RoomStatus');
const Floor = use('App/Models/Floor');
const Tower = use('App/Models/Tower');
const RoomFeaturesCategory = use('App/Models/RoomFeaturesCategory');
const Event = use('Event');
var moment = require('moment');
require('moment-round');
const Outlook = new (use('App/Outlook'))();
Expand All @@ -27,12 +26,6 @@ function randomString (times) {
return result;
}

async function asyncForEach (arr, callback) {
for (let i = 0; i < arr.length; i++) {
await callback(arr[i], i, arr);
}
}

class HomeController {
/**
*
Expand Down Expand Up @@ -106,7 +99,7 @@ class HomeController {
*
*/
async userDashboard ({ antl, view, auth, request }) {
const code = await this.getAvailableRooms({ antl, user: auth.user, view });
const code = randomString(4);
const freqRooms = await this.getFreqBooked(auth.user);
const upcoming = await this.getUpcomming(auth.user);
const userId = auth.user.id;
Expand Down Expand Up @@ -442,75 +435,6 @@ class HomeController {
User Functions
****************************************/

/**
*
* Retrieve currently available rooms and returns and array of size 2 with results
* User's Floor and Tower > User's Floor and ¬ Tower > User's Floor-1 and Tower > User's Floor+1 and Tower > User's Floor-1 and ¬ Tower
*
* @param {view}
*
*/
async getAvailableRooms ({ antl, user, view }) {
// If the tower is West then set the order to descending, else ascending
let towerOrder = (await user.getUserTower() === 'West') ? 'asc' : 'desc';
let lang = antl.currentLocale();

// look for rooms that are open
// order all rooms in the database by closest to the user's floor and tower
// order by ascending seats number and fetch results
// TODO: floor_id -> floor, tower_id
let searchResults = await Room
.query()
.where('state_id', 1)
.orderByRaw('ABS(floor_id-' + user.floor_id + ') ASC')
.orderBy('tower_id', towerOrder)
.orderBy('seats', 'asc')
.fetch();
const rooms = searchResults.toJSON();

const now = moment();
const remainder = 30 - (now.minute() % 30);
const date = moment().format('YYYY-MM-DD');
const from = moment(now).add(remainder, 'm').format('HH:mm');
const to = moment(now).add(remainder, 'm').add(1, 'h').format('HH:mm');
const duration = 1;

let formattedFrom, formattedTo;

const formattedDate = moment().locale(lang).format('ddd MMM DD, YYYY');
if (lang === 'fr') {
formattedFrom = moment(now).add(remainder, 'm').format('HH:mm');
formattedTo = moment(now).add(remainder, 'm').add(1, 'h').format('HH:mm');
} else {
formattedFrom = moment(now).add(remainder, 'm').format('h:mm A');
formattedTo = moment(now).add(remainder, 'm').add(1, 'h').format('h:mm A');
}

const code = randomString(4);
const checkRoomAvailability = async () => {
let numberOfRooms = 2;
await asyncForEach(rooms, async (item) => {
if (numberOfRooms !== 0 && await Outlook.getRoomAvailability({ date, from, to, duration, floor: item.floor_id, calendar: item.calendar })) {
Event.fire('send.room', {
card: view.render('components.smallCard', { room: item, datetime: { date: formattedDate, time: formattedFrom + ' - ' + formattedTo } }),
code: code
});
numberOfRooms--;
}
});

if (numberOfRooms === 2) {
Event.fire('send.empty', {
view: view.render('components.cardEmptyMessage', { faIcon: 'fas fa-ghost fa-5x', message: antl.formatMessage('userDash.FBError') }),
code: code
});
}
};

setTimeout(checkRoomAvailability, 800);
return code;
}

/**
*
* Retrieve the user's frew booked rooms and returns and array of size 2 with results and return results
Expand Down
79 changes: 79 additions & 0 deletions app/Controllers/Http/RoomController.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const FeaturePivot = use('App/Models/FeaturesRoomsPivot');
const RoomStatus = use('App/Models/RoomStatus');
const Review = use('App/Models/Review');
const Helpers = use('Helpers');
const Event = use('Event');
const Outlook = new (use('App/Outlook'))();

// Used for time related calcuklations and formatting
Expand Down Expand Up @@ -678,6 +679,84 @@ class RoomController {
return view.render('userPages.fixedSearchResults', { code: code, roomsLength: rooms.length, floors: floors });
}

/**
*
* Retrieve currently available rooms and returns and array of size 2 with results
* User's Floor and Tower > User's Floor and ¬ Tower > User's Floor-1 and Tower > User's Floor+1 and Tower > User's Floor-1 and ¬ Tower
*
* @param {view}
*
*/
async currentlyAvailable ({ antl, view, request }) {
try {
const body = request.all();
// check if user is valid
let user = await User.findByOrFail('id', body.user_id);
let code = body.code;

// If the tower is West then set the order to descending, else ascending
let towerOrder = (await user.getUserTower() === 'West') ? 'asc' : 'desc';
let lang = antl.currentLocale();

// format date
const now = moment();
const remainder = 30 - (now.minute() % 30);
const date = moment().format('YYYY-MM-DD');
const from = moment(now).add(remainder, 'm').format('HH:mm');
const to = moment(now).add(remainder, 'm').add(1, 'h').format('HH:mm');
const duration = 1;

let formattedFrom, formattedTo;

const formattedDate = moment().locale(lang).format('ddd MMM DD, YYYY');
if (lang === 'fr') {
formattedFrom = moment(now).add(remainder, 'm').format('HH:mm');
formattedTo = moment(now).add(remainder, 'm').add(1, 'h').format('HH:mm');
} else {
formattedFrom = moment(now).add(remainder, 'm').format('h:mm A');
formattedTo = moment(now).add(remainder, 'm').add(1, 'h').format('h:mm A');
}

// look for rooms that are open
// order all rooms in the database by closest to the user's floor and tower
// order by ascending seats number and fetch results
let searchResults = await Room
.query()
.where('state_id', 1)
.orderByRaw('ABS(floor_id-' + user.floor_id + ') ASC')
.orderBy('tower_id', towerOrder)
.orderBy('seats', 'asc')
.fetch();
const rooms = searchResults.toJSON();

// Search for rooms
let numberOfRooms = 2;
let roomsSearched = 0;
await rooms.forEach(async room => {
// check availability of room
let result = await Outlook.getRoomAvailability({ date, from, to, duration, floor: room.floor_id, calendar: room.calendar });
if (numberOfRooms !== 0 && result) {
Event.fire('send.room', {
card: view.render('components.smallCard', { room: room, datetime: { date: formattedDate, time: formattedFrom + ' - ' + formattedTo } }),
code: code
});
numberOfRooms--;
}

roomsSearched++;

// once 2 rooms are found or searched all rooms then send END sifnal
if (numberOfRooms === 0 || rooms.length === roomsSearched) {
Event.fire('send.done', {
code: code
});
}
});
} catch (error) {
console.log(error);
}
}

/**
* Returns true if the user has a review in the database, else false.
*
Expand Down
2 changes: 1 addition & 1 deletion resources/locales/en/userDash.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"CAHeading":"Currently Available",
"FBHeading": "Frequently booked",
"MBHeading": "My bookings",
"CAError": "Searching",
"CAError": "No rooms found",
"FBError": "No rooms found",
"MBError": "No bookings found"
}
2 changes: 1 addition & 1 deletion resources/locales/fr/userDash.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"CAHeading":"Présentment disponible",
"FBHeading": "Fréquemment Réservé",
"MBHeading": "Mes réservations",
"CAError": "Recherche",
"CAError": "Aucune salles trouvées",
"FBError": "Aucune salles trouvées",
"MBError": "Aucune réservation trouvées"
}
45 changes: 35 additions & 10 deletions resources/views/userPages/userDash.edge
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,23 @@
<div class='row'>
<div id='available' class='col-xl-12 col-xxl-6 mb-4' style='height:325px;'>
@component('components.generalCard', title=antl.formatMessage('userDash.CAHeading'), extraCSS='custom-card-header')
{{-- If there are no avail rooms display a message accordingly --}}
@slot('titleRight')
<div id="currently-avail-loading">
<div class="spinner-grow text-white spinner-grow-sm" role="status">
<span class="sr-only">{{antl.formatMessage('searchResults.searching')}}</span>
</div>
<strong class="px-2">{{antl.formatMessage('searchResults.searching')}}</strong>
</div>
<div id="currently-avail-done" class="d-none">
<i class="fas fa-check color-success"></i>
<strong class="px-1">{{antl.formatMessage('searchResults.done')}}</strong>
</div>
@endslot
@slot('body')
<div id='avail'></div>
{{-- spinner --}}
{{-- <div id="loading"> --}}
{{-- @!component('components.cardEmptyMessage',faIcon="fas fa-circle-notch fa-spin fa-4x", message=antl.formatMessage('userDash.CAError')) --}}
{{-- </div> --}}
<div id="currently-avail-no-results" class="d-none">
@!component('components.cardEmptyMessage',faIcon="fas fa-ghost fa-spin fa-4x", message=antl.formatMessage('userDash.CAError'))
</div>
@endslot
@endcomponent
</div>
Expand Down Expand Up @@ -98,6 +108,15 @@
{{ script('https://js.pusher.com/4.1/pusher.min.js') }}

<script>
$(function() {
$.post( "{{route('getCurrentlyAvail')}}", { user_id: '{{auth.user.id}}', code: '{{ code }}', _csrf: '{{ csrfToken }}' } )
.fail(function(xhr, textStatus, error) {
console.log(error);
});;
});
$('#message').keypress(function(e) {
if (e.which === 13 && !e.shiftKey) {
$('#sub').click();
Expand All @@ -113,22 +132,28 @@
//Subscribe to the channel we specified in our Adonis Application
let channel = pusher.subscribe('adonis-channel')
let availableCount=0;
//Listen for events on the channel
channel.bind('send-room', function (data) {
if (data.message.code == '{{ code }}') {
let listItem = $("<div class='row'><div class='col'>" + data.message.card + "</div></div>");
// $('#loading').hide();
$('#avail').prepend(listItem);
availableCount++;
}
});
channel.bind('send-empty', function (data) {
channel.bind('send-done', function (data) {
if (data.message.code == '{{ code }}') {
let listItem = $(data.message.view)
// $('#loading').hide();
$('#avail').empty().append(listItem)
$('#currently-avail-loading').addClass('d-none');
$('#currently-avail-done').removeClass('d-none');
if(availableCount==0){
$('#currently-avail-no-results').removeClass('d-none');
console.error("hello")
}
}
});
Expand Down
1 change: 1 addition & 0 deletions start/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ Route.get('/results', 'RoomController.findSpecific').as('results').middleware(['
Route.get('/search/fixed', 'RoomController.fixedSearchRooms').as('searchFixed').validator('SearchFixed');
Route.get('/search/flexible', 'RoomController.flexibleSearchRooms').as('searchFlexible').validator('SearchFlexible');
Route.get('/search/recurring', 'RoomController.searchRooms').as('searchRecurring').validator('SearchRoomFlexible'); // TODO
Route.post('/currentlyavail', 'RoomController.currentlyAvailable').as('getCurrentlyAvail').middleware(['auth']);

// Booking a Room
Route.post('/confirmBooking', 'BookingController.confirmBooking').as('confirmBooking').validator('BookRoom').middleware(['auth']);
Expand Down

0 comments on commit 58ce3a5

Please sign in to comment.