Passed
Push — master ( 81c21e...57d64e )
by Luiz Kim
02:20
created

ModelService::getContactByPeople()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 13
rs 9.9666
cc 2
nc 2
nop 1
1
<?php
2
3
namespace ControleOnline\Service;
4
5
use Doctrine\ORM\EntityManagerInterface;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\EntityManagerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use ControleOnline\Entity\City;
7
use ControleOnline\Entity\People;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\People was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use ControleOnline\Entity\Address;
9
use ControleOnline\Entity\Contract as MyContract;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\Contract was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use ControleOnline\Entity\SalesOrder;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\SalesOrder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use App\Library\Utils\Formatter;
0 ignored issues
show
Bug introduced by
The type App\Library\Utils\Formatter was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use ControleOnline\Entity\MyContractProduct;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\MyContractProduct was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
14
15
class ModelService
16
{
17
18
19
    protected $request;
20
    public function __construct(
21
        private EntityManagerInterface $manager,
22
23
    ) {}
24
25
26
    protected $daysWeek = [
27
        'monday'    => 'segunda-feira',
28
        'tuesday'   => 'terça-feira',
29
        'wednesday' => 'quarta-feira',
30
        'thursday'  => 'quinta-feira',
31
        'friday'    => 'sexta-feira',
32
        'saturday'  => 'sábado',
33
        'sunday'    => 'domingo'
34
    ];
35
36
    protected $vars = [
37
        'contract_id' => [
38
            'id',
39
            'contract_id'
40
        ],
41
        'order_id' => [
42
            'order_id',
43
            'quote_id'
44
        ],
45
        'order_price' => [
46
            'order_price'
47
        ],
48
        'order_price_text' => [
49
            'order_price_text'
50
        ],
51
        'product_cubage' => [
52
            'product_cubage'
53
        ],
54
        'product_type' => [
55
            'product_type',
56
            'car_name'
57
        ],
58
        'product_total_price' => [
59
            'product_total_price',
60
            'car_price'
61
        ],
62
        'student_name' => [
63
            'dados_aluno',
64
            'student_name',
65
            'contratante'
66
        ],
67
        'student_address' => [
68
            'endereco_aluno',
69
            'student_address',
70
            'contratante_endereco_completo'
71
        ],
72
        'student_small_address' => [
73
            'student_small_address',
74
            'contratante_endereco'
75
        ],
76
        'student_cep' => [
77
            'student_cep',
78
            'contratante_cep'
79
        ],
80
        'student_rg' => [
81
            'rg_aluno',
82
            'student_rg',
83
            'contratante_rg'
84
        ],
85
        'payer_document_type' => [
86
            'doc_aluno',
87
            'payer_document_type',
88
            'contratante_doc_type'
89
        ],
90
        'payer_document' => [
91
            'cpf_aluno',
92
            'payer_document',
93
            'contratante_cpf'
94
        ],
95
        'company_cnpj' => [
96
            'company_cnpj'
97
        ],
98
        'company_address' => [
99
            'company_address'
100
        ],
101
        'company_owners' => [
102
            'company_owners'
103
        ],
104
        'contract_place' => [
105
            'company_place',
106
            'contract_place'
107
        ],
108
        'contract_hours' => [
109
            'total_horas_contratadas',
110
            'contract_hours'
111
        ],
112
        'contract_schedule' => [
113
            'horarios_agendados',
114
            'contract_schedule'
115
        ],
116
        'contract_startdate' => [
117
            'data_inicio_contrato',
118
            'contract_startdate'
119
        ],
120
        'contract_amount' => [
121
            'valor_total_servicos',
122
            'contract_amount'
123
        ],
124
        'contract_enddate' => [
125
            'dia_vencimento',
126
            'contract_enddate'
127
        ],
128
        'contract_modality' => [
129
            'contract_modality'
130
        ],
131
        'contract_detail_services' => [
132
            'detalhe_total_servicos',
133
            'contract_detail_services'
134
        ],
135
        'origin_address' => [
136
            'origin_address'
137
        ],
138
        'origin_city' => [
139
            'origin_city'
140
        ],
141
        'origin_state' => [
142
            'origin_state'
143
        ],
144
        'destination_city' => [
145
            'destination_city'
146
        ],
147
        'destination_state' => [
148
            'destination_state'
149
        ],
150
        'origin_small_address' => [
151
            'origin_small_address'
152
        ],
153
        'origin_cep' => [
154
            'origin_cep'
155
        ],
156
        'destination_address' => [
157
            'destination_address'
158
        ],
159
        'destination_small_address' => [
160
            'destination_small_address'
161
        ],
162
        'destination_cep' => [
163
            'destination_cep'
164
        ],
165
        'company_address' => [
166
            'company_address'
167
        ],
168
        'company_cep' => [
169
            'company_cep'
170
        ],
171
        'company_small_address' => [
172
            'company_small_address'
173
        ],
174
        'today' => [
175
            'data_hoje',
176
            'today'
177
        ],
178
        'company_name' => [
179
            'company_name'
180
        ],
181
        'company_alias' => [
182
            'company_alias'
183
        ],
184
        'car_color' => [
185
            'car_color'
186
        ],
187
        'car_number' => [
188
            'car_number'
189
        ],
190
        'renavan' => [
191
            'renavan'
192
        ],
193
        'route_time' => [
194
            'route_time'
195
        ],
196
        'retrieve_address_type' => [
197
            'retrieve_address_type'
198
        ],
199
        'delivery_address_type' => [
200
            'delivery_address_type'
201
        ],
202
        'retrieve_address' => [
203
            'retrieve_address'
204
        ],
205
        'delivery_address' => [
206
            'delivery_address'
207
        ],
208
        'payment_type' => [
209
            'payment_type'
210
        ],
211
        'date' => [
212
            'date'
213
        ],
214
    ];
215
216
217
218
219
220
221
    /**
222
     * dados_aluno
223
     * endereco_aluno
224
     * rg_aluno
225
     * cpf_aluno
226
     * total_horas_contratadas
227
     * horarios_agendados
228
     * data_inicio_contrato
229
     * valor_total_servicos
230
     * dia_vencimento
231
     * data_hoje
232
     * company_place
233
     * company_cnpj
234
     * company_address
235
     * company_owners
236
     * contract_modality
237
     * detalhe_total_servicos
238
     */
239
    public function genetateFromModel(MyContract $contract): string
240
    {
241
        $values = $this->getTemplateVarsWithValues($contract);
242
        $content = preg_replace(
243
            $this->getRegex($values),
244
            array_values($values),
245
            $contract->getContractModel()->getContent()
246
        );
247
248
        return $content;
249
    }
250
251
    protected function getRegex(array $values): array
252
    {
253
254
        $reges = array();
255
256
        foreach (array_keys($values) as $key) {
257
            $variables = $this->vars[$key];
258
259
            $reges[] = "#\{\{\\s*\\n*\\t*(" . implode("|", $variables) . ")\\t*\\n*\\s*\}\}#";
260
        }
261
262
        return $reges;
263
    }
264
265
    protected function getTemplateVarsWithValues(MyContract $myContract): array
266
    {
267
        $student   = $this->getStudentsData($myContract);
268
        $contract  = $this->getContractData($myContract);
269
        $company   = $this->getCompanyData($myContract);
270
        $orderData = $this->getOrderData($myContract);
271
272
        $orderPriceText = new \NumberFormatter("pt-BR", \NumberFormatter::SPELLOUT);
273
274
275
        date_default_timezone_set('America/Sao_Paulo');
276
277
        $data = new \DateTime('now');
278
        $formatter = new \IntlDateFormatter(
279
            'pt_BR',
280
            \IntlDateFormatter::LONG,
281
            \IntlDateFormatter::NONE,
282
            'America/Sao_Paulo',
283
            \IntlDateFormatter::GREGORIAN
284
        );
285
286
        return [
287
            'contract_id'               => $myContract->getId(),
288
            'student_name'              => $student['student_name'],
289
            'student_address'           => $student['student_address'],
290
            'student_small_address'     => $student['student_small_address'],
291
            'student_cep'               => $student['student_cep'],
292
            'student_rg'                => $student['student_rg'],
293
            'payer_document'            => Formatter::document($student['payer_document']),
294
            'payer_document_type'       => $student['payer_document_type'],
295
            'today'                     => (new \DateTime('now'))->format('d/m/Y'),
296
            'date'                      => $formatter->format($data),
297
            'company_cnpj'              => Formatter::document($company['company_cnpj']),
298
            'company_address'           => $company['company_address'],
299
            'company_cep'               => $company['company_cep'],
300
            'company_small_address'     => $company['company_small_address'],
301
            'company_owners'            => $company['company_owners'],
302
            'company_name'              => $company['company_name'],
303
            'company_alias'             => $company['company_alias'],
304
            'contract_place'            => $contract['contract_place'],
305
            'contract_hours'            => $contract['contract_hours'],
306
            'contract_schedule'         => $contract['contract_schedule'],
307
            'contract_startdate'        => $contract['contract_startdate'],
308
            'contract_amount'           => Formatter::money($contract['contract_amount']),
309
            'contract_enddate'          => $contract['contract_enddate'],
310
            'contract_modality'         => $contract['contract_modality'],
311
            'contract_detail_services'  => $contract['contract_detail_services'],
312
            'order_id'                  => $orderData['order_id'],
313
            'order_price'               => $orderData['order_price'],
314
            'order_price_text'          => $orderPriceText->format(floatval($orderData['order_price'])),
315
            'product_cubage'            => $orderData['product_cubage'],
316
            'product_type'              => $orderData['product_type'],
317
            'product_total_price'       => $orderData['product_total_price'],
318
            'origin_address'            => $orderData['origin_address'],
319
            'origin_city'               => $orderData['origin_city'],
320
            'origin_state'              => $orderData['origin_state'],
321
            'origin_cep'                => $orderData['origin_cep'],
322
            'origin_small_address'      => $orderData['origin_small_address'],
323
            'destination_address'       => $orderData['destination_address'],
324
            'destination_city'          => $orderData['destination_city'],
325
            'destination_state'         => $orderData['destination_state'],
326
            'destination_cep'           => $orderData['destination_cep'],
327
            'destination_small_address' => $orderData['destination_small_address'],
328
            'retrieve_address_type'     => isset($orderData['other_informations']->retrieve_address_type) ? $orderData['other_informations']->retrieve_address_type : 'Base',
329
            'delivery_address_type'     => isset($orderData['other_informations']->delivery_address_type) ? $orderData['other_informations']->delivery_address_type : 'Base',
330
            'renavan'                   => isset($orderData['other_informations']->renavan) ? $orderData['other_informations']->renavan : 'Renavan não informado',
331
            'car_color'                 => isset($orderData['other_informations']->carColor) ? $orderData['other_informations']->carColor : null,
332
            'car_number'                => isset($orderData['other_informations']->carNumber) ? $orderData['other_informations']->carNumber : null,
333
            'route_time'                => $this->getRouteTime($orderData),
334
            'payment_type'              => $this->getPaymentType($orderData),
335
            'delivery_address'          => $this->getDeliveryAddress($orderData),
336
            'retrieve_address'          => $this->getRetrieveAddress($orderData),
337
338
        ];
339
    }
340
    protected function getRouteTime($orderData)
341
    {
342
        $route_time = (isset($orderData['other_informations']->route_time) && $orderData['other_informations']->route_time > 0 ? $orderData['other_informations']->route_time : 10);
343
344
        if (in_array($orderData['origin_state'], ['RR', 'AM', 'RO', 'AC']) || in_array($orderData['destination_state'], ['RR', 'AM', 'RO', 'AC'])) {
345
            $route_time += 10;
346
        }
347
348
        return  $route_time . ' a ' . ($route_time + 5) . ' dias';
349
    }
350
351
352
353
    protected function getDeliveryAddress($orderData)
354
    {
355
        if (!isset($orderData['other_informations']->delivery_address_type)) {
356
            return $orderData['destination_city'] . ' / ' . $orderData['destination_state'];
357
        } else if ($orderData['other_informations']->delivery_address_type == 'winch') {
358
            return $orderData['destination_address'] . ' - ' . $orderData['destination_city'] . ' / ' . $orderData['destination_state'];
359
        } else {
360
            return $orderData['destination_city'] . ' / ' . $orderData['destination_state'] . ' (Ponto de Encontro) ';
361
        }
362
    }
363
364
    protected function getRetrieveAddress($orderData)
365
    {
366
        if (!isset($orderData['other_informations']->retrieve_address_type)) {
367
            return $orderData['origin_city'] . ' / ' . $orderData['origin_state'];
368
        } else if ($orderData['other_informations']->retrieve_address_type == 'winch') {
369
            return $orderData['origin_address'] . ' - ' . $orderData['origin_city'] . ' / ' . $orderData['origin_state'];
370
        } else {
371
            return $orderData['origin_city'] . ' / ' . $orderData['origin_state'] . ' (Ponto de Encontro) ';
372
        }
373
    }
374
375
    protected function getPaymentType($orderData)
376
    {
377
        if ($orderData['other_informations'] && isset($orderData['other_informations']->paymentType)) {
378
            switch ($orderData['other_informations']->paymentType) {
379
                case '5':
380
                    return '
381
                    24 horas úteis (não considerados sábados, domingos e feriados) antes da retirada
382
                    do veículo, para que sejam realizados os procedimentos administrativos de liberação.
383
                    ';
384
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
385
                case '4':
386
                    return '
387
388
                    50% do valor na assinatura do contrato e os outros 50%, 24 horas úteis
389
                    (não considerados sábados, domingos e feriados) antes da retirada do veículo,
390
                    para que sejam realizados os procedimentos administrativos de liberação.
391
392
                        ';
393
                    break;
394
                case '3':
395
                    return '
396
397
                    na assinatura do contrato, via Cartão de Crédito, COM OS ACRÉSCIMOS DAS TAXAS
398
                    RELATIVAS AO CARTÃO. Para esta modalidade de pagamento, o veículo será liberado
399
                    após 24 horas úteis (não considerados sábados, domingos e feriados) da
400
                    confirmação da chegada, para que sejam realizados os procedimentos
401
                    administrativos de liberação
402
403
                    ';
404
                    break;
405
                case '2':
406
                    return '
407
408
                    60% do valor na assinatura do contrato e os outros 40%, 24 horas úteis
409
                    (não considerados sábados, domingos e feriados) antes da retirada do veículo,
410
                    para que sejam realizados os procedimentos administrativos de liberação.
411
412
413
                    ';
414
                    break;
415
                case '1':
416
                    return '
417
418
                    à vista. Para esta modalidade de pagamento, o veículo será liberado
419
                    após 24 horas úteis (não considerados sábados, domingos e feriados)
420
                    da confirmação da chegada, para que sejam realizados os procedimentos
421
                    administrativos de liberação.
422
423
                    ';
424
                    break;
425
                default:
426
                    return '
427
                    na
428
                    assinatura do contrato, via Transferência Bancaria/Boleto ou
429
                    Cartão de Crédito
430
                    ';
431
                    break;
432
            }
433
        } else {
434
            return ' na
435
            assinatura do contrato, via Transferência Bancaria/Boleto ou
436
            Cartão de Crédito
437
           ';
438
        }
439
    }
440
441
    protected function getOrderData(MyContract $myContract): array
442
    {
443
        $data = [
444
            'order_id'                  => '[order_id]',
445
            'order_price'               => '[order_price]',
446
            'product_cubage'            => '[product_cubage]',
447
            'product_type'              => '[product_type]',
448
            'product_total_price'       => '[product_total_price]',
449
            'origin_address'            => '[origin_address]',
450
            'origin_cep'                => '[origin_cep]',
451
            'origin_small_address'      => '[origin_small_address]',
452
            'destination_address'       => '[destination_address]',
453
            'destination_cep'           => '[destination_cep]',
454
            'destination_small_address' => '[destination_small_address]',
455
            'other_informations'        => '[other_informations]',
456
            'origin_city'               => '[origin_city]',
457
            'origin_state'              => '[origin_state]',
458
            'destination_city'          => '[destination_city]',
459
            'destination_state'         => '[destination_state]',
460
        ];
461
462
        $orderRepo = $this->manager->getRepository(SalesOrder::class);
463
464
        /**
465
         * @var SalesOrder $order
466
         */
467
        $order = $orderRepo->findOneBy([
468
            'contract' => $myContract->getId(),
469
            'orderType'  => 'sale'
470
        ]);
471
472
473
474
        if (!empty($order)) {
475
            $data['order_id']            = $order->getId();
476
            $data['order_price']         = number_format($order->getPrice(), 2, ',', '.');
477
            $data['product_cubage']      = $order->getCubage();
478
            $data['product_type']        = $order->getProductType();
479
            $data['product_total_price'] = number_format($order->getInvoiceTotal(), 2, ',', '.');
480
            $data['other_informations'] = $order->getOtherInformations(true);
481
            $origin = $order->getAddressOrigin();
482
            if (empty($origin)) {
483
                $origin = $order->getQuote()->getCityOrigin();
484
            }
485
486
            $adresO =             $this->getAddress($origin);
487
            if ($adresO) {
488
                $resOrigin = $this->getAddressVars('origin', $adresO);
489
                $data["origin_address"]       = $resOrigin["origin_address"];
490
                $data["origin_cep"]           = $resOrigin["origin_cep"];
491
                $data["origin_small_address"] = $resOrigin["origin_small_address"];
492
                $data["origin_city"] = $resOrigin["origin_city"];
493
                $data["origin_state"] = $resOrigin["origin_state"];
494
            } else {
495
                $data["origin_city"] = $order->getQuotes()->first()->getCityOrigin()->getCity();
496
                $data["origin_state"] = $order->getQuotes()->first()->getCityOrigin()->getState()->getUf();
497
            }
498
            $destination = $order->getAddressDestination();
499
            if (empty($destination)) {
500
                $destination = $order->getQuote()->getCityDestination();
501
            }
502
503
            $adresD =             $this->getAddress($destination);
504
            if ($adresD) {
505
                $resDestination = $this->getAddressVars('destination', $adresD);
506
                $data["destination_address"]       = $resDestination["destination_address"];
507
                $data["destination_cep"]           = $resDestination["destination_cep"];
508
                $data["destination_small_address"] = $resDestination["destination_small_address"];
509
                $data["destination_city"] = $resDestination["destination_city"];
510
                $data["destination_state"] = $resDestination["destination_state"];
511
            } else {
512
                $data["destination_city"] = $order->getQuotes()->first()->getCityDestination()->getCity();
513
                $data["destination_state"] = $order->getQuotes()->first()->getCityDestination()->getState()->getUf();
514
            }
515
        }
516
517
        return $data;
518
    }
519
520
    protected function getAddressVars(string $prefix, array $address): array
521
    {
522
        $data = [
523
            $prefix . '_address'       => '[_address]',
524
            $prefix . '_cep'           => '[_cep]',
525
            $prefix . '_small_address' => '[_small_address]',
526
        ];
527
528
        if ($address !== null) {
0 ignored issues
show
introduced by
The condition $address !== null is always true.
Loading history...
529
            $resAddress = [];
530
531
            $resAddress[] = sprintf('%s %s', $address['street'], $address['number']);
532
            $resAddress[] = $address['complement'];
533
            $resAddress[] = $address['district'];
534
            $resAddress[] = sprintf('%s - %s', $address['city'], $address['state']);
535
536
            $data[$prefix . '_small_address'] = array_filter($resAddress, 'strlen');
537
            $data[$prefix . '_small_address'] = implode(', ', $data[$prefix . '_small_address']);
0 ignored issues
show
Bug introduced by
$data[$prefix . '_small_address'] of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

537
            $data[$prefix . '_small_address'] = implode(', ', /** @scrutinizer ignore-type */ $data[$prefix . '_small_address']);
Loading history...
538
539
            $resAddress[] = sprintf('CEP %s', Formatter::mask('#####-###', $address['postalCode']));
540
541
            $data[$prefix . '_address'] = array_filter($resAddress, 'strlen');
542
            $data[$prefix . '_address'] = implode(', ', $data[$prefix . '_address']);
543
            $data[$prefix . '_cep']     = Formatter::mask('#####-###', $address['postalCode']);
544
            $data[$prefix . '_city'] = $address['city'];
545
            $data[$prefix . '_state'] = $address['state'];
546
        }
547
548
        return $data;
549
    }
550
551
    protected function getStudentsData(MyContract $myContract): array
552
    {
553
        $data = [
554
            'student_name'          => '[student_name]',
555
            'student_rg'            => '[student_rg]',
556
            'payer_document'        => '[payer_document]',
557
            'payer_document_type'   => '[payer_document_type]',
558
            'student_address'       => '[student_address]',
559
            'student_cep'           => '[student_cep]',
560
            'student_small_address' => '[student_small_address]',
561
        ];
562
563
        $peopleContract = $myContract->getContractPeople()
564
            ->filter(function ($contractPeople) {
565
                return $contractPeople->getPeopleType() == 'Payer';
566
            });
567
        if (!$peopleContract->isEmpty()) {
568
            $contact = $this->getContactByPeople($peopleContract->first()->getPeople());
569
570
            // name
571
572
            $data['student_name'] = sprintf('%s %s', $contact['name'], $contact['alias']);
573
574
            // documents
575
576
            if (!empty($contact['documents'])) {
577
578
                if (isset($contact['documents']['CNPJ']) && !empty($contact['documents']['CNPJ'])) {
579
                    $data['payer_document'] = $contact['documents']['CNPJ'];
580
                    $data['payer_document_type'] = 'CNPJ';
581
                }
582
583
                if (isset($contact['documents']['CPF']) && !empty($contact['documents']['CPF'])) {
584
                    $data['payer_document'] = $contact['documents']['CPF'];
585
                    $data['payer_document_type'] = 'CPF';
586
                }
587
588
                if (isset($contact['documents']['R.G'])) {
589
                    $data['student_rg']  = $contact['documents']['R.G'];
590
                }
591
            }
592
593
            // address
594
595
            if ($contact['address'] !== null) {
596
                $result = $this->getAddressVars('student', $contact['address']);
597
598
                $data["student_address"]       = $result["student_address"];
599
                $data["student_cep"]           = $result["student_cep"];
600
                $data["student_small_address"] = $result["student_small_address"];
601
            }
602
        }
603
604
        return $data;
605
    }
606
607
    protected function getContractData(MyContract $myContract): array
608
    {
609
        $data = [
610
            'contract_hours'           => '[contract_hours]',
611
            'contract_schedule'        => '[contract_schedule]',
612
            'contract_startdate'       => $myContract->getStartDate()->format('d/m/Y'),
613
            'contract_enddate'         => $myContract->getEndDate() !== null ? $myContract->getEndDate()->format('d/m/Y') : '-',
614
            'contract_amount'          => $this->getContractTotalPrice($myContract),
615
            'contract_place'           => '[contract_place]',
616
            'contract_modality'        => '[contract_modality]',
617
            'contract_detail_services' => '[contract_detail_services]',
618
        ];
619
620
        // place
621
622
        $company = $myContract->getBeneficiary();
623
        if ($company !== null) {
624
            $address = $this->getPeopleAddress($company);
625
            if (is_array($address) && isset($address['city'])) {
626
                $data['contract_place'] = $address['city'];
627
            }
628
        }
629
630
        // detail services
631
632
        $items  = [];
633
        $payers = $this->getContractPeoplePayers($myContract);
634
635
        $contractProducts = $this->manager->getRepository(MyContractProduct::class)
636
            ->getContractProducts($myContract->getId());
637
638
        //// total per month
639
        $products = array_filter(
640
            $contractProducts,
641
            function ($contractProduct) {
642
                return $contractProduct['product_subtype'] == 'Package'
643
                    && $contractProduct['billing_unit'] == 'Monthly';
644
            }
645
        );
646
        $total = 0;
647
        foreach ($products as $product) {
648
            $total += (float) $product['product_price'] * (int) $product['quantity'];
649
        }
650
        $items[] = sprintf(
651
            'Mensalidade de %s aplicada para os meses que seguem o contrato '
652
                . 'tendo seu vencimento para todo dia %s.',
653
            Formatter::money($total),
654
            !empty($payers) ? $payers[0]['paymentDay'] : '00'
655
        );
656
        //// contract tax
657
        $products = array_filter(
658
            $contractProducts,
659
            function ($contractProduct) {
660
                return $contractProduct['product_type'] == 'Registration'
661
                    && $contractProduct['billing_unit'] == 'Single';
662
            }
663
        );
664
        $product = current($products);
0 ignored issues
show
Unused Code introduced by
The assignment to $product is dead and can be removed.
Loading history...
665
        $total   = /*(float) $product['product_price'] * (int) $product['quantity']*/ 10;
666
        $parcels = /*(int) $product['parcels']*/ 0;
667
        if ($parcels > 1) {
668
            $items[] = sprintf(
669
                'Taxa administrativa: %s será '
670
                    . 'parcelada em %sx nas primeiras cobranças.',
671
                Formatter::money($total),
672
                $parcels
673
            );
674
        } else {
675
            $items[] = sprintf(
676
                'Taxa administrativa: %s será paga à vista '
677
                    . '(ou parcelada em 2x nas primeiras cobranças)',
678
                Formatter::money($total)
679
            );
680
        }
681
682
        if (!empty($items)) {
683
            $data['contract_detail_services'] = '';
684
            foreach ($items as $description) {
685
                $data['contract_detail_services'] .= '<li>' . $description . '</li>';
686
            }
687
        }
688
689
        return $data;
690
    }
691
692
    protected function getCompanyData(MyContract $myContract): array
693
    {
694
        $data = [
695
            'company_name'          => '[company_name]',
696
            'company_alias'         => '[company_alias]',
697
            'company_cnpj'          => '[company_cnpj]',
698
            'company_address'       => '[company_address]',
699
            'company_cep'           => '[company_cep]',
700
            'company_small_address' => '[company_small_address]',
701
            'company_owners'        => '[company_owners]',
702
        ];
703
704
        $company = $myContract->getBeneficiary();
705
        $contact = $this->getContactByPeople($company);
706
707
708
        $data['company_name']  = $company->getName();
709
        $data['company_alias'] = $company->getAlias();
710
711
        // get CNPJ
712
713
        if (!empty($contact['documents'])) {
714
            if (isset($contact['documents']['CNPJ'])) {
715
                $data['company_cnpj'] = $contact['documents']['CNPJ'];
716
            }
717
        }
718
719
        // get address
720
721
        if (isset($contact['address'])) {
722
            $result = $this->getAddressVars('company', $contact['address']);
0 ignored issues
show
Bug introduced by
It seems like $contact['address'] can also be of type null; however, parameter $address of ControleOnline\Service\M...rvice::getAddressVars() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

722
            $result = $this->getAddressVars('company', /** @scrutinizer ignore-type */ $contact['address']);
Loading history...
723
724
            $data["company_address"]       = $result["company_address"];
725
            $data["company_cep"]           = $result["company_cep"];
726
            $data["company_small_address"] = $result["company_small_address"];
727
        }
728
729
730
        /*
731
        // get owners
732
733
        $owners = $company->getCompany()->filter(function ($peopleLink) {
734
            return $peopleLink->getPeopleRole() == 'owner';
735
        });;
736
737
        if (!$owners->isEmpty()) {
738
            $ownersContact = [];
739
740
            foreach ($owners as $owner) {
741
                $ownerContact = $this->getContactByPeople($owner->getPeople());
742
743
                // name
744
745
                $ownerData = sprintf('%s %s', trim($ownerContact['name']), trim($ownerContact['alias']));
746
747
                // particulars
748
749
                $particulars = $this->manager->getRepository(Particulars::class)
750
                    ->getParticularsByPeopleAndContext($owner->getPeople(), 'contract_document');
751
                if (!empty($particulars)) {
752
                    $particularsValues = [];
753
754
                    foreach ($particulars as $particular) {
755
                        if ($particular['type_value'] == 'Naturalidade') {
756
                            $particularsValues[] = 'natural de ' . $particular['value'];
757
                        } else {
758
                            $particularsValues[] = $particular['value'];
759
                        }
760
                    }
761
762
                    if (!empty($particularsValues)) {
763
                        $ownerData .= ', ' . implode(', ', $particularsValues);
764
                    }
765
                }
766
767
                // documents
768
769
                if (!empty($ownerContact['documents'])) {
770
                    if (isset($ownerContact['documents']['R.G'])) {
771
                        $ownerData .= sprintf(
772
                            ', portador da cédula de identidade nº %s',
773
                            $ownerContact['documents']['R.G']
774
                        );
775
                    }
776
777
                    if (isset($ownerContact['documents']['CPF']) && !empty($ownerContact['documents']['CPF'])) {
778
                        $ownerData .= sprintf(
779
                            ', inscrito no CPF/MF %s',
780
                            Formatter::document($ownerContact['documents']['CPF'])
781
                        );
782
                    }
783
                }
784
785
                $ownersContact[] = $ownerData;
786
            }
787
788
            $lastOwner              = array_pop($ownersContact);
789
            $data['company_owners'] = implode(', ', $ownersContact) . ' e ' . $lastOwner;
790
        }
791
        */
792
793
        return $data;
794
    }
795
796
797
798
    protected function getContractTotalPrice(MyContract $myContract): float
799
    {
800
        $total = 0;
801
802
        // monthly products
803
804
        $contractProduct = $myContract->getContractProduct()
805
            ->filter(function ($contractProduct) {
806
                return $contractProduct->getProduct()->getProductSubtype() == 'Package'
807
                    && $contractProduct->getProduct()->getBillingUnit() == 'Monthly'
808
                    && $contractProduct->getPrice() > 0;
809
            });
810
811
        foreach ($contractProduct as $cproduct) {
812
            $total += $cproduct->getPrice() * $cproduct->getQuantity();
813
        }
814
815
        // contract tax
816
817
        $contractProduct = $myContract->getContractProduct()
818
            ->filter(function ($contractProduct) {
819
                return $contractProduct->getProduct()->getProductType() == 'Registration'
820
                    && $contractProduct->getProduct()->getBillingUnit() == 'Single'
821
                    && $contractProduct->getPrice() > 0;
822
            });
823
824
        foreach ($contractProduct as $cproduct) {
825
            $total += $cproduct->getPrice() * $cproduct->getQuantity();
826
        }
827
828
        return (float) $total;
829
    }
830
831
    protected function getContactByPeople(People $people): array
832
    {
833
        $documents = [];
834
        foreach ($people->getDocument() as $document) {
835
            $documents[$document->getDocumentType()->getDocumentType()] = $document->getDocument();
836
        }
837
838
        return [
839
            'id'        => $people->getId(),
840
            'name'      => $people->getName(),
841
            'alias'     => $people->getAlias(),
842
            'documents' => $documents,
843
            'address'   => $this->getPeopleAddress($people),
844
        ];
845
    }
846
847
    protected function getPeopleAddress(People $people): ?array
848
    {
849
        if (($address = $people->getAddress()->first()) === false)
850
            return null;
851
852
        return $this->getAddress($address);
853
    }
854
855
    /**
856
     * @param Address|City $address
857
     */
858
    protected function getAddress($address): ?array
859
    {
860
861
        $isAddress = true;
862
863
        $street   = null;
864
        $district = null;
865
        $city     = null;
866
        $state    = null;
867
868
        if (!empty($address)) {
869
            if ($address instanceof City) {
870
                $isAddress = false;
871
                $city      = $address;
872
                $state     = $address->getState();
873
            } else {
874
                $street   = $address->getStreet();
875
                $district = $street->getDistrict();
876
                $city     = $district->getCity();
877
                $state    = $city->getState();
878
            }
879
        } else {
880
            $isAddress = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $isAddress is dead and can be removed.
Loading history...
881
            return null;
882
        }
883
884
885
        return [
886
            'id'         => $isAddress        ? $address->getId() : '',
887
            'country'    => !empty($state)    ? $this->fixCountryName($state->getCountry()->getCountryName()) : '',
888
            'state'      => !empty($state)    ? $state->getUF() : '',
889
            'city'       => !empty($city)     ? $city->getCity() : '',
890
            'district'   => !empty($district) ? $district->getDistrict() : '',
891
            'postalCode' => !empty($street)   ? $this->fixPostalCode($street->getCep()->getCep()) : '',
892
            'street'     => !empty($street)   ? $street->getStreet() : '',
893
            'number'     => $isAddress        ? $address->getNumber() : '',
0 ignored issues
show
Bug introduced by
The method getNumber() does not exist on ControleOnline\Entity\City. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

893
            'number'     => $isAddress        ? $address->/** @scrutinizer ignore-call */ getNumber() : '',

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
894
            'complement' => $isAddress        ? $address->getComplement() : '',
0 ignored issues
show
Bug introduced by
The method getComplement() does not exist on ControleOnline\Entity\City. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

894
            'complement' => $isAddress        ? $address->/** @scrutinizer ignore-call */ getComplement() : '',

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
895
        ];
896
    }
897
898
    protected function fixCountryName(string $originalName): string
899
    {
900
        return strtolower($originalName) == 'brazil' ? 'Brasil' : $originalName;
901
    }
902
903
    protected function fixPostalCode(int $postalCode): string
904
    {
905
        $code = (string)$postalCode;
906
        return strlen($code) == 7 ? '0' . $code : $code;
907
    }
908
909
    protected function getContractPeoplePayers(MyContract $contract): array
910
    {
911
        $contractPeople = $contract->getContractPeople()
912
            ->filter(function ($contractPeople) {
913
                return $contractPeople->getPeopleType() == 'Payer' && $contractPeople->getContractPercentage() > 0;
914
            });
915
916
        $payers = [];
917
918
        if (!$contractPeople->isEmpty()) {
919
            foreach ($contractPeople as $cpeople) {
920
                $payers[] = [
921
                    'people'     => $cpeople->getPeople(),
922
                    'percent'    => $cpeople->getContractPercentage(),
923
                    'paymentDay' => $cpeople->getPeople()->getPaymentTerm()
924
                ];
925
            }
926
        }
927
928
        return $payers;
929
    }
930
}
931