Passed
Push — master ( 88ea97...aa75e3 )
by Joe Nilson
02:36
created

EditFacturaProveedor.js ➔ businessDocViewSave   F

Complexity

Conditions 14

Size

Total Lines 74
Code Lines 58

Duplication

Lines 74
Ratio 100 %

Importance

Changes 0
Metric Value
cc 14
eloc 58
c 0
b 0
f 0
dl 74
loc 74
rs 3.6

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:

Complexity

Complex classes like EditFacturaProveedor.js ➔ businessDocViewSave often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/*
2
 * Copyright (C) 2021 Joe Nilson <[email protected]>
3
 *
4
 * This program is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU Lesser General Public License as
6
 * published by the Free Software Foundation, either version 3 of the
7
 * License, or (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 * You should have received a copy of the GNU Lesser General Public License
14
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
 */
16 View Code Duplication
function businessDocViewSubjectChanged()
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
17
{
18
    var data = {};
19
    $.each($("#" + businessDocViewFormName).serializeArray(), function (key, value) {
0 ignored issues
show
Bug introduced by
The variable businessDocViewFormName seems to be never declared. If this is a global, consider adding a /** global: businessDocViewFormName */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
20
        data[value.name] = value.value;
21
    });
22
    data.action = "subject-changed";
23
    logConsole(data, "subject-changed");
24
25
    $.ajax({
26
        type: "POST",
27
        url: businessDocViewUrl,
0 ignored issues
show
Bug introduced by
The variable businessDocViewUrl seems to be never declared. If this is a global, consider adding a /** global: businessDocViewUrl */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
28
        dataType: "json",
29
        data: data,
30
        success: function (results) {
31
            $("#doc_codpago").val(results.codpago);
32
            $("#doc_codserie").val(results.codserie);
33
            $("#formEditFacturaProveedor select[name=ncftipopago]").val(results.ncftipopago);
34
35
            /**
36
             * Review the doc_codsubtipodoc existence,
37
             * if it exist we put the value from the customer data
38
             */
39
            if ($("#doc_codsubtipodoc").length !== 0) {
40
                $("#doc_codsubtipodoc").val(results.codsubtipodoc);
41
            }
42
            logConsole(results.codsubtipodoc,"codsubtipodoc");
43
            /**
44
             * Review the doc_codopersaciondoc existence,
45
             * if it exist we put the value from the customer data
46
             */
47
            if ($("#doc_codoperaciondoc").length !== 0) {
48
                $("#doc_codoperaciondoc").val(results.codoperaciondoc);
49
            }
50
            logConsole(results.codoperaciondoc,"codoperaciondoc");
51
52
            logConsole(results,"results");
53
54
            businessDocViewRecalculate();
55
        },
56
        error: function (xhr, status, error) {
0 ignored issues
show
Unused Code introduced by
The parameter status is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter error is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
57
            alert(xhr.responseText);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
58
        }
59
    });
60
}
61
62
async function cargarInfoProveedor()
63
{
64
    return $.ajax({
65
        url: 'ListNCFTipo',
66
        async: true,
67
        data: {'action': 'busca_infoproveedor', 'codproveedor': $("#codproveedorAutocomplete").val()},
68
        type: 'POST',
69
        datatype: 'json',
70
        success: function (response) {
71
            let data = JSON.parse(response);
72
            return data;
73
        },
74
        error: function (xhr, status) {
75
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
76
        }
77
    });
78
}
79
80
async function cargarTipoPago()
81
{
82
    return $.ajax({
83
        url: 'ListNCFTipoPago',
84
        async: true,
85
        data: {'action': 'busca_pago', 'tipopago': '02'},
86
        type: 'POST',
87
        datatype: 'json',
88
        success: function (response) {
89
            let data = JSON.parse(response);
90
            return data;
91
        },
92
        error: function (xhr, status) {
93
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
94
        }
95
    });
96
}
97
98
async function cargarTipoMovimiento()
99
{
100
    return $.ajax({
101
        url: 'ListNCFTipoMovimiento',
102
        async: true,
103
        data: {'action': 'busca_movimiento', 'tipomovimiento': 'COM'},
104
        type: 'POST',
105
        datatype: 'json',
106
        success: function (response) {
107
            let data = JSON.parse(response);
108
            return data;
109
        },
110
        error: function (xhr, status) {
111
            alert('Ha ocurrido algún tipo de error ' + status);
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
112
        }
113
    });
114
}
115
116
async function businessDocViewSave()
117
{
118
    if ($("#codproveedorAutocomplete").val() === '') {
119
        executeModal('errorNoProveedorDetectado','No hay Proveedor','Debe seleccionar un proveedor primero!', 'warning', '');
120
    } else {
121
        $("#btn-document-save").prop("disabled", true);
122
        var infoProveedor = await cargarInfoProveedor();
123
        logConsole(infoProveedor, 'infoProveedor');
124
        var datosProveedor = JSON.parse(infoProveedor);
125
126
        var tipoPago = await cargarTipoPago();
127
        var datosPago = JSON.parse(tipoPago);
128
129
        var tipoNCFs = await cargarTipoNCF('Compras');
130
        logConsole(tipoNCFs, 'tipoNCFs');
131
        var datosTipoNCFs = JSON.parse(tipoNCFs);
132
        let selectTiposNCF = "";
133
        var descInfoProveedorTipoComprobante = '';
134
        var formTipoComprobante = $("#formEditFacturaProveedor select[name=tipocomprobante]").val();
135
        var formNumeroNCF = $("#formEditFacturaProveedor input[name=numproveedor]").val();
136
        var formNumProveedorType = formNumeroNCF.slice(-10, -8);
137
        var tipoComprobanteActivo = (formTipoComprobante !== '') ? formTipoComprobante : formNumProveedorType;
138
        var tipoComprobanteActivo = (tipoComprobanteActivo === '') ? '01' : tipoComprobanteActivo;
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable tipoComprobanteActivo already seems to be declared on line 137. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
139
        var descDefault = datosTipoNCFs.tipocomprobantes[0].descripcion;
140
        $.each(datosTipoNCFs.tipocomprobantes, function (i, value) {
141
            let defaultSelected = (tipoComprobanteActivo === value.tipocomprobante) ? 'selected' : '';
142
            descInfoProveedorTipoComprobante = (formNumProveedorType === value.tipocomprobante)
143
                ? value.descripcion : descDefault;
144
            selectTiposNCF += '<option value="' + value.tipocomprobante + '"' + defaultSelected + '>' + value.descripcion + '</option>';
145
        });
146
147
        var ncfTipoPagoCliente = $("#formEditFacturaProveedor select[name=ncftipopago]").val();
148
        var readOnlySelects = ($("#formPurchaseDocumentLine #doc_idestado").val() === '11');
149
        var descInfoProveedorTipoPago = '';
150
        let selectOptionsPagos = "";
151
        $.each(datosPago.pagos, function (i, value) {
152
            let defaultSelected = ((value.codigo === '04' && ncfTipoPagoCliente === '') || ncfTipoPagoCliente === value.codigo) ? 'selected' : '';
153
            let noSelected = ($("#formPurchaseDocumentLine #doc_idestado").val() === '11' && defaultSelected !== 'selected') ? ' disabled' : '';
154
            descInfoProveedorTipoPago = (datosProveedor.infoproveedor.ncftipopago === value.codigo)
155
                ? value.descripcion : descInfoProveedorTipoPago;
156
            selectOptionsPagos += '<option value="' + value.codigo + '"' + defaultSelected + noSelected + '>' + value.descripcion + '</option>';
157
        });
158
159
        var tipoMovimiento = await cargarTipoMovimiento();
160
        var datosMovimiento = JSON.parse(tipoMovimiento);
161
162
        let selectOptionsMovimientos = "";
163
        $.each(datosMovimiento.movimientos, function (i, value) {
164
            let defaultSelected = (value.codigo === '09') ? 'selected' : '';
165
            let noSelected = ($("#formPurchaseDocumentLine #doc_idestado").val() === '11' && defaultSelected !== 'selected') ? ' disabled' : '';
166
            selectOptionsMovimientos += '<option value="' + value.codigo + '"' + defaultSelected + noSelected + '>' + value.descripcion + '</option>';
167
        });
168
169
        let message = setBusinessDocViewModalSave(
170
            'Proveedor',
171
            readOnlySelects,
172
            descInfoProveedorTipoComprobante,
173
            descInfoProveedorTipoPago,
174
            selectTiposNCF,
175
            selectOptionsPagos,
176
            selectOptionsMovimientos
177
        );
178
179
        executeModal(
180
            'completeNCFData',
181
            'Complete la información faltante',
182
            message,
183
            'default',
184
            'saveBussinessDocument'
185
        );
186
187
        $("#btn-document-save").prop("disabled", false);
188
    }
189
}
190