PluginProbe
VikBooking Hotel Booking Engine & PMS / 1.8.16
VikBooking Hotel Booking Engine & PMS v1.8.16
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.8.16, at admin/helpers/report/istat_ricestat.php

1,582 lines 53.2 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 });
369 });
370 function vboReportCheckDates(selectedDate, inst) {
371 if (selectedDate === null || inst === null) {
372 return;
373 }
374 var cur_from_date = jQuery(this).val();
375 if (jQuery(this).hasClass("vbo-report-datepicker-from") && cur_from_date.length) {
376 var nowstart = jQuery(this).datepicker("getDate");
377 var nowstartdate = new Date(nowstart.getTime());
378 jQuery(".vbo-report-datepicker-to").datepicker("option", {minDate: nowstartdate});
379 }
380 }
381 function vboReportChosenComune(comune) {
382 var c_code = comune.value;
383 var c_val = comune.options[comune.selectedIndex].text;
384 if (reportActiveCell !== null) {
385 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
386 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
387 alert("Error, cannot find element to update.");
388 } else {
389 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
390 if (!reportObj.hasOwnProperty(nowindex)) {
391 reportObj[nowindex] = {};
392 }
393 if (jQuery(reportActiveCell).hasClass("vbo-report-load-docplace")) {
394 reportObj[nowindex].docplace = c_code;
395 } else {
396 reportObj[nowindex].comres = c_code;
397 }
398 }
399 }
400 reportActiveCell = null;
401 vboHideOverlay();
402 jQuery("#choose-comune").val("").select2("data", null, false);
403 }
404 function vboReportChosenProvincia(prov) {
405 var c_code = prov.value;
406 var c_val = prov.options[prov.selectedIndex].text;
407 if (reportActiveCell !== null) {
408 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
409 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
410 alert("Error, cannot find element to update.");
411 } else {
412 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
413 if (!reportObj.hasOwnProperty(nowindex)) {
414 reportObj[nowindex] = {};
415 }
416 reportObj[nowindex].prores = c_code;
417 }
418 }
419 reportActiveCell = null;
420 vboHideOverlay();
421 jQuery("#choose-provincia").val("").select2("data", null, false);
422 }
423 function vboReportChosenNazione(naz) {
424 var c_code = naz.value;
425 var c_val = naz.options[naz.selectedIndex].text;
426 if (reportActiveCell !== null) {
427 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
428 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
429 alert("Error, cannot find element to update.");
430 } else {
431 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
432 if (!reportObj.hasOwnProperty(nowindex)) {
433 reportObj[nowindex] = {};
434 }
435 if (jQuery(reportActiveCell).hasClass("vbo-report-load-nazione")) {
436 reportObj[nowindex].stares = c_code;
437 } else if (jQuery(reportActiveCell).hasClass("vbo-report-load-docplace")) {
438 reportObj[nowindex].docplace = c_code;
439 } else {
440 reportObj[nowindex].citizen = c_code;
441 }
442 }
443 }
444 reportActiveCell = null;
445 vboHideOverlay();
446 jQuery("#choose-nazione").val("").select2("data", null, false);
447 }
448 function vboReportChosenSesso(sesso) {
449 var c_code = sesso.value;
450 var c_val = sesso.options[sesso.selectedIndex].text;
451 if (reportActiveCell !== null) {
452 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
453 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
454 alert("Error, cannot find element to update.");
455 } else {
456 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
457 if (!reportObj.hasOwnProperty(nowindex)) {
458 reportObj[nowindex] = {};
459 }
460 reportObj[nowindex].gender = c_code;
461 }
462 }
463 reportActiveCell = null;
464 vboHideOverlay();
465 jQuery("#choose-sesso").val("").select2("data", null, false);
466 }
467 function vboReportChosenTrasporto(trasporto) {
468 var c_code = trasporto.value;
469 var c_val = trasporto.options[trasporto.selectedIndex].text;
470 if (reportActiveCell !== null) {
471 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
472 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
473 alert("Error, cannot find element to update.");
474 } else {
475 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
476 if (!reportObj.hasOwnProperty(nowindex)) {
477 reportObj[nowindex] = {};
478 }
479 reportObj[nowindex].mezzo = c_code;
480 }
481 }
482 reportActiveCell = null;
483 vboHideOverlay();
484 jQuery("#choose-trasporto").val("").select2("data", null, false);
485 }
486 function vboReportChosenTurismo(turismo) {
487 var c_code = turismo.value;
488 var c_val = turismo.options[turismo.selectedIndex].text;
489 if (reportActiveCell !== null) {
490 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
491 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
492 alert("Error, cannot find element to update.");
493 } else {
494 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
495 if (!reportObj.hasOwnProperty(nowindex)) {
496 reportObj[nowindex] = {};
497 }
498 reportObj[nowindex].turismo = c_code;
499 }
500 }
501 reportActiveCell = null;
502 vboHideOverlay();
503 jQuery("#choose-turismo").val("").select2("data", null, false);
504 }
505 function vboReportChosenDbirth(val) {
506 var c_code = val, c_val = val;
507 if (reportActiveCell !== null) {
508 var nowindex = jQuery(".vbo-reports-output table tbody tr").index(jQuery(reportActiveCell).closest("tr"));
509 if (isNaN(nowindex) || parseInt(nowindex) < 0) {
510 alert("Error, cannot find element to update.");
511 } else {
512 jQuery(reportActiveCell).addClass("vbo-report-load-elem-filled").find("span").text(c_val);
513 if (!reportObj.hasOwnProperty(nowindex)) {
514 reportObj[nowindex] = {};
515 }
516 reportObj[nowindex].dbirth = c_code;
517 }
518 }
519 reportActiveCell = null;
520 vboHideOverlay();
521 jQuery("#choose-dbirth").val("");
522 }
523 //download function
524 function vboDownloadSchedaIstat() {
525 if (!confirm("Sei sicuro di aver compilato tutti i dati?")) {
526 return false;
527 }
528 document.adminForm.target = "_blank";
529 document.adminForm.action += "&tmpl=component";
530 vboSetFilters({exportreport: "1", filler: JSON.stringify(reportObj)}, true);
531 setTimeout(function() {
532 document.adminForm.target = "";
533 document.adminForm.action = document.adminForm.action.replace("&tmpl=component", "");
534 vboSetFilters({exportreport: "0", filler: ""}, false);
535 }, 1000);
536 }';
537 $this->setScript($js);
538
539 return $this->reportFilters;
540 }
541
542 /**
543 * Loads the report data from the DB.
544 * Returns true in case of success, false otherwise.
545 * Sets the columns and rows for the report to be displayed.
546 *
547 * @return boolean
548 */
549 public function getReportData()
550 {
551 if (strlen($this->getError())) {
552 //Export functions may set errors rather than exiting the process, and the View may continue the execution to attempt to render the report.
553 return false;
554 }
555 //Input fields and other vars
556 $pfromdate = VikRequest::getString('fromdate', '', 'request');
557 $ptodate = VikRequest::getString('todate', '', 'request');
558 $pkrsort = VikRequest::getString('krsort', $this->defaultKeySort, 'request');
559 $pkrsort = empty($pkrsort) ? $this->defaultKeySort : $pkrsort;
560 $pkrorder = VikRequest::getString('krorder', $this->defaultKeyOrder, 'request');
561 $pkrorder = empty($pkrorder) ? $this->defaultKeyOrder : $pkrorder;
562 $pkrorder = $pkrorder == 'DESC' ? 'DESC' : 'ASC';
563 $username = VikRequest::getString('riceusername', '', 'request');
564 $password = VikRequest::getString('ricepassword', '', 'request');
565 $actiontodo = VikRequest::getString('actiontodo', '', 'request');
566 $records = array();
567 $q = "SELECT SUM(`units`) AS `sommaunita`, SUM(`totpeople`) AS `numeropersone`, COUNT(*) AS `numerocamere` FROM `#__vikbooking_rooms` WHERE `avail`= '1';";
568 $this->dbo->setQuery($q);
569 $this->dbo->execute();
570 if ($this->dbo->getNumRows() > 0) {
571 $records = $this->dbo->loadAssocList();
572 }
573 $totalBeds =(int) ($records[0]['sommaunita'] * ($records[0]['numeropersone']/$records[0]['numerocamere']));
574 $pletti = VikRequest::getString('numletti', $totalBeds, 'request');
575 $currency_symb = VikBooking::getCurrencySymb();
576 $df = $this->getDateFormat();
577 $datesep = VikBooking::getDateSeparator();
578 if (empty($ptodate)) {
579 $ptodate = $pfromdate;
580 }
581 //Get dates timestamps
582 $from_ts = VikBooking::getDateTimestamp($pfromdate, 0, 0);
583 $to_ts = VikBooking::getDateTimestamp($ptodate, 23, 59, 59);
584 if (empty($pfromdate) || empty($from_ts) || empty($to_ts)) {
585 $this->setError(JText::translate('VBOREPORTSERRNODATES'));
586 return false;
587 }
588 if (empty($username)) {
589 $this->setError('Inserisci il codice della tua Struttura.<br/>Si tratta di un codice univoco di identificazione che ti viene assegnato dall\'Amministrazione competente.');
590 return false;
591 }
592 if (empty($actiontodo)) {
593 $this->setError('Devi specificare l\'azione da eseguire attraverso il menù a tendina qui sopra.');
594 return false;
595 }
596 if (empty($password)) {
597 $this->setError('Devi specificare la password della tua struttura attraverso il menù a tendina qui sopra.');
598 return false;
599 }
600
601 //Query to obtain the records (all check-ins within the dates filter)
602 $records = array();
603 if($actiontodo == 1){
604 $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`,".
605 "`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`,".
606 "`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` ".
607 "FROM `#__vikbooking_orders` AS `o` LEFT JOIN `#__vikbooking_ordersrooms` AS `or` ON `or`.`idorder`=`o`.`id` ".
608 "LEFT JOIN `#__vikbooking_customers_orders` AS `co` ON `co`.`idorder`=`o`.`id` LEFT JOIN `#__vikbooking_customers` AS `c` ON `c`.`id`=`co`.`idcustomer` ".
609 "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.")) ".
610 "ORDER BY `o`.`checkin` ASC, `o`.`id` ASC, `or`.`id` ASC;";
611 } else {
612 $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`,".
613 "`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`,".
614 "`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` ".
615 "FROM `#__vikbooking_orders` AS `o` LEFT JOIN `#__vikbooking_ordersrooms` AS `or` ON `or`.`idorder`=`o`.`id` ".
616 "LEFT JOIN `#__vikbooking_customers_orders` AS `co` ON `co`.`idorder`=`o`.`id` LEFT JOIN `#__vikbooking_customers` AS `c` ON `c`.`id`=`co`.`idcustomer` ".
617 "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.")) ".
618 "ORDER BY `o`.`checkin` ASC, `o`.`id` ASC, `or`.`id` ASC;";
619 }
620 $this->dbo->setQuery($q);
621 $records = $this->dbo->loadAssocList();
622
623 if (!$records) {
624 $this->setError(JText::translate('VBOREPORTSERRNORESERV'));
625 $this->setError('Nessun check-in nelle date selezionate.');
626 return false;
627 }
628 //nest records with multiple rooms booked inside sub-array
629 $bookings = array();
630 foreach ($records as $v) {
631 if (!isset($bookings[$v['id']])) {
632 $bookings[$v['id']] = array();
633 }
634 array_push($bookings[$v['id']], $v);
635 }
636 //define the columns of the report
637 $this->cols = array(
638 //id booking
639 array(
640 'key' => 'idbooking',
641 'attr' => array(
642 'class="center"'
643 ),
644 'label' => 'ID',
645 'sortable' => 1,
646 ),
647 //check-in
648 array(
649 'key' => 'checkin',
650 'attr' => array(
651 'class="center"'
652 ),
653 'sortable' => 1,
654 'label' => JText::translate('VBPICKUPAT')
655 ),
656 //checkout
657 array(
658 'key' => 'checkout',
659 'attr' => array(
660 'class="center"'
661 ),
662 'sortable' => 1,
663 'label' => 'Partenza'
664 ),
665 //cognome
666 array(
667 'key' => 'cognome',
668 'label' => JText::translate('VBTRAVELERLNAME'),
669 'sortable' => 1,
670 ),
671 //nome
672 array(
673 'key' => 'nome',
674 'label' => JText::translate('VBTRAVELERNAME'),
675 'sortable' => 1,
676 ),
677 //sesso
678 array(
679 'key' => 'gender',
680 'attr' => array(
681 'class="center"'
682 ),
683 'label' => JText::translate('VBCUSTOMERGENDER')
684 ),
685 //data di nascita
686 array(
687 'key' => 'dbirth',
688 'attr' => array(
689 'class="center"'
690 ),
691 'label' => JText::translate('VBCUSTOMERBDATE')
692 ),
693 //cittadinanza
694 array(
695 'key' => 'citizen',
696 'attr' => array(
697 'class="center"'
698 ),
699 'sortable' => 1,
700 'label' => 'Cittadinanza'
701 ),
702 //cittadinanza
703 array(
704 'key' => 'stares',
705 'attr' => array(
706 'class="center"'
707 ),
708 'sortable' => 1,
709 'label' => 'Stato di Residenza'
710 ),
711 //comune di residenza
712 array(
713 'key' => 'comres',
714 'attr' => array(
715 'class="center"'
716 ),
717 'sortable' => 1,
718 'label' => 'Comune Residenza',
719 'tip' => 'Inserire il comune di residenza solo se il cittadino è di nazionalità italiana.'
720 ),
721 //tipo
722 array(
723 'key' => 'tipo',
724 'attr' => array(
725 'class="vbo-report-longlbl"'
726 ),
727 'label' => 'Tipo Alloggiato'
728 ),
729 //quantità (numero di ospiti)
730 array(
731 'key' => 'guestsnum',
732 'attr' => array(
733 'class="center"'
734 ),
735 'sortable' => 1,
736 'label' => 'Numero Ospiti',
737 'tip' => 'Il numero di ospiti totali (adulti + bambini) per ogni prenotazione è un dato che verrà comunicato all\'ISTAT.',
738 ),
739 array(
740 'key' => 'roomsbooked',
741 'attr' => array(
742 'class="center"'
743 ),
744 'sortable' => 1,
745 'label' => 'Occupazione',
746 'tip' => 'Questo valore indica il numero di camere occupate da ogni prenotazione, ed è un dato che verrà comunicato all\'ISTAT.',
747 ),
748
749 // tipo di trasporto
750 array(
751 'key' => 'mezzo',
752 'attr' => array(
753 'class="center"'
754 ),
755 'label' => 'Mezzo di Trasporto'
756 ),
757 // tipo di turismo
758 array(
759 'key' => 'turismo',
760 'attr' => array(
761 'class="center"'
762 ),
763 'label' => 'Tipo di Turismo'
764 ),
765 );
766
767 // loop over the bookings to build the rows of the report
768 $from_info = getdate($from_ts);
769 foreach ($bookings as $gbook) {
770 $guestsnum = 0;
771 $guests_rows = array($gbook[0]);
772 $room_guests = array();
773 $tot_guests_rows = 1;
774
775 $tipo = 16;
776 // Codici Tipo Alloggiato
777 // 16 = Ospite Singolo
778 // 17 = Capofamiglia
779 // 18 = Capogruppo
780 // 19 = Familiare
781 // 20 = Membro Gruppo
782
783 foreach ($gbook as $book) {
784 $guestsnum += $book['adults'] + $book['children'];
785 $room_guests[] = ($book['adults'] + $book['children']);
786 }
787 $pax_data = null;
788 if (!empty($gbook[0]['pax_data'])) {
789 $pax_data = json_decode($gbook[0]['pax_data'], true);
790 if (is_array($pax_data) && count($pax_data)) {
791 $guests_rows[0]['pax_data'] = $pax_data;
792 $tot_guests_rows = 0;
793 foreach ($pax_data as $roomguests) {
794 $tot_guests_rows += count($roomguests);
795 }
796 for ($i = 1; $i < $tot_guests_rows; $i++) {
797 array_push($guests_rows, $guests_rows[0]);
798 }
799 $tipo = count($guests_rows) > 1 ? 17 : $tipo;
800 }
801 }
802
803 //create one row for each guest
804 $guest_ind = 1;
805 foreach ($guests_rows as $ind => $guests) {
806 // prepare row record
807 $insert_row = array();
808
809 // find the actual guest-room-index
810 $guest_room_ind = $this->calcGuestRoomIndex($room_guests, $guest_ind);
811
812 // booking ID
813 array_push($insert_row, array(
814 'key' => 'idbooking',
815 'attr' => array(
816 'class="center"'
817 ),
818 'callback' => function ($val) {
819 return '<a href="index.php?option=com_vikbooking&task=editorder&cid[]='.$val.'" target="_blank"><i class="'.VikBookingIcons::i('external-link').'"></i> '.$val.'</a>';
820 },
821 'callback_export' => function ($val) {
822 return $val;
823 },
824 'value' => $guests['id']
825 ));
826
827 // checkin date
828 array_push($insert_row, array(
829 'key' => 'checkin',
830 'attr' => array(
831 'class="center"'
832 ),
833 'callback' => function ($val) {
834 return date('Y-m-d', $val);
835 },
836 'callback_export' => function ($val) {
837 return date('Y-m-d', $val);
838 },
839 'value' => $guests['checkin']
840 ));
841
842 // checkout date
843 array_push($insert_row, array(
844 'key' => 'checkout',
845 'attr' => array(
846 'class="center"'
847 ),
848 'callback' => function ($val) {
849 return date('Y-m-d', $val);
850 },
851 'callback_export' => function ($val) {
852 return date('Y-m-d', $val);
853 },
854 'value' => $gbook[0]['checkout']
855 ));
856
857 // cognome
858 $cognome = !empty($guests['t_last_name']) ? $guests['t_last_name'] : $guests['last_name'];
859 $pax_cognome = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'last_name');
860 $cognome = !empty($pax_cognome) ? $pax_cognome : $cognome;
861 array_push($insert_row, array(
862 'key' => 'cognome',
863 'value' => $cognome
864 ));
865
866 // nome
867 $nome = !empty($guests['t_first_name']) ? $guests['t_first_name'] : $guests['first_name'];
868 $pax_nome = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'first_name');
869 $nome = !empty($pax_nome) ? $pax_nome : $nome;
870 array_push($insert_row, array(
871 'key' => 'nome',
872 'value' => $nome
873 ));
874
875 // sesso
876 $gender = !empty($guests['gender']) && $guest_ind < 2 ? strtoupper($guests['gender']) : '';
877 $gender = $gender == 'F' ? 2 : ($gender == 'M' ? 1 : $gender);
878 $pax_gender = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'gender');
879 $gender = !empty($pax_gender) ? $pax_gender : $gender;
880 if (is_numeric($gender)) {
881 $gender = (int)$gender;
882 } elseif (!strcasecmp($gender, 'F')) {
883 $gender = 2;
884 } elseif (!strcasecmp($gender, 'M')) {
885 $gender = 1;
886 }
887 array_push($insert_row, array(
888 'key' => 'gender',
889 'attr' => array(
890 'class="center'.(empty($gender) ? ' vbo-report-load-sesso' : '').'"'
891 ),
892 'callback' => function ($val) {
893 return $val == 2 ? 'F' : ($val == 1 ? 'M' : '?');
894 },
895 'callback_export' => function ($val) {
896 return $val == 2 ? 'F' : ($val == 1 ? 'M' : '?');
897 },
898 'value' => $gender
899 ));
900
901 // data di nascita
902 $dbirth = !empty($guests['bdate']) && $guest_ind < 2 ? VikBooking::getDateTimestamp($guests['bdate'], 0, 0) : '';
903 $pax_dbirth = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'date_birth');
904 $dbirth = !empty($pax_dbirth) ? $pax_dbirth : $dbirth;
905 $dbirth = (strpos($dbirth, '/') === false && strpos($dbirth, VikBooking::getDateSeparator()) === false) ? $dbirth : VikBooking::getDateTimestamp($dbirth, 0, 0);
906 array_push($insert_row, array(
907 'key' => 'dbirth',
908 'attr' => array(
909 'class="center'.(empty($dbirth) ? ' vbo-report-load-dbirth' : '').'"'
910 ),
911 'callback' => function ($val) {
912 if (empty($val)) {
913 return '?';
914 }
915 if (strpos($val, '/') === false && strpos($val, VikBooking::getDateSeparator()) === false) {
916 return date('Y-m-d', $val);
917 }
918 if (strpos($val, '/') !== false) {
919 return date('Y-m-d', VikBooking::getDateTimestamp($val, 0, 0));
920 }
921 return $val;
922 },
923 'value' => $dbirth
924 ));
925
926 // cittadinanza (compatible with pax data field of driver "Italy")
927 $pax_country_c = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'country_c');
928 $citizen = !empty($guests['country']) && $guest_ind < 2 ? $guests['country'] : '';
929 $citizenval = '';
930 if (!empty($citizen) && $guest_ind < 2) {
931 $citizenval = $this->checkCountry($citizen);
932 }
933 // check nationality field from pre-checkin
934 $pax_citizen = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'nationality');
935 $citizen = !empty($pax_citizen) ? $pax_citizen : $citizen;
936 $citizen = !empty($pax_country_c) ? $pax_country_c : $citizen;
937 $citizenval = !empty($pax_country_c) ? $pax_country_c : $this->checkCountry($citizen);
938 array_push($insert_row, array(
939 'key' => 'citizen',
940 'attr' => array(
941 'class="center'.(empty($citizen) ? ' vbo-report-load-cittadinanza' : '').'"'
942 ),
943 'callback' => function ($val) {
944 return !empty($val) ? $this->nazioni[$val]['name'] : '?';
945 },
946 'no_export_callback' => 1,
947 'value' => !empty($citizenval) ? $citizenval : ''
948 ));
949
950 // stato di residenza
951 $provstay = '';
952 $pax_provstay = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'country_s');
953 $provstay = !empty($pax_provstay) ? $pax_provstay : $provstay;
954 array_push($insert_row, array(
955 'key' => 'staprov',
956 'attr' => array(
957 'class="center'.(empty($provstay) ? ' vbo-report-load-nazione' : '').'"'
958 ),
959 'callback' => function($val) {
960 if (!empty($val) && isset($this->nazioni[$val])) {
961 return $this->nazioni[$val]['name'];
962 }
963 // information is missing and should be provided
964 return '?';
965 },
966 'no_export_callback' => 1,
967 'value' => $provstay
968 ));
969
970 // comune di residenza
971 $comstay = '';
972 $pax_comstay = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'comune_s');
973 $comstay = !empty($pax_comstay) ? $pax_comstay : $comstay;
974 array_push($insert_row, array(
975 'key' => 'comprov',
976 'attr' => array(
977 'class="center'.(empty($comstay) ? ' vbo-report-load-comune' : '').'"'
978 ),
979 'callback' => function($val) {
980 if (!empty($val) && isset($this->comuniProvince['comuni'][$val])) {
981 return $this->comuniProvince['comuni'][$val]['name'];
982 }
983 // information is missing and should be provided
984 return '?';
985 },
986 'no_export_callback' => 1,
987 'value' => $comstay
988 ));
989
990 // tipo alloggiato
991 $use_tipo = $ind > 0 && $tipo == 17 ? 19 : $tipo;
992 $pax_guest_type = $this->getGuestPaxDataValue($pax_data, $room_guests, $guest_ind, 'guest_type');
993 $use_tipo = !empty($pax_guest_type) ? $pax_guest_type : $use_tipo;
994 array_push($insert_row, array(
995 'key' => 'tipo',
996 'callback' => function ($val) {
997 switch ($val) {
998 case 16:
999 return 'Ospite Singolo';
1000 case 17:
1001 return 'Capofamiglia';
1002 case 18:
1003 return 'Capogruppo';
1004 case 19:
1005 return 'Familiare';
1006 case 20:
1007 return 'Membro Gruppo';
1008 default:
1009 return '?';
1010 }
1011 },
1012 'no_export_callback' => 1,
1013 'value' => $use_tipo
1014 ));
1015
1016 // numero persone in prenotazione
1017 array_push($insert_row, array(
1018 'key' => 'guestsnum',
1019 'attr' => array(
1020 'class="center"'
1021 ),
1022 'value' => $guestsnum
1023 ));
1024
1025 // camere prenotate
1026 array_push($insert_row, array(
1027 'key' => 'roomsbooked',
1028 'attr' => array(
1029 'class="center"'
1030 ),
1031 'value' => count($gbook)
1032 ));
1033
1034 // mezzo di trasporto
1035 array_push($insert_row, array(
1036 'key' => 'mezzo',
1037 'attr' => array(
1038 'class="center vbo-report-load-trasporto"'
1039 ),
1040 'value' => '?'
1041 ));
1042
1043 // tipo di turismo
1044 array_push($insert_row, array(
1045 'key' => 'turismo',
1046 'attr' => array(
1047 'class="center vbo-report-load-turismo"'
1048 ),
1049 'value' => '?'
1050 ));
1051
1052 // push fields in the rows array as a new row
1053 array_push($this->rows, $insert_row);
1054
1055 // increment guest index
1056 $guest_ind++;
1057 }
1058 }
1059
1060 // do not sort the rows for this report because the lines of the guests of the same booking must be consecutive
1061 // $this->sortRows($pkrsort, $pkrorder);
1062
1063 // the footer row will just print the amount of records to export
1064 array_push($this->footerRow, array(
1065 array(
1066 'attr' => array(
1067 'class="vbo-report-total"'
1068 ),
1069 'value' => '<h3>'.JText::translate('VBOREPORTSTOTALROW').'</h3>'
1070 ),
1071 array(
1072 'attr' => array(
1073 'colspan="'.(count($this->cols) - 1).'"'
1074 ),
1075 'value' => count($this->rows)
1076 )
1077 ));
1078
1079 // Debug
1080 if ($this->debug) {
1081 $this->setWarning('path to report file = '.urlencode(dirname(__FILE__)).'<br/>');
1082 $this->setWarning('$total_rooms_units = '.$total_rooms_units.'<br/>');
1083 $this->setWarning('$bookings:<pre>'.print_r($bookings, true).'</pre><br/>');
1084 }
1085
1086 return true;
1087 }
1088
1089 public function formatXML(&$xml)
1090 {
1091 if (!class_exists('DOMDocument')) {
1092 // we cannot format the XML because DOMDocument is missing
1093 return $xml;
1094 }
1095
1096 $dom = new DOMDocument;
1097 $dom->preserveWhiteSpace = false;
1098 $dom->loadXML($xml);
1099 $dom->formatOutput = true;
1100 $xml = $dom->saveXML();
1101
1102 return $xml;
1103 }
1104
1105 /**
1106 * Generates the report columns and rows, then it outputs a CSV file
1107 * for download. In case of errors, the process is not terminated (exit)
1108 * to let the View display the error message.
1109 * We use customExport() rather than exportCSV() only because we need a
1110 * different download button rather than the classic "Export as CSV".
1111 *
1112 * @param string $export_type Differentiates the type of export requested.
1113 *
1114 * @return void|bool Void in case of script termination, boolean otherwise.
1115 */
1116 public function customExport($export_type = 0)
1117 {
1118 if (!$this->getReportData()) {
1119 return false;
1120 }
1121
1122 $pfromdate = VikRequest::getString('fromdate', '', 'request');
1123 $ptodate = VikRequest::getString('todate', '', 'request');
1124 $pcodstru = VikRequest::getString('codstru', '', 'request');
1125 $actiontodo = VikRequest::getString('actiontodo', '', 'request');
1126 $username = VikRequest::getString('riceusername', '', 'request');
1127 $password = VikRequest::getString('ricepassword', '', 'request');
1128 $records = array();
1129
1130 // manual values in filler
1131 $pfiller = VikRequest::getString('filler', '', 'request', VIKREQUEST_ALLOWRAW);
1132 $pfiller = !empty($pfiller) ? json_decode($pfiller, true) : array();
1133 $pfiller = !is_array($pfiller) ? array() : $pfiller;
1134
1135 //Debug
1136 if ($this->debug) {
1137 $this->setError('<pre>'.print_r($pfiller, true).'</pre><br/>');
1138 return false;
1139 }
1140 // pool of booking IDs to update their history
1141 $booking_ids = array();
1142 // update the history for all bookings affected
1143 foreach ($booking_ids as $bid) {
1144 VikBooking::getBookingHistoryInstance()->setBid($bid)->store('RP', $this->reportName);
1145 }
1146 $insertedReservations = $this->initReservations();
1147
1148 $xml = '<?xml version="1.0" encoding="UTF-8"?>
1149 <MTO_SchedineRQ xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://ws.webci.it/webci.xsd" Version="1.0" PrimaryLangID="it">
1150 <POS>
1151 <Source>
1152 <RequestorID Type = "4" ID = "' . $this->providerusername . '" MessagePassword = "' . $this->providerpassword . '"/>
1153 </Source>
1154 <Source>
1155 <RequestorID Type = "10" ID = "' . $username . '" MessagePassword = "' . $password . '"/>
1156 </Source>
1157 </POS>';
1158
1159 if ($actiontodo == '1') {
1160 $xml .= $this->editInsert($insertedReservations, $pfiller);
1161 } else {
1162 $xml .= $this->deleteRes($insertedReservations);
1163 }
1164 $xml .= '</MTO_SchedineRQ>';
1165
1166 // format XML document
1167 $this->formatXML($xml);
1168
1169 /**
1170 * Custom export method supports a custom export handler, if previously set.
1171 *
1172 * @since 1.16.1 (J) - 1.6.1 (WP)
1173 */
1174 if ($this->hasExportHandler()) {
1175 // write data onto the custom file handler
1176 $fp = $this->getExportCSVHandler();
1177 fwrite($fp, $xml);
1178 fclose($fp);
1179
1180 return true;
1181 }
1182
1183 header('Content-Disposition: attachment; filename=' . $this->getExportCSVFileName());
1184 header('Content-type: text/xml');
1185 echo $xml;
1186
1187 exit;
1188 }
1189
1190 /**
1191 * Registers the name to give to the file being exported.
1192 *
1193 * @return void
1194 *
1195 * @since 1.16.1 (J) - 1.6.1 (WP)
1196 */
1197 private function registerExportFileName()
1198 {
1199 $pfromdate = VikRequest::getString('fromdate', '', 'request');
1200 $ptodate = VikRequest::getString('todate', '', 'request');
1201
1202 $this->setExportCSVFileName(str_replace(' ', '_', $this->reportName) . '-' . str_replace('/', '_', $pfromdate) . '.xml');
1203 }
1204
1205 private function editInsert($toEdit, $pfiller)
1206 {
1207 $xml = '';
1208 $insertedids = array();
1209 $insertedids = $toEdit;
1210
1211 foreach ($this->rows as $ind => $row) {
1212 $idswh = -1;
1213 foreach ($row as $field) {
1214 if (isset($field['ignore_export'])) {
1215 continue;
1216 }
1217 // check if a value for this field was filled in manually
1218 if (is_array($pfiller) && isset($pfiller[$ind]) && isset($pfiller[$ind][$field['key']])) {
1219 if (strlen($pfiller[$ind][$field['key']])) {
1220 $field['value'] = $pfiller[$ind][$field['key']];
1221 }
1222 }
1223 // values set to -1 are usually empty and should have been filled in manually
1224 if ($field['value'] === -1) {
1225 // we raise an error in this case without stopping the process
1226 $field['value'] = 0;
1227 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.');
1228 }
1229 if (isset($field['callback_export'])) {
1230 $field['callback'] = $field['callback_export'];
1231 }
1232 $export_value = !isset($field['no_export_callback']) && isset($field['callback']) && is_callable($field['callback']) ? $field['callback']($field['value']) : $field['value'];
1233
1234 if ($field['key'] == 'idbooking') {
1235 $idswh = $export_value;
1236 //retrieve customer ID
1237 $q = "SELECT `idcustomer` FROM `#__vikbooking_customers_orders` WHERE `idorder` = " . $idswh . ";";
1238 $this->dbo->setQuery($q);
1239 $this->dbo->execute();
1240 if ($this->dbo->getNumRows() > 0) {
1241 $clienti[$idswh]['idcustomer'] = $this->dbo->loadResult();
1242 }
1243 }
1244 if ($field['key'] == 'checkin') {
1245 $clienti[$idswh]['checkin'] = $export_value;
1246 }
1247 if ($field['key'] == 'guestsnum') {
1248 $clienti[$idswh]['guestsnum'] = $export_value;
1249 }
1250 if ($field['key'] == 'checkout') {
1251 $clienti[$idswh]['checkout'] = $export_value;
1252 }
1253 $clienti[$idswh]['idswh'] = $idswh;
1254 if ($field['key'] == 'tipo') {
1255 $clienti[$idswh]['tipoalloggiato'] = (string)$export_value;
1256 }
1257 if ($field['key'] == 'gender') {
1258 $clienti[$idswh]['sesso'] = $export_value;
1259 }
1260 if ($field['key'] == 'turismo') {
1261 $clienti[$idswh]['tipoturismo'] = $export_value;
1262 }
1263 if ($field['key'] == 'mezzo') {
1264 $clienti[$idswh]['mezzotrasporto'] = $export_value;
1265 }
1266 if ($field['key'] == 'citizen') {
1267 $clienti[$idswh]['cittadinanza'] = (string)$export_value;
1268 }
1269 if ($field['key'] == 'stares') {
1270 $clienti[$idswh]['statoresidenza'] = (string)$export_value;
1271 }
1272 if ($field['key'] == 'dbirth') {
1273 $date = str_replace('/', '-', $export_value);
1274 //$datanascita = date('Ymd', strtotime($date));
1275 $clienti[$idswh]['datanascita'] = (string)$date;
1276 }
1277 if (isset($clienti[$idswh]['cittadinanza']) && $clienti[$idswh]['cittadinanza'] == '100000100' && $field['key'] == 'comres') {
1278 $clienti[$idswh]['luogoresidenza'] = (string)$export_value;
1279 }
1280 if (isset($clienti[$idswh]['tipoalloggiato']) && ($clienti[$idswh]['tipoalloggiato'] == '19' || $clienti[$idswh]['tipoalloggiato'] == '20') && $field['key'] == 'tipo') {
1281 $clienti[$idswh]['idcapo'] = (string)$idswh;
1282 }
1283 }
1284 }
1285 if (in_array($clienti['idswh'], $toEdit)) {
1286 $xml .= '<Aggiornamento>';
1287 } else {
1288 $xml .= '<InserimentoAlloggiati>';
1289 }
1290
1291 foreach ($clienti as $cliente) {
1292 if ($cliente['guestsnum'] > 1) {
1293 $rooms = VikBooking::loadOrdersRoomsData($cliente['idswh']);
1294 foreach ($rooms as $room) {
1295 $totalaval = $room['adults'] + $room['children'];
1296 $xml .= '<Gruppo id="' . $cliente['idswh'] . '" >';
1297 for ($i = 0; $i < $totalaval; $i++) {
1298 $provenienza = '';
1299 if ($cliente['cittadinanza'] == '100000100') {
1300 $provincia = substr($cliente['luogoresidenza'], 0, 6);
1301 $provenienza = '<Italia CodiceComune="' . $cliente['luogoresidenza'] . '" Provincia="' . $provincia . '" Stato="' . $cliente['cittadinanza'] . '" />';
1302 } else {
1303 $provenienza = '<Estero Stato="' . $cliente['cittadinanza'] . '" />';
1304 }
1305 $tipoalloggiato = $i == 0 ? '17' : '19';
1306 $xml .= '<Ospite id="' . $cliente['idcustomer'] . '_' . $room['idroom'] . '_' . $i . '" IdCamera="' . $room['idroom'] . '" TipoAlloggiato="' . $tipoalloggiato . '" >' .
1307 '<DataDiArrivo>' . $cliente['checkin'] . '</DataDiArrivo>' .
1308 '<DataDiPartenza>' . $cliente['checkout'] . '</DataDiPartenza>' .
1309 '<DataDiNascita>' . $cliente['datanascita'] . '</DataDiNascita>' .
1310 '<Sesso>' . $cliente['sesso'] . '</Sesso>' .
1311 '<Provenienza>' . $provenienza . '</Provenienza>' .
1312 '<Cittadinanza>' . $cliente['cittadinanza'] . '</Cittadinanza>' .
1313 '</Ospite>';
1314 }
1315 $xml .= '</Gruppo>';
1316 }
1317 } else {
1318 $provenienza = '';
1319 if ($cliente['cittadinanza'] == '100000100') {
1320 $provincia = substr($cliente['luogoresidenza'], 0, 6);
1321 $provenienza = '<Italia CodiceComune="' . $cliente['luogoresidenza'] . '" Provincia="' . $provincia . '" Stato="' . $cliente['cittadinanza'] . '" />';
1322 } else {
1323 $provenienza = '<Estero Stato="' . $cliente['cittadinanza'] . '" />';
1324 }
1325 $rooms = VikBooking::loadOrdersRoomsData($cliente['idswh']);
1326 $xml .= '<OspiteSingolo id="' . $cliente['idswh'] . '" >' .
1327 '<Ospite id="' . $cliente['idcustomer'] . '" IdCamera="' . $rooms['0']['idroom'] . '" TipoAlloggiato="' . $cliente['tipoalloggiato'] . '" >' .
1328 '<DataDiArrivo>' . $cliente['checkin'] . '</DataDiArrivo>' .
1329 '<DataDiPartenza>' . $cliente['checkout'] . '</DataDiPartenza>' .
1330 '<DataDiNascita>' . $cliente['datanascita'] . '</DataDiNascita>' .
1331 '<Sesso>' . $cliente['sesso'] . '</Sesso>' .
1332 '<Provenienza>' . $provenienza . '</Provenienza>' .
1333 '<Cittadinanza>' . $cliente['cittadinanza'] . '</Cittadinanza>' .
1334 '</Ospite>' .
1335 '</OspiteSingolo>';
1336 }
1337 }
1338
1339 if (in_array($cliente['idswh'], $toEdit)) {
1340 $xml .= '</Aggiornamento>';
1341 } else {
1342 array_push($insertedids, $cliente['idswh']);
1343 $xml .= '</InserimentoAlloggiati>';
1344 }
1345
1346 $this->updateReservations($insertedids);
1347
1348 return $xml;
1349 }
1350
1351 private function deleteRes($toEdit) {
1352 $xml = '<Eliminazione >';
1353 foreach ($this->rows as $ind => $row) {
1354 foreach ($row as $field) {
1355 if ($field['key'] == 'idbooking') {
1356 $idswh = $export_value;
1357 for ($i = 0; $i < count($toEdit); $i++) {
1358 if ($toEdit[$i] == $idswh) {
1359 unset($toEdit[$i]);
1360 $xml .= '<Alloggiato id="' . $idswh .'" />';
1361 }
1362 }
1363 }
1364 }
1365 }
1366 $xml .= '</Eliminazione >';
1367
1368 return $xml;
1369 }
1370
1371 /**
1372 * Parses the file Comuni.csv and returns two associative
1373 * arrays: one for the Comuni and one for the Province.
1374 * Every line of the CSV is composed of: Codice, Comune, Provincia.
1375 *
1376 * @return array
1377 */
1378 private function loadComuniProvince()
1379 {
1380 $vals = array(
1381 'comuni' => array(
1382 0 => '-- Estero --'
1383 ),
1384 'province' => array(
1385 0 => '-- Estero --'
1386 )
1387 );
1388
1389 $csv = dirname(__FILE__).DIRECTORY_SEPARATOR.'Comuni.csv';
1390 $rows = file($csv);
1391 foreach ($rows as $row) {
1392 if (empty($row)) {
1393 continue;
1394 }
1395 $v = explode(';', $row);
1396 if (count($v) != 3) {
1397 continue;
1398 }
1399 $vals['comuni'][$v[0]]['name'] = $v[1];
1400 $vals['comuni'][$v[0]]['province'] = $v[2];
1401 $vals['province'][$v[2]] = $v[2];
1402 }
1403
1404 return $vals;
1405 }
1406
1407 /**
1408 * Parses the file Nazioni.csv and returns an associative
1409 * array with the code and name of the Nazione.
1410 * Every line of the CSV is composed of: Codice, Nazione.
1411 *
1412 * @return array
1413 */
1414 protected function loadNazioni()
1415 {
1416 $nazioni = [];
1417
1418 $csv = dirname(__FILE__).DIRECTORY_SEPARATOR.'Nazioni.csv';
1419 $rows = file($csv);
1420 foreach ($rows as $row) {
1421 if (empty($row)) {
1422 continue;
1423 }
1424 $v = explode(';', $row);
1425 if (count($v) != 3) {
1426 continue;
1427 }
1428
1429 // trim values
1430 $v[0] = trim($v[0]);
1431 $v[1] = trim($v[1]);
1432 $v[2] = trim($v[2]);
1433
1434 $nazioni[$v[0]]['name'] = $v[1];
1435 $nazioni[$v[0]]['three_code'] = $v[2];
1436
1437 }
1438
1439 return $nazioni;
1440 }
1441
1442 /**
1443 * Returns the key of the state selected by the user, if any.
1444 *
1445 * @param string $country The selected country code.
1446 *
1447 * @return string
1448 */
1449 protected function checkCountry($country)
1450 {
1451 $found = false;
1452 $staval = '';
1453
1454 if (!$this->nazioni) {
1455 $this->nazioni = $this->loadNazioni();
1456 }
1457
1458 if ($country && isset($this->nazioni[$country])) {
1459 return $country;
1460 }
1461
1462 foreach ($this->nazioni as $key => $value) {
1463 if (trim($value['three_code']) == trim($country)) {
1464 $staval = $key;
1465 $found = true;
1466 break;
1467 }
1468 }
1469
1470 if ($found !== true) {
1471 $staval = '';
1472 }
1473
1474 return $staval;
1475 }
1476
1477 private function initReservations()
1478 {
1479 $init_res = VBOFactory::getConfig()->get('ricestat_insertedres');
1480 if (empty($init_res)) {
1481 return [];
1482 }
1483
1484 return (array)json_decode($init_res, true);
1485 }
1486
1487 private function initConfiguration()
1488 {
1489 $init_res = VBOFactory::getConfig()->get('ricestat_loginvalsricestat');
1490 if (empty($init_res)) {
1491 return [];
1492 }
1493
1494 return (array)json_decode($init_res, true);
1495 }
1496
1497 private function updateLogin($updatevals)
1498 {
1499 $vals = json_encode($updatevals);
1500
1501 VBOFactory::getConfig()->set('ricestat_loginvalsricestat', $vals);
1502 }
1503
1504 private function updateReservations($updatevals)
1505 {
1506 $vals = json_encode($updatevals);
1507
1508 VBOFactory::getConfig()->set('ricestat_insertedres', $vals);
1509 }
1510
1511 /**
1512 * Helper method to quickly get a pax_data property for the guest.
1513 *
1514 * @param array $pax_data the current pax_data stored.
1515 * @param array $guests list of total guests per room.
1516 * @param int $guest_ind the guest index.
1517 * @param string $key the pax_data key to look for.
1518 *
1519 * @return mixed null on failure or value fetched.
1520 */
1521 private function getGuestPaxDataValue($pax_data, $guests, $guest_ind, $key)
1522 {
1523 if (!is_array($pax_data) || !count($pax_data) || empty($key)) {
1524 return null;
1525 }
1526
1527 // find room index for this guest number
1528 $room_num = 0;
1529 $use_guest_ind = $guest_ind;
1530 foreach ($guests as $room_index => $room_tot_guests) {
1531 // find the proper guest index for the room to which this belongs
1532 if ($use_guest_ind <= $room_tot_guests) {
1533 // proper room index found for this guest
1534 $room_num = $room_index;
1535 break;
1536 } else {
1537 // it's probably in a next room
1538 $use_guest_ind -= $room_tot_guests;
1539 }
1540 }
1541
1542 // check if a value exists for the requested key in the found room and guest indexes
1543 if (isset($pax_data[$room_num]) && isset($pax_data[$room_num][$use_guest_ind])) {
1544 if (isset($pax_data[$room_num][$use_guest_ind][$key])) {
1545 // we've got a value previously stored
1546 return $pax_data[$room_num][$use_guest_ind][$key];
1547 }
1548 }
1549
1550 // nothing was found
1551 return null;
1552 }
1553
1554 /**
1555 * Helper method to determine the exact number for this guest in the room booked.
1556 *
1557 * @param array $guests list of total guests per room.
1558 * @param int $guest_ind the guest index.
1559 *
1560 * @return int the actual guest room index starting from 1.
1561 */
1562 private function calcGuestRoomIndex($guests, $guest_ind)
1563 {
1564 // find room index for this guest number
1565 $room_num = 0;
1566 $use_guest_ind = $guest_ind;
1567 foreach ($guests as $room_index => $room_tot_guests) {
1568 // find the proper guest index for the room to which this belongs
1569 if ($use_guest_ind <= $room_tot_guests) {
1570 // proper room index found for this guest
1571 $room_num = $room_index;
1572 break;
1573 } else {
1574 // it's probably in a next room
1575 $use_guest_ind -= $room_tot_guests;
1576 }
1577 }
1578
1579 return $use_guest_ind;
1580 }
1581 }
1582