source: src/main/resources/static/js/homepage.js

Last change on this file was f29cd58, checked in by gjoko kostadinov <gjokokostadinov@…>, 6 months ago

Add services search functionality.

  • Property mode set to 100755
File size: 16.7 KB
Line 
1$(document).ready(function() {
2 var businessTypes = {};
3 var businesses = {};
4 var date = new Date();
5 var selectedServices = {};
6 var events = [];
7 var d = date.getDate();
8 var m = date.getMonth();
9 var y = date.getFullYear();
10
11 /* className colors
12
13 className: default(transparent), important(red), chill(pink), success(green), info(blue)
14
15 */
16
17 $.ajax({
18 type: 'GET',
19 url: "http://localhost:8080/api/user/me",
20 success: function(data, textStatus, request) {
21 if (data) {
22 $('#create').parent().removeClass('hidden-button');
23 $('#profile').parent().removeClass('hidden-button');
24 $('#logout').parent().removeClass('hidden-button');
25 $('#login').parent().addClass('hidden-button');
26 } else {
27 $('#create').parent().addClass('hidden-button');
28 $('#profile').parent().addClass('hidden-button');
29 $('#logout').parent().addClass('hidden-button');
30 $('#login').parent().removeClass('hidden-button');
31 }
32 },
33 error: function (request, textStatus, errorThrown) {
34 console.log(errorThrown);
35 }
36 });
37 /* initialize the external events
38 -----------------------------------------------------------------*/
39
40 $('#external-events div.external-event').each(function() {
41
42 // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
43 // it doesn't need to have a start or end
44 var eventObject = {
45 title: $.trim($(this).text()) // use the element's text as the event title
46 };
47
48 // store the Event Object in the DOM element so we can get to it later
49 $(this).data('eventObject', eventObject);
50
51 // make the event draggable using jQuery UI
52 $(this).draggable({
53 zIndex: 999,
54 revert: true, // will cause the event to go back to its
55 revertDuration: 0 // original position after the drag
56 });
57
58 });
59
60 $.ajax({
61 url: "http://localhost:8080/api/nomenclature/businessTypes"
62 }).then(function (data) {
63 businessTypes = data;
64 var $el = $("#companyType");
65 emptyDropdown($el);
66
67 $.each(data, function (index, obj) {
68 $el.append("<option value=" + obj.value + ">" + obj.text + "</option>");
69 });
70 });
71
72 $("#companyType").change(function () {
73 resetRatingCard();
74 var selectedVal = $(this).find(':selected').val();
75 var selectedObj = businessTypes[selectedVal - 1];
76 $.ajax({
77 url: "http://localhost:8080/api/business/" + selectedObj.value
78 }).then(function (data) {
79 businesses = data;
80 var $el = $("#company");
81 var $servicesEl = $("#service");
82 emptyDropdown($el);
83 emptyDropdown($servicesEl);
84
85 $.each(data, function (index, obj) {
86 $el.append("<option value=" + obj.id + ">" + obj.companyName + "</option>");
87 });
88
89 if (data && data.length === 1) {
90 selectedServices = data[0]["services"];
91 resetAndAppendServices(selectedServices);
92 }
93 });
94 });
95
96 $("#startdatetime").change(function() {
97 var date = new Date(document.getElementById("startdatetime").valueAsDate);
98 var minutes = parseInt($("#service").attr('duration'));
99 date.setMinutes(date.getMinutes() + minutes);
100 document.getElementById("enddatetime").value = date.toISOString().slice(0, 16);
101 });
102
103 /* initialize the calendar
104 -----------------------------------------------------------------*/
105 loadCalendar();
106
107 resetRatingCard();
108
109 $("#createAppointment").click(function() {
110 var appointment = {};
111 var business = {};
112 business['id'] = parseInt($('#company').attr('business-id'));
113 appointment['service'] = {'id': parseInt($('#service').attr('service-id')), 'business':business};
114 appointment['startTime'] = $("#startdatetime").val();
115 console.log(appointment);
116
117 $.ajax({
118 url: "http://localhost:8080/api/appointment",
119 type:"POST",
120 data: JSON.stringify(appointment),
121 contentType:"application/json; charset=utf-8",
122 dataType: 'text',
123 success: function(succ){
124 alert("Successful appointment!");
125 var companyId = parseInt($('#company').attr('business-id'));
126 getAppointmentsByBusiness(companyId, events);
127 destroyCalendar();
128 loadCalendar(events);
129 },
130 error: function(error) {
131 alert(error.responseText);
132 }
133 });
134 });
135
136 $('#search-input').keypress(function (e) {
137
138 var key = e.which;
139 if(key === 13) { // the enter key code
140 searchServices();
141 return false;
142 }
143 });
144
145});
146
147document.getElementById("login").addEventListener("click", function(event){
148 window.location = "/login";
149});
150
151function resetAndAppendServices(services) {
152 var $el = $("#service");
153 emptyDropdown($el);
154
155 $.each(services, function (index, obj) {
156 if (obj.serviceStatus === 'ACTIVE') {
157 $el.append("<option value=" + obj.id + ">" + obj.serviceType.name + "</option>");
158 }
159 });
160}
161
162function emptyDropdown(element) {
163 var defaultOption = element.children().get(0);
164 element.children().remove();
165 element.append(defaultOption);
166}
167
168function getAppointmentsByBusiness(businessId, events) {
169 $.ajax({
170 url: "http://localhost:8080/api/appointment/business/" + businessId,
171 type:"GET",
172 contentType:"application/json; charset=utf-8",
173 dataType: 'text',
174 success: function(data){
175 // reset events
176 events = [];
177 console.log(data);
178 $.each(JSON.parse(data), function (index, object) {
179 var event = {}
180 event['title'] = object['title'];
181 event['start'] = object['startTime'].replace('T', ' ');
182 event['end'] = object['endTime'].replace('T', ' ');
183 event['allDay'] = false;
184 event['color'] = 'blue';
185 events.push(event);
186 });
187
188 },
189 error: function(error) {
190 console.log(error.responseText);
191 }
192 });
193}
194
195function loadCalendar(events) {
196 $('#calendar').fullCalendar({
197 header: {
198 left: 'title',
199 center: 'agendaWeek',
200 right: 'prev,next today'
201 },
202 editable: false,
203 edit: function (start, end, allDay) {
204 console.log(start);
205 console.log(end);
206 },
207 firstDay: 1, // 1(Monday) this can be changed to 0(Sunday) for the USA system
208 selectable: false,
209 defaultView: 'agendaWeek',
210
211 axisFormat: 'h:mm',
212 columnFormat: {
213 month: 'ddd', // Mon
214 week: 'ddd d', // Mon 7
215 day: 'dddd M/d', // Monday 9/7
216 agendaDay: 'dddd d'
217 },
218 titleFormat: {
219 month: 'MMMM yyyy', // September 2009
220 week: "MMMM yyyy", // September 2009
221 day: 'MMMM yyyy' // Tuesday, Sep 8, 2009
222 },
223 allDaySlot: false,
224 selectHelper: true,
225 select: function(start, end, allDay) {
226 var title = prompt('Event Title:');
227 if (title) {
228 calendar.fullCalendar('renderEvent',
229 {
230 title: title,
231 start: start,
232 end: end,
233 allDay: allDay
234 },
235 true // make the event "stick"
236 );
237 }
238 calendar.fullCalendar('unselect');
239 },
240 droppable: false, // this allows things to be dropped onto the calendar !!!
241 drop: function(date, allDay) { // this function is called when something is dropped
242
243 // retrieve the dropped element's stored Event Object
244 var originalEventObject = $(this).data('eventObject');
245
246 // we need to copy it, so that multiple events don't have a reference to the same object
247 var copiedEventObject = $.extend({}, originalEventObject);
248
249 // assign it the date that was reported
250 copiedEventObject.start = date;
251 copiedEventObject.allDay = allDay;
252
253 // render the event on the calendar
254 // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
255 $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
256
257 // is the "remove after drop" checkbox checked?
258 if ($('#drop-remove').is(':checked')) {
259 // if so, remove the element from the "Draggable Events" list
260 $(this).remove();
261 }
262
263 },
264 events: function (start, end, callback) {
265 var selectedVal = $('#company').attr('business-id');
266 if(!isNaN(parseInt(selectedVal))) {
267 $.ajax({
268 url: "http://localhost:8080/api/appointment/business/" + selectedVal,
269 type:"GET",
270 contentType:"application/json; charset=utf-8",
271 dataType: 'text',
272 success: function(data){
273 // reset events
274 var events = [];
275 $.each(JSON.parse(data), function (index, object) {
276 var event = {}
277 event['title'] = object['title'];
278 event['start'] = object['startTime'].replace('T', ' ');
279 event['end'] = object['endTime'].replace('T', ' ');
280 event['allDay'] = false;
281 event['color'] = '#3b71ca';
282 event['textColor'] = '#FFFFFF';
283 events.push(event);
284 });
285 // load events
286 callback(events);
287 },
288 error: function(error) {
289 console.log(error.responseText);
290 }
291 });
292 }
293 },
294 });
295}
296
297function goToProfile() {
298 window.location = "/customer_admin";
299}
300
301function destroyCalendar() {
302 $('#calendar').fullCalendar('destroy');
303}
304
305function resetRatingCard() {
306 $('#rating-service-name').empty();
307 $('#rating-value').empty();
308 $('#rating-count').empty();
309 $('#reviews-li').remove();
310}
311
312function setRatingCard(name, value, count, serviceId) {
313 $('#rating-service-name').text(name);
314 $('#rating-value').text(value);
315 $('#rating-count').text(count);
316 $('#reviews-li').remove();
317 getReviewsForService(serviceId);
318
319}
320
321function getReviewsForService(serviceId){
322 $.ajax({
323 url: "http://localhost:8080/api/review/" + serviceId
324 }).then(function (data) {
325 var $el = $("#reviewsModalBody");
326 $('#reviews-ul').append($('<button type="button" id="reviews-li" class="btn btn-primary btn-block" data-bs-toggle="modal" data-bs-target="#showReviewsModal">Checkout reviews</button>'));
327 $el.empty();
328
329 $.each(data, function (index, obj) {
330 var element = '<div class="card m-3" style="max-width: 300px; padding: 0;">';
331 element += '<div class="card-header" style="' + generateHeaderStyle(obj['rating']) + '">' + generateStars(obj['rating']) + '</div>';
332 element += '<ul class="list-group list-group-flush">';
333 element += '<li class="list-group-item"><i><b>Business:</b></i> ' + obj['businessName'] + '</li>';
334 element += '<li class="list-group-item"><i><b>Service:</b></i> ' + obj['serviceName'] + '</li>';
335 element += '<li class="list-group-item"><i><b>Reviewer:</b></i> ' + obj['customerName'] + '</li>';
336 element += '<li class="list-group-item"><i><b>Comment:</b></i> ' + obj['comment'] + '</li>';
337 element += '<li class="list-group-item"><small class="text-body-secondary"><i>Created:</i> ' + obj['created'] + '</small></li>';
338 element += '</ul>';
339 element += '</div>';
340
341 $el.append(element);
342 });
343 });
344}
345
346function searchServices() {
347 let value = document.getElementById("search-input").value;
348 $.ajax({
349 type: 'GET',
350 url: "http://localhost:8080/api/service?searchKeyword=" + value,
351 success: function(data, textStatus, request) {
352
353 // clear previous data
354 $('#searchResultsModalBody').html('');
355
356 if (data.length === 0) {
357 showNoSearchResultsFound();
358 } else {
359 showSearchResults(data);
360 }
361
362 },
363 error: function (request, textStatus, errorThrown) {
364 console.log(errorThrown);
365 }
366 });
367}
368
369function showSearchResults(data) {
370 var searchResultsBody = $('#searchResultsModalBody')
371 searchResultsBody.append(
372 '<div class="form-outline col-lg-12 row">\n' +
373 ' <div class="form-outline col-lg-12">\n' +
374 ' <div class="table-responsive">\n' +
375 ' <table class="table">\n' +
376 ' <thead>\n' +
377 ' <tr>\n' +
378 ' <th scope="col">#</th>\n' +
379 ' <th scope="col">Business</th>\n' +
380 ' <th scope="col">Service name</th>\n' +
381 ' <th scope="col">Service Description</th>\n' +
382 ' <th scope="col">Durantion/Price</th>\n' +
383 ' <th scope="col">Rating/ReviewCount</th>\n' +
384 ' <th scope="col">Make reserviation</th>\n' +
385 ' </tr>\n' +
386 ' </thead>\n' +
387 ' <tbody id="search-results-table-body">\n' +
388 ' </tbody>\n' +
389 ' </table>\n' +
390 ' </div>\n' +
391 ' </div>\n' +
392 ' </div>');
393 let $el = $('#search-results-table-body');
394
395 $.each(data, function (index, obj) {
396 var element=
397 '<tr>' +
398 ' <th scope="row">' + (parseInt(index) + 1) + '</th>' +
399 ' <td>' + obj['businessName'] + '</td>' +
400 ' <td>' + obj['serviceName'] + '</td>' +
401 ' <td>' + obj['description'] + '</td>' +
402 ' <td>' + obj['duration'] + '/' + obj['price'] + '</td>' +
403 ' <td>' + obj['rating'] + '/' + obj['reviewsCount'] + '</td>' +
404 ' <td><button type="button" class="btn btn-primary" ' + 'onclick="makeReservation(\'' + obj['serviceName'] + '\',' + obj['rating'] + ',' + obj['reviewsCount'] + ',' + obj['id'] + ',\'' + obj['businessName'] + '\',' + obj['businessId'] + ',' + obj['duration'] + ')" ' + '>Reserve</button></td>' +
405 '</tr>';
406
407 $el.append(element);
408 });
409
410 $('#searchModal').modal('show');
411}
412
413function makeReservation(name, value, count, serviceId, businessName, businessId, duration) {
414 $('#searchModal').modal('hide');
415 $('#body-after-search').css("display", "inline");
416 $('#welcome-message').css('display', 'none');
417 $('#calendar').fullCalendar('render');
418 setRatingCard(name, value, count, serviceId);
419 $('#company').val(businessName);
420 $('#company').attr('business-id', businessId);
421 $('#service').val(name);
422 $('#service').attr('duration', duration);
423 $('#service').attr('service-id', serviceId);
424 $('#calendar').fullCalendar('refetchEvents');
425}
426
427function showNoSearchResultsFound() {
428 $('#searchResultsModalBody').text('Sorry we have no results for the thing that you search, please close the modal and search for something else.');
429 $('#searchModal').modal('show');
430}
431
432function generateStars(number) {
433 return '☆'.repeat(number);
434}
435
436function generateHeaderStyle(number) {
437 var style = '';
438 switch (number) {
439 case 5:
440 style = 'background-color: RGBA(13,110,253,var(--bs-bg-opacity,1)) !important; ';
441 break;
442 case 4:
443 style = 'background-color: RGBA(25,135,84,var(--bs-bg-opacity,1)) !important; ';
444 break;
445 case 3:
446 style = 'background-color: RGBA(108,117,125,var(--bs-bg-opacity,1)) !important; ';
447 break;
448 case 2:
449 style = 'background-color: RGBA(255,193,7,var(--bs-bg-opacity,1)) !important; ';
450 break;
451 case 1:
452 style = 'background-color: RGBA(220,53,69,var(--bs-bg-opacity,1)) !important; ';
453 break;
454 }
455
456 style += ' color: #fff !important;'
457 return style;
458}
Note: See TracBrowser for help on using the repository browser.