Test Failed
Pull Request — master (#1563)
by
unknown
09:08
created

EditCliente::loadData()   C

Complexity

Conditions 13
Paths 13

Size

Total Lines 58
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 41
nc 13
nop 2
dl 0
loc 58
rs 6.6166
c 0
b 0
f 0

How to fix   Long Method    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
 * This file is part of FacturaScripts
4
 * Copyright (C) 2017-2023 Carlos Garcia Gomez <[email protected]>
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, either version 3 of the
9
 * License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public License
17
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
namespace FacturaScripts\Core\Controller;
21
22
use FacturaScripts\Core\Base\DataBase\DataBaseWhere;
23
use FacturaScripts\Core\Lib\ExtendedController\BaseView;
24
use FacturaScripts\Core\Lib\ExtendedController\ComercialContactController;
25
use FacturaScripts\Core\Tools;
26
use FacturaScripts\Dinamic\Lib\CustomerRiskTools;
27
use FacturaScripts\Dinamic\Lib\RegimenIVA;
28
use FacturaScripts\Dinamic\Model\Cliente;
29
use FacturaScripts\Dinamic\Model\SettingsModel;
0 ignored issues
show
Bug introduced by
The type FacturaScripts\Dinamic\Model\SettingsModel 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...
30
31
/**
32
 * Controller to edit a single item from the Cliente model
33
 *
34
 * @author       Carlos García Gómez           <[email protected]>
35
 * @author       Jose Antonio Cuello Principal <[email protected]>
36
 * @author       Fco. Antonio Moreno Pérez     <[email protected]>
37
 * @collaborator Daniel Fernández Giménez      <[email protected]>
38
 */
39
class EditCliente extends ComercialContactController
40
{
41
    /**
42
     * Returns the customer's risk on pending delivery notes.
43
     *
44
     * @return string
45
     */
46
    public function getDeliveryNotesRisk(): string
47
    {
48
        $codcliente = $this->getViewModelValue('EditCliente', 'codcliente');
49
        $total = empty($codcliente) ? 0 : CustomerRiskTools::getDeliveryNotesRisk($codcliente);
50
        return Tools::money($total);
51
    }
52
53
    public function getImageUrl(): string
54
    {
55
        $mvn = $this->getMainViewName();
56
        return $this->views[$mvn]->model->gravatar();
0 ignored issues
show
Bug introduced by
The method gravatar() does not exist on FacturaScripts\Core\Model\Base\ModelClass. It seems like you code against a sub-type of said class. However, the method does not exist in FacturaScripts\Core\Model\Base\Address or FacturaScripts\Dinamic\Model\Base\ModelClass or FacturaScripts\Core\Model\Base\ModelOnChangeClass or FacturaScripts\Core\Model\Base\BankAccount or FacturaScripts\Core\Model\Base\Payment or FacturaScripts\Dinamic\Model\Base\Address or FacturaScripts\Core\Model\Base\Receipt or FacturaScripts\Core\Mode...se\BusinessDocumentLine or FacturaScripts\Dinamic\M...Base\ModelOnChangeClass or FacturaScripts\Core\Model\Base\BusinessDocument or FacturaScripts\Dinamic\Model\Base\Receipt or FacturaScripts\Dinamic\M...se\BusinessDocumentLine or FacturaScripts\Core\Mode...se\PurchaseDocumentLine or FacturaScripts\Core\Model\Base\SalesDocumentLine or FacturaScripts\Dinamic\M...se\PurchaseDocumentLine or FacturaScripts\Dinamic\M...\Base\SalesDocumentLine or FacturaScripts\Dinamic\Model\Base\BusinessDocument or FacturaScripts\Core\Model\Base\TransformerDocument or FacturaScripts\Core\Model\Base\PurchaseDocument or FacturaScripts\Dinamic\M...ase\TransformerDocument or FacturaScripts\Core\Model\Base\SalesDocument or FacturaScripts\Dinamic\Model\Base\PurchaseDocument or FacturaScripts\Dinamic\Model\Base\SalesDocument or FacturaScripts\Dinamic\Model\Base\BankAccount or FacturaScripts\Dinamic\Model\Base\Payment. Are you sure you never get one of those? ( Ignorable by Annotation )

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

56
        return $this->views[$mvn]->model->/** @scrutinizer ignore-call */ gravatar();
Loading history...
57
    }
58
59
    /**
60
     * Returns the customer's risk on unpaid invoices.
61
     *
62
     * @return string
63
     */
64
    public function getInvoicesRisk(): string
65
    {
66
        $codcliente = $this->getViewModelValue('EditCliente', 'codcliente');
67
        $total = empty($codcliente) ? 0 : CustomerRiskTools::getInvoicesRisk($codcliente);
68
        return Tools::money($total);
69
    }
70
71
    public function getModelClassName(): string
72
    {
73
        return 'Cliente';
74
    }
75
76
    /**
77
     * Returns the customer's risk on pending orders.
78
     *
79
     * @return string
80
     */
81
    public function getOrdersRisk(): string
82
    {
83
        $codcliente = $this->getViewModelValue('EditCliente', 'codcliente');
84
        $total = empty($codcliente) ? 0 : CustomerRiskTools::getOrdersRisk($codcliente);
85
        return Tools::money($total);
86
    }
87
88
    public function getPageData(): array
89
    {
90
        $data = parent::getPageData();
91
        $data['menu'] = 'sales';
92
        $data['title'] = 'customer';
93
        $data['icon'] = 'fas fa-users';
94
        return $data;
95
    }
96
97
    protected function createDocumentView(string $viewName, string $model, string $label)
98
    {
99
        $this->createCustomerListView($viewName, $model, $label);
100
101
        // botones
102
        $this->setSettings($viewName, 'btnPrint', true);
103
        $this->addButtonGroupDocument($viewName);
104
        $this->addButtonApproveDocument($viewName);
105
    }
106
107
    protected function createInvoiceView(string $viewName)
108
    {
109
        $this->createCustomerListView($viewName, 'FacturaCliente', 'invoices');
110
111
        // botones
112
        $this->setSettings($viewName, 'btnPrint', true);
113
        $this->addButtonLockInvoice($viewName);
114
    }
115
116
    /**
117
     * Create views
118
     */
119
    protected function createViews()
120
    {
121
        parent::createViews();
122
        $this->createContactsView();
123
        $this->addEditListView('EditCuentaBancoCliente', 'CuentaBancoCliente', 'customer-banking-accounts', 'fas fa-piggy-bank');
124
125
        if ($this->user->can('EditSubcuenta')) {
126
            $this->createSubaccountsView();
127
        }
128
129
        $this->createEmailsView();
130
        $this->createViewDocFiles();
131
132
        if ($this->user->can('EditFacturaCliente')) {
133
            $this->createInvoiceView('ListFacturaCliente');
134
            $this->createLineView('ListLineaFacturaCliente', 'LineaFacturaCliente');
135
        }
136
        if ($this->user->can('EditAlbaranCliente')) {
137
            $this->createDocumentView('ListAlbaranCliente', 'AlbaranCliente', 'delivery-notes');
138
        }
139
        if ($this->user->can('EditPedidoCliente')) {
140
            $this->createDocumentView('ListPedidoCliente', 'PedidoCliente', 'orders');
141
        }
142
        if ($this->user->can('EditPresupuestoCliente')) {
143
            $this->createDocumentView('ListPresupuestoCliente', 'PresupuestoCliente', 'estimations');
144
        }
145
        if ($this->user->can('EditReciboCliente')) {
146
            $this->createReceiptView('ListReciboCliente', 'ReciboCliente');
147
        }
148
149
        $this->createViewSettings();
150
    }
151
152
    protected function createViewSettings(string $viewName = 'EditSettingsModel'): void
153
    {
154
        $this->addEditListView($viewName, 'SettingsModel', 'settings', 'fas fa-wrench');
155
    }
156
157
    /**
158
     * @return bool
159
     */
160
    protected function editAction()
161
    {
162
        $return = parent::editAction();
163
        if ($return && $this->active === $this->getMainViewName()) {
164
            $this->checkSubaccountLength($this->getModel()->codsubcuenta);
165
166
            // update contact email and phones when customer email or phones are updated
167
            $this->updateContact($this->views[$this->active]->model);
168
        }
169
170
        return $return;
171
    }
172
173
    protected function execPreviousAction($action)
174
    {
175
        if ($this->active === 'EditSettingsModel' && in_array($action, ['edit', 'insert'])){
176
177
            /** @var Cliente $cliente */
178
            $cliente = $this->getModel();
179
            $cliente->loadFromCode($this->request->get('code'));
180
181
            /** @var SettingsModel $settingsModel */
182
            $settingsModel = $this->views[$this->active]->model;
183
            $settingsModel->loadFromCode('', [
184
                new DataBaseWhere('classnamemodel', get_class($cliente)),
185
                new DataBaseWhere('idmodel', $cliente->primaryColumnValue()),
186
                new DataBaseWhere('idempresa', $this->request->request->get('idempresa')),
187
            ]);
188
189
            $settingsModel->classnamemodel = get_class($cliente);
190
            $settingsModel->idmodel = $cliente->primaryColumnValue();
191
            $settingsModel->idempresa = $this->request->request->get('idempresa');
192
            $settingsModel->settings = json_encode([
193
                'codalmacen' => empty($this->request->request->get('codalmacen')) ? null : $this->request->request->get('codalmacen'),
194
                'codserie' => empty($this->request->request->get('codserie')) ? null : $this->request->request->get('codserie'),
195
                'coddivisa' => empty($this->request->request->get('coddivisa')) ? null : $this->request->request->get('coddivisa'),
196
                'codpago' => empty($this->request->request->get('codpago')) ? null : $this->request->request->get('codpago'),
197
            ]);
198
        }
199
200
        return parent::execPreviousAction($action);
201
    }
202
203
    /**
204
     * @return bool
205
     */
206
    protected function insertAction()
207
    {
208
        if (false === parent::insertAction()) {
209
            return false;
210
        }
211
212
        // redirect to returnUrl if return is defined
213
        $returnUrl = $this->request->query->get('return');
214
        if (!empty($returnUrl)) {
215
            $model = $this->views[$this->active]->model;
216
            $this->redirect($returnUrl . '?' . $model->primaryColumn() . '=' . $model->primaryColumnValue());
217
        }
218
219
        return true;
220
    }
221
222
    /**
223
     * Load view data procedure
224
     *
225
     * @param string $viewName
226
     * @param BaseView $view
227
     */
228
    protected function loadData($viewName, $view)
229
    {
230
        $mainViewName = $this->getMainViewName();
231
        $codcliente = $this->getViewModelValue($mainViewName, 'codcliente');
232
        $where = [new DataBaseWhere('codcliente', $codcliente)];
233
234
        switch ($viewName) {
235
            case 'EditCuentaBancoCliente':
236
                $view->loadData('', $where, ['codcuenta' => 'DESC']);
237
                break;
238
239
            case 'EditDireccionContacto':
240
                $view->loadData('', $where, ['idcontacto' => 'DESC']);
241
                break;
242
243
            case 'ListFacturaCliente':
244
                $view->loadData('', $where);
245
                $this->addButtonGenerateAccountingInvoices($viewName, $codcliente);
246
                break;
247
248
            case 'ListAlbaranCliente':
249
            case 'ListPedidoCliente':
250
            case 'ListPresupuestoCliente':
251
            case 'ListReciboCliente':
252
                $view->loadData('', $where);
253
                break;
254
255
            case 'ListLineaFacturaCliente':
256
                $inSQL = 'SELECT idfactura FROM facturascli WHERE codcliente = ' . $this->dataBase->var2str($codcliente);
257
                $where = [new DataBaseWhere('idfactura', $inSQL, 'IN')];
258
                $view->loadData('', $where);
259
                break;
260
261
            case 'EditSettingsModel':
262
                $where = [
263
                    new DataBaseWhere('classnamemodel', get_class($this->getModel())),
264
                    new DataBaseWhere('idmodel', $codcliente),
265
                ];
266
                $view->loadData('', $where);
267
268
                // agregamos al modelo las propiedades que hay dentro de settings
269
                // para conservar la clase con todas las propiedades y que detecte si el modelo existe o no.
270
                foreach($view->cursor as $model){
271
                    foreach ($model->settings as $key => $value) {
272
                        $model->{$key} = $value;
273
                    }
274
                }
275
276
                break;
277
278
            case $mainViewName:
279
                parent::loadData($viewName, $view);
280
                $this->loadLanguageValues($viewName);
281
                break;
282
283
            default:
284
                parent::loadData($viewName, $view);
285
                break;
286
        }
287
    }
288
289
    /**
290
     * Load the available language values from translator.
291
     */
292
    protected function loadLanguageValues(string $viewName)
293
    {
294
        $columnLangCode = $this->views[$viewName]->columnForName('language');
295
        if ($columnLangCode && $columnLangCode->widget->getType() === 'select') {
296
            $langs = [];
297
            foreach (Tools::lang()->getAvailableLanguages() as $key => $value) {
298
                $langs[] = ['value' => $key, 'title' => $value];
299
            }
300
301
            $columnLangCode->widget->setValuesFromArray($langs, false, true);
0 ignored issues
show
Bug introduced by
The method setValuesFromArray() does not exist on FacturaScripts\Core\Lib\Widget\BaseWidget. Did you maybe mean setValue()? ( Ignorable by Annotation )

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

301
            $columnLangCode->widget->/** @scrutinizer ignore-call */ 
302
                                     setValuesFromArray($langs, false, true);

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...
302
        }
303
    }
304
305
    protected function setCustomWidgetValues(string $viewName)
306
    {
307
        // Load values option to VAT Type select input
308
        $columnVATType = $this->views[$viewName]->columnForName('vat-regime');
309
        if ($columnVATType && $columnVATType->widget->getType() === 'select') {
310
            $columnVATType->widget->setValuesFromArrayKeys(RegimenIVA::all(), true);
0 ignored issues
show
Bug introduced by
The method setValuesFromArrayKeys() does not exist on FacturaScripts\Core\Lib\Widget\BaseWidget. Did you maybe mean setValue()? ( Ignorable by Annotation )

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

310
            $columnVATType->widget->/** @scrutinizer ignore-call */ 
311
                                    setValuesFromArrayKeys(RegimenIVA::all(), true);

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...
311
        }
312
313
        // Model exists?
314
        if (false === $this->views[$viewName]->model->exists()) {
315
            $this->views[$viewName]->disableColumn('billing-address');
316
            $this->views[$viewName]->disableColumn('shipping-address');
317
            return;
318
        }
319
320
        // Search for client contacts
321
        $codcliente = $this->getViewModelValue($viewName, 'codcliente');
322
        $where = [new DataBaseWhere('codcliente', $codcliente)];
323
        $contacts = $this->codeModel->all('contactos', 'idcontacto', 'descripcion', false, $where);
324
325
        // Load values option to default billing address from client contacts list
326
        $columnBilling = $this->views[$viewName]->columnForName('billing-address');
327
        if ($columnBilling && $columnBilling->widget->getType() === 'select') {
328
            $columnBilling->widget->setValuesFromCodeModel($contacts);
0 ignored issues
show
Bug introduced by
The method setValuesFromCodeModel() does not exist on FacturaScripts\Core\Lib\Widget\BaseWidget. Did you maybe mean setValue()? ( Ignorable by Annotation )

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

328
            $columnBilling->widget->/** @scrutinizer ignore-call */ 
329
                                    setValuesFromCodeModel($contacts);

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...
329
        }
330
331
        // Load values option to default shipping address from client contacts list
332
        $columnShipping = $this->views[$viewName]->columnForName('shipping-address');
333
        if ($columnShipping && $columnShipping->widget->getType() === 'select') {
334
            $contacts2 = $this->codeModel->all('contactos', 'idcontacto', 'descripcion', true, $where);
335
            $columnShipping->widget->setValuesFromCodeModel($contacts2);
336
        }
337
    }
338
}
339