private void GenReport_Click(object sender, RoutedEventArgs e) { //Common.ExportToExcel<RateView, List<RateView>> exporttoexcel = //new Common.ExportToExcel<RateView, List<RateView>>(); ////实例化exporttoexcel对象 //exporttoexcel.DataToPrint = (List<RateView>)dataGrid.ItemsSource; // create an instance of pdf export filter FastReport.Export.Pdf.PDFExport export = new FastReport.Export.Pdf.PDFExport(); // show the export options dialog and do the export //if (export.ShowDialog()) // report.Export(export, "result.pdf"); Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "报表"; // Default file name dlg.DefaultExt = ".pdf"; // Default file extension dlg.Filter = "pdf (.pdf)|*.pdf"; // Filter files by extension // Show save file dialog box Nullable <bool> result = dlg.ShowDialog(); string filename = string.Empty; // Process save file dialog box results if (result == true) { report.Export(export, dlg.FileName); LogHelper.WriteLog("导出报表成功:" + dlg.FileName); } else { return; } }
private FileStreamResult FastReportDownload(Report pdf) { if (pdf.Report.Prepare()) { // Set PDF export props FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport(); pdfExport.ShowProgress = false; pdfExport.Subject = "Subject"; pdfExport.Title = "xxxxxxx"; pdfExport.Compressed = true; pdfExport.AllowPrint = true; pdfExport.EmbeddingFonts = true; MemoryStream strm = new MemoryStream(); pdf.Report.Export(pdfExport, strm); pdf.Dispose(); pdfExport.Dispose(); strm.Position = 0; // return stream in browser return(File(strm, "application/pdf", "report.pdf")); } else { return(null); } }
private FileStreamResult ExportReport(Report report, int exportType, string fileName) { string mimeType = "application/pdf"; string extension = "pdf"; dynamic frExportType = new FastReport.Export.Pdf.PDFExport(); switch ((ExportTypes)exportType) { case ExportTypes.Excel: { mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; frExportType = new FastReport.Export.OoXML.Excel2007Export(); extension = "xlsx"; break; } case ExportTypes.Word: { mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; frExportType = new FastReport.Export.OoXML.Word2007Export(); extension = "docx"; break; } } var msx = new MemoryStream(); report.Export(frExportType, msx); msx.Position = 0; HttpContext.Response.AddHeader("content-disposition", "inline; filename=\"" + fileName + "." + extension + "\""); return(new FileStreamResult(msx, mimeType)); }
public static string GetReport(string Reportname, string DataSetName, string Subject, string Title, List <ReportParameters> parameters, DataTable result) { try { Report report = new Report(); string report_path = HttpContext.Current.Server.MapPath("~/ReportFormat/"); string reportName = string.Empty; report.Load(report_path + Reportname + ".frx"); result.TableName = DataSetName; report.RegisterData(result, DataSetName); //foreach (var param in parameters) //{ // report.SetParameterValue(param.Key, param.Value); //} if (report.Prepare()) { FastReport.Utils.Config.WebMode = true; // Set PDF export props FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport(); pdfExport.ShowProgress = false; pdfExport.Subject = Subject; pdfExport.Title = Title; pdfExport.Compressed = true; pdfExport.AllowPrint = true; pdfExport.EmbeddingFonts = false; pdfExport.Author = "Farrukh Khan"; pdfExport.Creator = "Fast Report"; var strm = new MemoryStream(); report.Export(pdfExport, strm); report.Dispose(); pdfExport.Dispose(); strm.Position = 0; reportName = Reportname + DateTime.Now.ToString("dd_MM_yyyy_HH_mm"); if (File.Exists(HttpContext.Current.Server.MapPath("~/Report/") + reportName + ".pdf")) { File.Delete(HttpContext.Current.Server.MapPath("~/Report/") + reportName + ".pdf"); } var fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/Report/") + reportName + ".pdf", FileMode.Create, FileAccess.Write); strm.CopyTo(fileStream); fileStream.Dispose(); } return(reportName + ".pdf"); } catch (Exception ex) { throw ex; } }
public static string GetReportWithDs(string reportName, string title, List <ReportParameters> parameters, DataSet result) { try { Report report = new Report(); string report_path = HttpContext.Current.Server.MapPath("~/ReportFormat/"); report.Load(report_path + reportName + ".frx"); report.RegisterData(result.Tables[0], "Table"); report.RegisterData(result.Tables[1], "Summary"); foreach (var param in parameters) { report.SetParameterValue(param.Key, param.Value); } if (report.Prepare()) { FastReport.Utils.Config.WebMode = true; // Set PDF export props FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport(); pdfExport.ShowProgress = false; pdfExport.Subject = title; pdfExport.Title = title; pdfExport.Compressed = true; pdfExport.AllowPrint = true; pdfExport.EmbeddingFonts = false; pdfExport.Author = "Farrukh Khan"; pdfExport.Creator = "Fast Report"; var strm = new MemoryStream(); report.Export(pdfExport, strm); report.Dispose(); pdfExport.Dispose(); strm.Position = 0; var fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/Report/") + reportName + ".pdf", FileMode.Create, FileAccess.Write); strm.CopyTo(fileStream); fileStream.Dispose(); } return(reportName + ".pdf"); } catch (Exception ex) { throw ex; } }
public static MemoryStream ShowData(string reportname, IEnumerable data) { using (Report report = GetLoadedReport(reportname)) { if (data != null) { RegisterData(report, data); } //report.Show(); if (report.Report.Prepare()) { // Set PDF export props FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport(); pdfExport.ShowProgress = false; pdfExport.Subject = "Subject"; pdfExport.Title = "Title"; pdfExport.Compressed = true; pdfExport.AllowPrint = true; pdfExport.EmbeddingFonts = true; //MemoryStream strm = new MemoryStream(); //report.Report.Export(pdfExport, strm); //report.Dispose(); //pdfExport.Dispose(); //strm.Position = 0; using (MemoryStream strm = new MemoryStream()) { report.Report.Export(pdfExport, strm); report.Dispose(); pdfExport.Dispose(); strm.Position = 0; //for check data //File.WriteAllBytes(@"C:\Users\job\Desktop\PD1F.pdf", strm.ToArray()); return(strm); } } else { return(new MemoryStream()); } } }
static byte[] ExportarRelatorio(Report report, TiposDeRelatorios tipoDeRelatorio) { FastReport.Export.ExportBase relatorio = new FastReport.Export.ExportBase(); byte[] relatorioGerado = null; switch (tipoDeRelatorio) { case TiposDeRelatorios.CSV: relatorio = new FastReport.Export.Csv.CSVExport(); break; case TiposDeRelatorios.HTML: relatorio = new FastReport.Export.Html.HTMLExport(); break; case TiposDeRelatorios.PDF: relatorio = new FastReport.Export.Pdf.PDFExport(); break; case TiposDeRelatorios.RTF: relatorio = new FastReport.Export.RichText.RTFExport(); break; case TiposDeRelatorios.TXT: relatorio = new FastReport.Export.Text.TextExport(); break; case TiposDeRelatorios.XML: relatorio = new FastReport.Export.Xml.XMLExport(); break; } using (MemoryStream relatorioExportadoEmMemoria = new MemoryStream()) { report.Report.Export(relatorio, relatorioExportadoEmMemoria); relatorioGerado = relatorioExportadoEmMemoria.ToArray(); } relatorio.Dispose(); return(relatorioGerado); }
private void btnStore_Click(object sender, EventArgs e) { FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport(); pdfExport.ShowProgress = true; pdfExport.Subject = "Subject"; pdfExport.Title = "Exam"; pdfExport.Compressed = true; pdfExport.AllowPrint = true; pdfExport.EmbeddingFonts = true; MemoryStream strm = new MemoryStream(); report.Prepare(); report.Export(pdfExport, strm); byte[] b = strm.ToArray(); string title = Microsoft.VisualBasic.Interaction.InputBox("Exam Paper Title", "Save Exam Paper", (cbAcedemicYear.Text) + (cbCourse.Text) + (comboBox4.Text)); DbProcess.ExamPapersInsert(frm1.PersonelId, title, b); MessageBox.Show("Done."); }
public IActionResult ReportePDF(string NombreReporte, IList <RepParametro> parametros) { FastReport.Utils.Config.WebMode = true; var rep = new WebReport(); var savePath = System.IO.Path.Combine(Startup.entorno.WebRootPath, "Reportes"); var path = $"{savePath}\\{NombreReporte}.frx";//guarda el frm del reporte creado de fast repor rep.Report.Load(path); var str = Resources.JsonStringProvider.GetJson(CultureInfo.CurrentCulture.Name); //idioma rep.Report.Dictionary.Connections[0].ConnectionString = StringProvider.StringGE; rep.Report.Dictionary.Connections[1].ConnectionString = StringProvider.StringEmpresas;// primera conexion rep.Report.Dictionary.Connections[2].ConnectionString = str; foreach (var item in parametros) { rep.Report.SetParameterValue(item.Nombre, item.Valor);// envia por parametro el idempresa a fast report } if (rep.Report.Prepare()) { FastReport.Export.Pdf.PDFExport imgExport = new FastReport.Export.Pdf.PDFExport(); MemoryStream strm = new MemoryStream(); rep.Report.Export(imgExport, strm); rep.Report.Dispose(); imgExport.Dispose(); strm.Position = 0; return(File(strm, "application/pdf", $"{NombreReporte}.pdf")); } else { return(null); } }
/// <summary> /// Report generation process. /// </summary> private void ExportReport() { try { //var filePath = HttpContext.Current.Request.PhysicalApplicationPath + "App_Data\\" + "xmlForFastReport.xml"; //m_xmlForfastReport.Save(filePath); // report init Report report = new Report(); // bind data System.Data.DataSet dataSet = new System.Data.DataSet(); dataSet.ReadXml(new StringReader(new XElement(m_xmlForfastReport).ToString())); //dataSet.ReadXml(filePath); report.Report.RegisterData(dataSet); // load report template and prepare the final report report.Load(m_fastReportTemplateLocation + m_fastReportTemplateName); report.Prepare(); // tuto to hadze chybu FastReport.Export.Pdf.PDFExport export = new FastReport.Export.Pdf.PDFExport(); // save generated report to disk if (!Directory.Exists(m_fileNameBuilder.GetDestinationPath())) // ak priecinok zatial neexistuje -> vytvor ho { Directory.CreateDirectory(m_fileNameBuilder.GetDestinationPath()); } m_destinationFilePath = m_fileNameBuilder.GetDestinationPath() + @DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + m_fileNameBuilder.GetPartnerName() + "_" + m_fileNameBuilder.GetCardOrderId() + "_" + m_fileNameBuilder.GetEnvironment() + ".pdf"; export.Export(report, m_destinationFilePath); export = null; // ??? necessary ??? report = null; // ??? necessary ??? } catch (Exception e) { throw; } }
private string ExportToPDF() { DirectoryInfo dir = new DirectoryInfo(@"C:\EmailPDF"); if (!dir.Exists) { dir.Create(); } Random rnd = new Random(); rnd.Next(10000); string fileName = dir + "\\tmpMail" + rnd.Next(10000).ToString().PadLeft(4, '0') + ".pdf"; FileInfo fi = new FileInfo(fileName); Stream sr = fi.Create(); FastReport.Export.Pdf.PDFExport imgExp = new FastReport.Export.Pdf.PDFExport(); imgExp.Export(previewControl1.Report, sr); sr.Close(); return(fileName); }
protected void btnPrint_Click(object sender, EventArgs e) { string Path = System.AppDomain.CurrentDomain.BaseDirectory + @"RptFiles\"; System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Path + @"PDF\"); foreach (System.IO.FileInfo fi in di.GetFiles()) { TimeSpan ts = DateTime.Now - fi.CreationTime; if (ts.Hours >= 2) { fi.Delete(); } } DataTable dt = bll.FillDataTable("WMS.SelectPrintBillDetail", new DataParameter[] { new DataParameter("@BillID", this.txtID.Text) }); DataTable dtNew = dt.Clone(); int pageNum = 0; if (dt.Rows.Count % 14 != 0) { pageNum = dt.Rows.Count / 14 + 1; } else { pageNum = dt.Rows.Count / 14; } for (int i = 0; i < pageNum; i++) { for (int j = 1; j <= 14; j++) { DataRow[] drs = dt.Select(string.Format("RowID={0}", i * 14 + j)); if (drs.Length > 0) { drs[0]["RowNum"] = j; dtNew.Rows.Add(drs[0].ItemArray); } else { DataRow dr = dtNew.NewRow(); dr["BillID"] = this.txtID.Text; dr["RowID"] = i * 14 + j; dr["RowNum"] = j; dtNew.Rows.Add(dr); } } } using (Report report = new Report()) { report.Load(Path + @"OutStockView.frx"); report.RegisterData(dtNew, "OutStockView"); report.Prepare(); //report.FinishReport += new EventHandler(report_FinishReport); string FileName = Path + @"PDF\OutStockView_" + this.txtID.Text + ".pdf"; FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport(); report.Export(pdfExport, FileName); FileName = "OutStockView_" + this.txtID.Text + ".pdf"; Response.Redirect("../Query/StockPrint.aspx?FormID=" + FormID + "&BillID=" + this.txtID.Text + "&PdfName=" + FileName + "&SubModuleCode=" + SubModuleCode + "&SqlCmd=" + SqlCmd + "&PagePath=OutStock"); } }
public string Process(CustomReportDisplayMode pViewMode, string pDestinationFileName = "") { string result = String.Empty; //Prepare Modes switch (pViewMode) { case CustomReportDisplayMode.Preview: case CustomReportDisplayMode.Print: case CustomReportDisplayMode.ExportPDF: case CustomReportDisplayMode.ExportPDFSilent: //Get Object Reference to Change CopyName TextObject textCopyName = (TextObject)this.FindObject("TextCopyName"); //Get Object Reference to Change SecondPrint Label for DocumentFinanceDocuments TextObject textSecondPrint = (TextObject)this.FindObject("TextSecondPrint"); //Loop Copies and Change CopyName for (int i = 0; i < this.PrintSettings.CopyNames.Length; i++) { if (textCopyName != null) { textCopyName.Text = this.PrintSettings.CopyNames[i]; } if (textSecondPrint != null) { textSecondPrint.Text = (_secondCopy && i < 1) ? Resx.global_print_second_print : String.Empty; } //Store PreparedFiles in Custom SystemVariable, Required to PageNo in Reports ex "[ToInt32([PreparedPages]) + [Page]]" //Else Page start aways in 1, when we call prepare, and we cannot have a usefull Page Counter working with .Prepare this.Dictionary.SystemVariables.FindByName("PreparedPages").Value = (this.PreparedPages != null) ? this.PreparedPages.Count : 0; //Call Report Prepare this.Prepare(true); } break; } //NOT USED ANYMORE : Now we can Reset Copies to 1 //this.PrintSettings.Copies = 1; //Send to ViewMode switch (pViewMode) { case CustomReportDisplayMode.Preview: this.ShowPrepared(); break; case CustomReportDisplayMode.Print: this.PrintPrepared(); break; case CustomReportDisplayMode.Design: this.Design(); break; case CustomReportDisplayMode.ExportPDF: case CustomReportDisplayMode.ExportPDFSilent: //Prepare FileName string fileName = String.Empty; if (pDestinationFileName != String.Empty) { fileName = pDestinationFileName; } //Default Filename else { string dateTimeFileFormat = SettingsApp.FileFormatDateTime; string dateTime = FrameworkUtils.CurrentDateTimeAtomic().ToString(dateTimeFileFormat); string reportName = (this.ReportInfo.Name != String.Empty) ? string.Format("_{0}", this.ReportInfo.Name) : String.Empty; fileName = string.Format("print_{0}{1}{2}", dateTime, reportName, ".pdf"); fileName = fileName.Replace('/', '-').Replace(' ', '_'); //2015-06-12 apmuga fileName = FrameworkUtils.OSSlash(string.Format(@"{0}{1}", GlobalFramework.Path["temp"], fileName)); //Mario //fileName = (GlobalFramework.Settings["AppEnvironment"].ToUpper() == "web".ToUpper()) // ? FrameworkUtils.OSSlash(string.Format(@"{0}{1}", GlobalFramework.Path["temp"], fileName)) // : FrameworkUtils.OSSlash(string.Format(@"{0}\{1}{2}", Environment.CurrentDirectory, GlobalFramework.Path["temp"], fileName)) //; } FastReport.Export.Pdf.PDFExport export = new FastReport.Export.Pdf.PDFExport(); //if (export.ShowDialog()) report.Export(export, fileName); try { this.Export(export, fileName); } catch (Exception ex) { _log.Error(ex.Message, ex); } //Show Pdf if (pViewMode == CustomReportDisplayMode.ExportPDF && File.Exists(fileName)) { if (GlobalFramework.CanOpenFiles) { //Use full Path, keep untoutched fileName for result System.Diagnostics.Process.Start(FrameworkUtils.OSSlash(string.Format(@"{0}\{1}", Environment.CurrentDirectory, fileName))); } } result = fileName; break; default: break; } return(result); }
private static Report FeGuardarArchivosFacturaDevolucion(ref FacturaElectronica oFacturaE, string sCfdiTimbrado, string sSerieFolio) { // Se obtienen las rutas a utilizar DateTime dAhora = DateTime.Now; string sRutaPdf = TheosProc.Config.Valor("Facturacion.Devolucion.RutaPdf"); string sRutaXml = TheosProc.Config.Valor("Facturacion.Devolucion.RutaXml"); string sAnioMes = (@"\" + dAhora.Year.ToString() + @"\" + dAhora.Month.ToString() + @"\"); sRutaPdf += sAnioMes; Directory.CreateDirectory(sRutaPdf); sRutaXml += sAnioMes; Directory.CreateDirectory(sRutaXml); // Se guarda el xml string sArchivoXml = (sRutaXml + sSerieFolio + ".xml"); File.WriteAllText(sArchivoXml, sCfdiTimbrado, Encoding.UTF8); // Se manda la salida de la factura string sArchivoPdf = (sRutaPdf + sSerieFolio + ".pdf"); var oRep = new Report(); oRep.Load(GlobalClass.ConfiguracionGlobal.pathReportes + "CfdiNotaDeCredito.frx"); var ObjetoCbb = new { Imagen = oFacturaE.GenerarCbb() }; oRep.RegisterData(new List<FacturaElectronica>() { oFacturaE }, "Factura"); oRep.RegisterData(new List<object>() { ObjetoCbb }, "Cbb"); oRep.SetParameterValue("Vendedor", oFacturaE.Adicionales["Vendedor"].ToUpper()); oRep.SetParameterValue("TotalConLetra", Util.ImporteALetra(oFacturaE.Total).ToUpper()); oRep.SetParameterValue("FacturaOrigen", oFacturaE.Adicionales["FacturaOrigen"]); UtilLocal.EnviarReporteASalida("Reportes.VentaFacturaDevolucion.Salida", oRep); // Se guarda el pdf var oRepPdf = new FastReport.Export.Pdf.PDFExport() { ShowProgress = true }; oRep.Prepare(); oRep.Export(oRepPdf, sArchivoPdf); return oRep; }
public HttpResponseMessage PostReport(JObject JsonRequest) { int status = 0; string error = ""; try { String className = "FastReport." + JsonRequest["ClassName"].ToString(); string rootPath = System.Environment.CurrentDirectory; string outputPath = Path.Combine(rootPath, "output.pdf"); //FastReport.Report report = new FastReport.Report(); //string filename = @"C:\Users\lipan\Desktop\report3.frx"; //report.Load(filename); FastReport.Report report = (FastReport.Report)Activator.CreateInstance(System.Type.GetType(className)); DataSet data = new DataSet(); DataTable table = new DataTable(); int num = 0; foreach (var item in JsonRequest) { if (item.Key.StartsWith("ClassName")) { continue; } if (item.Key.StartsWith("Signature")) { DataTable dt = new DataTable(); dt.TableName = item.Key; dt.Columns.Add(item.Key, typeof(byte[])); WebClient wc = new WebClient(); byte[] bytes; if (item.Value.ToString() == "") { //此处留空时处理; bytes = wc.DownloadData(Path.Combine(rootPath, "EmptySignature.PNG")); } else { bytes = wc.DownloadData(item.Value.ToString()); } MemoryStream msIMG = new MemoryStream(bytes); Image img = System.Drawing.Image.FromStream(msIMG); //Image img = Image.FromFile(folderPath + item.Key + ".PNG"); DataRow row = dt.NewRow(); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); row[item.Key] = ms.ToArray(); dt.Rows.Add(row); data.Tables.Add(dt); continue; } table = CSVHelper.ConvertJsonToDatatable(JsonRequest.ToString(), num); table.TableName = item.Key; data.Tables.Add(table); num++; } report.RegisterData(data); int tableNum = data.Tables.Count; for (int i = 0; i < tableNum; i++) { report.GetDataSource(data.Tables[i].TableName).Enabled = true; } report.Prepare(); FastReport.Export.Pdf.PDFExport export = new FastReport.Export.Pdf.PDFExport(); report.Export(export, outputPath); System.Diagnostics.Process.Start(outputPath); } catch (Exception e) { status = -1; error = e.ToString(); } String returnValue = JsonConvert.SerializeObject(new { status = status.ToString(), error = error }); return(ResultToJson.toJson(returnValue)); }
private bool Corte() { // Se ejecuta una acción dependiendo del "paso" en el que vaya el proceso // Paso 0: Corte mostrado // Paso 1: Pantalla para conteo mostrada // Paso 2: Corte mostrado con conteo realizado // Paso 3: Pantalla de tickets del día (para Factura Global) CajaCorte oCorte = this.ctlCajaGeneral.ctlCorte; switch (oCorte.Paso) { case 0: // De momento no aplica return false; case 1: oCorte.RegistrarConteo(oCorte.ctlConteo.Total); oCorte.Paso = 2; return false; /* case 2: oCorte.ctlFacturaGlobal = new CajaFacturaGlobal() { Dock = DockStyle.Fill }; oCorte.Parent.Controls.Add(oCorte.ctlFacturaGlobal); oCorte.ctlFacturaGlobal.BringToFront(); oCorte.Paso = 3; return false; */ } // Se valida que no haya ventas por cobrar DateTime dHoy = DateTime.Today; if (Datos.Exists<Venta>(c => c.VentaEstatusID == Cat.VentasEstatus.Realizada && EntityFunctions.TruncateTime(c.Fecha) == dHoy && c.Estatus)) { UtilLocal.MensajeAdvertencia("Existen una o más ventas por cobrar. No se puede continuar."); return false; } // Se valida que se haya hecho el fondo de caja var oDia = Datos.GetEntity<CajaEfectivoPorDia>(q => q.SucursalID == GlobalClass.SucursalID && q.Dia == dHoy && q.Estatus); if (oDia == null) { UtilLocal.MensajeAdvertencia("No se ha realizado el Fondo de Caja, por lo tanto no se puede continuar."); return false; } // Se valida que no haya autorizaciones pendientes if (Datos.Exists<Autorizacion>(c => c.SucursalID == GlobalClass.SucursalID && EntityFunctions.TruncateTime(c.FechaRegistro) == dHoy && !c.Autorizado)) { UtilLocal.MensajeAdvertencia("No se han completado todas las Autorizaciones del día. No se puede continuar."); return false; } // Se valida que se hayan recibido todos los traspasos marcados if (Datos.Exists<MovimientoInventario>(c => c.TipoOperacionID == Cat.TiposDeOperacionMovimientos.Traspaso && c.SucursalDestinoID == GlobalClass.SucursalID && c.TraspasoEntregado.HasValue && c.TraspasoEntregado.Value && !c.FechaRecepcion.HasValue)) { UtilLocal.MensajeAdvertencia("No se han registrado todos los traspasos que ya se marcaron como entregados."); return false; } // Se valida que no haya conteos de inventario pendientes if (Util.Logico(Config.Valor("Inventario.Conteo.RevisarEnCorte"))) { var oConteosPen = UtilDatos.InventarioUsuariosConteoPendiente(); if (oConteosPen.Count > 0) { UtilLocal.MensajeAdvertencia("No se han realizado todos los conteos de inventario. No se puede continuar."); return false; } } // Se valida que no haya Control de Cascos pendientes por completar if (Datos.Exists<CascosRegistrosView>(c => c.NumeroDeParteRecibido == null && c.FolioDeCobro == null && (c.VentaEstatusID != Cat.VentasEstatus.Cancelada && c.VentaEstatusID != Cat.VentasEstatus.CanceladaSinPago))) { UtilLocal.MensajeAdvertencia("No se han completado todos los registros de cascos. No se puede continuar."); return false; } // Se confirma la operación string sMensaje = string.Format("¿Estás seguro que deseas realizar el Cierre de Caja con un importe de {0}?", oCorte.Conteo.ToString(GlobalClass.FormatoMoneda)); if (oCorte.Diferencia != 0) sMensaje += string.Format("\n\nToma en cuenta que hay una diferencia de {0} y por tanto se requerirá una autorización para continuar.", oCorte.Diferencia.ToString(GlobalClass.FormatoMoneda)); if (UtilLocal.MensajePregunta(sMensaje) != DialogResult.Yes) return false; // Se solicita la validación del usuario var Res = UtilLocal.ValidarObtenerUsuario("Ventas.CorteDeCaja.Agregar"); if (Res.Error) return false; var oUsuario = Res.Respuesta; // Se solicita la validación de autorización, si aplica Usuario oAutorizo = null; if (oCorte.Diferencia != 0) { Res = UtilLocal.ValidarObtenerUsuario("Autorizaciones.Ventas.CorteDeCaja.Diferencia", "Autorización"); //if (Res.Exito) oAutorizo = Res.Respuesta; } // Se procede a guardar los datos DateTime dAhora = DateTime.Now; // Se manda a generar la Factura Global bool bFacturaGlobal = this.FacturaGlobal(oDia); if (!bFacturaGlobal) return false; // Se manda guardar el histórico del corte bool bSeguir = this.GuardarHistoricoCorte(); if (!bSeguir) return false; // Se registra el cierre de caja oDia.CierreDebeHaber = oCorte.Total; oDia.Cierre = oCorte.Conteo; oDia.CierreUsuarioID = oUsuario.UsuarioID; Datos.Guardar<CajaEfectivoPorDia>(oDia); // Se registra la póliza de la diferencia, si hubo if (oCorte.Diferencia != 0) { if (oCorte.Diferencia > 0) ContaProc.CrearPoliza(Cat.ContaTiposDePoliza.Diario, "DIFERENCIA EN CORTE", Cat.ContaCuentasAuxiliares.Caja, Cat.ContaCuentasAuxiliares.FondoDeCaja , oCorte.Diferencia, DateTime.Now.ToShortDateString(), Cat.Tablas.CajaEfectivoPorDia, oDia.CajaEfectivoPorDiaID); else ContaProc.CrearPoliza(Cat.ContaTiposDePoliza.Diario, "DIFERENCIA EN CORTE", Cat.ContaCuentasAuxiliares.FondoDeCaja, Cat.ContaCuentasAuxiliares.Caja , (oCorte.Diferencia * -1), DateTime.Now.ToShortDateString(), Cat.Tablas.CajaEfectivoPorDia, oDia.CajaEfectivoPorDiaID); } // Se genera y guarda la autorización, si aplica if (oCorte.Diferencia != 0) { int iAutorizoID = (oAutorizo == null ? 0 : oAutorizo.UsuarioID); VentasProc.GenerarAutorizacion(Cat.AutorizacionesProcesos.CorteDeCaja, Cat.Tablas.CajaEfectivoPorDia, oDia.CajaEfectivoPorDiaID, iAutorizoID); } // Se genera un pdf con la información del corte var Rep = new Report(); Rep.Load(GlobalClass.ConfiguracionGlobal.pathReportes + "CajaCorte.frx"); Rep.RegisterData(oCorte.GenerarDatosCorte(), "Corte"); Rep.RegisterData(this.ctlCajaGeneral.ctlDetalleCorte.GenerarDatosDetalle(), "Detalle"); Rep.RegisterData(oCorte.GenerarDatosCambios(), "Cambios"); Rep.RegisterData(new List<ConteoCaja>() { oCorte.ctlConteo.GenerarConteo() }, "Conteo"); Rep.SetParameterValue("Sucursal", GlobalClass.NombreTienda); // Se obtiene el nombre del archivo string sRuta = Config.Valor("Caja.Corte.RutaArchivos"); if (!Directory.Exists(sRuta)) Directory.CreateDirectory(sRuta); string sArchivo = (sRuta + DateTime.Now.ToString("yyyyMMdd") + "_" + GlobalClass.NombreTienda + ".pdf"); // Se genera el Pdf var oRepPdf = new FastReport.Export.Pdf.PDFExport() { ShowProgress = true }; Rep.Prepare(); Rep.Export(oRepPdf, sArchivo); // Se manda la impresion UtilLocal.EnviarReporteASalida("Reportes.CajaCorte.Salida", Rep, true); // Se regresa el paso del proceso oCorte.Paso = 0; // Se muestra una notifiación con el resultado UtilLocal.MostrarNotificacion("Procedimiento completado correctamente."); return true; }
private bool CambioTurno() { // Se ejecuta una acción dependiendo del "paso" en el que vaya el proceso // Paso 0: Corte mostrado // Paso 1: Pantalla para conteo mostrada // Paso 2: Corte mostrado con conteo realizado CajaCambioTurno oCambioTurno = this.ctlCajaGeneral.ctlCambioTurno; switch (oCambioTurno.Paso) { case 0: // De momento no aplica return false; case 1: oCambioTurno.RegistrarConteo(oCambioTurno.ctlConteo.Total); oCambioTurno.Paso = 2; return false; } // Se piden las contraseñas var oResU1 = UtilLocal.ValidarObtenerUsuario(null, false, "Engrega"); if (oResU1.Error) return false; var oResU2 = UtilLocal.ValidarObtenerUsuario(null, false, "Recibe"); if (oResU2.Error) return false; // Se genera un pdf con la información del corte var Rep = new Report(); Rep.Load(GlobalClass.ConfiguracionGlobal.pathReportes + "CajaCorte.frx"); Rep.RegisterData(oCambioTurno.GenerarDatosCorte(), "Corte"); Rep.RegisterData(this.ctlCajaGeneral.ctlDetalleCorte.GenerarDatosDetalle(), "Detalle"); Rep.RegisterData(oCambioTurno.GenerarDatosCambios(), "Cambios"); Rep.RegisterData(new List<ConteoCaja>() { oCambioTurno.ctlConteo.GenerarConteo() }, "Conteo"); Rep.SetParameterValue("Sucursal", GlobalClass.NombreTienda); Rep.SetParameterValue("Entrega", oResU1.Respuesta.NombreUsuario); Rep.SetParameterValue("Recibe", oResU2.Respuesta.NombreUsuario); // Se obtiene el nombre del archivo int iConsecutivo = 0; string sRuta = Config.Valor("Caja.CambioTurno.RutaArchivos"); string sFormato = (sRuta + DateTime.Now.ToString("yyyyMMdd") + "-{0}.pdf"); string sArchivo; do { sArchivo = string.Format(sFormato, ++iConsecutivo); } while (File.Exists(sArchivo)); // Se genera el Pdf var oRepPdf = new FastReport.Export.Pdf.PDFExport() { ShowProgress = true }; Rep.Prepare(); Rep.Export(oRepPdf, sArchivo); // Se manda la impresion UtilLocal.EnviarReporteASalida("Reportes.CajaCorte.Salida", Rep, true); // Se regresa el paso del proceso oCambioTurno.Paso = 0; // Se registra el cambio de turno en la base de datos Datos.Guardar<CajaCambioDeTurno>(new CajaCambioDeTurno() { SucursalID = GlobalClass.SucursalID, Fecha = DateTime.Now, EntregaUsuarioID = oResU1.Respuesta.UsuarioID, RecibeUsuarioID = oResU2.Respuesta.UsuarioID, Total = oCambioTurno.Total, Conteo = oCambioTurno.Conteo }); // Se muestra una notifiación con el resultado UtilLocal.MostrarNotificacion("Procedimiento completado correctamente."); return true; }