Passed
Push — master ( e40575...c62cbd )
by Joe Nilson
02:27
created

EditFacturaProveedor.js ➔ businessDocViewSave   D

Complexity

Conditions 13

Size

Total Lines 70
Code Lines 55

Duplication

Lines 70
Ratio 100 %

Importance

Changes 0
Metric Value
cc 13
eloc 55
c 0
b 0
f 0
dl 70
loc 70
rs 4.2

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
    $("#btn-document-save").prop("disabled", true);
119
    var infoProveedor = await cargarInfoProveedor();
120
    logConsole(infoProveedor, 'infoProveedor');
121
    var datosProveedor = JSON.parse(infoProveedor);
122
123
    var tipoPago = await cargarTipoPago();
124
    var datosPago = JSON.parse(tipoPago);
125
126
    var tipoNCFs = await cargarTipoNCF('Compras');
127
    logConsole(tipoNCFs, 'tipoNCFs');
128
    var datosTipoNCFs = JSON.parse(tipoNCFs);
129
    let selectTiposNCF = "";
130
    var descInfoProveedorTipoComprobante = '';
131
    var formTipoComprobante = $("#formEditFacturaProveedor select[name=tipocomprobante]").val();
132
    var formNumeroNCF = $("#formEditFacturaProveedor input[name=numproveedor]").val();
133
    var formNumProveedorType = formNumeroNCF.slice(-10,-8);
134
    var tipoComprobanteActivo  = (formTipoComprobante !== '') ? formTipoComprobante : formNumProveedorType;
135
    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 134. 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...
136
    var descDefault = datosTipoNCFs.tipocomprobantes[0].descripcion;
137
    $.each(datosTipoNCFs.tipocomprobantes, function (i, value) {
138
        let defaultSelected = (tipoComprobanteActivo === value.tipocomprobante) ? 'selected' : '';
139
        descInfoProveedorTipoComprobante = (formNumProveedorType === value.tipocomprobante)
140
            ? value.descripcion : descDefault;
141
        selectTiposNCF += '<option value="'+value.tipocomprobante+'"'+defaultSelected+'>'+value.descripcion+'</option>';
142
    });
143
144
    var ncfTipoPagoCliente = $("#formEditFacturaProveedor select[name=ncftipopago]").val();
145
    var readOnlySelects = ($("#formPurchaseDocumentLine #doc_idestado").val() === '11');
146
    var descInfoProveedorTipoPago = '';
147
    let selectOptionsPagos = "";
148
    $.each(datosPago.pagos, function (i, value) {
149
        let defaultSelected = ((value.codigo === '04' && ncfTipoPagoCliente === '') || ncfTipoPagoCliente === value.codigo) ? 'selected' : '';
150
        let noSelected = ($("#formPurchaseDocumentLine #doc_idestado").val() === '11' && defaultSelected !== 'selected') ? ' disabled' : '';
151
        descInfoProveedorTipoPago = (datosProveedor.infoproveedor.ncftipopago === value.codigo)
152
            ? value.descripcion : descInfoProveedorTipoPago;
153
        selectOptionsPagos += '<option value="'+value.codigo+'"'+defaultSelected+noSelected+'>'+value.descripcion+'</option>';
154
    });
155
156
    var tipoMovimiento = await cargarTipoMovimiento();
157
    var datosMovimiento = JSON.parse(tipoMovimiento);
158
159
    let selectOptionsMovimientos = "";
160
    $.each(datosMovimiento.movimientos, function (i, value) {
161
        let defaultSelected = (value.codigo === '09') ? 'selected' : '';
162
        let noSelected = ($("#formPurchaseDocumentLine #doc_idestado").val() === '11' && defaultSelected !== 'selected') ? ' disabled' : '';
163
        selectOptionsMovimientos += '<option value="'+value.codigo+'"'+defaultSelected+noSelected+'>'+value.descripcion+'</option>';
164
    });
165
166
    let message = setBusinessDocViewModalSave(
167
        'Proveedor',
168
        readOnlySelects,
169
        descInfoProveedorTipoComprobante,
170
        descInfoProveedorTipoPago,
171
        selectTiposNCF,
172
        selectOptionsPagos,
173
        selectOptionsMovimientos
174
    );
175
176
    executeModal(
177
        'completeNCFData',
178
        'Complete la información faltante',
179
        message,
180
        'default',
181
        'saveBussinessDocument'
182
    );
183
184
    $("#btn-document-save").prop("disabled", false);
185
}
186