Completed
Push — master ( 8acc04...458fbe )
by Laurent
02:26
created

flightLog.lib.php ➔ select_balloons()   B

Complexity

Conditions 11
Paths 12

Size

Total Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 12
nop 4
dl 0
loc 47
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @deprecated use the BillableFlightQueryHandler for that.
4
 *
5
 * @param DoliDb $db
6
 * @param string $sql
7
 * @param bool   $total
8
 * @param string $year
9
 *
10
 * @return array
11
 */
12
function sqlToArray(DoliDb $db, $sql, $total = true, $year = '')
13
{
14
    $resql = $db->query($sql);
15
    $array = array();
16
    if ($resql) {
17
        $num = $db->num_rows($resql);
18
        $i = 0;
19
        if ($num) {
20
            while ($i < $num) {
21
                $obj = $db->fetch_object($resql); //vol
22
                if ($obj) {
23
                    $array[$obj->pilot][$obj->type]['time'] = $obj->time;
24
                    $array[$obj->pilot][$obj->type]['count'] = $obj->nbr;
25
                    $array[$obj->pilot]['name'] = $obj->prenom . ' ' . $obj->nom;
26
                    $array[$obj->pilot]['id'] = $obj->pilot;
27
                }
28
                $i++;
29
            }
30
        }
31
    }
32
33
    //total orga
34
    $sql = 'SELECT llx_user.lastname as name , llx_user.firstname,llx_user.rowid, count(idBBC_vols) as total FROM llx_bbc_vols LEFT JOIN llx_user ON rowid = fk_organisateur WHERE YEAR(date) = \'' . $year . '\' AND fk_type IN (1,2) GROUP BY fk_organisateur';
35
    $resql = $db->query($sql);
36 View Code Duplication
    if ($resql && $total) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
37
        $num = $db->num_rows($resql);
38
        $i = 0;
39
        if ($num) {
40
            while ($i < $num) {
41
                $obj = $db->fetch_object($resql); //vol
42
43
                if ($obj) {
44
                    $array[$obj->rowid]['name'] = $obj->firstname . ' ' . $obj->name;
45
                    $array[$obj->rowid]['orga']['count'] = $obj->total;
46
                }
47
                $i++;
48
            }
49
        }
50
    }
51
52
    //total orga T6 - instructeur
53
    $sql = 'SELECT llx_user.lastname as name , llx_user.firstname,llx_user.rowid, count(idBBC_vols) as total FROM llx_bbc_vols LEFT JOIN llx_user ON rowid = fk_organisateur WHERE YEAR(date) = \'' . $year . '\' AND fk_type = 6 GROUP BY fk_organisateur';
54
    $resql = $db->query($sql);
55 View Code Duplication
    if ($resql && $total) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
        $num = $db->num_rows($resql);
57
        $i = 0;
58
        if ($num) {
59
            while ($i < $num) {
60
                $obj = $db->fetch_object($resql); //vol
61
62
                if ($obj) {
63
                    $array[$obj->rowid]['name'] = $obj->firstname . ' ' . $obj->name;
64
                    $array[$obj->rowid]['orga_T6']['count'] = $obj->total;
65
                }
66
                $i++;
67
            }
68
        }
69
    }
70
71
    return $array;
72
}
73
74
/**
75
 * @param int $active
76
 *
77
 * @return BbctypesLine[]
78
 */
79
function fetchBbcFlightTypes($active = 1)
80
{
81
    global $db;
82
83
    $bbcTypes = new Bbctypes($db);
84
85
    $bbcTypes->fetchAll('', '', 0, 0, [
86
        "active" => $active
87
    ]);
88
89
    return $bbcTypes->lines;
90
}
91
92
/**
93
 * Return list of flight type
94
 *
95
 * @param   mixed $selected  Preselected type
96
 * @param   mixed $htmlname  Name of field in form
97
 * @param   mixed $showempty Add an empty field
98
 */
99
function select_flight_type($selected = '1', $htmlname = 'type', $showempty = false)
100
{
101
102
    global $langs;
103
    $langs->load("trips");
104
105
    $types = fetchBbcFlightTypes();
106
107
    print '<select class="flat" name="' . $htmlname . '">';
108
109
    if ($showempty) {
110
        print sprintf('<option selected="%s" value=""></option>', (($selected == "" || $selected == 0 || $selected == -1) ? "selected" : ""));
111
    }
112
113
    foreach ($types as $flightType) {
114
        print '<option value="' . $flightType->id . '"';
115
        if ($flightType->numero == $selected) {
116
            print ' selected="selected"';
117
        }
118
        print '>';
119
        echo "T" . $flightType->numero . '-' . $flightType->nom;
120
        print "</option>";
121
    }
122
123
    print '</select>';
124
}
125
126
/**
127
 * @param string $selected
128
 * @param string $htmlname
129
 * @param int    $showimmat
130
 * @param int    $showDeclasse
131
 */
132
function select_balloons($selected = '', $htmlname = 'ballon', $showimmat = 0, $showDeclasse = 1)
133
{
134
135
    global $db, $langs;
136
137
    $langs->load("trips");
138
    print '<!-- select_balloons in form class -->';
139
    print '<select class="flat" name="' . $htmlname . '">';
140
141
    print '<option value=""';
142
    if ($selected == -1 || $selected == '' || $selected == 0) {
143
        print ' selected="selected"';
144
    }
145
    print '>&nbsp;</option>';
146
147
    if (!$showDeclasse) {
148
        $resql = $db->query("SELECT B.immat,B.rowid FROM llx_bbc_ballons as B WHERE is_disable = false ");
149
    } else {
150
        $resql = $db->query("SELECT B.immat,B.rowid FROM llx_bbc_ballons as B");
151
    }
152
153
    if ($resql) {
154
        $num = $db->num_rows($resql);
155
        $i = 0;
156
        if ($num) {
157
            while ($i < $num) {
158
                $obj = $db->fetch_object($resql);
159
                if ($obj) {
160
                    if ($showimmat) {
161
                        print '<option value="' . $obj->immat . '"';
162
                    } else {
163
                        print '<option value="' . $obj->rowid . '"';
164
                    }
165
                    if ($obj->rowid == $selected) {
166
                        print ' selected="selected"';
167
                    }
168
                    print '>';
169
                    echo strtoupper($obj->immat);
170
                    print "</option>";
171
                }
172
                $i++;
173
            }
174
        }
175
    }
176
177
    print '</select>';
178
}
179
180
/**
181
 * @param null $year
182
 * @param null $pilotId
183
 * @param null $quarter
184
 * @param bool $groupBy
185
 *
186
 * @return string
187
 */
188
function generateQuarterQuery($year = null, $pilotId = null, $quarter = null, $groupBy = true)
189
{
190
191
    global $db;
192
193
    $sql = "SELECT USR.rowid, USR.lastname, USR.firstname, QUARTER(VOL.date) as quartil ";
194
195
    if ($groupBy) {
196
        $sql .= " , SUM(VOL.kilometers) as SUM";
197
        $sql .= " , COUNT(VOL.idBBC_vols) as nbrFlight";
198
    } else {
199
        $sql .= " , VOL.*";
200
    }
201
202
    $sql .= " FROM llx_bbc_vols as VOL";
203
    $sql .= " LEFT OUTER JOIN llx_user AS USR ON VOL.fk_pilot = USR.rowid";
204
    $sql .= " WHERE ";
205
    $sql .= " 1 = 1 ";
206
    $sql .= " AND YEAR(VOL.date) = " . ($year ?: 'YEAR(NOW())');
207
    $sql .= " AND ( VOL.fk_type = 1 OR VOL.fk_type = 2 ) ";
208
209
    if ($pilotId !== null) {
210
        $sql .= " AND USR.rowid = " . $pilotId;
211
    }
212
213
    if ($quarter !== null) {
214
        $sql .= " AND QUARTER(VOL.date) = " . $quarter;
215
    }
216
217
    if ($groupBy) {
218
        $sql .= " GROUP BY QUARTER(VOL.date), VOL.fk_pilot";
219
    }
220
    $sql .= " ORDER BY QUARTER(VOL.date), VOL.fk_pilot";
221
222
    return $db->escape($sql);
223
}
224
225
/**
226
 * @param int $pilotId
227
 * @param int $year
228
 * @param int $quarter
229
 *
230
 * @return array
231
 */
232
function findFlightByPilotAndQuarter($pilotId, $year, $quarter)
233
{
234
    global $db;
235
236
    $sql = generateQuarterQuery($year, $pilotId, $quarter, false);
237
    $flights = [];
238
    $resql = $db->query($sql);
239
    if ($resql) {
240
        $num = $db->num_rows($resql);
241
        $i = 0;
242
        if ($num) {
243
            while ($i < $num) {
244
                $flight = $db->fetch_object($resql);
245
                if ($flight) {
246
                    $flights[] = $flight;
247
                }
248
                $i++;
249
            }
250
        }
251
    }
252
253
254
    return $flights;
255
}
256
257
/**
258
 * @param int $year
259
 *
260
 * @return array
261
 */
262
function bbcKilometersByQuartil($year)
263
{
264
    global $db;
265
266
    $sql = generateQuarterQuery($year);
267
    $resql = $db->query($sql);
268
269
    $kmByQuartil = array();
270
    if ($resql) {
271
        $num = $db->num_rows($resql);
272
        $i = 0;
273
        if ($num) {
274
            while ($i < $num) {
275
                $obj = $db->fetch_object($resql); //vol
276
                if ($obj) {
277
278
                    $rowId = $obj->rowid;
279
                    $name = $obj->lastname;
280
                    $firstname = $obj->firstname;
281
                    $sum = $obj->SUM;
282
                    $quartil = $obj->quartil;
283
284
                    $kmByQuartil[$rowId]["name"] = $name;
285
                    $kmByQuartil[$rowId]["name"] = $name;
286
                    $kmByQuartil[$rowId]["name"] = $name;
287
                    $kmByQuartil[$rowId]["firstname"] = $firstname;
288
289
                    $kmByQuartil[$rowId]["quartil"][$quartil]["km"] = $sum;
290
                    $kmByQuartil[$rowId]["quartil"][$quartil]["flight"] = $obj->nbrFlight;
291
292
293
                }
294
                $i++;
295
            }
296
        }
297
    }
298
299
    return $kmByQuartil;
300
}
301
302
/**
303
 * @param $kmByQuartil
304
 * @param $tauxRemb
305
 */
306
function printBbcKilometersByQuartil($kmByQuartil, $tauxRemb, $unitPriceMission)
307
{
308
    print '<table class="border" width="100%">';
309
310
    print '<tr>';
311
    print '<td></td>';
312
    print '<td></td>';
313
314
    print '<td class="liste_titre" colspan="5">Trimestre 1 (Jan - Mars)</td>';
315
    print '<td class="liste_titre" colspan="5">Trimestre 2 (Avr - Juin)</td>';
316
    print '<td class="liste_titre" colspan="5">Trimestre 3 (Juil - Sept)</td>';
317
    print '<td class="liste_titre" colspan="5">Trimestre 4 (Oct - Dec)</td>';
318
    print '<td class="liste_titre" >Total</td>';
319
320
    print '</tr>';
321
322
    print '<tr class="liste_titre">';
323
    print '<td class="liste_titre" > Nom </td>';
324
    print '<td class="liste_titre" > Prenom </td>';
325
326
327
    print '<td class="liste_titre" > # T1 & T2</td>';
328
    print '<td class="liste_titre" > Forfaits pil </td>';
329
    print '<td class="liste_titre" > Total des KM </td>';
330
    print '<td class="liste_titre" > Remb km €</td>';
331
    print '<td class="liste_titre" > Total € </td>';
332
333
    print '<td class="liste_titre" > # T1 & T2</td>';
334
    print '<td class="liste_titre" > Forfaits pil </td>';
335
    print '<td class="liste_titre" > Total des KM </td>';
336
    print '<td class="liste_titre" > Remb km €</td>';
337
    print '<td class="liste_titre" > Total € </td>';
338
339
    print '<td class="liste_titre" > # T1 & T2</td>';
340
    print '<td class="liste_titre" > Forfaits pil </td>';
341
    print '<td class="liste_titre" > Total des KM </td>';
342
    print '<td class="liste_titre" > Remb km €</td>';
343
    print '<td class="liste_titre" > Total € </td>';
344
345
    print '<td class="liste_titre" > # T1 & T2</td>';
346
    print '<td class="liste_titre" > Forfaits pil </td>';
347
    print '<td class="liste_titre" > Total des KM </td>';
348
    print '<td class="liste_titre" > Remb km €</td>';
349
    print '<td class="liste_titre" > Total € </td>';
350
351
    print '<td class="liste_titre" > Total € </td>';
352
    print '</tr>';
353
354
    $totalQ1 = 0;
355
    $totalQ2 = 0;
356
    $totalQ3 = 0;
357
    $totalQ4 = 0;
358
359
    $curMonth = date("m", time());
360
    $curQuarter = ceil($curMonth/3);
361
    $disableColor = 'style="background-color: lightyellow;" title="N/A" data-toggle="tooltip"';
362
363
    foreach ($kmByQuartil as $id => $rembKm) {
364
        $name = $rembKm["name"];
365
        $firstname = $rembKm["firstname"];
366
        $sumQ1 = isset($rembKm["quartil"]["1"]["km"]) ? $rembKm["quartil"]["1"]["km"] : 0;
367
        $sumQ2 = isset($rembKm["quartil"]["2"]["km"]) ? $rembKm["quartil"]["2"]["km"] : 0;
368
        $sumQ3 = isset($rembKm["quartil"]["3"]["km"]) ? $rembKm["quartil"]["3"]["km"] : 0;
369
        $sumQ4 = isset($rembKm["quartil"]["4"]["km"]) ? $rembKm["quartil"]["4"]["km"] : 0;
370
371
        $flightsQ1 = isset($rembKm["quartil"]["1"]["flight"]) ? $rembKm["quartil"]["1"]["flight"] : 0;
372
        $flightsQ2 = isset($rembKm["quartil"]["2"]["flight"]) ? $rembKm["quartil"]["2"]["flight"] : 0;
373
        $flightsQ3 = isset($rembKm["quartil"]["3"]["flight"]) ? $rembKm["quartil"]["3"]["flight"] : 0;
374
        $flightsQ4 = isset($rembKm["quartil"]["4"]["flight"]) ? $rembKm["quartil"]["4"]["flight"] : 0;
375
376
        $amoutQ1 = ($sumQ1 * $tauxRemb) + ($flightsQ1 * $unitPriceMission);
377
        $amoutQ2 = ($sumQ2 * $tauxRemb) + ($flightsQ2 * $unitPriceMission);
378
        $amoutQ3 = ($sumQ3 * $tauxRemb) + ($flightsQ3 * $unitPriceMission);
379
        $amoutQ4 = ($sumQ4 * $tauxRemb) + ($flightsQ4 * $unitPriceMission);
380
381
        $totalQ1 += $amoutQ1;
382
        $totalQ2 += $amoutQ2;
383
        $totalQ3 += $amoutQ3;
384
        $totalQ4 += $amoutQ4;
385
386
        $sumKm = ($sumQ1 + $sumQ2 + $sumQ3 + $sumQ4);
387
        $sumFlights = ($flightsQ1 + $flightsQ2 + $flightsQ3 + $flightsQ4);
388
389
        print '<tr>';
390
391
        print '<td>' . $name . '</td>';
392
        print '<td>' . $firstname . '</td>';
393
394
        print '<td'.($curQuarter < 1 ? $disableColor: '').'>' . ($flightsQ1) . '</td>';
395
        print '<td'.($curQuarter < 1 ? $disableColor: '').'>' . ($flightsQ1 * $unitPriceMission) . '€</td>';
396
        print '<td'.($curQuarter < 1 ? $disableColor: '').'>' . $sumQ1 . '</td>';
397
        print '<td'.($curQuarter < 1 ? $disableColor: '').'>' . ($sumQ1 * $tauxRemb) . '</td>';
398
        print '<td'.($curQuarter < 1 ? $disableColor: '').'><b>' . $amoutQ1 . '€</b></td>';
399
400
        print '<td '.($curQuarter < 2 ? $disableColor: '').'>' . ($flightsQ2) . '</td>';
401
        print '<td '.($curQuarter < 2 ? $disableColor: '').'>' . ($flightsQ2 * $unitPriceMission) . '€</td>';
402
        print '<td '.($curQuarter < 2 ? $disableColor: '').'>' . $sumQ2 . '</td>';
403
        print '<td '.($curQuarter < 2 ? $disableColor: '').'>' . ($sumQ2 * $tauxRemb) . '</td>';
404
        print '<td '.($curQuarter < 2 ? $disableColor: '').'><b>' . $amoutQ2 . '€</b></td>';
405
406
        print '<td '.($curQuarter < 3 ? $disableColor: '').'>' . ($flightsQ3) . '</td>';
407
        print '<td '.($curQuarter < 3 ? $disableColor: '').'>' . ($flightsQ3 * $unitPriceMission) . '€</td>';
408
        print '<td '.($curQuarter < 3 ? $disableColor: '').'>' . $sumQ3 . '</td>';
409
        print '<td '.($curQuarter < 3 ? $disableColor: '').'>' . ($sumQ3 * $tauxRemb) . '</td>';
410
        print '<td '.($curQuarter < 3 ? $disableColor: '').'><b>' . $amoutQ3 . '€</b></td>';
411
412
        print '<td '.($curQuarter < 4 ? $disableColor: '').'>' . ($flightsQ4) . '</td>';
413
        print '<td '.($curQuarter < 4 ? $disableColor: '').'>' . ($flightsQ4 * $unitPriceMission) . '€</td>';
414
        print '<td '.($curQuarter < 4 ? $disableColor: '').'>' . $sumQ4 . '</td>';
415
        print '<td '.($curQuarter < 4 ? $disableColor: '').'>' . ($sumQ4 * $tauxRemb) . '</td>';
416
        print '<td '.($curQuarter < 4 ? $disableColor: '').'><b>' . $amoutQ4 . '€</b></td>';
417
418
        print '<td>' . (($sumFlights * $unitPriceMission) + ($sumKm * $tauxRemb)) . '€</td>';
419
420
        print '</tr>';
421
    }
422
423
    print "<td colspan='6'></td>";
424
    print "<td>".price($totalQ1)."€</td>";
425
    print "<td colspan='4'></td>";
426
    print "<td>".price($totalQ2)."€</td>";
427
    print "<td colspan='4'></td>";
428
    print "<td>".price($totalQ3)."€</td>";
429
    print "<td colspan='4'></td>";
430
    print "<td>".price($totalQ4)."€</td>";
431
    print "<td></td>";
432
433
    print '</table>';
434
}
435
436
/**
437
 * @return int[]
438
 */
439
function getFlightYears()
440
{
441
    global $db;
442
443
    $results = [];
444
445
    $sqlYear = "SELECT DISTINCT(YEAR(llx_bbc_vols.date)) as annee FROM llx_bbc_vols ";
446
    $resql_years = $db->query($sqlYear);
447
448
    $num = $db->num_rows($resql_years);
449
    $i = 0;
450
    if ($num) {
451
        while ($i < $num) {
452
            $obj = $db->fetch_object($resql_years);
453
454
            if ($obj->annee) {
455
                $results[] = $obj->annee;
456
            }
457
458
            $i++;
459
        }
460
    }
461
462
    return $results;
463
}
464
465
/**
466
 * @param array $results
467
 * @param int   $year
468
 * @param int   $type
469
 * @param int   $val
470
 *
471
 * @return array
472
 * @throws Exception
473
 */
474
function addValueForYear($results, $year, $type, $val)
475
{
476
    if (!is_array($results)) {
477
        return $results;
478
    }
479
480
    $countResults = count($results);
481
482
    for ($i = 0; $i < $countResults; $i++) {
483
        $resultLine = $results[$i];
484
        if (!is_array($resultLine)) {
485
            throw new \Exception("not an array ");
486
        }
487
488
        if (in_array($year, $resultLine)) {
489
            $results[$i][$type] = $val;
490
            return $results;
491
        }
492
    }
493
494
    //not found add a new entry
495
    $results[] = [
496
        $year,
497
        $type => $val
498
    ];
499
500
    return $results;
501
502
}
503
504
/**
505
 * @param GraphicalData $graphData
506
 *
507
 * @return GraphicalData
508
 */
509
function fetchGraphByTypeAndYearData(GraphicalData $graphData)
510
{
511
    global $db;
512
513
    $sql = "SELECT YEAR(date) as year, fk_type as type,COUNT(idBBC_vols) as val FROM llx_bbc_vols GROUP BY YEAR(date), fk_type ORDER BY year,fk_type";
514
    $resql = $db->query($sql);
515
516
    $num = $db->num_rows($resql);
517
    $i = 0;
518
    if ($num) {
519
        while ($i < $num) {
520
            $obj = $db->fetch_object($resql);
521
522
            if ($obj->year) {
523
                $graphData->addValue($obj->year, new GraphicalValue($obj->val, $obj->year, $obj->type));
524
            }
525
526
            $i++;
527
        }
528
    }
529
530
    return $graphData;
531
}
532
533
/**
534
 * @return GraphicalData
535
 */
536
function getGraphByTypeAndYearData()
537
{
538
539
    $flightTypes = fetchBbcFlightTypes();
540
541
    $graphData = new GraphicalData();
542
543
    foreach (getFlightYears() as $flightYear) {
544
        $pieceData = new YearGraphicalData($flightYear);
545
546
        foreach ($flightTypes as $flightType) {
547
            $pieceData->addType(new GraphicalType($flightType->id, $flightType->nom));
548
        }
549
550
        $graphData->addData($pieceData);
551
    }
552
553
    return fetchGraphByTypeAndYearData($graphData);
554
}