/// <summary> /// Generates Recibos de caja. /// </summary> /// <param name="items">It is a pair of values</param> /// <param name="type">The type of recibo de caja</param> /// <returns>True if files were generated succesfully</returns> public override bool GenerateFiles(List <Tuple <Factura, Customer> > items, string type, object sender, System.Windows.Controls.TextBlock text) { for (int i = 0; i < items.Count; ++i) { //Change current operation description base.UpdateCurrentOperationDescription("Proceso iniciado " + (i + 1) + "/" + items.Count); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); string concepto = String.Empty; int ct = 0; foreach (Cargo cargo in items.ElementAt(i).Item1.cargos) { concepto += cargo.Concepto.ToString().ToUpper(); concepto += new StringBuilder(" ").Append(cargo.MesCargado.ToString().ToUpper()); if (!(items.ElementAt(i).Item1.cargos.Count - 1 == ct++)) { concepto += "-"; } } using (ExcelPackage xlPackage = new ExcelPackage(new System.IO.FileInfo(@UserPreferences.GetRecibosLocation()))) { //Change current operation description base.UpdateCurrentOperationDescription("Obteniendo directorio"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); StringBuilder DirectoryLocation = new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(type); var directoryInfo = System.IO.Directory.CreateDirectory(@DirectoryLocation.ToString()); //Change Current Operation Description base.UpdateCurrentOperationDescription("Generando nombres de archivo"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); StringBuilder FileLocationXlsx = new StringBuilder(directoryInfo.FullName).Append(@"\").Append(items.ElementAt(i).Item1.NumeroFactura).Append(FileExtensions.ExcelFormat); StringBuilder FileLocationPDF = new StringBuilder(directoryInfo.FullName).Append(@"\").Append(items.ElementAt(i).Item1.NumeroFactura).Append(FileExtensions.PDFFormat); try { var worksheet = xlPackage.Workbook.Worksheets.First(); var totalRows = worksheet.Dimension.End.Row; var totalColumns = worksheet.Dimension.End.Column; //Change Current Operation Description base.UpdateCurrentOperationDescription("Escaneando plantilla"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); int count = 0; for (int rowNum = 1; rowNum <= totalRows; ++rowNum) { for (int colNum = 1; colNum <= totalColumns; ++colNum) { var row = worksheet.Cells[rowNum, colNum].Select(c => c.Value == null ? String.Empty : c.Value.ToString()); string cellValue = String.Join(",", row); if (cellValue == RecibosKeyWords.NUMERORECIBO) { int numero_recibo = UserPreferences.GetNumeroRecibo(); worksheet.Cells[rowNum, colNum].Value = new StringBuilder("#").Append(numero_recibo).ToString(); UserPreferences.SaveNumeroRecibo(++numero_recibo); } if (cellValue == RecibosKeyWords.NOMBRES) { worksheet.Cells[rowNum, colNum].Value = new StringBuilder(items.ElementAt(i).Item2.Nombre).Append(" ").Append(items.ElementAt(i).Item2.Apellido).ToString(); } if (cellValue == RecibosKeyWords.FECHA) { worksheet.Cells[rowNum, colNum].Value = DateManager.GetDateInSpanish(); } if (cellValue == RecibosKeyWords.CEDULA) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Cedula; } if (cellValue == RecibosKeyWords.DIRECCION) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Direccion; } if (cellValue == RecibosKeyWords.BARRIO) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Barrio; } if (cellValue == RecibosKeyWords.CONCEPTO) { worksheet.Cells[rowNum, colNum].Value = concepto; } if (cellValue == RecibosKeyWords.NODO) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Nodo; } if (cellValue == RecibosKeyWords.TELEFONO) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Telefono; } if (cellValue == RecibosKeyWords.MES) { worksheet.Cells[rowNum, colNum].Value = DateManager.GetMonthInSpanish(); } if (cellValue == RecibosKeyWords.VALOR) { string valorToDisplay = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", Valor); worksheet.Cells[rowNum, colNum].Value = valorToDisplay; } //Change progress value int newProgress = (int)((((float)(++count) / (float)(totalRows * totalColumns)) * (1.0f / (float)items.Count)) * 100); base.UpdateProgreso(newProgress); (sender as BackgroundWorker).ReportProgress(Progress); } } //Change Current Operation Description base.UpdateCurrentOperationDescription("Generando archivo PDF"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); xlPackage.SaveAs(new System.IO.FileInfo(@FileLocationXlsx.ToString())); Workbook workbook = new Application().Workbooks.Open(@FileLocationXlsx.ToString()); workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, @FileLocationPDF.ToString()); workbook.Close(); } catch (Exception) { RollBack(FileLocationXlsx.ToString(), FileLocationPDF.ToString()); throw; } finally { File.Delete(@FileLocationXlsx.ToString()); } } } base.UpdateProgreso(100); (sender as BackgroundWorker).ReportProgress(Progress); return(true); }
/// <summary> /// Creates a single invoice /// </summary> /// <param name="customer">Customer associated with the invoice</param> /// <returns>A invoice object</returns> private Factura CreateInvoice(Customer customer) { StringBuilder numeroFactura = new StringBuilder(customer.Cedula).Append("-").Append(TypeOfRecibos.MENSUALIDAD).Append("-").Append(DateManager.GetMonthInSpanish()).Append("-").Append(DateManager.GetToday().Year); DateTime fecha = DateManager.GetToday(); Mes mesCargado = DateManager.GetMonth(); DateTime fechaLimite; List <Cargo> cargos = new List <Cargo>(); if (customer.HasTV && customer.HasInternet) { fechaLimite = DateManager.GetDateLimit(false); if (customer.EstadoTV == Estado.Pendiente || customer.EstadoInternet == Estado.Pendiente) { return(null); } else { //No pending int internet = 0, tv = 0; switch (customer.Megas) { case 3: (tv, internet) = UserPreferences.GetCombo3(); break; case 5: (tv, internet) = UserPreferences.GetCombo5(); break; case 7: (tv, internet) = UserPreferences.GetCombo7(); break; case 10: (tv, internet) = UserPreferences.GetCombo10(); break; } internet -= customer.Descuento; if (IncompleteCharge(customer.FechaAfiliacionInternet)) { Calculadora.CalcularPrecioRealBasadoEnDias(ref internet, 30 - DateManager.GetToday().Day); } if (IncompleteCharge(customer.FechaAfiliacionTV)) { if (DateManager.GetToday().Day < 16) { Calculadora.CalcularPrecioRealBasadoEnDias(ref tv, 30 - DateManager.GetToday().Day); } else { tv = 0; } } Cargo cargoTV = new Cargo(tv, 0, Concepto.TV); Cargo cargoInternet = new Cargo(internet, 0, Concepto.Internet); cargos.Add(cargoTV); cargos.Add(cargoInternet); AddPreviousCharges(customer.Cedula, cargos); return(new Factura(numeroFactura.ToString(), fecha, fechaLimite, mesCargado, cargos, customer.Cedula)); } } else if (customer.HasInternet) { if (customer.EstadoInternet == Estado.Pendiente) { return(null); } fechaLimite = DateManager.GetDateLimit(false); int internet = 0; switch (customer.Megas) { case 3: internet = UserPreferences.Get3MegasValue(); break; case 5: internet = UserPreferences.Get5MegasValue(); break; case 7: internet = UserPreferences.Get7MegasValue(); break; case 10: internet = UserPreferences.Get10MegasValue(); break; } internet -= customer.Descuento; if (IncompleteCharge(customer.FechaAfiliacionInternet)) { Calculadora.CalcularPrecioRealBasadoEnDias(ref internet, 30 - DateManager.GetToday().Day); } Cargo cargoInternet = new Cargo(internet, 0, Concepto.Internet); cargos.Add(cargoInternet); AddPreviousCharges(customer.Cedula, cargos); return(new Factura(numeroFactura.ToString(), fecha, fechaLimite, mesCargado, cargos, customer.Cedula)); } else if (customer.HasTV) { if (customer.EstadoTV == Estado.Pendiente) { return(null); } fechaLimite = DateManager.GetDateLimit(true); int tv = UserPreferences.GetTVValue(); if (IncompleteCharge(customer.FechaAfiliacionTV)) { if (DateManager.GetToday().Day < 16) { Calculadora.CalcularPrecioRealBasadoEnDias(ref tv, 30 - DateManager.GetToday().Day); } else { tv = 0; } } Cargo cargoTV = new Cargo(tv, 0, Concepto.TV); cargos.Add(cargoTV); AddPreviousCharges(customer.Cedula, cargos); return(new Factura(numeroFactura.ToString(), fecha, fechaLimite, mesCargado, cargos, customer.Cedula)); } else { if (customer.Saldo == 0) { return(null); } //If program hits this part, it means customer has no services but it owes money fechaLimite = DateManager.GetDateLimit(true); } //Get previous charges AddPreviousCharges(customer.Cedula, cargos); return(new Factura(numeroFactura.ToString(), fecha, fechaLimite, mesCargado, cargos, customer.Cedula)); }
/// <summary> /// Creates a customer based on input data /// </summary> private void CreateCustomer() { String cedula, nombre, apellido, telefono, celular, correo, direccion, barrio, mac, precinto; int nodo, megas, saldo, descuento; bool internet, tv; DateTime?fechaAfiliacionTv, fechaAfiliacionInternet; Estado estadoTv, estadoInternet; cedula = this.CedulaText.Text != string.Empty ? this.CedulaText.Text.Trim() : null; nombre = this.NombresText.Text != String.Empty ? this.NombresText.Text.Trim() : null; apellido = this.ApellidosText.Text != String.Empty ? this.ApellidosText.Text.Trim() : null; telefono = this.TelefonoText.Text != String.Empty ? this.TelefonoText.Text.Trim() : null; celular = this.CelularText.Text != String.Empty ? this.CelularText.Text.Trim() : null; correo = this.CorreoText.Text != String.Empty ? this.CorreoText.Text.Trim() : null; direccion = this.DireccionText.Text != String.Empty ? this.DireccionText.Text.Trim() : null; barrio = this.BarrioBox.Text != String.Empty ? this.BarrioBox.Text : null; mac = this.MACText.Text != String.Empty ? this.MACText.Text.Trim() : null; precinto = this.PrecintoText.Text != String.Empty ? this.PrecintoText.Text.Trim() : null; nodo = Int32.TryParse(this.NodoBox.Text.Trim(), out nodo) ? nodo : -1; megas = Int32.TryParse(this.MegasBox.Text.Trim(), out megas) ? megas : -1; descuento = Int32.TryParse(this.DescuentoText.Text.Trim(), out descuento) ? descuento : 0; internet = this.InternetRadioButton.IsChecked ?? false; tv = this.TelevisionRadioButton.IsChecked ?? false; fechaAfiliacionTv = null; fechaAfiliacionInternet = null; estadoTv = Estado.Pendiente; estadoInternet = Estado.Pendiente; saldo = 0; if (cedula == null) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.CedulaIsAMandatoryField, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (nombre == null) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.NombreIsAMandatoryField, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (apellido == null) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.ApellidoIsAMandatoryField, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (direccion == null) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.DireccionIsAMandatoryField, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (barrio == null) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.BarrioIsAMandatoryField, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (nodo == -1) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.NodoIsAMandatoryField, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (megas == -1) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.MegasIsAMandatoryField, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (!(internet || tv)) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.AtLeastOneServiceMustBeProvided, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (megas != 0 && !internet) { SystemSounds.Beep.Play(); MessageBox.Show(Messages.InputRequirements.MegasOnlyApplyForInternetService, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } Customer customer = new Customer(cedula, nombre, apellido, telefono, celular, correo, direccion, barrio, mac, precinto, nodo, megas, saldo, descuento, tv, internet, fechaAfiliacionTv, fechaAfiliacionInternet, estadoTv, estadoInternet); StringBuilder numeroFactura = new StringBuilder(cedula).Append("-").Append(TypeOfRecibos.AFILIACION).Append("-").Append(DateManager.GetDateInSpanish()); List <Cargo> cargos = new List <Cargo>(); Cargo cargo = new Cargo(UserPreferences.GetAfiliacionValue(), UserPreferences.GetAfiliacionValue(), Concepto.Afiliacion); cargos.Add(cargo); Factura factura = new Factura(numeroFactura.ToString(), DateManager.GetToday(), null, null, cargos, customer.Cedula); RecibosManager RecibosManager = new RecibosManager(); Tuple <Factura, Customer> pair = new Tuple <Factura, Customer>(factura, customer); List <Tuple <Factura, Customer> > info = new List <Tuple <Factura, Customer> >(); info.Add(pair); try { RecibosManager.Valor = cargo.Valor; LoadingWindow loadingWindow = new LoadingWindow(); loadingWindow.Show(); loadingWindow.StartWorking((object sender, DoWorkEventArgs e) => { RecibosManager.GenerateFiles(info, TypeOfRecibos.AFILIACION, sender, loadingWindow.Status); try { if (BDManager.CreateCustomerWithInitialFinancialInformation(customer, factura, cargo)) { this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.customerWasSuccesfullyCreated, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); Clean(); }); } } catch (MySqlException ex) { if (ex.Number == (int)MySqlErrorCode.DuplicateKeyEntry) { this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show(Messages.Errors.CustomerAlreadyExists, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); }); } else if (ex.Number == (int)MySqlErrorCode.DataTooLong) { this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show("Uno de los campos no es valido. La informacion es demasiado larga!", Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); }); } else { this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show(Messages.Errors.setErrorCodeMessage(ex.Number.ToString()), Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error); }); } } } ); } catch (Exception) { this.Dispatcher.Invoke(delegate { SystemSounds.Beep.Play(); MessageBox.Show(Messages.Errors.CouldntReadFile, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); }); } }
/// <summary> /// Adds a traslado to a customer /// </summary> private void AddTraslado() { Customer customer = this.ListViewCustomers.SelectedItem as Customer; List <Cargo> cargos = new List <Cargo>(); SystemSounds.Beep.Play(); var r = MessageBox.Show("¿Esta seguro de que desea generar un traslado para el cliente con cedula " + customer.Cedula + " ?", "Informacion", MessageBoxButton.YesNo, MessageBoxImage.Question); if ((r == MessageBoxResult.Yes)) { string numeroFactura = new StringBuilder(customer.Cedula).Append("-").Append(TypeOfRecibos.TRASLADO).Append("-").Append(DateManager.GetDateInSpanish()).ToString(); int traslado_value = UserPreferences.GetTrasladoValue(); Cargo cargo = new Cargo(traslado_value, traslado_value, Concepto.Traslado); cargos.Add(cargo); Factura factura = new Factura(numeroFactura, DateManager.GetToday(), null, null, cargos, customer.Cedula); RecibosManager recibosManager = new RecibosManager(); Tuple <Factura, Customer> pair = new Tuple <Factura, Customer>(factura, customer); List <Tuple <Factura, Customer> > info = new List <Tuple <Factura, Customer> >(); info.Add(pair); try { recibosManager.Valor = cargo.Valor; LoadingWindow loadingWindow = new LoadingWindow(); loadingWindow.Show(); loadingWindow.StartWorking((object sender, DoWorkEventArgs e) => { recibosManager.GenerateFiles(info, TypeOfRecibos.TRASLADO, sender, loadingWindow.Status); try { if (BDManager.AddChargeSimple(factura)) { this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show("Traslado generado exitosamente!", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); }); } } catch (MySqlException ex) { this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show(Messages.Errors.setErrorCodeMessage(ex.Number.ToString()), Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error); }); } catch (Exception ex) { this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show(ex.Message, Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error); }); } } ); } catch (Exception) { this.Dispatcher.Invoke(delegate { SystemSounds.Beep.Play(); MessageBox.Show(Messages.Errors.CouldntReadFile, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); }); } } }
/// <summary> /// Updates user preferences /// </summary> /// <param name="userPreference"></param> private void UpdatePreferences(EUserPreferences userPreference) { switch (userPreference) { case EUserPreferences.TV: UserPreferences.SaveTVValue(TVvalue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Megas3: UserPreferences.Save3MegasValue(Megas3Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Megas5: UserPreferences.Save5MegasValue(Megas5Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Megas7: UserPreferences.Save7MegasValue(Megas7Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Megas10: UserPreferences.Save10MegasValue(Megas10Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo3TV: UserPreferences.SaveCombo3TV(ComboTV3Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo3Internet: UserPreferences.SaveCombo3Internet(ComboInternet3Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo5TV: UserPreferences.SaveCombo5TV(ComboTV5Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo5Internet: UserPreferences.SaveCombo5Internet(ComboInternet5Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo7TV: UserPreferences.SaveCombo7TV(ComboTV7Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo7Internet: UserPreferences.SaveCombo7Internet(ComboInternet7Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo10TV: UserPreferences.SaveCombo10TV(ComboTV10Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Combo10Internet: UserPreferences.SaveCombo10Internet(ComboInternet10Value); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Reconexion: UserPreferences.SaveReconexionValue(ReconexionValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Afiliacion: UserPreferences.SaveAfiliacionValue(AfiliacionValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Derivacion: UserPreferences.SaveDerivacionValue(DerivacionValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Traslado: UserPreferences.SaveTrasladoValue(TrasladoValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Descuento: UserPreferences.SaveDescuento(DescuentoValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Recibos: UserPreferences.SaveRecibosLocation(RecibosValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Facturas: UserPreferences.SaveFacturasLocation(FacturasValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.Archivos: UserPreferences.SavePreferredLocation(UbicacionValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); return; case EUserPreferences.NumeroRecibo: if (IsNumeroReciboValid()) { UserPreferences.SaveNumeroRecibo(NumeroReciboValue); SystemSounds.Beep.Play(); MessageBox.Show(Messages.SuccesfulOperation.PreferenceWasUpdatedSuccesfully, Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); } else { SystemSounds.Beep.Play(); MessageBox.Show("Valor invalido!", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Warning); } return; default: Debugger.Break(); return; } }
/// <summary> /// Searches for files associated with a customer /// </summary> private void FindFile() { this.ListViewFiles.Items.Clear(); this.PDFViewer.Navigate(new Uri(BlankPage)); string cedula = this.CedulaText.Text.Trim(); //Mensualidad try { DirectoryInfo dirMensualidad = new DirectoryInfo(new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(TypeOfRecibos.MENSUALIDAD).Append(@"\").ToString()); if (!(dirMensualidad is null)) { if (Directory.Exists(dirMensualidad.FullName)) { DirectoryInfo[] DirecIndir = dirMensualidad.GetDirectories(); foreach (DirectoryInfo foundFolder in DirecIndir) { DirectoryInfo dirPerMes = new DirectoryInfo(@foundFolder.FullName); FileInfo[] fileinPerMes = dirPerMes.GetFiles(cedula + "*.pdf"); foreach (FileInfo foundFile in fileinPerMes) { this.ListViewFiles.Items.Add(new FileView(foundFile.Name.Replace(FileExtensions.PDFFormat, String.Empty), foundFile.FullName)); } } } } //Pagos DirectoryInfo dirPagos = new DirectoryInfo(new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(TypeOfRecibos.PAGO).Append(@"\").ToString()); if (!(dirPagos is null)) { if (Directory.Exists(dirPagos.FullName)) { FileInfo[] fileinPerPago = dirPagos.GetFiles(cedula + "*.pdf"); foreach (FileInfo foundFile in fileinPerPago) { this.ListViewFiles.Items.Add(new FileView(foundFile.Name.Replace(FileExtensions.PDFFormat, String.Empty), foundFile.FullName)); } } } //Afiliaciones DirectoryInfo dirAfiliaciones = new DirectoryInfo(new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(TypeOfRecibos.AFILIACION).Append(@"\").ToString()); if (!(dirAfiliaciones is null)) { if (Directory.Exists(dirAfiliaciones.FullName)) { FileInfo[] fileinPerAfiliaciones = dirAfiliaciones.GetFiles(cedula + "*.pdf"); foreach (FileInfo foundFile in fileinPerAfiliaciones) { this.ListViewFiles.Items.Add(new FileView(foundFile.Name.Replace(FileExtensions.PDFFormat, String.Empty), foundFile.FullName)); } } } //Derivaciones DirectoryInfo dirDerivaciones = new DirectoryInfo(new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(TypeOfRecibos.DERIVACION).Append(@"\").ToString()); if (!(dirDerivaciones is null)) { if (Directory.Exists(dirDerivaciones.FullName)) { FileInfo[] fileinDerivaciones = dirDerivaciones.GetFiles(cedula + "*.pdf"); foreach (FileInfo foundFile in fileinDerivaciones) { this.ListViewFiles.Items.Add(new FileView(foundFile.Name.Replace(FileExtensions.PDFFormat, String.Empty), foundFile.FullName)); } } } //Traslado DirectoryInfo dirTraslado = new DirectoryInfo(new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(TypeOfRecibos.TRASLADO).Append(@"\").ToString()); if (!(dirTraslado is null)) { if (Directory.Exists(dirTraslado.FullName)) { FileInfo[] fileinTraslado = dirTraslado.GetFiles(cedula + "*.pdf"); foreach (FileInfo foundFile in fileinTraslado) { this.ListViewFiles.Items.Add(new FileView(foundFile.Name.Replace(FileExtensions.PDFFormat, String.Empty), foundFile.FullName)); } } } //Otros DirectoryInfo dirOtros = new DirectoryInfo(new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(TypeOfRecibos.OTROS).Append(@"\").ToString()); if (!(dirOtros is null)) { if (Directory.Exists(dirOtros.FullName)) { FileInfo[] fileinOtros = dirOtros.GetFiles(cedula + "*.pdf"); foreach (FileInfo foundFile in fileinOtros) { this.ListViewFiles.Items.Add(new FileView(foundFile.Name.Replace(FileExtensions.PDFFormat, String.Empty), foundFile.FullName)); } } } } catch (Exception) { SystemSounds.Beep.Play(); MessageBox.Show("Error!", Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error); } if (this.ListViewFiles.Items.Count == 0) { SystemSounds.Beep.Play(); MessageBox.Show("No se encontro ningun registro", Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); } }
/// <summary> /// Generates Invoices /// </summary> /// <param name="items">It is a pair of values in which none can be null</param> /// <param name="type">The type of invoices</param> /// <returns>True if files were generated succesfully</returns> public override bool GenerateFiles(List <Tuple <Factura, Customer> > items, string type, object sender, System.Windows.Controls.TextBlock text) { for (int i = 0; i < items.Count; ++i) { int total = 0; foreach (Cargo cargo in items.ElementAt(i).Item1.cargos) { total += cargo.Valor; } //Change Current Operation Description base.UpdateCurrentOperationDescription("Proceso iniciado: " + (i + 1) + "/" + items.Count); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); using (ExcelPackage xlPackage = new ExcelPackage(new System.IO.FileInfo(@UserPreferences.GetFacturasLocation()))) { //Change Current Operation Description base.UpdateCurrentOperationDescription("Obteniendo directorio"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); StringBuilder DirectoryLocation = new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(type).Append(@"\").Append(DateManager.GetMonthInSpanish().ToUpper()); var directoryInfo = System.IO.Directory.CreateDirectory(@DirectoryLocation.ToString()); //Change Current Operation Description base.UpdateCurrentOperationDescription("Generando nombres de archivo"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); StringBuilder FileLocationXlsx = new StringBuilder(directoryInfo.FullName).Append(@"\").Append(items.ElementAt(i).Item1.NumeroFactura).Append(FileExtensions.ExcelFormat); StringBuilder FileLocationPDF = new StringBuilder(directoryInfo.FullName).Append(@"\").Append(items.ElementAt(i).Item1.NumeroFactura).Append(FileExtensions.PDFFormat); if (File.Exists(FileLocationPDF.ToString())) { continue; } try { var worksheet = xlPackage.Workbook.Worksheets.First(); var totalRows = worksheet.Dimension.End.Row; var totalColumns = worksheet.Dimension.End.Column; //Change Current Operation Description base.UpdateCurrentOperationDescription("Escaneando plantilla"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); for (int rowNum = 1; rowNum <= totalRows; ++rowNum) { for (int colNum = 1; colNum <= totalColumns; ++colNum) { var row = worksheet.Cells[rowNum, colNum].Select(c => c.Value == null ? String.Empty : c.Value.ToString()); string cellValue = String.Join(",", row); if (cellValue == FacturasKeyWords.CEDULA) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Cedula; } if (cellValue == FacturasKeyWords.NOMBRES) { worksheet.Cells[rowNum, colNum].Value = new StringBuilder(items.ElementAt(i).Item2.Nombre).Append(" ").Append(items.ElementAt(i).Item2.Apellido).ToString(); } if (cellValue == FacturasKeyWords.BARRIO) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Barrio; } if (cellValue == FacturasKeyWords.DIRECCION) { worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Direccion; } if (cellValue == FacturasKeyWords.FECHA) { worksheet.Cells[rowNum, colNum].Value = DateManager.GetDateInSpanish(items.ElementAt(i).Item1.Fecha); } if (cellValue == FacturasKeyWords.FECHADEPAGO) { worksheet.Cells[rowNum, colNum].Value = DateManager.GetDateInSpanish(items.ElementAt(i).Item1.FechaLimite.Value); } if (cellValue == FacturasKeyWords.TOTAL) { string valorToDisplay = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", total); worksheet.Cells[rowNum, colNum].Value = valorToDisplay; } //Adjusts charges int j = 0; foreach (Cargo cargo in items.ElementAt(i).Item1.cargos) { //Avoid index out of range if (j == FacturasKeyWords.SIZEOFCARGO) { break; } if (cellValue == FacturasKeyWords.CONCEPTO.ElementAt(j)) { worksheet.Cells[rowNum, colNum].Value = cargo.Concepto.ToString().ToUpper(); } if (cellValue == FacturasKeyWords.PERIODO.ElementAt(j)) { if (cargo.MesCargado is null) { worksheet.Cells[rowNum, colNum].Value = DateManager.GetMonthInSpanish((int)items.ElementAt(i).Item1.MesCargado + 1); } else { worksheet.Cells[rowNum, colNum].Value = cargo.MesCargado.ToString().ToUpper(); } } if (cellValue == FacturasKeyWords.VALOR.ElementAt(j)) { int valorSinIva = cargo.Valor; if (cargo.Concepto == Concepto.TV) { Calculadora.CalcularValorSinIVA(out valorSinIva, out int iva, cargo.Valor); } string valorToDisplay = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", valorSinIva); worksheet.Cells[rowNum, colNum].Value = valorToDisplay; } if (cellValue == FacturasKeyWords.IVA.ElementAt(j)) { int iva = 0; if (cargo.Concepto == Concepto.TV) { Calculadora.CalcularValorSinIVA(out int valorSinIva, out iva, cargo.Valor); } string valorToDisplay = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", iva); worksheet.Cells[rowNum, colNum].Value = valorToDisplay; } if (cellValue == FacturasKeyWords.NETO.ElementAt(j)) { string valorToDisplay = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", cargo.Valor); worksheet.Cells[rowNum, colNum].Value = valorToDisplay; } ++j; } //Change progress value int newProgress = (int)((100 * ((float)i / (float)items.Count))); base.UpdateProgreso(newProgress); (sender as BackgroundWorker).ReportProgress(Progress); } } //Clean unused fields in facturas for (int rowNum = 1; rowNum <= totalRows; ++rowNum) { for (int colNum = 1; colNum <= totalColumns; ++colNum) { var row = worksheet.Cells[rowNum, colNum].Select(c => c.Value == null ? String.Empty : c.Value.ToString()); string cellValue = String.Join(",", row); for (int j = 0; j < FacturasKeyWords.SIZEOFCARGO; j++) { if (cellValue == FacturasKeyWords.CONCEPTO.ElementAt(j)) { worksheet.Cells[rowNum, colNum].Value = String.Empty; } if (cellValue == FacturasKeyWords.PERIODO.ElementAt(j)) { worksheet.Cells[rowNum, colNum].Value = String.Empty; } if (cellValue == FacturasKeyWords.VALOR.ElementAt(j)) { worksheet.Cells[rowNum, colNum].Value = String.Empty; } if (cellValue == FacturasKeyWords.IVA.ElementAt(j)) { worksheet.Cells[rowNum, colNum].Value = String.Empty; } if (cellValue == FacturasKeyWords.NETO.ElementAt(j)) { worksheet.Cells[rowNum, colNum].Value = String.Empty; } } } } //Change Current Operation Description base.UpdateCurrentOperationDescription("Generando archivo PDF"); text.Dispatcher.Invoke(delegate { text.Text = CurrentOperationDescription; }); xlPackage.SaveAs(new System.IO.FileInfo(@FileLocationXlsx.ToString())); Workbook workbook = new Application().Workbooks.Open(@FileLocationXlsx.ToString()); workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, @FileLocationPDF.ToString()); ++NumberOfFilesCreated; workbook.Close(); } catch (System.InvalidOperationException) { RollBack(FileLocationXlsx.ToString(), FileLocationPDF.ToString()); throw; } finally { File.Delete(@FileLocationXlsx.ToString()); } } } base.UpdateProgreso(100); (sender as BackgroundWorker).ReportProgress(Progress); return(true); }
/// <summary> /// Processes the payment /// </summary> private void Pay() { if (CedulaCliente is null) { SystemSounds.Beep.Play(); MessageBox.Show("Cedula invalida", Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); return; } List <Cargo> cargosActualizados = new List <Cargo>(); foreach (Compra _compra in this.ListViewCompras.Items) { Cargo cargo = (Cargo)_compra.CargoView; cargosActualizados.Add(cargo); } int pagoTotal = int.Parse(this.TotalText.Content.ToString(), NumberStyles.Currency); try { Factura factura = new Factura(); //In this case NumeroFactura is used for the name of the file, so its safe not to provide the object with more values //Must add number of file to the name of the file to avoid file from being removed if two or more payments happen the same day factura.NumeroFactura = new StringBuilder(CedulaCliente).Append("-").Append(DateManager.GetMonthInSpanish()).Append("-").Append(UserPreferences.GetNumeroRecibo()).ToString(); factura.cargos = cargosActualizados; Customer customer = BDManager.GetCustomer(CedulaCliente); if (customer is null) { SystemSounds.Beep.Play(); MessageBox.Show("Error inesperado", Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error); return; } RecibosManager recibosManager = new RecibosManager(); Tuple <Factura, Customer> pair = new Tuple <Factura, Customer>(factura, customer); List <Tuple <Factura, Customer> > info = new List <Tuple <Factura, Customer> >(); info.Add(pair); try { recibosManager.Valor = pagoTotal; LoadingWindow loadingWindow = new LoadingWindow(); loadingWindow.Show(); loadingWindow.StartWorking((object sender, DoWorkEventArgs e) => { recibosManager.GenerateFiles(info, TypeOfRecibos.PAGO, sender, loadingWindow.Status); this.Dispatcher.Invoke(delegate { loadingWindow.Hide(); SystemSounds.Beep.Play(); MessageBox.Show("Archivo creado exitosamente", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); }); } ); } catch (Exception) { this.Dispatcher.Invoke(delegate { SystemSounds.Beep.Play(); MessageBox.Show(Messages.Errors.CouldntReadFile, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); }); return; } try { if (descuento == 0) { if (BDManager.Pay(cargosActualizados, CedulaCliente, pagoTotal)) { SystemSounds.Beep.Play(); MessageBox.Show("Pago exitoso!", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); Clean(); } } else { if (BDManager.Pay(cargosActualizados, CedulaCliente, pagoTotal, descuento, descuentoCargo)) { SystemSounds.Beep.Play(); MessageBox.Show("Pago exitoso!", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information); Clean(); } } } catch (Exception) { SystemSounds.Beep.Play(); MessageBox.Show("No se pudo efectuar el pago", Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning); int resetNumeber = UserPreferences.GetNumeroRecibo(); UserPreferences.SaveNumeroRecibo(--resetNumeber); } } catch (Exception e) { SystemSounds.Beep.Play(); MessageBox.Show("Error inesperado. Elimine el archivo generado!" + "\n" + e.Message, Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error); } }