Ejemplo n.º 1
0
        //


        private Document InsertDocument(documentDTO new_document)
        {
            var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
            var sid      = identity.Claims.Where(c => c.Type == ClaimTypes.Sid)
                           .Select(c => c.Value).SingleOrDefault();

            return(_iserviceDocument.InsertNewDocument(new_document, User.Identity.Name, sid));
        }
 public void ResetAllValues()
 {
     _typeDocument       = null;
     _maskedDocumentDTO  = null;
     _purcharseOrder     = null;
     _enterpriseClient   = null;
     _enterpriseProvider = null;
 }
Ejemplo n.º 3
0
 public Document ObtenerMapperDocument(documentDTO documentDTO)
 {
     try
     {
         var new_documento = _mapper.Map <documento>(documentDTO);
         return(_mapper.Map <Document>(new_documento));
     }
     catch (Exception err)
     {
         throw err;
     }
 }
Ejemplo n.º 4
0
        public ActionResult insertDTObyXML([FromBody] documentDTO newDocument)
        {
            _iDocumentValidatorService.setDocument(newDocument);
            ValDocuments valDoc = new ValDocuments(_iDocumentValidatorService);

            var errores = valDoc.verificador();

            if (errores.Count() == 0)
            {
                newDocument = _iDocumentValidatorService.getMaskedDocument();
                _iserviceDocument.InsertNewDocument(newDocument, "", "By Email");
                return(Ok(newDocument));
            }
            else
            {
                _iserviceDocument.InsertErrorDocument(newDocument, errores);
                return(BadRequest(new { errors = errores }));
            }
        }
Ejemplo n.º 5
0
 public Document InsertNewDocument(documentDTO documentDTO, string ruc_supplier, string user_supplier)
 {
     try
     {
         var new_documento = _mapper.Map <documento>(documentDTO);
         new_documento.usuario_modificacion = user_supplier;
         new_documento.usuario_verificacion = user_supplier;
         //_dbContext.documento.Add(new_documento);
         //var temp = _mapper.Map<Document>(new_documento);
         //_dbContext.SaveChanges();
         //var temp2 = _mapper.Map<Document>(new_documento);
         return(InsertDocument(new_documento).Result);
         //return _mapper.Map<Document>(new_documento);
     }
     catch (Exception err)
     {
         throw err;
     }
 }
Ejemplo n.º 6
0
 public Document InsertNewDocument2(documentDTO documentDTO, string ruc_supplier)
 {
     try
     {
         using (var context = _dbContext)
         {
             using (var transaction = context.Database.BeginTransaction())
             {
                 var new_documento = _mapper.Map <documento>(documentDTO);
                 new_documento.usuario_modificacion = ruc_supplier;
                 _dbContext.documento.Add(new_documento);
                 _dbContext.SaveChanges();
                 return(_mapper.Map <Document>(new_documento));
             }
         }
     }
     catch (Exception err)
     {
         throw err;
     }
 }
Ejemplo n.º 7
0
        public ActionResult insertDocument([FromBody] documentDTO newDocument)
        {
            var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

            /*var sid = identity.Claims.Where(c => c.Type == ClaimTypes.Sid)
             *     .Select(c => c.Value).SingleOrDefault();*/

            var sid = User.Claims.Where(c => c.Type == ClaimTypes.Sid)
                      .Select(c => c.Value).SingleOrDefault();

            newDocument.ruc_empresa_proveedor = User.Identity.Name;
            _iDocumentValidatorService.setDocument(newDocument);
            ValDocuments valDoc  = new ValDocuments(_iDocumentValidatorService);
            var          errores = valDoc.verificador();

            if (errores.Count() > 0)
            {
                return(BadRequest(new { errors = errores }));
                //return new HttpStatusCodeResult(400,);
            }
            else
            {
                newDocument = _iDocumentValidatorService.getMaskedDocument();
                var doc = _iserviceDocument.InsertNewDocument(newDocument, User.Identity.Name, sid);

                /*
                 * var errores = valDocumentsx.verificador();
                 * if (errores.Count()==0)
                 * {
                 *  _iserviceDocument.InsertNewDocument(newDocument,User.Identity.Name);
                 *  return Ok(newDocument);
                 * }
                 * return BadRequest(new { errors = errores });
                 */

                return(Ok(doc));
            }
            //pasamos los servicios
        }
Ejemplo n.º 8
0
        public void InsertErrorDocument(documentDTO NewDocument, Dictionary <string, List <string> > errores)
        {
            var empresaCliente   = _dbContext.empresas.Where(ent => ent.ruc_empresa.Equals(NewDocument.ruc_empresa_cliente)).FirstOrDefault();
            var empresaProveedor = _dbContext.empresas.Where(ent => ent.ruc_empresa.Equals(NewDocument.ruc_empresa_proveedor)).FirstOrDefault();

            string razon_social_cliente   = (empresaCliente != null) ? empresaCliente.razon_social : "--";
            string razon_social_proveedor = (empresaProveedor != null) ? empresaProveedor.razon_social : "--";

            ErrorsByDocument doc = new ErrorsByDocument()
            {
                razon_social_cliente   = razon_social_cliente,
                razon_social_proveedor = razon_social_proveedor,
                documento = NewDocument,
                errores   = errores,
                //correos = empresaProveedor.correo,
            };


            var docx = _mapper.Map <documento_errores>(doc);

            _dbContext.documento_errores.Add(docx);
            _dbContext.SaveChanges();



            /*
             * string output = JsonConvert.SerializeObject(NewDocument);
             *
             * string erroresx = JsonConvert.SerializeObject(errores);
             *
             * Document deserializedProduct = JsonConvert.DeserializeObject<Document>(output);
             *
             * Dictionary<string, List<string>> mecmec = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(erroresx);
             *
             * var temp = "a";
             *
             * var tempx = output.Length;
             */
        }
Ejemplo n.º 9
0
 public Document insertdocument(documentDTO newdocument)
 {
     return(null);
 }
Ejemplo n.º 10
0
        public void verify_document(documentDTO new_document, ref Dictionary <string, List <string> > errorx)
        {
            // ########################################################################################################
            //                                  logica de negocio 0
            // ########################################################################################################
            //                      Primera verificación :V [decorator Data Anotation]

            var context = new ValidationContext(new_document);
            var results = new List <ValidationResult>();


            //new_document.ruc_empresa_cliente = null;

            if (DateTime.Compare(new_document.fecha_emision, new DateTime()) == 0)
            {
                InsertErrorIntoDiccionary(ref errorx, nameof(new_document.fecha_emision), "Debe Insertar una fecha de Emisión");
            }

            var temp = Validator.TryValidateObject(new_document, context, results, true);

            foreach (ValidationResult vr in results)
            {
                InsertErrorIntoDiccionary(ref errorx, vr.MemberNames.First(), vr.ErrorMessage);
            }

            // ########################################################################################################
            //                                  logica de negocio 1
            // ########################################################################################################
            //                      verificar todo lo relacionado al tipo de documento

            //el tipo de documento
            TypeDocument typeDoc = _typeDocs.Find(t => t.id_tipo_documento.Equals(new_document.id_tipo_documento));

            if (typeDoc != null)
            {
                //hay que identificar si es físico o electrónico
                string formatSerial = (new_document.fis_elec) ? typeDoc.formato_serie_fisica : typeDoc.formato_serie_electronica;

                //valuamos las expresiones regulares del número de serie y el correlativo
                var matchSerial      = Regex.Match(new_document.num_serie, formatSerial, RegexOptions.IgnoreCase);
                var matchCorrelative = Regex.Match(new_document.num_correlativo, typeDoc.formato_correlativo, RegexOptions.IgnoreCase);

                //si no cumplen con el formato, lo insertamos en el diccionario :V
                if (matchSerial.Success)
                {
                    if (matchCorrelative.Success)
                    {
                        if (_iserviceDocument.getDocumentByID(new_document.ruc_empresa_proveedor, new_document.id_tipo_documento, new_document.num_serie + "-" + new_document.num_correlativo) != null)
                        {
                            InsertErrorIntoDiccionary(ref errorx, nameof(new_document.num_correlativo), $"Existe duplicidad con este correlativo.");
                        }
                    }
                    else
                    {
                        InsertErrorIntoDiccionary(ref errorx, nameof(new_document.num_correlativo), $"El Formato no cumple para el número correlativo.");
                    }
                }
                else
                {
                    InsertErrorIntoDiccionary(ref errorx, nameof(new_document.num_serie), $"El Formato no cumple para el número serial.");
                    if (!matchCorrelative.Success)
                    {
                        InsertErrorIntoDiccionary(ref errorx, nameof(new_document.num_correlativo), $"El Formato no cumple para el número correlativo.");
                    }
                }
            }
            else
            {
                InsertErrorIntoDiccionary(ref errorx, nameof(new_document.id_tipo_documento), $"No existe ese tipo de documento.");
                return;
            }
            //duplicidad en los documentos



            // ########################################################################################################
            //                                  logica de negocio 2
            // ########################################################################################################
            //                              Todo lo relacionado a los permisos


            // Primero: preguntamos si la empresa cliente existe
            Enterprise enterprise_client = _iServiceEnterprice.getIfTheEnterpriseIsClient(new_document.ruc_empresa_cliente.Trim());

            if (enterprise_client != null)
            {
                //segundo: preguntamos si existe la relacion entre el cliente y el proveedor
                Boolean RelationClientProvider = _iServiceEnterprice
                                                 .getIfExistRelationBetweenClientAndProvider(
                    new_document.ruc_empresa_cliente.Trim(),
                    new_document.ruc_empresa_proveedor);

                if (RelationClientProvider)
                {
                    //Tercero: Preguntamos si existe la orden de compra
                    PurcharseOrder po = null;

                    //tercero - primero:
                    //si la id de la orden de compra es "--" signfica que el proveedor no
                    //ha adjuntado la orden de compra :V
                    if (new_document.id_orden_compra.Equals("--"))
                    {
                        //cuarto - primero: preguntamos si el cliente permite que se le adjunten facturas nulas
                        po = _iservicePurcharseOrder.GetPurcharseOrderNullIfClientAllowsIt(new_document.ruc_empresa_cliente);
                        if (po != null)
                        {
                            //quinto: calcular si los montos son correctos: :V
                            calculateAmounts(ref errorx, new_document, enterprise_client);
                            return;
                        }
                        else
                        {
                            InsertErrorIntoDiccionary(ref errorx, nameof(new_document.id_orden_compra), $"El cliente exige una orden de compra.");
                            return;
                        }
                    }
                    //tercero - segundo:
                    //El cliente exige la orden de compra
                    else
                    {
                        po = _iservicePurcharseOrder.GetPurcharseOrderIfNotExistReturnNull(
                            new_document.ruc_empresa_cliente,
                            new_document.id_orden_compra);
                        //cuarto - segundo: Existe esa orden de compra?
                        if (po != null)
                        {
                            //quinto: calcular si los montos son correctos: :V
                            calculateAmounts(ref errorx, new_document, enterprise_client);
                            return;
                        }
                        else
                        {
                            InsertErrorIntoDiccionary(ref errorx, nameof(new_document.id_orden_compra), $"La orden de compra no existe.");
                            return;
                        }
                    }
                }
                else
                {
                    InsertErrorIntoDiccionary(ref errorx, nameof(new_document.ruc_empresa_cliente), $"Usted no tiene permisos de realizar una subida de datos a ese cliente.");
                    return;
                }
            }
            else
            {
                InsertErrorIntoDiccionary(ref errorx, nameof(new_document.ruc_empresa_cliente), $"No existe ese RUC de empresa cliente.");
                return;
            }
        }
Ejemplo n.º 11
0
        private void calculateAmounts(ref Dictionary <string, List <string> > DictErrores, documentDTO new_document, Enterprise enterprise_client)
        {
            decimal subtotal_afecto   = new_document.monto_subtotal_afecto;
            decimal subtotal_inafecto = new_document.monto_subtotal_inafecto;
            decimal igv   = new_document.monto_igv;
            decimal total = new_document.monto_total;

            //primero: el igv es del 18%?
            if (igv == Math.Round(subtotal_afecto * _igv, 2))
            {
                //segundo: el monto total es la suma de todos los subtotales incluyendo el IGV?
                if (total == subtotal_afecto + subtotal_inafecto + igv)
                {
                    return;
                }
                else
                {
                    InsertErrorIntoDiccionary(ref DictErrores, nameof(new_document.monto_total), $"El monto Total está mal calculado.");
                    return;
                }
            }
            else
            {
                InsertErrorIntoDiccionary(ref DictErrores, nameof(new_document.monto_igv), $"El IGV está mal calculado.");
                return;
            }
        }
 public void setMaskedDocument(documentDTO newDocumentDTO)
 {
     this._maskedDocumentDTO = newDocumentDTO;
 }
 public void setDocument(documentDTO newDocumentDTO)
 {
     this._documentDTO = newDocumentDTO;
 }
Ejemplo n.º 14
0
        public Dictionary <int, documentDTO> ConvertRowExceltoDTO(ISheet sheet)
        {
            documentDTO docx;
            IRow        row;
            Dictionary <int, documentDTO> dict = new Dictionary <int, documentDTO>();

            #region Read Excel File
            int n = (sheet.LastRowNum >= 500) ? sheet.LastRowNum : 500;
            for (int i = (sheet.FirstRowNum + 2); i <= n; i++) //Read Excel File
            {
                row = sheet.GetRow(i);
                if (row == null)
                {
                    continue;
                }
                if (row.Cells.All(d => d.CellType == CellType.Blank))
                {
                    continue;
                }


                decimal total_amount_affected   = getAmount(row.GetCell((int)ExcelPosition.monto_subtotal_afecto));
                decimal total_amount_unaffected = getAmount(row.GetCell((int)ExcelPosition.monto_subtotal_inafecto));

                docx = new documentDTO()
                {
                    num_serie       = getString(row.GetCell((int)ExcelPosition.num_serie)),
                    num_correlativo = getString(row.GetCell((int)ExcelPosition.num_correlativo)),

                    id_tipo_documento = getString(row.GetCell((int)ExcelPosition.id_tipo_documento)).Split('-')[0],
                    id_orden_compra   = (getString(row.GetCell((int)ExcelPosition.id_orden_compra)).Equals("") ?
                                         "--" : row.GetCell((int)ExcelPosition.id_orden_compra).ToString()),
                    ruc_empresa_cliente = getString(row.GetCell((int)ExcelPosition.ruc_empresa_cliente)),
                    ceco  = (!getString(row.GetCell((int)ExcelPosition.ceco)).Equals("") ? getString(row.GetCell((int)ExcelPosition.ceco)):"--"),
                    orden = (!getString(row.GetCell((int)ExcelPosition.orden)).Equals("") ? getString(row.GetCell((int)ExcelPosition.orden)) : "--"),
                    factura_negociable = (string.IsNullOrEmpty(getString(row.GetCell((int)ExcelPosition.factura_negociable))) ? null : (Boolean?)
                                          (getString(row.GetCell((int)ExcelPosition.factura_negociable)).Equals("SI")? true:false)),
                    fecha_emision = getDate(row.GetCell((int)ExcelPosition.fecha_emision)),     //Convert.ToDateTime(row.GetCell((int)ExcelPosition.fecha_emision).ToString()),

                    id_tipo_detracciones = getString(row.GetCell((int)ExcelPosition.id_tipo_detracciones)).Split('-')[0].Trim(),

                    id_tipo_moneda = getString(row.GetCell((int)ExcelPosition.id_tipo_moneda)),

                    /*monto_subtotal_afecto = total_amount_affected,
                     * monto_subtotal_inafecto = total_amount_unaffected,
                     * monto_igv = Math.Round(total_amount_affected * (decimal).18, 2),
                     * monto_isc =
                     * monto_total = Math.Round(total_amount_affected * (decimal)1.18, 2) + total_amount_unaffected,*/

                    factura_origen_serie       = getString(row.GetCell((int)ExcelPosition.factura_origen_serie)),
                    factura_origen_correlativo = getString(row.GetCell((int)ExcelPosition.factura_origen_correlativo)),

                    monto_subtotal_afecto   = getAmount(row.GetCell((int)ExcelPosition.monto_subtotal_afecto)),
                    monto_subtotal_inafecto = getAmount(row.GetCell((int)ExcelPosition.monto_subtotal_inafecto)),
                    monto_isc   = getAmount(row.GetCell((int)ExcelPosition.monto_isc).NumericCellValue),
                    monto_igv   = getAmount(row.GetCell((int)ExcelPosition.monto_igv).NumericCellValue),
                    monto_total = getAmount(row.GetCell((int)ExcelPosition.monto_total).NumericCellValue),

                    nombre_documento_excel = nameFile,
                    url_imagen             = new string [] {},

                    //id_tipo_documento_estado = 1,
                    ruc_empresa_proveedor = User.Identity.Name,
                    fis_elec = true,
                };


                dict.Add(i, docx);
            }

            return(dict);

            #endregion
        }
Ejemplo n.º 15
0
 //ObtenerMapperDocument   --nuevo
 private Document ObtenerMapperDocument(documentDTO new_document)
 {
     return(_iserviceDocument.ObtenerMapperDocument(new_document));
 }
        public ActionResult OnPostImport(IFormFile xmlFile)
        {
            var uploads  = _hostingEnvironment.WebRootPath;
            var filePath = Path.Combine(uploads, xmlFile.FileName).ToString();

            if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
            {
                using (XmlReader xmlReader = XmlReader.Create(xmlFile.OpenReadStream()))
                {
                    var doc = new XmlDocument();
                    doc.Load(xmlReader);
                    var            nsmgr = new XmlNamespaceManager(doc.NameTable);
                    XPathNavigator nav   = doc.CreateNavigator();

                    nsmgr.AddNamespace("cac", @"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                    nsmgr.AddNamespace("cbc", @"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                    nsmgr.AddNamespace("ccts", @"urn:un:unece:uncefact:documentation:2");
                    nsmgr.AddNamespace("ds ", @"http://www.w3.org/2000/09/xmldsig#");
                    nsmgr.AddNamespace("ext", @"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                    nsmgr.AddNamespace("qdt", @"urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                    nsmgr.AddNamespace("udt", @"urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                    nsmgr.AddNamespace("xsi", @"http://www.w3.org/2001/XMLSchema-instance");
                    nsmgr.AddNamespace("ns", @"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2");

                    GetTextFromXML getXml = new GetTextFromXML(nav, nsmgr);

                    documentDTO newDocument = new documentDTO()
                    {
                        ruc_empresa_cliente   = getXml.GetString(urlXmlSunat.ruc_empresa_cliente),
                        ruc_empresa_proveedor = getXml.GetString(urlXmlSunat.ruc_empresa_proveedor),
                        num_correlativo       = getXml.GetString(urlXmlSunat.id_factura).Contains("-") ? getXml.GetString(urlXmlSunat.id_factura).Split("-")[1] : "",
                        num_serie             = getXml.GetString(urlXmlSunat.id_factura).Contains("-") ? getXml.GetString(urlXmlSunat.id_factura).Split("-")[0] : "",
                        fis_elec      = false,
                        fecha_emision = getXml.GetDateHour(urlXmlSunat.dia_emision, urlXmlSunat.hora_emision),

                        monto_subtotal_afecto = getXml.GetAmount(urlXmlSunat.monto_subtotal_afecto),
                        monto_igv             = getXml.GetAmount(urlXmlSunat.monto_igv),
                        monto_total           = getXml.GetAmount(urlXmlSunat.monto_total),

                        monto_subtotal_inafecto = 0,
                    };



                    return(Ok(newDocument));

                    string a = "";

                    /*
                     * XmlDocument doc = new XmlDocument();
                     *
                     * doc.Load(xmlReader);
                     *
                     * //XPathDocument doc = new XPathDocument(xmlReader);
                     *
                     * XPathNavigator nav = doc.CreateNavigator();
                     * //object xx = nav.GetAttribute(@"/Invoice");
                     *
                     * XmlNamespaceManager nsmgr =
                     *       new XmlNamespaceManager(doc.NameTable);
                     *
                     *
                     *
                     *
                     * //nsmgr.AddNamespace("xmlns", @"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"); ;
                     * nsmgr.AddNamespace("cac" , @"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                     * nsmgr.AddNamespace("cbc" , @"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                     * nsmgr.AddNamespace("ccts" , @"urn:un:unece:uncefact:documentation:2");
                     * nsmgr.AddNamespace("ds ", @"http://www.w3.org/2000/09/xmldsig#");
                     * nsmgr.AddNamespace("ext" , @"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                     * nsmgr.AddNamespace("qdt" , @"urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                     * nsmgr.AddNamespace("udt" , @"urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                     * nsmgr.AddNamespace("xsi", @"http://www.w3.org/2001/XMLSchema-instance");
                     *
                     * string xpath = @"/invoice/cac:PrepaidPayment";
                     * string xxx = @"/invoice/cac:InvoiceLine/cac:DocumentReference/cbc:ID";
                     *
                     * string pochito = @"cac:PrepaidPayment";
                     * string xxx2 = @"cac:InvoiceLine/cac:DocumentReference/cbc:ID";
                     *
                     * XPathNavigator element = nav.SelectSingleNode(xpath, nsmgr);
                     * XPathNavigator element2 = nav.SelectSingleNode(xxx, nsmgr);
                     * XPathNavigator element3 = nav.SelectSingleNode(pochito, nsmgr);
                     * XPathNavigator element4 = nav.SelectSingleNode(xxx2, nsmgr);
                     *
                     * XmlNodeList list = doc.SelectNodes(xpath, nsmgr);
                     * XmlNodeList list2 = doc.SelectNodes(xxx, nsmgr);
                     * XmlNodeList list3 = doc.SelectNodes(pochito, nsmgr);
                     * XmlNodeList list4 = doc.SelectNodes(xxx2, nsmgr);
                     *
                     * return Ok(list);
                     *
                     * /*
                     * var list = doc.XPathSelectElement(xpath, nsmgr);
                     * var list1 = doc.XPathSelectElement(xxx, nsmgr);
                     * var list2 = doc.XPathSelectElement(pochito, nsmgr);
                     * var list3 = doc.XPathSelectElement(xxx2, nsmgr);
                     *
                     *
                     * //XmlNodeList list = doc.Root.SetValue("//cbc:ID", manager);
                     *
                     * var id = doc.Root.XPathSelectElement("cbc:ID", nsmgr).Value;
                     *
                     *
                     * object o = nav.GetNamespace(xxx);
                     * //XmlNodeList xnl = root.SelectNodes(xpath, nsmgr);
                     *
                     * var x = doc.Root.XPathEvaluate(xxx, nsmgr);
                     *
                     * return Ok(element);
                     *
                     * Console.WriteLine("Element Prefix:" + element.Prefix +
                     *         " Local name:" + element.LocalName);
                     * Console.WriteLine("Namespace URI: " +
                     *          element.NamespaceURI);
                     */
                }
            }
            return(BadRequest());
        }