PluginProbe
VikBooking Hotel Booking Engine & PMS / 1.6.6
VikBooking Hotel Booking Engine & PMS v1.6.6
1.8.16 1.8.15 1.8.14 1.8.13 1.8.12 1.8.11 1.8.10 1.8.9 1.8.6 1.8.7 1.8.8 trunk 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 1.6.5 1.6.6 1.6.7 1.6.8 1.6.9 1.7.0 1.7.1 1.7.2 All 37 releases
vikbooking / admin / helpers / report / istat_ricestat.php

istat_ricestat.php in VikBooking Hotel Booking Engine & PMS 1.6.6, at admin/helpers/report/istat_ricestat.php

1,547 lines 52.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * @package VikBooking
4 * @subpackage com_vikbooking
5 * @author Alessio Gaggii - e4j - Extensionsforjoomla.com
6 * @copyright Copyright (C) 2019 e4j - Extensionsforjoomla.com. All rights reserved.
7 * @license GNU General Public License version 2 or later; see LICENSE
8 * @link https://vikwp.com
9 */
10
11 defined('ABSPATH') or die('No script kiddies please!');
12
13 /**
14 * ISTAT Ricestat child Class of VikBookingReport.
15 */
16 class VikBookingReportIstatRicestat extends VikBookingReport
17 {
18 /**
19 * Property 'defaultKeySort' is used by the View that renders the report.
20 */
21 public $defaultKeySort = 'idbooking';
22 /**
23 * Property 'defaultKeyOrder' is used by the View that renders the report.
24 */
25 public $defaultKeyOrder = 'ASC';
26 /**
27 * Property 'customExport' is used by the View to display custom export buttons.
28 */
29 public $customExport = '';
30 /**
31 * Debug mode is activated by passing the value 'e4j_debug' > 0
32 */
33 private $debug;
34
35 // username and password for the structure
36 private $providerusername;
37 private $providerpassword;
38
39 /**
40 * Other private vars of this sub-class.
41 */
42 private $comuniProvince;
43 private $nazioni;
44 private $documenti;
45 public $tipoTurismo;
46 public $mezzoDiTrasporto;
47
48 /**
49 * Class constructor should define the name of the report and
50 * other vars. Call the parent constructor to define the DB object.
51 */
52 function __construct()
53 {
54 $this->reportFile = basename(__FILE__, '.php');
55 $this->reportName = JText::translate('ISTAT Ricestat');
56 $this->reportFilters = array();
57
58 $this->providerusername = 'Prova';
59 $this->providerpassword = 'Prova';
60
61 $this->cols = array();
62 $this->rows = array();
63 $this->footerRow = array();
64
65 $this->debug = (VikRequest::getInt('e4j_debug', 0, 'request') > 0);
66
67 $this->comuniProvince = array();
68 $this->nazioni = array();
69 $this->mezzoDiTrasporto = array(
70 '0' => 'Auto',
71 '1' => 'Aereo',
72 '2' => 'Aereo+Pullman',
73 '3' => 'Aereo+Navetta/Taxi/Auto',
74 '4' => 'Aereo+Treno',
75 '5' => 'Treno',
76 '6' => 'Pullman',
77 '7' => 'Caravan/Autocaravan',
78 '8' => 'Barca/Nave/Traghetto',
79 '9' => 'Moto',
80 '10' => 'Bicicletta',
81 '11' => 'A piedi',
82 '12' => 'Altro motivo',
83 '13' => 'Non specificato'
84 );
85 $this->tipoTurismo = array(
86 '0' => 'Culturale',
87 '1' => 'Balneare',
88 '2' => 'Congressuale/Affari',
89 '3' => 'Fieristico',
90 '4' => 'Sportivo/Fitness',
91 '5' => 'Scolastico',
92 '6' => 'Religioso',
93 '7' => 'Sociale',
94 '8' => 'Parchi Tematici',
95 '9' => 'Termale/Trattamenti salute',
96 '10' => 'Enogastronomico',
97 '11' => 'Cicloturismo',
98 '12' => 'Escursionistico/Naturalistico',
99 '13' => 'Altro motivo',
100 '14' => 'Non specificato'
101 );
102
103 $this->registerExportFileName();
104
105 parent::__construct();
106 }
107
108 /**
109 * Returns the name of this report.
110 *
111 * @return string
112 */
113 public function getName()
114 {
115 return $this->reportName;
116 }
117
118 /**
119 * Returns the name of this file without .php.
120 *
121 * @return string
122 */
123 public function getFileName()
124 {
125 return $this->reportFile;
126 }
127
128 /**
129 * Returns the filters of this report.
130 *
131 * @return array
132 */
133 public function getFilters()
134 {
135 if ($this->reportFilters) {
136 //do not run this method twice, as it could load JS and CSS files.
137 return $this->reportFilters;
138 }
139
140 $doc = JFactory::getDocument();
141 $css = '.vbo-report-load-trasporto span, .vbo-report-load-turismo span {
142 display: inline-block;
143 border: 1px solid #dd0000;
144 cursor: pointer;
145 color: #dd0000;
146 padding: 0px 7px;
147 }';
148 $doc->addStyleDeclaration($css);
149
150 //load the jQuery UI Datepicker
151 $this->loadDatePicker();
152
153 //custom export button
154 $this->customExport = '<a href="JavaScript: void(0);" onclick="vboDownloadSchedaIstat();" class="vbcsvexport"><i class="'.VikBookingIcons::i('download').'"></i> <span>Download File</span></a>';
155
156 //build the hidden values for the selection of Comuni & Province.
157 $this->comuniProvince = $this->loadComuniProvince();
158 $this->nazioni = $this->loadNazioni();
159 $hidden_vals = '<div id="vbo-report-alloggiati-hidden" style="display: none;">';
160 //Comuni
161 $hidden_vals .= ' <div id="vbo-report-alloggiati-comune" class="vbo-report-alloggiati-selcont" style="display: none;">';
162 $hidden_vals .= ' <select id="choose-comune" onchange="vboReportChosenComune(this);"><option value=""></option>';
163 if (isset($this->comuniProvince['comuni']) && count($this->comuniProvince['comuni'])) {
164 foreach ($this->comuniProvince['comuni'] as $code => $comune) {
165 $hidden_vals .= ' <option value="' . $code . '">' . (is_array($comune) ? $comune['name'] : '') . '</option>'."\n";
166 }
167 }
168 $hidden_vals .= ' </select>';
169 $hidden_vals .= ' </div>';
170 //
171 //Mezzi di Trasporto
172 $hidden_vals .= ' <div id="vbo-report-trasporto" class="vbo-report-alloggiati-selcont" style="display: none;">';
173 $hidden_vals .= ' <select id="choose-trasporto" onchange="vboReportChosenTrasporto(this);"><option value=""></option>';
174 foreach ($this->mezzoDiTrasporto as $key => $value) {
175 $hidden_vals .= ' <option value="'.$value.'">'.$value.'</option>'."\n";
176 }
177 $hidden_vals .= ' </select>';
178 $hidden_vals .= ' </div>';
179 //
180 //Tipo di turismo
181 $hidden_vals .= ' <div id="vbo-report-turismo" class="vbo-report-alloggiati-selcont" style="display: none;">';
182 $hidden_vals .= ' <select id="choose-turismo" onchange="vboReportChosenTurismo(this);"><option value=""></option>';
183 foreach ($this->tipoTurismo as $key => $value) {
184 $hidden_vals .= ' <option value="'.$value.'">'.$value.'</option>'."\n";
185 }
186 $hidden_vals .= ' </select>';
187 $hidden_vals .= ' </div>';
188 //
189 //Province
190 $hidden_vals .= ' <div id="vbo-report-alloggiati-provincia" class="vbo-report-alloggiati-selcont" style="display: none;">';
191 $hidden_vals .= ' <select id="choose-provincia" onchange="vboReportChosenProvincia(this);"><option value=""></option>';
192 if (isset($this->comuniProvince['province']) && count($this->comuniProvince['province'])) {
193 foreach ($this->comuniProvince['province'] as $code => $provincia) {
194 $hidden_vals .= ' <option value="'.$code.'">'.$provincia.'</option>'."\n";
195 }
196 }
197 $hidden_vals .= ' </select>';
198 $hidden_vals .= ' </div>';
199 //
200 //Nazioni
201 $hidden_vals .= ' <div id="vbo-report-alloggiati-nazione" class="vbo-report-alloggiati-selcont" style="display: none;">';
202 $hidden_vals .= ' <select id="choose-nazione" onchange="vboReportChosenNazione(this);"><option value=""></option>';
203 if (count($this->nazioni)) {
204 foreach ($this->nazioni as $code => $nazione) {
205 $hidden_vals .= ' <option value="'.$code.'">'.$nazione['name'].'</option>';
206 }
207 }
208 $hidden_vals .= ' </select>';
209 $hidden_vals .= ' </div>';
210 //
211 //Sesso
212 $hidden_vals .= ' <div id="vbo-report-alloggiati-sesso" class="vbo-report-alloggiati-selcont" style="display: none;">';
213 $hidden_vals .= ' <select id="choose-sesso" onchange="vboReportChosenSesso(this);"><option value=""></option>';
214 $sessos = array(
215 1 => 'M',
216 2 => 'F'
217 );
218 foreach ($sessos as $code => $ses) {
219 $hidden_vals .= ' <option value="'.$code.'">'.$ses.'</option>'."\n";
220 }
221 $hidden_vals .= ' </select>';
222 $hidden_vals .= ' </div>';
223 //
224 //Numero Documento
225 $hidden_vals .= ' <div id="vbo-report-alloggiati-docnum" class="vbo-report-alloggiati-selcont" style="display: none;">';
226 $hidden_vals .= ' <input type="text" size="40" id="choose-docnum" placeholder="Numero Documento..." value="" /><br/>';
227 $hidden_vals .= ' <button type="button" class="btn" onclick="vboReportChosenDocnum(document.getElementById(\'choose-docnum\').value);">'.JText::translate('VBAPPLY').'</button>';
228 $hidden_vals .= ' </div>';
229 //
230 //Data di Nascita
231 $hidden_vals .= ' <div id="vbo-report-alloggiati-dbirth" class="vbo-report-alloggiati-selcont" style="display: none;">';
232 $hidden_vals .= ' <input type="text" size="40" id="choose-dbirth" placeholder="Data di Nascita" value="" /><br/>';
233 $hidden_vals .= ' <button type="button" class="btn" onclick="vboReportChosenDbirth(document.getElementById(\'choose-dbirth\').value);">'.JText::translate('VBAPPLY').'</button>';
234 $hidden_vals .= ' </div>';
235 //
236 $hidden_vals .= '</div>';
237
238 //From Date Filter (with hidden values for the dropdown menus of Comuni, Province, Stati etc..)
239 $filter_opt = array(
240 'label' => '<label for="fromdate">'.JText::translate('VBOREPORTSDATEFROM').'</label>',
241 'html' => '<input type="text" id="fromdate" name="fromdate" value="" class="vbo-report-datepicker vbo-report-datepicker-from" />'.$hidden_vals,
242 'type' => 'calendar',
243 'name' => 'fromdate'
244 );
245 array_push($this->reportFilters, $filter_opt);
246
247 // Azione da eseguire: 1 per inserire/modificare, 2 per cancellare.
248 $actiontodo = VikRequest::getString('actiontodo', '', 'request');
249 $filter_opt = array(
250 'label' => '<label for="actiontodo">Azione da Eseguire</label>',
251 'html' => '<select id="choose-actiontodo" name="actiontodo"> <option value="" '.((empty($actiontodo) || ($actiontodo != '1' && $actiontodo != '2')) ? 'selected="selected"' : '' ).'></option><option value="1" ' .((!empty($actiontodo) && $actiontodo == '1') ? 'selected="selected"' : '') .'> Inserire/Modificare una prenotazione. </option> <option value="NO"' .((!empty($actiontodo) && $actiontodo == '2') ? 'selected="selected"' : '') .'> Eliminare una prenotazione. </option> </select>',
252 'type' => 'text',
253 'name' => 'actiontodo'
254 );
255 array_push($this->reportFilters, $filter_opt);
256
257 $loginvals = $this->initConfiguration();
258 $updatevals = false; //if false, do not trigger update for login vals
259 // Username
260 $username = VikRequest::getString('riceusername', '', 'request');
261
262 if (empty($username) && !empty($loginvals) && !empty($loginvals['username'])) {
263 $username = $loginvals['username'];
264 } else if (!empty($username) && (empty($loginvals) || empty($loginvals['username'])) ){
265 $loginvals['username'] = $username;
266 $updatevals = true;
267 }
268
269 $filter_opt = array(
270 'label' => '<label for="riceusername">Codice Struttura</label>',
271 'html' => '<input type="text" id="riceusername" name="riceusername" value="'.$username.'" size="10" />',
272 'type' => 'text',
273 'name' => 'riceusername'
274 );
275 array_push($this->reportFilters, $filter_opt);
276
277 // Password
278 $password = VikRequest::getString('ricepassword', '', 'request');
279
280 if (empty($password) && !empty($loginvals) && !empty($loginvals['password'])) {
281 $password = $loginvals['password'];
282 } else if (!empty($password) && (empty($loginvals) || empty($loginvals['password'])) ){
283 $loginvals['password'] = $password;
284 $updatevals = true;
285 }
286 $filter_opt = array(
287 'label' => '<label for="ricepassword">Password Struttura</label>',
288 'html' => '<input type="password" id="ricepassword" name="ricepassword" value="'.$password.'" size="10" />',
289 'type' => 'text',
290 'name' => 'ricepassword'
291 );
292 array_push($this->reportFilters, $filter_opt);
293
294 if ($updatevals) {
295 $this->updateLogin($loginvals);
296 }
297 //jQuery code for the datepicker calendars, select2 and triggers for the dropdown menus
298 $pfromdate = VikRequest::getString('fromdate', '', 'request');
299 $ptodate = VikRequest::getString('todate', '', 'request');
300 $js = 'var reportActiveCell = null, reportObj = {};
301 jQuery(function() {
302 //prepare main filters
303 jQuery(".vbo-report-datepicker:input").datepicker({
304 maxDate: 0,
305 dateFormat: "'.$this->getDateFormat('jui').'",
306 onSelect: vboReportCheckDates
307 });
308 '.(!empty($pfromdate) ? 'jQuery(".vbo-report-datepicker-from").datepicker("setDate", "'.$pfromdate.'");' : '').'
309 '.(!empty($ptodate) ? 'jQuery(".vbo-report-datepicker-to").datepicker("setDate", "'.$ptodate.'");' : '').'
310 //prepare filler helpers
311 jQuery("#vbo-report-alloggiati-hidden").children().detach().appendTo(".vbo-info-overlay-report");
312 jQuery("#choose-comune").select2({placeholder: "- Seleziona un Comune -", width: "200px"});
313 jQuery("#choose-provincia").select2({placeholder: "- Seleziona una Provincia -", width: "200px"});
314 jQuery("#choose-nazione").select2({placeholder: "- Seleziona una Nazione -", width: "200px"});
315 jQuery("#choose-sesso").select2({placeholder: "- Seleziona Sesso -", width: "200px"});
316 jQuery("#choose-turismo").select2({placeholder: "- Seleziona Tipo di Turismo -", width: "300px"});
317 jQuery("#choose-trasporto").select2({placeholder: "- Seleziona Mezzo di Trasporto -", width: "300px"});
318
319 jQuery("#choose-dbirth").datepicker({
320 maxDate: 0,
321 dateFormat: "dd/mm/yy",
322 changeMonth: true,
323 changeYear: true,
324 yearRange: "'.(date('Y') - 100).':'.date('Y').'"
325 });
326 //click events
327 jQuery(".vbo-report-load-comune").click(function() {
328 reportActiveCell = this;
329 jQuery(".vbo-report-alloggiati-selcont").hide();
330 jQuery("#vbo-report-alloggiati-comune").show();
331 vboShowOverlay();
332 });
333 jQuery(".vbo-report-load-provincia").click(function() {
334 reportActiveCell = this;
335 jQuery(".vbo-report-alloggiati-selcont").hide();
336 jQuery("#vbo-report-alloggiati-provincia").show();
337 vboShowOverlay();
338 });
339 jQuery(".vbo-report-load-nazione, .vbo-report-load-cittadinanza").click(function() {
340 reportActiveCell = this;
341 jQuery(".vbo-report-alloggiati-selcont").hide();
342 jQuery("#vbo-report-alloggiati-nazione").show();
343 vboShowOverlay();
344 });
345 jQuery(".vbo-report-load-sesso").click(function() {
346 reportActiveCell = this;
347 jQuery(".vbo-report-alloggiati-selcont").hide();
348 jQuery("#vbo-report-alloggiati-sesso").show();
349 vboShowOverlay();
350 });
351 jQuery(".vbo-report-load-turismo").click(function() {
352 reportActiveCell = this;
353 jQuery(".vbo-report-alloggiati-selcont").hide();
354 jQuery("#vbo-report-turismo").show();
355 vboShowOverlay();
356 });
357 jQuery(".vbo-report-load-trasporto").click(function() {
358 reportActiveCell = this;
359 jQuery(".vbo-report-alloggiati-selcont").hide();
360 jQuery("#vbo-report-trasporto").show();
361 vboShowOverlay();
362 });
363 jQuery(".vbo-report-load-dbirth").click(function() {
364 reportActiveCell = this;
365 jQuery(".vbo-report-alloggiati-selcont").hide();
366 jQuery("#vbo-report-alloggiati-dbirth").show();
367 vboShowOverlay();
368 //pretend the overlay is off, or navigating in the datepicker will close the modal.
369 setTimeout(function(){vbo_overlay_on = false;}, 800);
370 //
371 });
372 });
373 function vboReportCheckDates(selectedDate, inst) {
374 if (selectedDate === null || inst === null) {
375 return;
376 }
377 var cur_from_date = jQuery(this).val();
378 if (jQuery(this).hasClass("vbo-report-datepicker-from") && cur_from_date.length) {
379 var nowstart = jQuery(this).datepicker("getDate");
380 var nowstartdate = new Date(nowstart.getTime());
381 jQuery(".vbo-report-datepicker-to").datepicker("option", {minDate: nowstartdate});
382 }
383 }
384 function vboReportChosenComune(comune) {
385 var c_code = comune.value;
386 var c_val = comune.options[comune.selectedIndex].text;
387 if (reportActiveCell !== null) {
388 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
389 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
390 alert("Error, cannot find element to update.");
391 } else {
392 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
393 if (!reportObj.hasOwnProperty(nowindex)) {
394 reportObj[nowindex] = {};
395 }
396 if (jQuery(reportActiveCell).hasClass("vbo-report-load-docplace")) {
397 reportObj[nowindex].docplace = c_code;
398 } else {
399 reportObj[nowindex].comres = c_code;
400 }
401 }
402 }
403 reportActiveCell = null;
404 vboHideOverlay();
405 jQuery("#choose-comune").val("").select2("data", null, false);
406 }
407 function vboReportChosenProvincia(prov) {
408 var c_code = prov.value;
409 var c_val = prov.options[prov.selectedIndex].text;
410 if (reportActiveCell !== null) {
411 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
412 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
413 alert("Error, cannot find element to update.");
414 } else {
415 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
416 if (!reportObj.hasOwnProperty(nowindex)) {
417 reportObj[nowindex] = {};
418 }
419 reportObj[nowindex].prores = c_code;
420 }
421 }
422 reportActiveCell = null;
423 vboHideOverlay();
424 jQuery("#choose-provincia").val("").select2("data", null, false);
425 }
426 function vboReportChosenNazione(naz) {
427 var c_code = naz.value;
428 var c_val = naz.options[naz.selectedIndex].text;
429 if (reportActiveCell !== null) {
430 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
431 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
432 alert("Error, cannot find element to update.");
433 } else {
434 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
435 if (!reportObj.hasOwnProperty(nowindex)) {
436 reportObj[nowindex] = {};
437 }
438 if (jQuery(reportActiveCell).hasClass("vbo-report-load-nazione")) {
439 reportObj[nowindex].stares = c_code;
440 } else if (jQuery(reportActiveCell).hasClass("vbo-report-load-docplace")) {
441 reportObj[nowindex].docplace = c_code;
442 } else {
443 reportObj[nowindex].citizen = c_code;
444 }
445 }
446 }
447 reportActiveCell = null;
448 vboHideOverlay();
449 jQuery("#choose-nazione").val("").select2("data", null, false);
450 }
451 function vboReportChosenSesso(sesso) {
452 var c_code = sesso.value;
453 var c_val = sesso.options[sesso.selectedIndex].text;
454 if (reportActiveCell !== null) {
455 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
456 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
457 alert("Error, cannot find element to update.");
458 } else {
459 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
460 if (!reportObj.hasOwnProperty(nowindex)) {
461 reportObj[nowindex] = {};
462 }
463 reportObj[nowindex].gender = c_code;
464 }
465 }
466 reportActiveCell = null;
467 vboHideOverlay();
468 jQuery("#choose-sesso").val("").select2("data", null, false);
469 }
470 function vboReportChosenTrasporto(trasporto) {
471 var c_code = trasporto.value;
472 var c_val = trasporto.options[trasporto.selectedIndex].text;
473 if (reportActiveCell !== null) {
474 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
475 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
476 alert("Error, cannot find element to update.");
477 } else {
478 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
479 if (!reportObj.hasOwnProperty(nowindex)) {
480 reportObj[nowindex] = {};
481 }
482 reportObj[nowindex].mezzo = c_code;
483 }
484 }
485 reportActiveCell = null;
486 vboHideOverlay();
487 jQuery("#choose-trasporto").val("").select2("data", null, false);
488 }
489 function vboReportChosenTurismo(turismo) {
490 var c_code = turismo.value;
491 var c_val = turismo.options[turismo.selectedIndex].text;
492 if (reportActiveCell !== null) {
493 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
494 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
495 alert("Error, cannot find element to update.");
496 } else {
497 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
498 if (!reportObj.hasOwnProperty(nowindex)) {
499 reportObj[nowindex] = {};
500 }
501 reportObj[nowindex].turismo = c_code;
502 }
503 }
504 reportActiveCell = null;
505 vboHideOverlay();
506 jQuery("#choose-turismo").val("").select2("data", null, false);
507 }
508 function vboReportChosenDbirth(val) {
509 var c_code = val, c_val = val;
510 if (reportActiveCell !== null) {
511 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
512 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
513 alert("Error, cannot find element to update.");
514 } else {
515 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
516 if (!reportObj.hasOwnProperty(nowindex)) {
517 reportObj[nowindex] = {};
518 }
519 reportObj[nowindex].dbirth = c_code;
520 }
521 }
522 reportActiveCell = null;
523 vboHideOverlay();
524 jQuery("#choose-dbirth").val("");
525 }
526 //download function
527 function vboDownloadSchedaIstat() {
528 if (!confirm("Sei sicuro di aver compilato tutti i dati?")) {
529 return false;
530 }
531 document.adminForm.target = "_blank";
532 document.adminForm.action += "&tmpl=component";
533 vboSetFilters({exportreport: "1", filler: JSON.stringify(reportObj)}, true);
534 setTimeout(function() {
535 document.adminForm.target = "";
536 document.adminForm.action = document.adminForm.action.replace("&tmpl=component", "");
537 vboSetFilters({exportreport: "0", filler: ""}, false);
538 }, 1000);
539 }';
540 $this->setScript($js);
541
542 return $this->reportFilters;
543 }
544
545 /**
546 * Loads the report data from the DB.
547 * Returns true in case of success, false otherwise.
548 * Sets the columns and rows for the report to be displayed.
549 *
550 * @return boolean
551 */
552 public function getReportData()
553 {
554 if (strlen($this->getError())) {
555 //Export functions may set errors rather than exiting the process, and the View may continue the execution to attempt to render the report.
556 return false;
557 }
558 //Input fields and other vars
559 $pfromdate = VikRequest::getString('fromdate', '', 'request');
560 $ptodate = VikRequest::getString('todate', '', 'request');
561 $pkrsort = VikRequest::getString('krsort', $this->defaultKeySort, 'request');
562 $pkrsort = empty($pkrsort) ? $this->defaultKeySort : $pkrsort;
563 $pkrorder = VikRequest::getString('krorder', $this->defaultKeyOrder, 'request');
564 $pkrorder = empty($pkrorder) ? $this->defaultKeyOrder : $pkrorder;
565 $pkrorder = $pkrorder == 'DESC' ? 'DESC' : 'ASC';
566 $username = VikRequest::getString('riceusername', '', 'request');
567 $password = VikRequest::getString('ricepassword', '', 'request');
568 $actiontodo = VikRequest::getString('actiontodo', '', 'request');
569 $records = array();
570 $q = "SELECT SUM(`units`) AS `sommaunita`, SUM(`totpeople`) AS `numeropersone`, COUNT(*) AS `numerocamere` FROM `#__vikbooking_rooms` WHERE `avail`= '1';";
571 $this->dbo->setQuery($q);
572 $this->dbo->execute();
573 if ($this->dbo->getNumRows() > 0) {
574 $records = $this->dbo->loadAssocList();
575 }
576 $totalBeds =(int) ($records[0]['sommaunita'] * ($records[0]['numeropersone']/$records[0]['numerocamere']));
577 $pletti = VikRequest::getString('numletti', $totalBeds, 'request');
578 $currency_symb = VikBooking::getCurrencySymb();
579 $df = $this->getDateFormat();
580 $datesep = VikBooking::getDateSeparator();
581 if (empty($ptodate)) {
582 $ptodate = $pfromdate;
583 }
584 //Get dates timestamps
585 $from_ts = VikBooking::getDateTimestamp($pfromdate, 0, 0);
586 $to_ts = VikBooking::getDateTimestamp($ptodate, 23, 59, 59);
587 if (empty($pfromdate) || empty($from_ts) || empty($to_ts)) {
588 $this->setError(JText::translate('VBOREPORTSERRNODATES'));
589 return false;
590 }
591 if (empty($username)) {
592 $this->setError('Inserisci il codice della tua Struttura.<br/>Si tratta di un codice univoco di identificazione che ti viene assegnato dall\'Amministrazione competente.');
593 return false;
594 }
595 if (empty($actiontodo)) {
596 $this->setError('Devi specificare l\'azione da eseguire attraverso il menù a tendina qui sopra.');
597 return false;
598 }
599 if (empty($password)) {
600 $this->setError('Devi specificare la password della tua struttura attraverso il menù a tendina qui sopra.');
601 return false;
602 }
603
604 //Query to obtain the records (all check-ins within the dates filter)
605 $records = array();
606 if($actiontodo == 1){
607 $q = "SELECT `o`.`id`,`o`.`custdata`,`o`.`ts`,`o`.`days`,`o`.`checkin`,`o`.`checkout`,`o`.`totpaid`,`o`.`roomsnum`,`o`.`total`,`o`.`idorderota`,`o`.`channel`,`o`.`country`,".
608 "`or`.`idorder`,`or`.`idroom`,`or`.`adults`,`or`.`children`,`or`.`t_first_name`,`or`.`t_last_name`,`or`.`cust_cost`,`or`.`cust_idiva`,`or`.`extracosts`,`or`.`room_cost`,".
609 "`co`.`idcustomer`,`co`.`pax_data`,`c`.`first_name`,`c`.`last_name`,`c`.`country` AS `customer_country`,`c`.`doctype`,`c`.`docnum`,`c`.`gender`,`c`.`bdate`,`c`.`pbirth` ".
610 "FROM `#__vikbooking_orders` AS `o` LEFT JOIN `#__vikbooking_ordersrooms` AS `or` ON `or`.`idorder`=`o`.`id` ".
611 "LEFT JOIN `#__vikbooking_customers_orders` AS `co` ON `co`.`idorder`=`o`.`id` LEFT JOIN `#__vikbooking_customers` AS `c` ON `c`.`id`=`co`.`idcustomer` ".
612 "WHERE `o`.`status`='confirmed' AND `o`.`closure`=0 AND ((`o`.`checkin`>=".$from_ts." AND `o`.`checkin`<=".$to_ts.") OR (`o`.`checkout`>=".$from_ts." AND `o`.`checkout`<=".$to_ts.") "."OR (`o`.`ts`>=".$from_ts." AND `o`.`ts`<=".$to_ts.")) ".
613 "ORDER BY `o`.`checkin` ASC, `o`.`id` ASC;";
614 } else {
615 $q = "SELECT `o`.`id`,`o`.`custdata`,`o`.`ts`,`o`.`days`,`o`.`checkin`,`o`.`checkout`,`o`.`totpaid`,`o`.`roomsnum`,`o`.`total`,`o`.`idorderota`,`o`.`channel`,`o`.`country`,".
616 "`or`.`idorder`,`or`.`idroom`,`or`.`adults`,`or`.`children`,`or`.`t_first_name`,`or`.`t_last_name`,`or`.`cust_cost`,`or`.`cust_idiva`,`or`.`extracosts`,`or`.`room_cost`,".
617 "`co`.`idcustomer`,`co`.`pax_data`,`c`.`first_name`,`c`.`last_name`,`c`.`country` AS `customer_country`,`c`.`doctype`,`c`.`docnum`,`c`.`gender`,`c`.`bdate`,`c`.`pbirth` ".
618 "FROM `#__vikbooking_orders` AS `o` LEFT JOIN `#__vikbooking_ordersrooms` AS `or` ON `or`.`idorder`=`o`.`id` ".
619 "LEFT JOIN `#__vikbooking_customers_orders` AS `co` ON `co`.`idorder`=`o`.`id` LEFT JOIN `#__vikbooking_customers` AS `c` ON `c`.`id`=`co`.`idcustomer` ".
620 "WHERE `o`.`status`='cancelled' AND `o`.`closure`=0 AND ((`o`.`checkin`>=".$from_ts." AND `o`.`checkin`<=".$to_ts.") OR (`o`.`checkout`>=".$from_ts." AND `o`.`checkout`<=".$to_ts.") "."OR (`o`.`ts`>=".$from_ts." AND `o`.`ts`<=".$to_ts.")) ".
621 "ORDER BY `o`.`checkin` ASC, `o`.`id` ASC;";
622 }
623 $this->dbo->setQuery($q);
624 $this->dbo->execute();
625 if ($this->dbo->getNumRows() > 0) {
626 $records = $this->dbo->loadAssocList();
627 }
628 if (!count($records)) {
629 $this->setError(JText::translate('VBOREPORTSERRNORESERV'));
630 $this->setError('Nessun check-in nelle date selezionate.');
631 return false;
632 }
633 //nest records with multiple rooms booked inside sub-array
634 $bookings = array();
635 foreach ($records as $v) {
636 if (!isset($bookings[$v['id']])) {
637 $bookings[$v['id']] = array();
638 }
639 array_push($bookings[$v['id']], $v);
640 }
641 //define the columns of the report
642 $this->cols = array(
643 //id booking
644 array(
645 'key' => 'idbooking',
646 'attr' => array(
647 'class="center"'
648 ),
649 'label' => 'ID',
650 'sortable' => 1,
651 ),
652 //check-in
653 array(
654 'key' => 'checkin',
655 'attr' => array(
656 'class="center"'
657 ),
658 'sortable' => 1,
659 'label' => JText::translate('VBPICKUPAT')
660 ),
661 //checkout
662 array(
663 'key' => 'checkout',
664 'attr' => array(
665 'class="center"'
666 ),
667 'sortable' => 1,
668 'label' => 'Partenza'
669 ),
670 //cognome
671 array(
672 'key' => 'cognome',
673 'label' => JText::translate('VBTRAVELERLNAME'),
674 'sortable' => 1,
675 ),
676 //nome
677 array(
678 'key' => 'nome',
679 'label' => JText::translate('VBTRAVELERNAME'),
680 'sortable' => 1,
681 ),
682 //sesso
683 array(
684 'key' => 'gender',
685 'attr' => array(
686 'class="center"'
687 ),
688 'label' => JText::translate('VBCUSTOMERGENDER')
689 ),
690 //data di nascita
691 array(
692 'key' => 'dbirth',
693 'attr' => array(
694 'class="center"'
695 ),
696 'label' => JText::translate('VBCUSTOMERBDATE')
697 ),
698 //cittadinanza
699 array(
700 'key' => 'citizen',
701 'attr' => array(
702 'class="center"'
703 ),
704 'sortable' => 1,
705 'label' => 'Cittadinanza'
706 ),
707 //cittadinanza
708 array(
709 'key' => 'stares',
710 'attr' => array(
711 'class="center"'
712 ),
713 'sortable' => 1,
714 'label' => 'Stato di Residenza'
715 ),
716 //comune di residenza
717 array(
718 'key' => 'comres',
719 'attr' => array(
720 'class="center"'
721 ),
722 'sortable' => 1,
723 'label' => 'Comune Residenza',
724 'tip' => 'Inserire il comune di residenza solo se il cittadino è di nazionalità italiana.'
725 ),
726 //tipo
727 array(
728 'key' => 'tipo',
729 'attr' => array(
730 'class="vbo-report-longlbl"'
731 ),
732 'label' => 'Tipo Alloggiato'
733 ),
734 //quantità (numero di ospiti)
735 array(
736 'key' => 'guestsnum',
737 'attr' => array(
738 'class="center"'
739 ),
740 'sortable' => 1,
741 'label' => 'Numero Ospiti',
742 'tip' => 'Il numero di ospiti totali (adulti + bambini) per ogni prenotazione è un dato che verrà comunicato all\'ISTAT.',
743 ),
744 array(
745 'key' => 'roomsbooked',
746 'attr' => array(
747 'class="center"'
748 ),
749 'sortable' => 1,
750 'label' => 'Occupazione',
751 'tip' => 'Questo valore indica il numero di camere occupate da ogni prenotazione, ed è un dato che verrà comunicato all\'ISTAT.',
752 ),
753
754 // tipo di trasporto
755 array(
756 'key' => 'mezzo',
757 'attr' => array(
758 'class="center"'
759 ),
760 'label' => 'Mezzo di Trasporto'
761 ),
762 // tipo di turismo
763 array(
764 'key' => 'turismo',
765 'attr' => array(
766 'class="center"'
767 ),
768 'label' => 'Tipo di Turismo'
769 ),
770 );
771
772 // loop over the bookings to build the rows of the report
773 $from_info = getdate($from_ts);
774 foreach ($bookings as $gbook) {
775 $guestsnum = 0;
776 $guests_rows = array($gbook[0]);
777 $room_guests = array();
778 $tot_guests_rows = 1;
779
780 $tipo = 16;
781 // Codici Tipo Alloggiato
782 // 16 = Ospite Singolo
783 // 17 = Capofamiglia
784 // 18 = Capogruppo
785 // 19 = Familiare
786 // 20 = Membro Gruppo
787
788 foreach ($gbook as $book) {
789 $guestsnum += $book['adults'] + $book['children'];
790 $room_guests[] = ($book['adults'] + $book['children']);
791 }
792 $pax_data = null;
793 if (!empty($gbook[0]['pax_data'])) {
794 $pax_data = json_decode($gbook[0]['pax_data'], true);
795 if (is_array($pax_data) && count($pax_data)) {
796 $guests_rows[0]['pax_data'] = $pax_data;
797 $tot_guests_rows = 0;
798 foreach ($pax_data as $roomguests) {
799 $tot_guests_rows += count($roomguests);
800 }
801 for ($i = 1; $i < $tot_guests_rows; $i++) {
802 array_push($guests_rows, $guests_rows[0]);
803 }
804 $tipo = count($guests_rows) > 1 ? 17 : $tipo;
805 }
806 }
807
808 //create one row for each guest
809 $guest_ind = 1;
810 foreach ($guests_rows as $ind => $guests) {
811 // prepare row record
812 $insert_row = array();
813
814 // find the actual guest-room-index
815 $guest_room_ind = $this->calcGuestRoomIndex($room_guests, $guest_ind);
816
817 // booking ID
818 array_push($insert_row, array(
819 'key' => 'idbooking',
820 'attr' => array(
821 'class="center"'
822 ),
823 'callback' => function ($val) {
824 return '<a href="index.php?option=com_vikbooking&task=editorder&cid[]='.$val.'" target="_blank"><i class="'.VikBookingIcons::i('external-link').'"></i> '.$val.'</a>';
825 },
826 'callback_export' => function ($val) {
827 return $val;
828 },
829 'value' => $guests['id']
830 ));
831
832 // checkin date
833 array_push($insert_row, array(
834 'key' => 'checkin',
835 'attr' => array(
836 'class="center"'
837 ),
838 'callback' => function ($val) {
839 return date('Y-m-d', $val);
840 },
841 'callback_export' => function ($val) {
842 return date('Y-m-d', $val);
843 },
844 'value' => $guests['checkin']
845 ));
846
847 // checkout date
848 array_push($insert_row, array(
849 'key' => 'checkout',
850 'attr' => array(
851 'class="center"'
852 ),
853 'callback' => function ($val) {
854 return date('Y-m-d', $val);
855 },
856 'callback_export' => function ($val) {
857 return date('Y-m-d', $val);
858 },
859 'value' => $gbook[0]['checkout']
860 ));
861
862 // cognome
863 $cognome = !empty($guests['t_last_name']) ? $guests['t_last_name'] : $guests['last_name'];
864 $pax_cognome = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'last_name');
865 $cognome = !empty($pax_cognome) ? $pax_cognome : $cognome;
866 array_push($insert_row, array(
867 'key' => 'cognome',
868 'value' => $cognome
869 ));
870
871 // nome
872 $nome = !empty($guests['t_first_name']) ? $guests['t_first_name'] : $guests['first_name'];
873 $pax_nome = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'first_name');
874 $nome = !empty($pax_nome) ? $pax_nome : $nome;
875 array_push($insert_row, array(
876 'key' => 'nome',
877 'value' => $nome
878 ));
879
880 // sesso
881 $gender = !empty($guests['gender']) && $guest_ind < 2 ? strtoupper($guests['gender']) : '';
882 $gender = $gender == 'F' ? 2 : ($gender == 'M' ? 1 : $gender);
883 $pax_gender = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'gender');
884 $gender = !empty($pax_gender) ? $pax_gender : $gender;
885 if (is_numeric($gender)) {
886 $gender = (int)$gender;
887 } elseif (!strcasecmp($gender, 'F')) {
888 $gender = 2;
889 } elseif (!strcasecmp($gender, 'M')) {
890 $gender = 1;
891 }
892 array_push($insert_row, array(
893 'key' => 'gender',
894 'attr' => array(
895 'class="center'.(empty($gender) ? ' vbo-report-load-sesso' : '').'"'
896 ),
897 'callback' => function ($val) {
898 return $val == 2 ? 'F' : ($val == 1 ? 'M' : '?');
899 },
900 'callback_export' => function ($val) {
901 return $val == 2 ? 'F' : ($val == 1 ? 'M' : '?');
902 },
903 'value' => $gender
904 ));
905
906 // data di nascita
907 $dbirth = !empty($guests['bdate']) && $guest_ind < 2 ? VikBooking::getDateTimestamp($guests['bdate'], 0, 0) : '';
908 $pax_dbirth = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'date_birth');
909 $dbirth = !empty($pax_dbirth) ? $pax_dbirth : $dbirth;
910 $dbirth = (strpos($dbirth, '/') === false && strpos($dbirth, VikBooking::getDateSeparator()) === false) ? $dbirth : VikBooking::getDateTimestamp($dbirth, 0, 0);
911 array_push($insert_row, array(
912 'key' => 'dbirth',
913 'attr' => array(
914 'class="center'.(empty($dbirth) ? ' vbo-report-load-dbirth' : '').'"'
915 ),
916 'callback' => function ($val) {
917 if (empty($val)) {
918 return '?';
919 }
920 if (strpos($val, '/') === false && strpos($val, VikBooking::getDateSeparator()) === false) {
921 return date('Y-m-d', $val);
922 }
923 if (strpos($val, '/') !== false) {
924 return date('Y-m-d', VikBooking::getDateTimestamp($val, 0, 0));
925 }
926 return $val;
927 },
928 'value' => $dbirth
929 ));
930
931 // cittadinanza (compatible with pax data field of driver "Italy")
932 $pax_country_c = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'country_c');
933 $citizen = !empty($guests['country']) && $guest_ind < 2 ? $guests['country'] : '';
934 $citizenval = '';
935 if (!empty($citizen) && $guest_ind < 2) {
936 $citizenval = $this->checkCountry($citizen);
937 }
938 // check nationality field from pre-checkin
939 $pax_citizen = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'nationality');
940 $citizen = !empty($pax_citizen) ? $pax_citizen : $citizen;
941 $citizen = !empty($pax_country_c) ? $pax_country_c : $citizen;
942 $citizenval = !empty($pax_country_c) ? $pax_country_c : $this->checkCountry($citizen);
943 array_push($insert_row, array(
944 'key' => 'citizen',
945 'attr' => array(
946 'class="center'.(empty($citizen) ? ' vbo-report-load-cittadinanza' : '').'"'
947 ),
948 'callback' => function ($val) {
949 return !empty($val) ? $this->nazioni[$val]['name'] : '?';
950 },
951 'no_export_callback' => 1,
952 'value' => !empty($citizenval) ? $citizenval : ''
953 ));
954
955 // stato di residenza
956 $provstay = '';
957 $pax_provstay = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'country_s');
958 $provstay = !empty($pax_provstay) ? $pax_provstay : $provstay;
959 array_push($insert_row, array(
960 'key' => 'staprov',
961 'attr' => array(
962 'class="center'.(empty($provstay) ? ' vbo-report-load-nazione' : '').'"'
963 ),
964 'callback' => function($val) {
965 if (!empty($val) && isset($this->nazioni[$val])) {
966 return $this->nazioni[$val]['name'];
967 }
968 // information is missing and should be provided
969 return '?';
970 },
971 'no_export_callback' => 1,
972 'value' => $provstay
973 ));
974
975 // comune di residenza
976 $comstay = '';
977 $pax_comstay = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'comune_s');
978 $comstay = !empty($pax_comstay) ? $pax_comstay : $comstay;
979 array_push($insert_row, array(
980 'key' => 'comprov',
981 'attr' => array(
982 'class="center'.(empty($comstay) ? ' vbo-report-load-comune' : '').'"'
983 ),
984 'callback' => function($val) {
985 if (!empty($val) && isset($this->comuniProvince['comuni'][$val])) {
986 return $this->comuniProvince['comuni'][$val]['name'];
987 }
988 // information is missing and should be provided
989 return '?';
990 },
991 'no_export_callback' => 1,
992 'value' => $comstay
993 ));
994
995 // tipo alloggiato
996 $use_tipo = $ind > 0 && $tipo == 17 ? 19 : $tipo;
997 $pax_guest_type = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'guest_type');
998 $use_tipo = !empty($pax_guest_type) ? $pax_guest_type : $use_tipo;
999 array_push($insert_row, array(
1000 'key' => 'tipo',
1001 'callback' => function ($val) {
1002 switch ($val) {
1003 case 16:
1004 return 'Ospite Singolo';
1005 case 17:
1006 return 'Capofamiglia';
1007 case 18:
1008 return 'Capogruppo';
1009 case 19:
1010 return 'Familiare';
1011 case 20:
1012 return 'Membro Gruppo';
1013 default:
1014 return '?';
1015 }
1016 },
1017 'no_export_callback' => 1,
1018 'value' => $use_tipo
1019 ));
1020
1021 // numero persone in prenotazione
1022 array_push($insert_row, array(
1023 'key' => 'guestsnum',
1024 'attr' => array(
1025 'class="center"'
1026 ),
1027 'value' => $guestsnum
1028 ));
1029
1030 // camere prenotate
1031 array_push($insert_row, array(
1032 'key' => 'roomsbooked',
1033 'attr' => array(
1034 'class="center"'
1035 ),
1036 'value' => count($gbook)
1037 ));
1038
1039 // mezzo di trasporto
1040 array_push($insert_row, array(
1041 'key' => 'mezzo',
1042 'attr' => array(
1043 'class="center vbo-report-load-trasporto"'
1044 ),
1045 'value' => '?'
1046 ));
1047
1048 // tipo di turismo
1049 array_push($insert_row, array(
1050 'key' => 'turismo',
1051 'attr' => array(
1052 'class="center vbo-report-load-turismo"'
1053 ),
1054 'value' => '?'
1055 ));
1056
1057 // push fields in the rows array as a new row
1058 array_push($this->rows, $insert_row);
1059
1060 // increment guest index
1061 $guest_ind++;
1062 }
1063 }
1064
1065 // do not sort the rows for this report because the lines of the guests of the same booking must be consecutive
1066 // $this->sortRows($pkrsort, $pkrorder);
1067
1068 // the footer row will just print the amount of records to export
1069 array_push($this->footerRow, array(
1070 array(
1071 'attr' => array(
1072 'class="vbo-report-total"'
1073 ),
1074 'value' => '<h3>'.JText::translate('VBOREPORTSTOTALROW').'</h3>'
1075 ),
1076 array(
1077 'attr' => array(
1078 'colspan="'.(count($this->cols) - 1).'"'
1079 ),
1080 'value' => count($this->rows)
1081 )
1082 ));
1083
1084 // Debug
1085 if ($this->debug) {
1086 $this->setWarning('path to report file = '.urlencode(dirname(__FILE__)).'<br/>');
1087 $this->setWarning('$total_rooms_units = '.$total_rooms_units.'<br/>');
1088 $this->setWarning('$bookings:<pre>'.print_r($bookings, true).'</pre><br/>');
1089 }
1090
1091 return true;
1092 }
1093
1094 public function formatXML(&$xml)
1095 {
1096 if (!class_exists('DOMDocument')) {
1097 // we cannot format the XML because DOMDocument is missing
1098 return $xml;
1099 }
1100
1101 $dom = new DOMDocument;
1102 $dom->preserveWhiteSpace = false;
1103 $dom->loadXML($xml);
1104 $dom->formatOutput = true;
1105 $xml = $dom->saveXML();
1106
1107 return $xml;
1108 }
1109
1110 /**
1111 * Generates the report columns and rows, then it outputs a CSV file
1112 * for download. In case of errors, the process is not terminated (exit)
1113 * to let the View display the error message.
1114 * We use customExport() rather than exportCSV() only because we need a
1115 * different download button rather than the classic "Export as CSV".
1116 *
1117 * @param int $export_type the view will pass this argument to the method to call different types of export.
1118 *
1119 * @return mixed void on success with script termination, false otherwise.
1120 */
1121 public function customExport($export_type = 0)
1122 {
1123 if (!$this->getReportData()) {
1124 return false;
1125 }
1126
1127 $pfromdate = VikRequest::getString('fromdate', '', 'request');
1128 $ptodate = VikRequest::getString('todate', '', 'request');
1129 $pcodstru = VikRequest::getString('codstru', '', 'request');
1130 $actiontodo = VikRequest::getString('actiontodo', '', 'request');
1131 $username = VikRequest::getString('riceusername', '', 'request');
1132 $password = VikRequest::getString('ricepassword', '', 'request');
1133 $records = array();
1134
1135 // manual values in filler
1136 $pfiller = VikRequest::getString('filler', '', 'request', VIKREQUEST_ALLOWRAW);
1137 $pfiller = !empty($pfiller) ? json_decode($pfiller, true) : array();
1138 $pfiller = !is_array($pfiller) ? array() : $pfiller;
1139
1140 //Debug
1141 if ($this->debug) {
1142 $this->setError('<pre>'.print_r($pfiller, true).'</pre><br/>');
1143 return false;
1144 }
1145 // pool of booking IDs to update their history
1146 $booking_ids = array();
1147 // update the history for all bookings affected
1148 foreach ($booking_ids as $bid) {
1149 VikBooking::getBookingHistoryInstance()->setBid($bid)->store('RP', $this->reportName);
1150 }
1151 $insertedReservations = $this->initReservations();
1152
1153 $xml = '<?xml version="1.0" encoding="UTF-8"?>
1154 <MTO_SchedineRQ xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://ws.webci.it/webci.xsd" Version="1.0" PrimaryLangID="it">
1155 <POS>
1156 <Source>
1157 <RequestorID Type = "4" ID = "' . $this->providerusername . '" MessagePassword = "' . $this->providerpassword . '"/>
1158 </Source>
1159 <Source>
1160 <RequestorID Type = "10" ID = "' . $username . '" MessagePassword = "' . $password . '"/>
1161 </Source>
1162 </POS>';
1163
1164 if ($actiontodo == '1') {
1165 $xml .= $this->editInsert($insertedReservations, $pfiller);
1166 } else {
1167 $xml .= $this->deleteRes($insertedReservations);
1168 }
1169 $xml .= '</MTO_SchedineRQ>';
1170
1171 // format XML document
1172 $this->formatXML($xml);
1173
1174 /**
1175 * Custom export method supports a custom export handler, if previously set.
1176 *
1177 * @since 1.16.1 (J) - 1.6.1 (WP)
1178 */
1179 if ($this->hasExportHandler()) {
1180 // write data onto the custom file handler
1181 $fp = $this->getExportCSVHandler();
1182 fwrite($fp, $xml);
1183 fclose($fp);
1184
1185 return true;
1186 }
1187
1188 header('Content-Disposition: attachment; filename=' . $this->getExportCSVFileName());
1189 header('Content-type: text/xml');
1190 echo $xml;
1191
1192 exit;
1193 }
1194
1195 /**
1196 * Registers the name to give to the file being exported.
1197 *
1198 * @return void
1199 *
1200 * @since 1.16.1 (J) - 1.6.1 (WP)
1201 */
1202 private function registerExportFileName()
1203 {
1204 $pfromdate = VikRequest::getString('fromdate', '', 'request');
1205 $ptodate = VikRequest::getString('todate', '', 'request');
1206
1207 $this->setExportCSVFileName(str_replace(' ', '_', $this->reportName) . '-' . str_replace('/', '_', $pfromdate) . '.xml');
1208 }
1209
1210 private function editInsert($toEdit, $pfiller)
1211 {
1212 $xml = '';
1213 $insertedids = array();
1214 $insertedids = $toEdit;
1215
1216 foreach ($this->rows as $ind => $row) {
1217 $idswh = -1;
1218 foreach ($row as $field) {
1219 if (isset($field['ignore_export'])) {
1220 continue;
1221 }
1222 // check if a value for this field was filled in manually
1223 if (is_array($pfiller) && isset($pfiller[$ind]) && isset($pfiller[$ind][$field['key']])) {
1224 if (strlen($pfiller[$ind][$field['key']])) {
1225 $field['value'] = $pfiller[$ind][$field['key']];
1226 }
1227 }
1228 // values set to -1 are usually empty and should have been filled in manually
1229 if ($field['value'] === -1) {
1230 // we raise an error in this case without stopping the process
1231 $field['value'] = 0;
1232 VikError::raiseWarning('', 'La riga #'.$ind.' ha un valore vuoto che doveva essere riempito manualmente cliccando sul blocco in rosso. Il file potrebbe contenere valori invalidi per questa riga.');
1233 }
1234 if (isset($field['callback_export'])) {
1235 $field['callback'] = $field['callback_export'];
1236 }
1237 $export_value = !isset($field['no_export_callback']) && isset($field['callback']) && is_callable($field['callback']) ? $field['callback']($field['value']) : $field['value'];
1238
1239 if ($field['key'] == 'idbooking') {
1240 $idswh = $export_value;
1241 //retrieve customer ID
1242 $q = "SELECT `idcustomer` FROM `#__vikbooking_customers_orders` WHERE `idorder` = " . $idswh . ";";
1243 $this->dbo->setQuery($q);
1244 $this->dbo->execute();
1245 if ($this->dbo->getNumRows() > 0) {
1246 $clienti[$idswh]['idcustomer'] = $this->dbo->loadResult();
1247 }
1248 }
1249 if ($field['key'] == 'checkin') {
1250 $clienti[$idswh]['checkin'] = $export_value;
1251 }
1252 if ($field['key'] == 'guestsnum') {
1253 $clienti[$idswh]['guestsnum'] = $export_value;
1254 }
1255 if ($field['key'] == 'checkout') {
1256 $clienti[$idswh]['checkout'] = $export_value;
1257 }
1258 $clienti[$idswh]['idswh'] = $idswh;
1259 if ($field['key'] == 'tipo') {
1260 $clienti[$idswh]['tipoalloggiato'] = (string)$export_value;
1261 }
1262 if ($field['key'] == 'gender') {
1263 $clienti[$idswh]['sesso'] = $export_value;
1264 }
1265 if ($field['key'] == 'turismo') {
1266 $clienti[$idswh]['tipoturismo'] = $export_value;
1267 }
1268 if ($field['key'] == 'mezzo') {
1269 $clienti[$idswh]['mezzotrasporto'] = $export_value;
1270 }
1271 if ($field['key'] == 'citizen') {
1272 $clienti[$idswh]['cittadinanza'] = (string)$export_value;
1273 }
1274 if ($field['key'] == 'stares') {
1275 $clienti[$idswh]['statoresidenza'] = (string)$export_value;
1276 }
1277 if ($field['key'] == 'dbirth') {
1278 $date = str_replace('/', '-', $export_value);
1279 //$datanascita = date('Ymd', strtotime($date));
1280 $clienti[$idswh]['datanascita'] = (string)$date;
1281 }
1282 if (isset($clienti[$idswh]['cittadinanza']) && $clienti[$idswh]['cittadinanza'] == '100000100' && $field['key'] == 'comres') {
1283 $clienti[$idswh]['luogoresidenza'] = (string)$export_value;
1284 }
1285 if (isset($clienti[$idswh]['tipoalloggiato']) && ($clienti[$idswh]['tipoalloggiato'] == '19' || $clienti[$idswh]['tipoalloggiato'] == '20') && $field['key'] == 'tipo') {
1286 $clienti[$idswh]['idcapo'] = (string)$idswh;
1287 }
1288 }
1289 }
1290 if (in_array($clienti['idswh'], $toEdit)) {
1291 $xml .= '<Aggiornamento>';
1292 } else {
1293 $xml .= '<InserimentoAlloggiati>';
1294 }
1295
1296 foreach ($clienti as $cliente) {
1297 if ($cliente['guestsnum'] > 1) {
1298 $rooms = VikBooking::loadOrdersRoomsData($cliente['idswh']);
1299 foreach ($rooms as $room) {
1300 $totalaval = $room['adults'] + $room['children'];
1301 $xml .= '<Gruppo id="' . $cliente['idswh'] . '" >';
1302 for ($i = 0; $i < $totalaval; $i++) {
1303 $provenienza = '';
1304 if ($cliente['cittadinanza'] == '100000100') {
1305 $provincia = substr($cliente['luogoresidenza'], 0, 6);
1306 $provenienza = '<Italia CodiceComune="' . $cliente['luogoresidenza'] . '" Provincia="' . $provincia . '" Stato="' . $cliente['cittadinanza'] . '" />';
1307 } else {
1308 $provenienza = '<Estero Stato="' . $cliente['cittadinanza'] . '" />';
1309 }
1310 $tipoalloggiato = $i == 0 ? '17' : '19';
1311 $xml .= '<Ospite id="' . $cliente['idcustomer'] . '_' . $room['idroom'] . '_' . $i . '" IdCamera="' . $room['idroom'] . '" TipoAlloggiato="' . $tipoalloggiato . '" >' .
1312 '<DataDiArrivo>' . $cliente['checkin'] . '</DataDiArrivo>' .
1313 '<DataDiPartenza>' . $cliente['checkout'] . '</DataDiPartenza>' .
1314 '<DataDiNascita>' . $cliente['datanascita'] . '</DataDiNascita>' .
1315 '<Sesso>' . $cliente['sesso'] . '</Sesso>' .
1316 '<Provenienza>' . $provenienza . '</Provenienza>' .
1317 '<Cittadinanza>' . $cliente['cittadinanza'] . '</Cittadinanza>' .
1318 '</Ospite>';
1319 }
1320 $xml .= '</Gruppo>';
1321 }
1322 } else {
1323 $provenienza = '';
1324 if ($cliente['cittadinanza'] == '100000100') {
1325 $provincia = substr($cliente['luogoresidenza'], 0, 6);
1326 $provenienza = '<Italia CodiceComune="' . $cliente['luogoresidenza'] . '" Provincia="' . $provincia . '" Stato="' . $cliente['cittadinanza'] . '" />';
1327 } else {
1328 $provenienza = '<Estero Stato="' . $cliente['cittadinanza'] . '" />';
1329 }
1330 $rooms = VikBooking::loadOrdersRoomsData($cliente['idswh']);
1331 $xml .= '<OspiteSingolo id="' . $cliente['idswh'] . '" >' .
1332 '<Ospite id="' . $cliente['idcustomer'] . '" IdCamera="' . $rooms['0']['idroom'] . '" TipoAlloggiato="' . $cliente['tipoalloggiato'] . '" >' .
1333 '<DataDiArrivo>' . $cliente['checkin'] . '</DataDiArrivo>' .
1334 '<DataDiPartenza>' . $cliente['checkout'] . '</DataDiPartenza>' .
1335 '<DataDiNascita>' . $cliente['datanascita'] . '</DataDiNascita>' .
1336 '<Sesso>' . $cliente['sesso'] . '</Sesso>' .
1337 '<Provenienza>' . $provenienza . '</Provenienza>' .
1338 '<Cittadinanza>' . $cliente['cittadinanza'] . '</Cittadinanza>' .
1339 '</Ospite>' .
1340 '</OspiteSingolo>';
1341 }
1342 }
1343
1344 if (in_array($cliente['idswh'], $toEdit)) {
1345 $xml .= '</Aggiornamento>';
1346 } else {
1347 array_push($insertedids, $cliente['idswh']);
1348 $xml .= '</InserimentoAlloggiati>';
1349 }
1350
1351 $this->updateReservations($insertedids);
1352
1353 return $xml;
1354 }
1355
1356 private function deleteRes($toEdit) {
1357 $xml = '<Eliminazione >';
1358 foreach ($this->rows as $ind => $row) {
1359 foreach ($row as $field) {
1360 if ($field['key'] == 'idbooking') {
1361 $idswh = $export_value;
1362 for ($i = 0; $i < count($toEdit); $i++) {
1363 if ($toEdit[$i] == $idswh) {
1364 unset($toEdit[$i]);
1365 $xml .= '<Alloggiato id="' . $idswh .'" />';
1366 }
1367 }
1368 }
1369 }
1370 }
1371 $xml .= '</Eliminazione >';
1372
1373 return $xml;
1374 }
1375
1376 /**
1377 * Parses the file Comuni.csv and returns two associative
1378 * arrays: one for the Comuni and one for the Province.
1379 * Every line of the CSV is composed of: Codice, Comune, Provincia.
1380 *
1381 * @return array
1382 */
1383 private function loadComuniProvince()
1384 {
1385 $vals = array(
1386 'comuni' => array(
1387 0 => '-- Estero --'
1388 ),
1389 'province' => array(
1390 0 => '-- Estero --'
1391 )
1392 );
1393
1394 $csv = dirname(__FILE__).DIRECTORY_SEPARATOR.'Comuni.csv';
1395 $rows = file($csv);
1396 foreach ($rows as $row) {
1397 if (empty($row)) {
1398 continue;
1399 }
1400 $v = explode(';', $row);
1401 if (count($v) != 3) {
1402 continue;
1403 }
1404 $vals['comuni'][$v[0]]['name'] = $v[1];
1405 $vals['comuni'][$v[0]]['province'] = $v[2];
1406 $vals['province'][$v[2]] = $v[2];
1407 }
1408
1409 return $vals;
1410 }
1411
1412 /**
1413 * Parses the file Nazioni.csv and returns an associative
1414 * array with the code and name of the Nazione.
1415 * Every line of the CSV is composed of: Codice, Nazione.
1416 *
1417 * @return array
1418 */
1419 protected function loadNazioni()
1420 {
1421 $nazioni = array();
1422
1423 $csv = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Nazioni.csv';
1424 $rows = file($csv);
1425 foreach ($rows as $row) {
1426 if (empty($row)) {
1427 continue;
1428 }
1429
1430 $v = explode(';', $row);
1431 if (count($v) != 3) {
1432 continue;
1433 }
1434
1435 $nazioni[$v[0]]['name'] = $v[1];
1436 $nazioni[$v[0]]['three_code'] = $v[2];
1437 }
1438
1439 return $nazioni;
1440 }
1441
1442 private function initReservations()
1443 {
1444 $init_res = VBOFactory::getConfig()->get('ricestat_insertedres');
1445 if (empty($init_res)) {
1446 return [];
1447 }
1448
1449 return (array)json_decode($init_res, true);
1450 }
1451
1452 private function initConfiguration()
1453 {
1454 $init_res = VBOFactory::getConfig()->get('ricestat_loginvalsricestat');
1455 if (empty($init_res)) {
1456 return [];
1457 }
1458
1459 return (array)json_decode($init_res, true);
1460 }
1461
1462 private function updateLogin($updatevals)
1463 {
1464 $vals = json_encode($updatevals);
1465
1466 VBOFactory::getConfig()->set('ricestat_loginvalsricestat', $vals);
1467 }
1468
1469 private function updateReservations($updatevals)
1470 {
1471 $vals = json_encode($updatevals);
1472
1473 VBOFactory::getConfig()->set('ricestat_insertedres', $vals);
1474 }
1475
1476 /**
1477 * Helper method to quickly get a pax_data property for the guest.
1478 *
1479 * @param array $pax_data the current pax_data stored.
1480 * @param array $guests list of total guests per room.
1481 * @param int $guest_ind the guest index.
1482 * @param string $key the pax_data key to look for.
1483 *
1484 * @return mixed null on failure or value fetched.
1485 */
1486 private function getGuestPaxDataValue($pax_data, $guests, $guest_ind, $key)
1487 {
1488 if (!is_array($pax_data) || !count($pax_data) || empty($key)) {
1489 return null;
1490 }
1491
1492 // find room index for this guest number
1493 $room_num = 0;
1494 $use_guest_ind = $guest_ind;
1495 foreach ($guests as $room_index => $room_tot_guests) {
1496 // find the proper guest index for the room to which this belongs
1497 if ($use_guest_ind <= $room_tot_guests) {
1498 // proper room index found for this guest
1499 $room_num = $room_index;
1500 break;
1501 } else {
1502 // it's probably in a next room
1503 $use_guest_ind -= $room_tot_guests;
1504 }
1505 }
1506
1507 // check if a value exists for the requested key in the found room and guest indexes
1508 if (isset($pax_data[$room_num]) && isset($pax_data[$room_num][$use_guest_ind])) {
1509 if (isset($pax_data[$room_num][$use_guest_ind][$key])) {
1510 // we've got a value previously stored
1511 return $pax_data[$room_num][$use_guest_ind][$key];
1512 }
1513 }
1514
1515 // nothing was found
1516 return null;
1517 }
1518
1519 /**
1520 * Helper method to determine the exact number for this guest in the room booked.
1521 *
1522 * @param array $guests list of total guests per room.
1523 * @param int $guest_ind the guest index.
1524 *
1525 * @return int the actual guest room index starting from 1.
1526 */
1527 private function calcGuestRoomIndex($guests, $guest_ind)
1528 {
1529 // find room index for this guest number
1530 $room_num = 0;
1531 $use_guest_ind = $guest_ind;
1532 foreach ($guests as $room_index => $room_tot_guests) {
1533 // find the proper guest index for the room to which this belongs
1534 if ($use_guest_ind <= $room_tot_guests) {
1535 // proper room index found for this guest
1536 $room_num = $room_index;
1537 break;
1538 } else {
1539 // it's probably in a next room
1540 $use_guest_ind -= $room_tot_guests;
1541 }
1542 }
1543
1544 return $use_guest_ind;
1545 }
1546 }
1547