Completed
Push — master ( c2d14e...abe7b9 )
by Laurent
02:09
created

generateBilling.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * When a user generates the expense report for all pilots
4
 */
5
define("EXPENSE_REPORT_GENERATOR_ACTION_GENERATE", "generate");
6
7
/**
8
 * When a user has to select year and quartil
9
 */
10
define("EXPENSE_REPORT_GENERATOR_ACTION_SELECT", "select");
11
12
/**
13
 * \file    generateExpenseNote.php
14
 * \ingroup flightLog
15
 * \brief   Generate expense notes for a quartil
16
 *
17
 */
18
19
// Load Dolibarr environment
20
if (false === (@include '../main.inc.php')) {  // From htdocs directory
21
    require '../../documents/custom/main.inc.php'; // From "custom" directory
22
}
23
24
dol_include_once('/compta/facture/class/facture.class.php');
25
dol_include_once('/adherents/class/adherent.class.php');
26
dol_include_once("/flightLog/lib/flightLog.lib.php");
27
dol_include_once('/core/modules/facture/modules_facture.php');
28
29
global $db, $langs, $user, $conf;
30
31
// Load translation files required by the page
32
$langs->load("mymodule@mymodule");
33
$langs->load("trips");
34
$langs->load("bills");
35
36
// Get parameters
37
$id = GETPOST('id', 'int');
38
$action = GETPOST('action', 'alpha');
39
$year = GETPOST('year', 'int', 3);
40
41
//post parameters
42
$additionalBonus = GETPOST('additional_bonus', 'array', 2);
43
$pilotIds = GETPOST('pilot', 'array', 2);
44
$amouts = GETPOST('amout', 'array', 2);
45
$amoutDiscounts = GETPOST('amoutDiscount', 'array', 2);
46
$publicNote = GETPOST('public_note', 'alpha', 2);
47
$privateNote = GETPOST('private_note', 'alpha', 2);
48
$type = GETPOST("type", "int", 3);
49
$conditionReglement = GETPOST("cond_reglement_id", "int", 3);
50
$modeReglement = GETPOST("mode_reglement_id", "int", 3);
51
$bankAccount = GETPOST("fk_account", "int", 3);
52
$documentModel = GETPOST("model", "alpha", 3);
53
54
55
$currentYear = date('Y');
56
57
//Query
58
$sql = "SELECT USR.lastname AS nom , USR.firstname AS prenom ,COUNT(`idBBC_vols`) AS nbr,fk_pilot as pilot, TT.numero as type,SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(heureA,heureD)))) AS time";
59
$sql .= " FROM llx_bbc_vols, llx_user AS USR,llx_bbc_types AS TT ";
60
$sql .= " WHERE `fk_pilot`= USR.rowid AND fk_type = TT.idType AND YEAR(llx_bbc_vols.date) = " . $year;
61
$sql .= " GROUP BY fk_pilot,`fk_type`";
62
63
$flightYears = getFlightYears();
64
65
//pdf
66
$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails',
67
    'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
68
$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc',
69
    'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
70
$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref',
71
    'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
72
73
$object = new Facture($db);
74
$vatrate = "0.000";
75
76
// Access control
77 View Code Duplication
if (!$conf->facture->enabled || !$user->rights->flightLog->vol->status || !$user->rights->flightLog->vol->financialGenerateDocuments) {
0 ignored issues
show
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...
78
    accessforbidden();
79
}
80
81
// Default action
82
if (empty($action)) {
83
    $action = EXPENSE_REPORT_GENERATOR_ACTION_SELECT;
84
}
85
86
llxHeader('', $langs->trans('Generate billing'), '');
87
print load_fiche_titre("Générer factures");
88
89
/*
90
 * ACTIONS
91
 *
92
 * Put here all code to do according to value of "action" parameter
93
 */
94
95
if ($action == EXPENSE_REPORT_GENERATOR_ACTION_GENERATE) {
96
97
    if ($year < $currentYear) {
98
99
        if (empty($documentModel) || $conditionReglement == 0 || empty($conditionReglement) || $modeReglement == 0 || empty($modeReglement)) {
100
            dol_htmloutput_errors("Erreur de configuration !");
101
        } else {
102
            $table = sqlToArray($db, $sql, true, $year);
103
104
            foreach ($table as $currentMissionUserId => $value) {
105
106
                $expenseNoteUser = new User($db);
107
                $expenseNoteUser->fetch($currentMissionUserId);
108
109
                $adherent = new Adherent($db);
110
                $adherent->fetch($expenseNoteUser->fk_member);
111
112
                $addBonus = (int)$additionalBonus[$currentMissionUserId];
113
                if ($addBonus < 0) {
114
                    dol_htmloutput_mesg("Facture ignorée " . $adherent->getFullName($langs), '', 'warning');
115
                    continue;
116
                }
117
118
                $totalFlights = $value['1']['count'] + $value['2']['count'] + $value['orga']['count'] + $value['3']['count'] + $value['4']['count'] + $value['6']['count'] + $value['7']['count'];
119
                $totalBonus = $value['1']['count'] * 50 + $value['2']['count'] * 50 + $value['orga']['count'] * 25 + $addBonus;
120
121
                $totalFacture = $value['3']['count'] * 150 + $value['4']['count'] * 100 + $value['6']['count'] * 50 + $value['7']['count'] * 75;
122
123
                $facturable = ($totalFacture - $totalBonus < 0 ? 0 : $totalFacture - $totalBonus);
124
125
                if ($facturable == 0) {
126
                    continue;
127
                }
128
129
                $object = new Facture($db);
130
                $object->fetch_thirdparty();
131
132
                $object->socid = $adherent->fk_soc;
133
                $object->type = $type;
134
                $object->number = "provisoire";
135
                $object->date = (new DateTime())->getTimestamp();
136
                $object->date_pointoftax = "";
137
                $object->note_public = $publicNote;
138
                $object->note_private = $privateNote;
139
                $object->ref_client = "";
140
                $object->ref_int = "";
141
                $object->modelpdf = $documentModel;
142
                $object->cond_reglement_id = $conditionReglement;
143
                $object->mode_reglement_id = $modeReglement;
144
                $object->fk_account = $bankAccount;
145
146
                $id = $object->create($user);
147
148
                $soc = new Societe($db);
149
                $soc->fetch($adherent->fk_soc);
150
151
                if ($id <= 0) {
152
                    setEventMessages($object->error, $object->errors, 'errors');
153
                }
154
155
                $localtax1_tx = get_localtax(0, 1, $object->thirdparty);
156
                $localtax2_tx = get_localtax(0, 2, $object->thirdparty);
157
158
                //T3
159
                $pu_ht = price2num(150, 'MU');
160
                $pu_ttc = price2num(150, 'MU');
161
                $pu_ht_devise = price2num(150, 'MU');
162
                $qty = $value['3']['count'];
163
                $desc = "Vols T3 (privé) en " . $year;
164
165
                $result = $object->addline(
166
                    $desc,
167
                    $pu_ht,
168
                    $qty,
169
                    0,
170
                    $localtax1_tx,
171
                    $localtax2_tx,
172
                    0,
173
                    $discount,
174
                    '',
175
                    '',
176
                    0,
177
                    0,
178
                    '',
179
                    'HT',
180
                    $pu_ttc,
181
                    1,
182
                    -1,
183
                    0,
184
                    '',
185
                    0,
186
                    0,
187
                    '',
188
                    '',
189
                    '',
190
                    [],
191
                    100,
192
                    '',
193
                    0,
194
                    0
195
                );
196
197
                //T4
198
                $pu_ht = price2num(100, 'MU');
199
                $pu_ttc = price2num(100, 'MU');
200
                $pu_ht_devise = price2num(100, 'MU');
201
                $qty = $value['4']['count'];
202
                $desc = "Vols T4 (meeting) en " . $year;
203
204
                $result = $object->addline(
205
                    $desc,
206
                    $pu_ht,
207
                    $qty,
208
                    0,
209
                    $localtax1_tx,
210
                    $localtax2_tx,
211
                    0,
212
                    $discount,
213
                    '',
214
                    '',
215
                    0,
216
                    0,
217
                    '',
218
                    'HT',
219
                    $pu_ttc,
220
                    1,
221
                    -1,
222
                    0,
223
                    '',
224
                    0,
225
                    0,
226
                    '',
227
                    '',
228
                    '',
229
                    [],
230
                    100,
231
                    '',
232
                    0,
233
                    0
234
                );
235
236
                //T6
237
                $pu_ht = price2num(50, 'MU');
238
                $pu_ttc = price2num(50, 'MU');
239
                $pu_ht_devise = price2num(50, 'MU');
240
                $qty = $value['6']['count'];
241
                $desc = "Vols T6 (écolage) en " . $year;
242
243
                $result = $object->addline(
244
                    $desc,
245
                    $pu_ht,
246
                    $qty,
247
                    0,
248
                    $localtax1_tx,
249
                    $localtax2_tx,
250
                    0,
251
                    $discount,
252
                    '',
253
                    '',
254
                    0,
255
                    0,
256
                    '',
257
                    'HT',
258
                    $pu_ttc,
259
                    1,
260
                    -1,
261
                    0,
262
                    '',
263
                    0,
264
                    0,
265
                    '',
266
                    '',
267
                    '',
268
                    [],
269
                    100,
270
                    '',
271
                    0,
272
                    0
273
                );
274
275
                //T7
276
                $pu_ht = price2num(75, 'MU');
277
                $pu_ttc = price2num(75, 'MU');
278
                $pu_ht_devise = price2num(75, 'MU');
279
                $qty = $value['7']['count'];
280
                $desc = "Vols T7(< 50 vols) en " . $year;
281
282
                $result = $object->addline(
283
                    $desc,
284
                    $pu_ht,
285
                    $qty,
286
                    0,
287
                    $localtax1_tx,
288
                    $localtax2_tx,
289
                    0,
290
                    $discount,
291
                    '',
292
                    '',
293
                    0,
294
                    0,
295
                    '',
296
                    'HT',
297
                    $pu_ttc,
298
                    1,
299
                    -1,
300
                    0,
301
                    '',
302
                    0,
303
                    0,
304
                    '',
305
                    '',
306
                    '',
307
                    [],
308
                    100,
309
                    '',
310
                    0,
311
                    0
312
                );
313
314
                //### DISCOUNTS
315
316
                //T1
317
                $pu_ht = price2num(50 * $value['1']['count'], 'MU');
318
                $desc = $year . " - Vols T1 (Sponsor) - (" . $value['1']['count'] . " * 50)";
319
320
                $discountid = $soc->set_remise_except($pu_ht, $user, $desc, 0);
321
                $object->insert_discount($discountid);
322
323
                //T2
324
                $pu_ht = price2num(50 * $value['2']['count'], 'MU');
325
                $desc = $year . " - Vols T2 (Vol passagers) - (" . $value['2']['count'] . " * 50)";
326
327
                $discountid = $soc->set_remise_except($pu_ht, $user, $desc, 0);
328
                $object->insert_discount($discountid);
329
330
                //Orga
331
                $pu_ht = price2num(25 * $value['orga']['count'], 'MU');
332
                $desc = $year . " - Vols dont vous êtes organisateur - (" . $value['orga']['count'] . " * 25)";
333
334
                $discountid = $soc->set_remise_except($pu_ht, $user, $desc, 0);
335
                $object->insert_discount($discountid);
336
337
                //Additional bonus
338
                if ((int)$addBonus > 0) {
339
340
                    $pu_ht = price2num($addBonus, 'MU');
341
342
                    $desc = sprintf("%s - %s", $year, GETPOST("additional_message", 3));
343
344
                    $discountid = $soc->set_remise_except($pu_ht, $user, $desc, 0);
345
                    $object->insert_discount($discountid);
346
                }
347
348
                $ret = $object->fetch($id);
349
                $result = $object->generateDocument("crabe", $langs, $hidedetails, $hidedesc, $hideref);
350
351
                // Validate
352
                $object->fetch($id);
353
                $object->validate($user);
354
355
                // Generate document
356
                $object->fetch($id);
357
                $result = $object->generateDocument("crabe", $langs, $hidedetails, $hidedesc, $hideref);
358
359
            }
360
361
            if ($result > 0) {
362
                dol_htmloutput_mesg("Facture créées");
363
            } else {
364
                dol_htmloutput_errors("Note de frais non créée");
365
            }
366
        }
367
368
    } else {
369
        //Quarter not yet finished
370
        dol_htmloutput_errors("L'année n'est pas encore finie !");
371
    }
372
}
373
374
/*
375
 * VIEW
376
 *
377
 * Put here all code to build page
378
 */
379
380
381
$form = new Form($db);
382
383
$tabLinks = [];
384 View Code Duplication
foreach ($flightYears as $currentFlightYear) {
0 ignored issues
show
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...
385
    $tabLinks[] = [
386
        DOL_URL_ROOT . "/flightLog/generateBilling.php?year=" . $currentFlightYear,
387
        $currentFlightYear,
388
        "tab_" . $currentFlightYear
389
    ];
390
}
391
392
dol_fiche_head($tabLinks, "tab_" . $year);
393
394
?>
395
    <form method="POST">
396
397
        <!-- action -->
398
        <input type="hidden" name="action" value="<?= EXPENSE_REPORT_GENERATOR_ACTION_GENERATE ?>">
399
400
        <?php
401
402
        //tableau par pilote
403
404
        $resql = $db->query($sql);
405
        $pilotNumberFlight = array();
406
        if ($resql):
407
408
            print '<div class="tabBar">';
409
            print '<table class="border" width="100%">';
410
411
            print '<tr class="liste_titre">';
412
            print '<td colspan="2">Nom</td>';
413
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Type 1 : Sponsor") . '</td>';
414
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Type 2 : Baptême") . '</td>';
415
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Organisateur (T1/T2)") . '</td>';
416
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Total bonus") . '</td>';
417
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Type 3 : Privé") . '</td>';
418
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Type 4: Meeting") . '</td>';
419
            print '<td class="liste_titre" colspan="1">' . $langs->trans("Type 5: Chambley") . '</td>';
420
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Type 6: instruction") . '</td>';
421
            print '<td class="liste_titre" colspan="2">' . $langs->trans("Type 7: vols < 50 ") . '</td>';
422
            print '<td class="liste_titre" colspan="1">' . $langs->trans("Facture") . '</td>';
423
            print '<td class="liste_titre" colspan="1">' . $langs->trans("A payer") . '</td>';
424
            print '<tr>';
425
426
            print '<tr class="liste_titre">';
427
            print '<td colspan="2" class="liste_titre"></td>';
428
429
            print '<td class="liste_titre"> # </td>';
430
            print '<td class="liste_titre"> Pts </td>';
431
432
            print '<td class="liste_titre"> # </td>';
433
            print '<td class="liste_titre"> Pts </td>';
434
435
            print '<td class="liste_titre"> # </td>';
436
            print '<td class="liste_titre"> Pts </td>';
437
438
            print '<td class="liste_titre"> Bonus gagnés </td>';
439
            print '<td class="liste_titre"> Bonus additional (ROI) </td>';
440
441
            print '<td class="liste_titre"> # </td>';
442
            print '<td class="liste_titre"> € </td>';
443
444
            print '<td class="liste_titre"> # </td>';
445
            print '<td class="liste_titre"> € </td>';
446
447
            print '<td class="liste_titre"> # </td>';
448
449
            print '<td class="liste_titre"> # </td>';
450
            print '<td class="liste_titre"> € </td>';
451
452
            print '<td class="liste_titre"> #</td>';
453
            print '<td class="liste_titre"> €</td>';
454
455
            print '<td class="liste_titre"> € </td>';
456
            print '<td class="liste_titre"> Balance (A payer) €</td>';
457
458
            print'</tr>';
459
            $table = sqlToArray($db, $sql, true, $year);
460
            $total = 0;
461
            foreach ($table as $key => $value) {
462
463
                $totalBonus = $value['1']['count'] * 50 + $value['2']['count'] * 50 + $value['orga']['count'] * 25;
464
                $totalFacture = $value['3']['count'] * 150 + $value['4']['count'] * 100 + $value['6']['count'] * 50 + $value['7']['count'] * 75;
465
                $facturable = ($totalFacture - $totalBonus < 0 ? 0 : $totalFacture - $totalBonus);
466
                $total += $facturable;
467
468
                $pilotNumberFlight[$value['id']] = array(
469
                    "1" => $value['1']['count'],
470
                    "2" => $value['2']['count'],
471
                    "3" => $value['3']['count'],
472
                    "4" => $value['4']['count'],
473
                    "5" => $value['5']['count'],
474
                    "6" => $value['6']['count'],
475
                    "7" => $value['7']['count'],
476
                );
477
478
                print '<tr>';
479
                print '<td>' . $key;
480
                print sprintf('<input type="hidden" name="pilot[%s]" value="%s" />', $key, $key);
481
                print '</td>';
482
                print '<td>' . $value['name'] . '</td>';
483
484
                print '<td>' . $value['1']['count'] . '</td>';
485
                print '<td>' . $value['1']['count'] * 50 . '</td>';
486
487
                print '<td>' . $value['2']['count'] . '</td>';
488
                print '<td>' . $value['2']['count'] * 50 . '</td>';
489
490
                print '<td>' . $value['orga']['count'] . '</td>';
491
                print '<td>' . $value['orga']['count'] * 25 . '</td>';
492
493
                print '<td><b>' . ($totalBonus) . '</b></td>';
494
                print '<td>' . sprintf('<input type="number" value="0" name="additional_bonus[%s]"/>',
495
                        $key) . '</b></td>';
496
497
                print '<td>' . $value['3']['count'] . '</td>';
498
                print '<td>' . price($value['3']['count'] * 150) . '€</td>';
499
500
                print '<td>' . $value['4']['count'] . '</td>';
501
                print '<td>' . price($value['4']['count'] * 100) . '€</td>';
502
503
                print '<td>' . $value['5']['count'] . '</td>';
504
505
                print '<td>' . $value['6']['count'] . '</td>';
506
                print '<td>' . price($value['6']['count'] * 50) . '€</td>';
507
508
                print '<td>' . $value['7']['count'] . '</td>';
509
                print '<td>' . price($value['7']['count'] * 75) . '€</td>';
510
511
                print '<td>';
512
                print sprintf('<input type="hidden" value="%d" name="amout[%d]"/>', $totalFacture, $key);
513
                print price($totalFacture);
514
                print '€ </td>';
515
516
517
                print '<td>';
518
                print sprintf('<input type="hidden" value="%d" name="amoutDiscount[%d]"/>', $facturable, $key);
519
                print price($facturable);
520
                print '€ </td>';
521
522
                print '</tr>';
523
524
            }
525
526
527
            ?>
528
529
            <tr>
530
                <td colspan='19'></td>
531
                <td>Total à reçevoir</td>
532
                <td><?= price($total) ?>€</td>
533
            </tr>
534
535
            </table>
536
537
        <?php endif; ?>
538
539
540
        <!-- Additional Point message -->
541
        <label>Message de réduction pour points supplémentaire (Commun à toutes les factures)</label><br/>
542
        <textarea name="additional_message" wrap="soft" class="quatrevingtpercent" rows="2">
543
            Points additionel (cf.annexe du ROI)
544
        </textarea>
545
        <br/>
546
        <br/>
547
548
        <!-- Billing type -->
549
        <label><?= $langs->trans("Type de facture"); ?></label><br/>
550
        <input type="radio" id="radio_standard" name="type" value="0" checked="checked"/>
551
        <?= $form->textwithpicto($langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1,
552
            'help', '', 0, 3) ?>
553
        <br/>
554
        <br/>
555
556
        <!-- Payment mode -->
557
        <label><?= $langs->trans("Mode de payement"); ?></label><br/>
558
        <?php $form->select_types_paiements(0, 'mode_reglement_id', 'CRDT'); ?>
559
        <br/>
560
        <br/>
561
562
        <!-- bank account -->
563
        <label><?= $langs->trans("Compte en banque"); ?></label><br/>
564
        <?php $form->select_comptes(0, 'fk_account', 0, '', 1); ?>
565
        <br/>
566
        <br/>
567
568
        <!-- Public note -->
569
        <label><?= $langs->trans("Note publique (commune à toutes les factures)"); ?></label><br/>
570
        <textarea name="public_note" wrap="soft" class="quatrevingtpercent" rows="2">
571
            Les vols sont facturés comme le stipule l'annexe du ROI.
572
        </textarea>
573
        <br/>
574
        <br/>
575
576
        <!-- Private note -->
577
        <label><?= $langs->trans("Note privée (commune à toutes les factures)"); ?></label><br/>
578
        <textarea name="private_note" wrap="soft" class="quatrevingtpercent" rows="2">
579
            Aux points de vols, s'ajoutent une indemnité pour les membres du CA/CD de 300 points.
580
        </textarea>
581
        <br/>
582
583
        <!-- model document -->
584
        <label><?= $langs->trans("Model de document "); ?></label><br/>
585
        <?php $liste = ModelePDFFactures::liste_modeles($db); ?>
586
        <?= $form->selectarray('model', $liste, $conf->global->FACTURE_ADDON_PDF); ?>
587
        <br/>
588
        <br/>
589
590
        <?php if ($year >= $currentYear) : ?>
591
            <a class="butActionRefused" href="#">Générer</a>
592
        <?php else: ?>
593
            <button class="butAction" type="submit">Générer</button>
594
        <?php endif; ?>
595
596
    </form>
597
598
<?php
599
llxFooter();