Completed
Push — feature/select_customer_on_fli... ( c85fa6 )
by Laurent
02:07
created

CreateExpenseNoteCommandHandler::addFlight()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 2
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A CreateExpenseNoteCommandHandler::getAmountByMission() 0 4 1
1
<?php
2
/**
3
 *
4
 */
5
6
namespace flightlog\command;
7
8
use DoliDB;
9
use Exception;
10
use ExpenseReport;
11
use ExpenseReportLine;
12
use flightlog\exceptions\NoMissionException;
13
use flightlog\model\missions\FlightMission;
14
use flightlog\query\FlightForQuarterAndPilotQuery;
15
use flightlog\query\FlightForQuarterAndPilotQueryHandler;
16
use flightlog\query\GetPilotsWithMissionsQuery;
17
use flightlog\query\GetPilotsWithMissionsQueryHandler;
18
use PilotMissions;
19
use stdClass;
20
use Translate;
21
use User;
22
23
/**
24
 * Create the expense not for flights.
25
 *
26
 * @author Laurent De Coninck <[email protected]>
27
 */
28
class CreateExpenseNoteCommandHandler
29
{
30
    const FLIGHT_ELEMENT = 'flightlog_bbcvols';
31
32
    /**
33
     * @var stdClass
34
     */
35
    protected $conf;
36
37
    /**
38
     * @var Translate
39
     */
40
    protected $langs;
41
42
    /**
43
     * @var User
44
     */
45
    protected $user;
46
47
    /**
48
     * @var DoliDB
49
     */
50
    protected $db;
51
52
    /**
53
     * @var GetPilotsWithMissionsQueryHandler
54
     */
55
    private $getMissionsQueryHandler;
56
57
    /**
58
     * @var FlightForQuarterAndPilotQueryHandler
59
     */
60
    private $flightForQuarterAndPilotHandler;
61
62
63
    /**
64
     * @param DoliDB                               $db
65
     * @param stdClass                             $conf
66
     * @param User                                 $user
67
     * @param Translate                            $langs
68
     * @param GetPilotsWithMissionsQueryHandler    $missionsQueryHandler
69
     * @param FlightForQuarterAndPilotQueryHandler $flightForQuarterAndPilotQueryHandler
70
     */
71
    public function __construct(
72
        $db,
73
        $conf,
74
        $user,
75
        $langs,
76
        GetPilotsWithMissionsQueryHandler $missionsQueryHandler,
77
        FlightForQuarterAndPilotQueryHandler $flightForQuarterAndPilotQueryHandler
78
    ) {
79
        $this->db = $db;
80
        $this->conf = $conf;
81
        $this->user = $user;
82
        $this->langs = $langs;
83
        $this->getMissionsQueryHandler = $missionsQueryHandler;
84
        $this->flightForQuarterAndPilotHandler = $flightForQuarterAndPilotQueryHandler;
85
    }
86
87
    /**
88
     * @param CreateExpenseNoteCommand $command
89
     *
90
     * @throws Exception
91
     */
92
    public function __invoke(CreateExpenseNoteCommand $command)
93
    {
94
        $missions = $this->getMissionsQueryHandler->__invoke(new GetPilotsWithMissionsQuery($command->getYear(), $command->getQuartile()));
95
96
        if (!$missions->hasMission()) {
97
            throw new NoMissionException();
98
        }
99
100
        /** @var PilotMissions $currentMission */
101
        foreach ($missions as $currentMission) {
102
            $expenseNote = $this->createExpenseNote($command);
103
104
            $flightsForQuarter = $this->flightForQuarterAndPilotHandler->__invoke(new FlightForQuarterAndPilotQuery($currentMission->getPilotId(),
105
                $command->getQuartile(), $command->getYear()));
106
107
            /** @var FlightMission $currentFlightForQuarter */
108
            foreach ($flightsForQuarter as $currentFlightForQuarter) {
109
                $expenseNote = $this->addKilometersLine($currentFlightForQuarter, $expenseNote);
110
                $expenseNote = $this->addMissionLine($currentFlightForQuarter, $expenseNote);
111
            }
112
113
            $expenseNote = $this->saveExpenseNote($currentMission->getPilotId(), $expenseNote);
114
            if (null === $expenseNote) {
115
                dol_htmloutput_errors("Erreur lors de la création de la note de frais", $expenseNote->errors);
116
                continue;
117
            }
118
119
            /** @var FlightMission $currentFlightForQuarter */
120
            foreach ($flightsForQuarter as $currentFlightForQuarter) {
121
                $expenseNote->add_object_linked(self::FLIGHT_ELEMENT, $currentFlightForQuarter->getId());
122
            }
123
124
            $expenseNote->fetch($expenseNote->id);
125
            $expenseNote->setValidate($this->user);
126
            $expenseNote->setApproved($this->user);
127
            $expenseNote->setDocModel($this->user, "standard");
128
129
            $error = false;
130
            //$error = $expenseNote->generateDocument($expenseNote->modelpdf, $this->langs) <= 0;
131
132
            if (!$error) {
133
                dol_htmloutput_mesg(sprintf("Notes de frais crée pour %s", $currentMission->getPilotName()));
134
                continue;
135
            }
136
137
            dol_htmloutput_errors(sprintf("Notes de frais non crée pour %s", $currentMission->getPilotName()));
138
        }
139
    }
140
141
    /**
142
     * @param FlightMission $currentFlightForQuarter
143
     * @param ExpenseReport $expenseNote
144
     *
145
     * @return ExpenseReport
146
     */
147
    private function addKilometersLine(FlightMission $currentFlightForQuarter, $expenseNote)
148
    {
149
        $object_ligne = new ExpenseReportLine($this->db);
150
        $object_ligne->comments = $this->langs->trans(sprintf("Vol (id: %d) %s à %s  détail: %s",
151
            $currentFlightForQuarter->getId(), $currentFlightForQuarter->getStartPoint(),
152
            $currentFlightForQuarter->getEndPoint(), $currentFlightForQuarter->getKilometersComment()));
153
        $object_ligne->qty = $currentFlightForQuarter->getNumberOfKilometers();
154
        $object_ligne->value_unit = $this->getAmountByKilometer();
155
156
        $object_ligne->date = $currentFlightForQuarter->getDate()->format('Y-m-d');
157
158
        $object_ligne->fk_c_type_fees = 2;
159
        $object_ligne->fk_projet = '';
160
161
        $object_ligne->vatrate = price2num($this->getVatRate());
162
163
        $tmp = calcul_price_total($object_ligne->qty, $object_ligne->value_unit, 0, $this->getVatRate(), 0, 0, 0, 'TTC',
164
            0,
165
            0, '');
166
        $object_ligne->total_ttc = $tmp[2];
167
        $object_ligne->total_ht = $tmp[0];
168
        $object_ligne->total_tva = $tmp[1];
169
170
        $expenseNote->lines[] = $object_ligne;
171
172
        return $expenseNote;
173
    }
174
175
    /**
176
     * @param FlightMission $currentFlightForQuarter
177
     * @param ExpenseReport $expenseReport
178
     *
179
     * @return ExpenseReport
180
     */
181
    private function addMissionLine(FlightMission $currentFlightForQuarter, ExpenseReport $expenseReport)
182
    {
183
        $object_ligne = new ExpenseReportLine($this->db);
184
        $object_ligne->comments = sprintf("Vol (id: %d) %s à %s", $currentFlightForQuarter->getId(),
185
            $currentFlightForQuarter->getStartPoint(), $currentFlightForQuarter->getEndPoint());
186
        $object_ligne->qty = 1;
187
        $object_ligne->value_unit = $this->getAmountByMission();
188
189
        $object_ligne->date = $currentFlightForQuarter->getDate()->format('Y-m-d');
190
191
        $object_ligne->fk_c_type_fees = 8;
192
        $object_ligne->fk_projet = '';
193
194
        $object_ligne->vatrate = price2num($this->getVatRate());
195
196
        $tmp = calcul_price_total($object_ligne->qty, $object_ligne->value_unit, 0, $this->getVatRate(), 0, 0, 0, 'TTC',
197
            0,
198
            0, '');
199
        $object_ligne->total_ttc = $tmp[2];
200
        $object_ligne->total_ht = $tmp[0];
201
        $object_ligne->total_tva = $tmp[1];
202
203
        $expenseReport->lines[] = $object_ligne;
204
205
        return $expenseReport;
206
    }
207
208
    /**
209
     * Get the unit price pe KM.
210
     *
211
     * @return int
212
     */
213
    private function getAmountByKilometer()
214
    {
215
        return isset($this->conf->global->BBC_FLIGHT_LOG_TAUX_REMB_KM) ? $this->conf->global->BBC_FLIGHT_LOG_TAUX_REMB_KM : 0;
216
    }
217
218
    /**
219
     * @return mixed
220
     */
221
    private function getAmountByMission()
222
    {
223
        return $this->conf->global->BBC_FLIGHT_LOG_UNIT_PRICE_MISSION;
224
    }
225
226
    /**
227
     * @return string
228
     */
229
    private function getVatRate()
230
    {
231
        return '0.000';
232
    }
233
234
    /**
235
     * @param CreateExpenseNoteCommand $command
236
     *
237
     * @return ExpenseReport
238
     * @throws Exception
239
     */
240
    private function createExpenseNote(CreateExpenseNoteCommand $command)
241
    {
242
        $startDate = new \DateTime();
243
        $startDate->setDate($command->getYear(), (($command->getQuartile() - 1) * 3) + 1, 1);
244
245
        $endDate = new \DateTime();
246
        $endDate->setDate($command->getYear(), $command->getQuartile() * 3, 1);
247
        $endDate->add(new \DateInterval("P1M"))->sub(new \DateInterval("P1D"));
248
249
        $object = new ExpenseReport($this->db);
250
        $object->date_debut = $startDate->format("Y-m-d");
251
        $object->date_fin = $endDate->format("Y-m-d");
252
253
        $object->fk_statut = 1;
254
        $object->fk_user_validator = $command->getUserValidatorId();
255
        $object->note_public = $command->getPublicNote();
256
        $object->note_private = $command->getPrivateNote();
257
258
        return $object;
259
    }
260
261
    /**
262
     * @param int           $currentMissionUserId
263
     * @param ExpenseReport $expenseNote
264
     *
265
     * @return ExpenseReport
266
     */
267
    private function saveExpenseNote($currentMissionUserId, ExpenseReport $expenseNote)
268
    {
269
        $expenseNoteUser = new User($this->db);
270
        $expenseNoteUser->id = $currentMissionUserId;
271
        $id = $expenseNote->create($expenseNoteUser);
272
        if($id < 0){
273
            return null;
274
        }
275
276
        return $expenseNote;
277
    }
278
279
}