Completed
Push — master ( 3a683c...464735 )
by Laurent
01:31
created

generateExpenseNote.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('/expensereport/class/expensereport.class.php');
25
dol_include_once("/flightlog/lib/flightLog.lib.php");
26
27
global $db, $langs, $user, $conf;
28
29
// Load translation files required by the page
30
$langs->load("mymodule@mymodule");
31
$langs->load("trips");
32
$langs->load("bills");
33
$langs->load("mails");
34
35
// Get parameters
36
$id = GETPOST('id', 'int');
37
$action = GETPOST('action', 'alpha');
38
$year = GETPOST('year', 'int', 3);
39
$quarter = GETPOST('quarter', 'int');
40
41
$startDate = new \DateTime();
42
$startDate->setDate($year, (($quarter - 1) * 3) + 1, 1);
43
44
$endDate = new \DateTime();
45
$endDate->setDate($year, $quarter * 3, 1);
46
$endDate->add(new \DateInterval("P1M"))->sub(new \DateInterval("P1D"));
47
48
$currentYear = date('Y');
49
$currentQuarter = floor((date('n') - 1) / 3) + 1;
50
51
$tauxRemb = isset($conf->global->BBC_FLIGHT_LOG_TAUX_REMB_KM) ? $conf->global->BBC_FLIGHT_LOG_TAUX_REMB_KM : 0;
52
$unitPriceMission = $conf->global->BBC_FLIGHT_LOG_UNIT_PRICE_MISSION;
53
54
$flightYears = getFlightYears();
55
56
$object = new ExpenseReport($db);
57
$vatrate = "0.000";
58
59
// Access control
60 View Code Duplication
if (!$conf->expensereport->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...
61
    accessforbidden();
62
}
63
64
// Default action
65
if (empty($action)) {
66
    $action = EXPENSE_REPORT_GENERATOR_ACTION_SELECT;
67
}
68
69
llxHeader('', $langs->trans('Generate expense report'), '');
70
print load_fiche_titre("Générer note de frais");
71
72
/*
73
 * ACTIONS
74
 *
75
 * Put here all code to do according to value of "action" parameter
76
 */
77
78
if ($action == EXPENSE_REPORT_GENERATOR_ACTION_GENERATE) {
79
80
    if (!empty($quarter) && ($year < $currentYear || ($year == $currentYear && $quarter < $currentQuarter))) {
81
82
        $missions = bbcKilometersByQuartil($year);
83
84
        foreach($missions as $currentMissionUserId => $currentMission){
85
86
            if($currentMission["quartil"][$quarter]["km"] == 0 && $currentMission["quartil"][$quarter]["flight"] == 0){
87
                continue;
88
            }
89
90
            $expenseNoteUser = new User($db);
91
            $expenseNoteUser->id = $currentMissionUserId;
92
93
            $object = new ExpenseReport($db);
94
            $object->date_debut = $startDate->format("Y-m-d");
95
            $object->date_fin = $endDate->format("Y-m-d");
96
97
            $object->fk_statut = 1;
98
            $object->fk_user_validator = GETPOST("fk_user_validator", 'int');
99
            $object->note_public = GETPOST('public_note', 'alpha');
100
            $object->note_private = GETPOST('private_note','alpha');
101
102
            $expenseNoteId = $object->create($expenseNoteUser);
103
            if($expenseNoteId < 0){
104
                dol_htmloutput_errors("Erreur lors de la création de la note de frais" , $object->errors);
105
                continue;
106
            }
107
108
109
            $flightsForQuarter = findFlightByPilotAndQuarter($currentMissionUserId, $year, $quarter);
110
111
            foreach($flightsForQuarter as $currentFlightForQuarter) {
112
113
                // Kilometers
114
                $object_ligne = new ExpenseReportLine($db);
115
                $object_ligne->comments = $langs->trans(sprintf("Vol (id: %d) %s à %s  détail: %s", $currentFlightForQuarter->idBBC_vols, $currentFlightForQuarter->lieuD, $currentFlightForQuarter->lieuA, $currentFlightForQuarter->justif_kilometers));
116
                $object_ligne->qty = $currentFlightForQuarter->kilometers;
117
                $object_ligne->value_unit = $tauxRemb;
118
119
                $object_ligne->date = $currentFlightForQuarter->date;
120
121
                $object_ligne->fk_c_type_fees = 2;
122
                $object_ligne->fk_expensereport = $expenseNoteId;
123
                $object_ligne->fk_projet = '';
124
125
                $object_ligne->vatrate = price2num($vatrate);
126
127
                $tmp = calcul_price_total($object_ligne->qty, $object_ligne->value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0,
128
                    0, '');
129
                $object_ligne->total_ttc = $tmp[2];
130
                $object_ligne->total_ht = $tmp[0];
131
                $object_ligne->total_tva = $tmp[1];
132
133
                $resultLine = $object_ligne->insert();
134
135
                // Missions
136
                $object_ligne = new ExpenseReportLine($db);
137
                $object_ligne->comments = sprintf("Vol (id: %d) %s à %s", $currentFlightForQuarter->idBBC_vols, $currentFlightForQuarter->lieuD, $currentFlightForQuarter->lieuA);
138
                $object_ligne->qty = 1;
139
                $object_ligne->value_unit = $unitPriceMission;
140
141
                $object_ligne->date = $currentFlightForQuarter->date;
142
143
                $object_ligne->fk_c_type_fees = 8;
144
                $object_ligne->fk_expensereport = $expenseNoteId;
145
                $object_ligne->fk_projet = '';
146
147
                $object_ligne->vatrate = price2num($vatrate);
148
149
                $tmp = calcul_price_total($object_ligne->qty, $object_ligne->value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0,
150
                    0, '');
151
                $object_ligne->total_ttc = $tmp[2];
152
                $object_ligne->total_ht = $tmp[0];
153
                $object_ligne->total_tva = $tmp[1];
154
155
                $resultLine = $object_ligne->insert();
156
            }
157
158
            $object->fetch($expenseNoteId);
159
            $object->setValidate($user);
160
            $object->setApproved($user);
161
162
            $object->fetch($expenseNoteId);
163
            $object->setDocModel($user, "standard");
164
            $result = $object->generateDocument($object->modelpdf, $langs);
165
166
        }
167
168
169
        if ($result > 0) {
170
            dol_htmloutput_mesg("Notes de frais créées");
171
        }else{
172
            dol_htmloutput_errors("Note de frais non créée");
173
        }
174
    } else {
175
        //Quarter not yet finished
176
        dol_htmloutput_errors("Le quartil n'est pas encore fini !");
177
    }
178
}
179
180
/*
181
 * VIEW
182
 *
183
 * Put here all code to build page
184
 */
185
186
187
$form = new Form($db);
188
189
$tabLinks = [];
190 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...
191
    $tabLinks[] = [
192
        DOL_URL_ROOT."/flightlog/generateExpenseNote.php?year=".$currentFlightYear,
193
        $currentFlightYear,
194
        "tab_".$currentFlightYear
195
    ];
196
}
197
198
dol_fiche_head($tabLinks, "tab_".$year);
199
200
?>
201
    <form method="POST">
202
203
        <!-- action -->
204
        <input type="hidden" name="action" value="<?= EXPENSE_REPORT_GENERATOR_ACTION_GENERATE ?>">
205
206
        <?php printBbcKilometersByQuartil(bbcKilometersByQuartil($year), $tauxRemb, $unitPriceMission); ?>
207
208
        <!-- Quarter -->
209
        <label for="field_quarter">Q : </label>
210
        <br/>
211
        <select name="quarter" id="field_quarter">
212
            <option value="1" <?= ($year == $currentYear && $currentQuarter <= 1) ? 'disabled="disabled"' : "" ?>>1</option>
213
            <option value="2" <?= ($year == $currentYear && $currentQuarter <= 2) ? 'disabled="disabled"' : "" ?>>2</option>
214
            <option value="3" <?= ($year == $currentYear && $currentQuarter <= 3) ? 'disabled="disabled"': "" ?>>3</option>
215
            <option value="4" <?= ($year == $currentYear && $currentQuarter <= 4) ? 'disabled="disabled"' : "" ?>>4</option>
216
        </select>
217
        <br/>
218
219
        <!-- Validator -->
220
        <label><?= $langs->trans("Validateur de la note de frais")?></label><br/>
221
        <?php
222
            $include_users = $object->fetch_users_approver_expensereport();
223
            print $form->select_dolusers($user->id,"fk_user_validator",1,"",0,$include_users);
224
        ?>
225
        <br/>
226
227
        <!-- Public note -->
228
        <label><?= $langs->trans("Note publique (commune à toutes les notes de frais)"); ?></label><br/>
229
        <textarea name="public_note" wrap="soft" class="quatrevingtpercent" rows="2">
230
            Les frais pilotes regroupent tous les frais qu'à le pilote pour organiser son vol (Champagne, Téléphone, Diplômes, ...).
231
        </textarea>
232
        <br/>
233
234
        <!-- Private note -->
235
        <label><?= $langs->trans("Note privée (commune à toutes les notes de frais)"); ?></label><br/>
236
        <textarea name="private_note" wrap="soft" class="quatrevingtpercent" rows="2"></textarea>
237
        <br/>
238
239
        <button class="butAction" type="submit">Générer</button>
240
    </form>
241
242
<?php
243
llxFooter();