-
Notifications
You must be signed in to change notification settings - Fork 31
/
jsonDeMainValidate.service.ts
2657 lines (2398 loc) · 100 KB
/
jsonDeMainValidate.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import stringUtilService from './StringUtil.service';
import fechaUtilService from './FechaUtil.service';
import constanteService from './constants.service';
import jsonDteItemValidate from './jsonDteItemValidate.service';
import jsonDteTotales from './jsonDteTotales.service';
import { XmlgenConfig } from './type.interface.';
class JSonDeMainValidateService {
errors: Array<string>;
constructor() {
this.errors = new Array<string>();
}
/**
* Valida los datos ingresados en el data
* A. Campos firmados del Documento Electrónico (A001-A099)
* 1 - Validacion automática
* 2 - Se realiza en el SIFEN, pero puede ser realizado en la API de integración
* 3 - Se realiza en el SIFEN, pero puede ser realizado en la API de integración
* 4 - Validacion automática
* 5 - Se realiza en el SIFEN, la fecha/hora del servidor debe sincronizarse con el SIFEN
* 6 - Falta, pero es AO
*
* B. Campos inherentes a la operación comercial de los Documentos Electrónicos (B001 -B099)
* 7 - Falta
* 8 - Validacion automática, via constante.service
*
* C. Campos de datos del Timbrado (C001 - C099)
* 9 - Validacion automática, via constante.service
* 10 - Se realiza en el SIFEN, se valida solo la primera vez
* 11 - Se realiza en el SIFEN, se valida solo la primera vez
* 12 - Se realiza en el SIFEN, se valida solo la primera vez
* 13 - Se realiza en el SIFEN, se valida solo la primera vez
* 14 - Se realiza en el SIFEN, se valida solo la primera vez
* 15 - Se realiza en el SIFEN, se valida solo la primera vez
* 16 - Se realiza en el SIFEN, pero puede ser realizado en la API de integración
*
* @param data
*/
public validateValues(params: any, data: any, config: XmlgenConfig) {
this.errors = new Array<string>();
if (constanteService.tiposDocumentos.filter((um) => um.codigo === data['tipoDocumento']).length == 0) {
this.errors.push("Tipo de Documento '" + data['tipoDocumento']) +
"' en data.tipoDocumento no válido. Valores: " +
constanteService.tiposDocumentos.map((a) => a.codigo + '-' + a.descripcion);
}
if (typeof data['cliente'] == 'undefined') {
this.errors.push('Debe especificar los datos del Cliente en data.cliente');
}
if (data['cliente']) {
if (typeof data['cliente']['contribuyente'] == 'undefined') {
this.errors.push(
'Debe indicar si el Cliente es o no un Contribuyente true|false en data.cliente.contribuyente',
);
}
if (typeof data['cliente']['contribuyente'] == 'undefined') {
this.errors.push(
'Debe indicar si el Cliente es o no un Contribuyente true|false en data.cliente.contribuyente',
);
}
if (!(data['cliente']['contribuyente'] === true || data['cliente']['contribuyente'] === false)) {
this.errors.push('data.cliente.contribuyente debe ser true|false');
}
}
this.generateCodigoControlValidate(params, data);
this.datosEmisorValidate(params, data);
this.generateDatosOperacionValidate(params, data);
this.generateDatosGeneralesValidate(params, data, config);
this.generateDatosEspecificosPorTipoDEValidate(params, data);
if (data['tipoDocumento'] == 4) {
this.generateDatosAutofacturaValidate(params, data);
}
if (data['tipoDocumento'] == 1 || data['tipoDocumento'] == 4) {
this.generateDatosCondicionOperacionDEValidate(params, data);
}
this.errors = jsonDteItemValidate.generateDatosItemsOperacionValidate(params, data, config, this.errors);
this.generateDatosComplementariosComercialesDeUsoEspecificosValidate(params, data);
if (data['tipoDocumento'] == 1 || data['tipoDocumento'] == 7) {
//1 Opcional, 7 Obligatorio
if (data['tipoDocumento'] == 7) {
if (!data['detalleTransporte']) {
this.errors.push('Debe especificar el detalle de tranporte en data.tranporte para el Tipo de Documento = 7');
} else {
this.generateDatosTransporteValidate(params, data);
}
} else {
//Es por que tipoDocumento = 1
if (data['detalleTransporte']) {
this.generateDatosTransporteValidate(params, data);
}
}
}
if (data['tipoDocumento'] != 7) {
this.generateDatosTotalesValidate(params, data, config);
}
if (data['complementarios']) {
this.generateDatosComercialesUsoGeneralValidate(params, data);
}
if (data['moneda'] != 'PYG' && data['condicionTipoCambio'] == 1) {
if (!data['cambio']) {
this.errors.push(
'Debe especificar el valor del Cambio en data.cambio cuando moneda != PYG y la Cotización es Global',
);
}
}
if (data['tipoDocumento'] == 4 || data['tipoDocumento'] == 5 || data['tipoDocumento'] == 6) {
if (!data['documentoAsociado']) {
this.errors.push(
'Documento asociado es obligatorio para el tipo de documento electrónico (' +
data['tipoDocumento'] +
') seleccionado',
);
}
}
if (
data['tipoDocumento'] == 1 ||
data['tipoDocumento'] == 4 ||
data['tipoDocumento'] == 5 ||
data['tipoDocumento'] == 6 ||
data['tipoDocumento'] == 7
) {
if (data['documentoAsociado']) {
if (!Array.isArray(data['documentoAsociado'])) {
this.generateDatosDocumentoAsociadoValidate(params, data['documentoAsociado'], data);
} else {
//Caso sea un array.
for (var i = 0; i < data['documentoAsociado'].length; i++) {
const dataDocumentoAsociado = data['documentoAsociado'][i];
this.generateDatosDocumentoAsociadoValidate(params, dataDocumentoAsociado, data);
}
}
}
}
//Tratamiento Final, del Envio del Error, no tocar
if (this.errors.length > 0) {
let errorExit: any = new Error();
let msgErrorExit = '';
let recorrerHasta = this.errors.length;
if ((config.errorLimit || 3) < recorrerHasta) {
recorrerHasta = config.errorLimit || 3;
}
for (let i = 0; i < recorrerHasta; i++) {
const error = this.errors[i];
msgErrorExit += error;
if (i < recorrerHasta - 1) {
msgErrorExit += config.errorSeparator + '';
}
}
errorExit.message = msgErrorExit;
/*errorExit.firstMessage = this.errors[0];
errorExit.errorsArray = this.errors;*/
throw errorExit;
}
}
generateCodigoControlValidate(params: any, data: any) {
if (data.cdc && (data.cdc + '').length == 44) {
//Caso ya se le pase el CDC
//const codigoSeguridad = data.cdc.substring(34, 43);
const codigoControl = data.cdc;
//Como se va utilizar el CDC enviado como parametro, va a verificar que todos los datos del XML coincidan con el CDC.
const tipoDocumentoCDC = codigoControl.substring(0, 2);
//const rucCDC = this.codigoControl.substring(2, 10);
//const dvCDC = this.codigoControl.substring(10, 11);
const establecimientoCDC = codigoControl.substring(11, 14);
const puntoCDC = codigoControl.substring(14, 17);
const numeroCDC = codigoControl.substring(17, 24);
//const tipoContribuyenteCDC = this.codigoControl.substring(24, 25);
const fechaCDC = codigoControl.substring(25, 33);
const tipoEmisionCDC = codigoControl.substring(33, 34);
if (+data['tipoDocumento'] != +tipoDocumentoCDC) {
this.errors.push(
"El Tipo de Documento '" +
data['tipoDocumento'] +
"' en data.tipoDocumento debe coincidir con el CDC re-utilizado (" +
+tipoDocumentoCDC +
')',
);
}
const establecimiento = stringUtilService.leftZero(data['establecimiento'], 3);
if (establecimiento != establecimientoCDC) {
this.errors.push(
"El Establecimiento '" +
establecimiento +
"'en data.establecimiento debe coincidir con el CDC reutilizado (" +
establecimientoCDC +
')',
);
}
const punto = stringUtilService.leftZero(data['punto'], 3);
if (punto != puntoCDC) {
this.errors.push(
"El Punto '" + punto + "' en data.punto debe coincidir con el CDC reutilizado (" + puntoCDC + ')',
);
}
const numero = stringUtilService.leftZero(data['numero'], 7);
if (numero != numeroCDC) {
this.errors.push(
"El Numero de Documento '" +
numero +
"'en data.numero debe coincidir con el CDC reutilizado (" +
numeroCDC +
')',
);
}
/*if (+data['tipoContribuyente'] != +tipoContribuyenteCDC) {
this.errors.push("El Tipo de Contribuyente '" + data['tipoContribuyente'] + "' en data.tipoContribuyente debe coincidir con el CDC reutilizado (" + tipoContribuyenteCDC + ")");
}*/
const fecha =
(data['fecha'] + '').substring(0, 4) +
(data['fecha'] + '').substring(5, 7) +
(data['fecha'] + '').substring(8, 10);
if (fecha != fechaCDC) {
this.errors.push(
"La fecha '" + fecha + "' en data.fecha debe coincidir con el CDC reutilizado (" + fechaCDC + ')',
);
}
if (+data['tipoEmision'] != +tipoEmisionCDC) {
this.errors.push(
"El Tipo de Emisión '" +
data['tipoEmision'] +
"' en data.tipoEmision debe coincidir con el CDC reutilizado (" +
tipoEmisionCDC +
')',
);
}
}
}
private datosEmisorValidate(params: any, data: any) {
if (params['ruc'].indexOf('-') == -1) {
this.errors.push('RUC debe contener dígito verificador en params.ruc');
}
let rucEmisor = params['ruc'].split('-')[0];
const dvEmisor = params['ruc'].split('-')[1];
var reg = new RegExp(/^\d+$/);
if (!reg.test(rucEmisor)) {
this.errors.push("La parte que corresponde al RUC '" + params['ruc'] + "' en params.ruc debe ser numérico");
}
if (rucEmisor.length > 8) {
this.errors.push(
"La parte que corresponde al RUC '" + params['ruc'] + "' en params.ruc debe contener de 1 a 8 caracteres",
);
}
if (!reg.test(dvEmisor)) {
this.errors.push(
"La parte que corresponde al DV del RUC '" + params['ruc'] + "' en params.ruc debe ser numérico",
);
}
if (dvEmisor > 9) {
this.errors.push(
"La parte que corresponde al DV del RUC '" + params['ruc'] + "' en params.ruc debe ser del 1 al 9",
);
}
if (!((params['timbradoNumero'] + '').length == 8)) {
this.errors.push('Debe especificar un Timbrado de 8 caracteres en params.timbradoNumero');
}
if (!fechaUtilService.isIsoDate(params['timbradoFecha'])) {
this.errors.push(
"Valor de la Fecha '" + params['timbradoFecha'] + "' en params.fecha no válido. Formato: yyyy-MM-dd",
);
}
if (params['tipoRegimen']) {
if (constanteService.tiposRegimenes.filter((um) => um.codigo === params['tipoRegimen']).length == 0) {
this.errors.push(
"Tipo de Regimen '" +
data['tipoRegimen'] +
"' en params.tipoRegimen no válido. Valores: " +
constanteService.tiposRegimenes.map((a) => a.codigo + '-' + a.descripcion),
);
}
}
if (!params['razonSocial']) {
this.errors.push('La razon social del emisor en params.razonSocial no puede ser vacio');
} else {
if (!((params['razonSocial'] + '').length >= 4 && (params['razonSocial'] + '').length <= 250)) {
this.errors.push(
"La razon Social del Emisor '" +
params['razonSocial'] +
"' en params.razonSocial debe tener de 4 a 250 caracteres",
);
}
}
if (params['nombreFantasia'] && (params['nombreFantasia'] + '').length > 0) {
if (!((params['nombreFantasia'] + '').length >= 4 && (params['nombreFantasia'] + '').length <= 250)) {
this.errors.push(
"El nombre de Fantasia del Emisor '" +
params['nombreFantasia'] +
"' en params.nombreFantasia debe tener de 4 a 250 caracteres",
);
}
}
//Aqui hay que verificar los datos de las sucursales
if (!(params['establecimientos'] && Array.isArray(params['establecimientos']))) {
this.errors.push('Debe especificar un array de establecimientos en params.establecimientos');
} else {
for (let i = 0; i < params['establecimientos'].length; i++) {
const establecimiento = params['establecimientos'][i];
if (!establecimiento.codigo) {
this.errors.push(
'Debe especificar el código del establecimiento en params.establecimientos[' + i + '].codigo',
);
}
}
}
}
private generateDatosOperacionValidate(params: any, data: any) {
/*if (params['ruc'].indexOf('-') == -1) { //removido temporalmente, parece que no hace falta
this.errors.push('RUC debe contener dígito verificador en params.ruc');
}*/
if (constanteService.tiposEmisiones.filter((um) => um.codigo === data['tipoEmision']).length == 0) {
this.errors.push(
"Tipo de Emisión '" +
data['tipoEmision'] +
"' en data.tipoEmision no válido. Valores: " +
constanteService.tiposEmisiones.map((a) => a.codigo + '-' + a.descripcion),
);
}
//Validar aqui "dInfoFisc"
if (data['tipoDocumento'] == 7) {
//Nota de Remision
if (!(data['descripcion'] && (data['descripcion'] + '').trim().length > 0)) {
this.errors.push('Debe informar la Descripción en data.descripcion para el Documento Electrónico');
}
}
}
private generateDatosGeneralesValidate(params: any, data: any, config: XmlgenConfig) {
this.generateDatosGeneralesInherentesOperacionValidate(params, data);
this.generateDatosGeneralesEmisorDEValidate(params, data);
if (config.userObjectRemove == false) {
//Si está TRUE no crea el objeto usuario
if (data['usuario']) {
//No es obligatorio
this.generateDatosGeneralesResponsableGeneracionDEValidate(params, data);
}
}
this.generateDatosGeneralesReceptorDEValidate(params, data);
}
private generateDatosGeneralesInherentesOperacionValidate(params: any, data: any) {
if (data['tipoDocumento'] == 7) {
//C002
return; //No informa si el tipo de documento es 7
}
if (!fechaUtilService.isIsoDateTime(data['fecha'])) {
this.errors.push(
"Valor de la Fecha '" + data['fecha'] + "' en data.fecha no válido. Formato: yyyy-MM-ddTHH:mm:ss",
);
}
if (!data['tipoImpuesto']) {
this.errors.push('Debe especificar el Tipo de Impuesto en data.tipoImpuesto');
} else {
if (constanteService.tiposImpuestos.filter((um) => um.codigo === data['tipoImpuesto']).length == 0) {
this.errors.push(
"Tipo de Impuesto '" +
data['tipoImpuesto'] +
"' en data.tipoImpuesto no válido. Valores: " +
constanteService.tiposImpuestos.map((a) => a.codigo + '-' + a.descripcion),
);
}
}
let moneda = data['moneda'];
if (!moneda) {
moneda = 'PYG';
}
if (constanteService.monedas.filter((um) => um.codigo === moneda).length == 0) {
this.errors.push(
"Moneda '" +
moneda +
"' en data.moneda no válido. Valores: " +
constanteService.monedas.map((a) => a.codigo + '-' + a.descripcion),
);
}
if (data['condicionAnticipo']) {
if (constanteService.globalPorItem.filter((um) => um.codigo === data['condicionAnticipo']).length == 0) {
this.errors.push(
"Condición de Anticipo '" +
data['condicionAnticipo'] +
"' en data.condicionAnticipo no válido. Valores: " +
constanteService.globalPorItem.map((a) => a.codigo + '-Anticipo ' + a.descripcion),
);
}
} else {
//condicionAnticipo - si no tiene condicion anticipo, pero tipo transaccion es 9, que de un error.
}
if (constanteService.tiposTransacciones.filter((um) => um.codigo === data['tipoTransaccion']).length == 0) {
this.errors.push(
"Tipo de Transacción '" +
data['tipoTransaccion'] +
"' en data.tipoTransaccion no válido. Valores: " +
constanteService.tiposTransacciones.map((a) => a.codigo + '-' + a.descripcion),
);
}
if (data['tipoDocumento'] == 1 || data['tipoDocumento'] == 4) {
//Obligatorio informar iTipTra D011
if (!data['tipoTransaccion']) {
this.errors.push('Debe proveer el Tipo de Transacción en data.tipoTransaccion');
}
}
if (moneda != 'PYG') {
if (!data['condicionTipoCambio']) {
this.errors.push('Debe informar el tipo de Cambio en data.condicionTipoCambio');
}
}
if (data['condicionTipoCambio'] == 1 && moneda != 'PYG') {
if (!(data['cambio'] && data['cambio'] > 0)) {
this.errors.push('Debe informar el valor del Cambio en data.cambio');
}
}
}
private generateDatosGeneralesEmisorDEValidate(params: any, data: any) {
var regExpOnlyNumber = new RegExp(/^\d+$/);
if (!(params && params.establecimientos)) {
this.errors.push('Debe proveer un Array con la información de los establecimientos en params');
}
//Validar si el establecimiento viene en params
let establecimiento = stringUtilService.leftZero(data['establecimiento'], 3);
//let punto = stringUtilService.leftZero(data['punto'], 3);
if (params.establecimientos.filter((um: any) => um.codigo === establecimiento).length == 0) {
this.errors.push(
"Establecimiento '" +
establecimiento +
"' no encontrado en params.establecimientos*.codigo. Valores: " +
params.establecimientos.map((a: any) => a.codigo + '-' + a.denominacion),
);
}
/*if (params['ruc'].indexOf('-') == -1) { //Removido temporalmente, al parecer no hace falta
this.errors.push('RUC debe contener dígito verificador en params.ruc');
}*/
if (!(params['actividadesEconomicas'] && params['actividadesEconomicas'].length > 0)) {
this.errors.push('Debe proveer el array de actividades económicas en params.actividadesEconomicas');
}
//Validacion de algunos datos de la sucursal
const establecimientoUsado = params['establecimientos'].filter((e: any) => e.codigo === establecimiento)[0];
if (!establecimientoUsado) {
this.errors.push(
'Debe especificar los datos del Establecimiento "' + establecimiento + '" en params.establecimientos*',
);
} else {
if (!establecimientoUsado.ciudad) {
this.errors.push('Debe proveer la Ciudad del establecimiento en params.establecimientos*.ciudad');
}
if (!establecimientoUsado.distrito) {
this.errors.push('Debe proveer la Distrito del establecimiento en params.establecimientos*.distrito');
}
if (!establecimientoUsado.departamento) {
this.errors.push('Debe proveer la Departamento del establecimiento en params.establecimientos*.departamento');
}
constanteService.validateDepartamentoDistritoCiudad(
'params.establecimientos*',
+establecimientoUsado.departamento,
+establecimientoUsado.distrito,
+establecimientoUsado.ciudad,
this.errors,
);
if (establecimientoUsado['numeroCasa']) {
if (!regExpOnlyNumber.test(establecimientoUsado['numeroCasa'])) {
this.errors.push('El Número de Casa en params.establecimientos*.numeroCasa debe ser numérico');
}
}
}
}
private generateDatosGeneralesResponsableGeneracionDEValidate(params: any, data: any) {
if (
constanteService.tiposDocumentosIdentidades.filter((um: any) => um.codigo === +data['usuario']['documentoTipo'])
.length == 0
) {
this.errors.push(
"Tipo de Documento '" +
data['usuario']['documentoTipo'] +
"' no encontrado en data.usuario.documentoTipo. Valores: " +
constanteService.tiposDocumentosIdentidades.map((a: any) => a.codigo + '-' + a.descripcion),
);
}
if (!data['usuario']['documentoNumero']) {
this.errors.push('El Documento del Responsable en data.usuario.documentoNumero no puede ser vacio');
}
if (!data['usuario']['nombre']) {
this.errors.push('El Nombre del Responsable en data.usuario.nombre no puede ser vacio');
}
if (!data['usuario']['cargo']) {
this.errors.push('El Cargo del Responsable en data.usuario.cargo no puede ser vacio');
}
}
private generateDatosGeneralesReceptorDEValidate(params: any, data: any) {
if (!data['cliente']) {
return; //El error de cliente vacio, ya fue validado arriba
}
if (!data['cliente']['tipoOperacion']) {
this.errors.push('Tipo de Operación del Cliente en data.cliente.tipoOperacion es requerido > 0');
} else {
if (
constanteService.tiposOperaciones.filter((um: any) => um.codigo === +data['cliente']['tipoOperacion']).length ==
0
) {
this.errors.push(
"Tipo de Operación '" +
data['cliente']['tipoOperacion'] +
"' del Cliente en data.cliente.tipoOperacion no encontrado. Valores: " +
constanteService.tiposOperaciones.map((a: any) => a.codigo + '-' + a.descripcion),
);
}
}
if (!data['cliente']['contribuyente'] && data['cliente']['tipoOperacion'] != 4) {
if (
constanteService.tiposDocumentosReceptor.filter((um: any) => um.codigo === +data['cliente']['documentoTipo'])
.length == 0
) {
this.errors.push(
"Tipo de Documento '" +
data['cliente']['documentoTipo'] +
"' del Cliente en data.cliente.documentoTipo no encontrado. Valores: " +
constanteService.tiposDocumentosReceptor.map((a: any) => a.codigo + '-' + a.descripcion),
);
if (+data['cliente']['documentoTipo'] == 9) {
if (!data['cliente']['documentoTipoDescripcion']) {
this.errors.push(
'Debe especificar la Descripción para el tipo de Documento en data.cliente.documentoTipoDescripcion para documentoTipo=9',
);
}
}
}
}
var regExpOnlyNumber = new RegExp(/^\d+$/);
if (data['cliente']['contribuyente']) {
if (!data['cliente']['ruc']) {
this.errors.push('Debe proporcionar el RUC en data.cliente.ruc');
} else {
if (data['cliente']['ruc'].indexOf('-') == -1) {
this.errors.push('RUC debe contener dígito verificador en data.cliente.ruc');
}
const rucCliente = data['cliente']['ruc'].split('-');
//Un RUC puede ser alphanumerico
/*if (!regExpOnlyNumber.test((rucCliente[0] + '').trim())) {
this.errors.push(
"La parte del RUC del Cliente '" + data['cliente']['ruc'] + "' en data.cliente.ruc debe ser numérico",
);
}*/
if (!regExpOnlyNumber.test((rucCliente[1] + '').trim())) {
this.errors.push(
"La parte del DV del RUC del Cliente '" +
data['cliente']['ruc'] +
"' en data.cliente.ruc debe ser numérico",
);
}
if (!(rucCliente[0].length >= 3 && rucCliente[0].length <= 8)) {
this.errors.push(
"La parte del RUC '" + data['cliente']['ruc'] + "' en data.cliente.ruc debe contener de 3 a 8 caracteres",
);
}
if (rucCliente[1] > 9) {
this.errors.push(
"La parte del DV del RUC '" + data['cliente']['ruc'] + "' en data.cliente.ruc debe ser del 1 al 9",
);
}
}
if (!data['cliente']['tipoContribuyente']) {
this.errors.push('Debe proporcionar el Tipo de Contribuyente en data.cliente.tipoContribuyente');
}
}
if (!data['cliente']['razonSocial']) {
this.errors.push('La razon social del receptor en data.cliente.razonSocial no puede ser vacio');
} else {
if (!((data['cliente']['razonSocial'] + '').length >= 4 && (data['cliente']['razonSocial'] + '').length <= 250)) {
this.errors.push(
"La razon Social del Cliente '" +
data['cliente']['razonSocial'] +
"' en data.cliente.razonSocial debe tener de 4 a 250 caracteres",
);
}
}
if (data['cliente']['nombreFantasia'] && (data['cliente']['nombreFantasia'] + '').length > 0) {
if (
!(
(data['cliente']['nombreFantasia'] + '').length >= 4 && (data['cliente']['nombreFantasia'] + '').length <= 250
)
) {
this.errors.push(
"El nombre de Fantasia del Cliente '" +
data['cliente']['nombreFantasia'] +
"' en data.cliente.nombreFantasia debe tener de 4 a 250 caracteres",
);
}
}
if (constanteService.paises.filter((pais: any) => pais.codigo === data['cliente']['pais']).length == 0) {
this.errors.push(
"Pais '" +
data['cliente']['pais'] +
"' del Cliente en data.cliente.pais no encontrado. Valores: " +
constanteService.paises.map((a: any) => a.codigo + '-' + a.descripcion),
);
}
if (data['tipoDocumento'] == 4) {
if (data['cliente']['tipoOperacion'] != 2) {
this.errors.push('El Tipo de Operación debe ser 2-B2C para el Tipo de Documento AutoFactura');
}
}
if (!data['cliente']['contribuyente'] && data['cliente']['tipoOperacion']) {
//No es contribuyente
//Obligatorio completar D210
if (!data['cliente']['contribuyente'] && data['cliente']['tipoOperacion'] != 4) {
if (!data['cliente']['documentoTipo']) {
//Val.: 59
this.errors.push('Debe informar el Tipo de Documento del Cliente en data.cliente.documentoTipo');
}
//Cuando el campo puede ser un número, y se admite el valor cero, mejor preguntar de ésta forma
if (typeof data['cliente']['documentoNumero'] == 'undefined') {
//Val.: 65
this.errors.push('Debe informar el número de documento en data.cliente.documentoNumero');
} else {
//Validar que documentoNumero no tenga .
if ((data['cliente']['documentoNumero'] + '').indexOf('.') > -1) {
this.errors.push(
'El valor "' + data['cliente']['documentoNumero'] + '" en data.cliente.documentoNumero no es válido ',
);
}
//Validar que documentoNumero no tenga /
if ((data['cliente']['documentoNumero'] + '').indexOf('/') > -1) {
this.errors.push(
'El valor "' + data['cliente']['documentoNumero'] + '" en data.cliente.documentoNumero no es válido ',
);
}
}
}
}
if (
!data['cliente']['contribuyente'] &&
data['tipoDocumento'] != 4 &&
data['cliente']['tipoOperacion'] != 2 &&
data['cliente']['tipoOperacion'] != 4
) {
//Val.: 46. parrafo 1
this.errors.push('El tipo de Operación debe ser 2-B2C o 4-B2F para el Receptor "No Contribuyente"');
}
if (data['cliente']['tipoOperacion'] == 4 && data['cliente']['contribuyente'] == true) {
//Val.: 46. parrafo 2
this.errors.push('La naturaleza del Receptor debe ser "No contribuyente" para el Tipo de Operación = 4-B2F');
}
//Temporal Mercosys
/*if (data['tipoDocumento'] === 7 || data['cliente']['tipoOperacion'] === 4) {
if (!data['cliente']['direccion']) {
this.errors.push('data.cliente.direccion es Obligatorio para Tipo de Documento 7 o Tipo de Operación 4');
}
}*/
if (data['tipoDocumento'] === 7) {
if (!data['cliente']['direccion']) {
this.errors.push('data.cliente.direccion es Obligatorio para Tipo de Documento 7');
}
}
if (data['cliente']['direccion']) {
//Si tiene dirección hay que completar numero de casa.
if (
!(
(data['cliente']['direccion'] + '').trim().length >= 1 &&
(data['cliente']['direccion'] + '').trim().length <= 255
)
) {
this.errors.push(
"La dirección del Receptor '" +
data['cliente']['direccion'] +
"' en data.cliente.direccion debe tener de 1 a 255 caracteres",
);
}
if (data['cliente']['numeroCasa'] == null) {
this.errors.push('Debe informar el Número de casa del Receptor en data.cliente.numeroCasa');
}
if (!((data['cliente']['numeroCasa'] + '').length > 0)) {
this.errors.push('Debe informar el Número de casa del Receptor en data.cliente.numeroCasa');
}
}
if (data['cliente']['numeroCasa']) {
if (!regExpOnlyNumber.test(data['cliente']['numeroCasa'])) {
this.errors.push('El Número de Casa en data.cliente.numeroCasa debe ser numérico');
}
}
if (data['cliente']['direccion'] && data['cliente']['tipoOperacion'] != 4) {
if (!data['cliente']['ciudad']) {
this.errors.push('Obligatorio especificar la Ciudad en data.cliente.ciudad para Tipo de Documento != 4');
} else {
if (
constanteService.ciudades.filter((ciudad: any) => ciudad.codigo === +data['cliente']['ciudad']).length == 0
) {
this.errors.push(
"Ciudad '" +
data['cliente']['ciudad'] +
"' del Cliente en data.cliente.ciudad no encontrado. Valores: " +
constanteService.ciudades.map((a: any) => a.codigo + '-' + a.descripcion),
);
}
//De acuerdo a la Ciudad pasada como parametro, buscar el distrito y departamento y asignar dichos
//valores de forma predeterminada, auque este valor sera sobre-escrito, caso el usuario envie
//data['cliente']['distrito'] y data['cliente']['departamento']
let objCiudad: any = constanteService.ciudades.filter((ciu) => ciu.codigo === +data['cliente']['ciudad']);
if (objCiudad && objCiudad[0]) {
let objDistrito: any = constanteService.distritos.filter((dis) => dis.codigo === +objCiudad[0]['distrito']);
let objDepartamento: any = constanteService.departamentos.filter(
(dep) => dep.codigo === +objDistrito[0]['departamento'],
);
data['cliente']['distrito'] = objDistrito[0]['codigo'];
data['cliente']['departamento'] = objDepartamento[0]['codigo'];
}
}
if (data['cliente']['direccion'] && data['cliente']['tipoOperacion'] != 4) {
if (!data['cliente']['distrito']) {
this.errors.push('Obligatorio especificar el Distrito en data.cliente.distrito para Tipo de Documento != 4');
}
if (
constanteService.distritos.filter((distrito: any) => distrito.codigo === +data['cliente']['distrito'])
.length == 0
) {
this.errors.push(
"Distrito '" +
data['cliente']['distrito'] +
"' del Cliente en data.cliente.distrito no encontrado. Valores: " +
constanteService.distritos.map((a: any) => a.codigo + '-' + a.descripcion),
);
}
}
if (data['cliente']['direccion'] && data['cliente']['tipoOperacion'] != 4) {
if (!data['cliente']['departamento']) {
this.errors.push(
'Obligatorio especificar el Departamento en data.cliente.departamento para Tipo de Documento != 4',
);
}
if (
constanteService.departamentos.filter(
(departamento: any) => departamento.codigo === +data['cliente']['departamento'],
).length == 0
) {
this.errors.push(
"Departamento '" +
data['cliente']['departamento'] +
"' del Cliente en data.cliente.departamento no encontrado. Valores: " +
constanteService.departamentos.map((a: any) => a.codigo + '-' + a.descripcion),
);
}
}
if (data['cliente']['tipoOperacion'] == 4) {
if (data['cliente']['pais'] == 'PRY') {
this.errors.push('El tipo de Operación = 4-B2F requiere un pais diferente a PRY');
}
}
}
constanteService.validateDepartamentoDistritoCiudad(
'data.cliente',
+data['cliente']['departamento'],
+data['cliente']['distrito'],
+data['cliente']['ciudad'],
this.errors,
);
if (data['cliente']['telefono']) {
if (!(data['cliente']['telefono'].length >= 6 && data['cliente']['telefono'].length <= 15)) {
this.errors.push(
"El valor '" +
data['cliente']['telefono'] +
"' en data.cliente.telefono debe tener una longitud de 6 a 15 caracteres",
);
}
}
if (data['cliente']['celular']) {
if (!(data['cliente']['celular'].length >= 10 && data['cliente']['celular'].length <= 20)) {
this.errors.push(
"El valor '" +
data['cliente']['celular'] +
"' en data.cliente.celular debe tener una longitud de 10 a 20 caracteres",
);
}
}
if (data['cliente']['email']) {
let email = new String(data['cliente']['email']); //Hace una copia, para no alterar.
//Verificar si tiene varios correos.
if (email.indexOf(',') > -1) {
//Si el Email tiene , (coma) entonces va enviar solo el primer valor, ya que la SET no acepta Comas
email = email.split(',')[0].trim();
}
//Verificar espacios
if (email.indexOf(' ') > -1) {
this.errors.push("El valor '" + email + "' en data.cliente.email no puede poseer espacios");
}
if (!(email.length >= 3 && email.length <= 80)) {
this.errors.push("El valor '" + email + "' en data.cliente.email debe tener una longitud de 3 a 80 caracteres");
}
//se valida el mail
var regExEmail = new RegExp(/^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$/gm);
if (!regExEmail.test(email + '')) {
this.errors.push("El valor '" + email + "' en data.cliente.email es inválido");
}
}
if (data['cliente']['codigo']) {
if (!((data['cliente']['codigo'] + '').length >= 3 && (data['cliente']['codigo'] + '').length <= 15)) {
this.errors.push(
"El código del Cliente '" +
data['cliente']['codigo'] +
"' en data.cliente.codigo debe tener de 3 a 15 caracteres",
);
}
}
}
private generateDatosEspecificosPorTipoDEValidate(params: any, data: any) {
if (data['tipoDocumento'] === 1) {
this.generateDatosEspecificosPorTipoDE_FacturaElectronicaValidate(params, data);
}
if (data['tipoDocumento'] === 4) {
this.generateDatosEspecificosPorTipoDE_AutofacturaValidate(params, data);
}
if (data['tipoDocumento'] === 5 || data['tipoDocumento'] === 6) {
this.generateDatosEspecificosPorTipoDE_NotaCreditoDebitoValidate(params, data);
}
if (data['tipoDocumento'] === 7) {
this.generateDatosEspecificosPorTipoDE_RemisionElectronicaValidate(params, data);
}
}
private generateDatosEspecificosPorTipoDE_FacturaElectronicaValidate(params: any, data: any) {
if (!data['factura']) {
this.errors.push('Debe indicar los datos especificos de la Factura en data.factura');
return; // Termina el metodos
}
if (
constanteService.indicadoresPresencias.filter((um: any) => um.codigo === data['factura']['presencia']).length == 0
) {
this.errors.push(
"Indicador de Presencia '" +
data['factura']['presencia'] +
"' en data.factura.presencia no encontrado. Valores: " +
constanteService.indicadoresPresencias.map((a: any) => a.codigo + '-' + a.descripcion),
);
}
if (data['factura']['fechaEnvio']) {
let fechaFactura = new Date(data['fecha']);
let fechaEnvio = new Date(data['factura']['fechaEnvio']);
if (fechaFactura.getTime() > fechaEnvio.getTime()) {
this.errors.push(
"La Fecha de envío '" +
data['factura']['fechaEnvio'] +
"'en data.factura.fechaEnvio, debe ser despues de la fecha de Factura",
);
}
}
if (data['cliente']['tipoOperacion'] === 3) {
this.generateDatosEspecificosPorTipoDE_ComprasPublicasValidate(params, data);
}
}
/**
* Datos especificos cuando el tipo de operacion del receptor es B2G (Campo D202)
* Dentro de la factura electronica
*
* @param params
* @param data
* @param options
*/
private generateDatosEspecificosPorTipoDE_ComprasPublicasValidate(params: any, data: any) {
if (!(data['dncp'] && data['dncp']['modalidad'] && data['dncp']['modalidad'].length > 0)) {
this.errors.push('Debe informar la modalidad de Contratación DNCP en data.dncp.modalidad');
}
if (!(data['dncp'] && data['dncp']['entidad'] && data['dncp']['entidad'].length > 0)) {
this.errors.push('Debe informar la entidad de Contratación DNCP en data.dncp.entidad');
}
if (!(data['dncp'] && data['dncp']['año'] && data['dncp']['año'].length > 0)) {
this.errors.push('Debe informar la año de Contratación DNCP en data.dncp.año');
}
if (!(data['dncp'] && data['dncp']['secuencia'] && data['dncp']['secuencia'].length > 0)) {
this.errors.push('Debe informar la secuencia de Contratación DNCP en data.dncp.secuencia');
}
if (!(data['dncp'] && data['dncp']['fecha'] && data['dncp']['fecha'].length > 0)) {
this.errors.push('Debe informar la fecha de emisión de código de Contratación DNCP en data.dncp.fecha');
}
}
private generateDatosEspecificosPorTipoDE_AutofacturaValidate(params: any, data: any) {
if (!data['autoFactura']) {
this.errors.push('Para tipoDocumento = 4 debe proveer los datos de Autofactura en data.autoFactura');
}
if (!data['autoFactura']['ubicacion']) {
this.errors.push(
'Para tipoDocumento = 4 debe proveer los datos del Lugar de Transacción de la Autofactura en data.autoFactura.ubicacion',