/// <summary> /// This is an auxiliary method because it's invoker "VndBSVendas.DepoisDeGravar" has parameters by reference /// and async methods doesn't support parameters by reference. /// </summary> private async void PrintPdfAndEmailDocument(VndBEDocumentoVenda clsDocumentoVenda, string outputPdf, string emailAdress) { // Print asyncronously in a new thread, because Crystal Reports uses UI and since // we're in the context of the ERP Engine we can't handle Crystal Reports UI. await Task.Run(() => GlobalFunctions.PrintInvoice(PSO, BSO, outputPdf, clsDocumentoVenda.Tipodoc, clsDocumentoVenda.Serie, clsDocumentoVenda.NumDoc)) .ContinueWith(taskResult => { var strAssunto = new StringBuilder(); strAssunto.Append("A new invoice was created."); strAssunto.Append(clsDocumentoVenda.Tipodoc); strAssunto.Append(clsDocumentoVenda.Serie); strAssunto.Append(clsDocumentoVenda.NumDoc); PSO.Mail.Inicializa(); PSO.Mail.EnviaMailEx(emailAdress, null, null, strAssunto.ToString(), null, outputPdf, false); }, TaskScheduler.FromCurrentSynchronizationContext()); }
/// <summary> /// Fill the grid with the selected entity account amount. /// </summary> void LoadGrid() { StringBuilder sql = new StringBuilder(); string query = string.Empty; // Get the DocumentoVenda object by reflection. VndBEDocumentoVenda documentoVenda = (VndBEDocumentoVenda)formContext.GetType().GetProperty("DocumentoVenda").GetValue(formContext, null); // Get the connection string from the context. string connectionString = plataform.BaseDados.DaConnectionStringNET (plataform.BaseDados.DaNomeBDdaEmpresa(engine.Contexto.CodEmp), "Default"); sql.Append("SELECT TipoDoc,TipoConta, SUM(ValorPendente) AS Total , SUM(Valortotal) AS Pendente FROM"); sql.Append(" Pendentes WHERE entidade='@1@' and TipoDoc = '@2@'"); sql.Append(" GROUP BY TipoConta,TipoDoc"); query = sql .Replace("@1@", this.EntityKey.ToString()) .Replace("@2@", documentoVenda.Tipodoc.ToString()) .ToString(); try { dataGridPendentes.ReadOnly = true; SqlConnection connection = new SqlConnection(connectionString); SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection); SqlCommandBuilder comBuilder = new SqlCommandBuilder(dataAdapter); DataSet ds = new DataSet(); dataAdapter.Fill(ds); dataGridPendentes.DataSource = ds.Tables[0]; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public override void DepoisDeGravar(VndBEDocumentoVenda clsDocumentoVenda, ref string strAvisos, ref string IdDocLiqRet, ref string IdDocLiqRetGar, ExtensibilityEventArgs e) { try { const string outputPdf = @"C:\temp\invoice.pdf"; const string emailAdress = @" -- INSERT A VALID EMAIL WHERE -- "; PrintPdfAndEmailDocument(clsDocumentoVenda, outputPdf, emailAdress); } catch (Exception ex) { throw new Exception("Cannot send the email to the customer. \n" + ex.Message); } finally { base.DepoisDeGravar(clsDocumentoVenda, ref strAvisos, ref IdDocLiqRet, ref IdDocLiqRetGar, e); } }
/// <summary> /// Creates a new invoice. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CmdSave_Click(object sender, EventArgs e) { VndBEDocumentoVenda invoice = new VndBEDocumentoVenda(); string avisos = string.Empty; invoice.Tipodoc = txtTipoDoc.Text; invoice.Entidade = txtEntidade.Text; invoice.TipoEntidade = "C"; invoice.Serie = txtSerie.Text; // To save the document as draft set this flag to true //invoice.Rascunho = true ; try { if (checkBox1.Checked) { // Set all the entity related information. PriEngine.Engine.Vendas.Documentos.PreencheDadosRelacionados(invoice); } if (listView1.Items.Count > 0) { foreach (ListViewItem item in listView1.Items) { VndBELinhasDocumentoVenda linhas = new VndBELinhasDocumentoVenda(); double qtd = Convert.ToDouble(item.SubItems[1].Text); // Add new line to the invoice and set all the item related information. PriEngine.Engine.Vendas.Documentos.AdicionaLinha(invoice, item.SubItems[0].Text, ref qtd); linhas = invoice.Linhas; linhas.GetEdita(1).Desconto1 = 10; linhas.GetEdita(1).DataEntrega = DateTime.Now.Date.AddDays(10); } if (txtobs.Text.Length > 0) { PriEngine.Engine.Vendas.Documentos.AdicionaLinhaEspecial(invoice, vdTipoLinhaEspecial.vdLinha_Comentario, 0, txtobs.Text); } } else { MessageBox.Show("There are no items."); } PriEngine.Engine.Vendas.Documentos.CalculaValoresTotais(invoice); // Save the document as draft. // PriEngine.Engine.Comercial.Vendas.ActualizaRascunho(invoice, ref strAvisos); PriEngine.Engine.Vendas.Documentos.Actualiza(invoice, ref avisos); // Accountig PriEngine.Engine.Base.LigacaoCBL.IntegraDocumentoLogCBL("V", invoice.Tipodoc, invoice.Serie, invoice.NumDoc, invoice.Filial, 1, ref avisos, true); // Show warning any message. if (avisos.Length > 0) { MessageBox.Show(avisos.ToString()); } // Send the invoice by email StringBuilder assunto = new StringBuilder(); string body = "<html><body><div class='count-center'><div class='top'><h1>EXEMPLO HTML</h1></div></body></html>"; assunto.Append("A new invoice was created - "); assunto.Append(invoice.Tipodoc.ToString()); assunto.Append("/"); assunto.Append(invoice.NumDoc.ToString()); PriEngine.Platform.Mail.Inicializa(); PriEngine.Platform.Mail.EnviaMailEx("*****@*****.**", null, null, assunto.ToString(), body.ToString(), null, false); } catch (Exception ex) { MessageBox.Show("Unable to save document. \n" + ex.Message); } }
/// <summary> /// Creates a new invoice. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CmdReservar_Click(object sender, EventArgs e) { try { InvBE100.InvBELinhasReserva objReservas = new InvBE100.InvBELinhasReserva(); double dblQtdEncomenda = priGrelhaEncomendas.GetGRID_GetValorCelula(priGrelhaEncomendas.Grelha.ActiveRow, m_colQuantidade); double dblQtdReserva = 0; for (int i = 1; i <= priGrelhaDocs.Grelha.DataRowCnt; i++) { if (dblQtdReserva > dblQtdEncomenda) { break; } if (priGrelhaDocs.GetGRID_GetValorCelula(i, m_colSeleccionado) == 1) { InvBE100.InvBELinhaReserva objLinhaReserva = new InvBE100.InvBELinhaReserva(); objLinhaReserva.Artigo = priGrelhaEncomendas.GetGRID_GetValorCelula(priGrelhaEncomendas.Grelha.ActiveRow, m_colArtigo); objLinhaReserva.Armazem = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colArmazem); objLinhaReserva.Localizacao = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colLocalizacao); objLinhaReserva.Lote = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colLote); objLinhaReserva.IdTipoOrigemDestino = PriEngine.Engine.Inventario.TiposOrigem.DaIDTipoOrigem(ConstantesPrimavera100.AbreviaturasApl.Vendas, ConstantesPrimavera100.Modulos.Vendas); //Indicamos a origem apenas se a reserva não é de stock disponível string strIdTipoOrigem = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colIdTipoOrigem); if (!string.IsNullOrWhiteSpace(strIdTipoOrigem)) { objLinhaReserva.IdTipoOrigemOrigem = strIdTipoOrigem; objLinhaReserva.IdChaveOrigem = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colIdLinha); objLinhaReserva.DescricaoOrigem = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colDocumento); objLinhaReserva.EstadoOrigem = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colEstado); objLinhaReserva.EstadoDestino = "PREV.RES"; } else { objLinhaReserva.EstadoOrigem = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colEstado); objLinhaReserva.EstadoDestino = "RES"; } objLinhaReserva.DescricaoDestino = priGrelhaEncomendas.GetGRID_GetValorCelula(priGrelhaEncomendas.Grelha.ActiveRow, m_colDocumento); objLinhaReserva.IdChaveDestino = priGrelhaEncomendas.GetGRID_GetValorCelula(priGrelhaEncomendas.Grelha.ActiveRow, m_colIdLinha); objLinhaReserva.Quantidade = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colQuantidadeDisponivel); dblQtdReserva += objLinhaReserva.Quantidade; if (dblQtdReserva > dblQtdEncomenda) { objLinhaReserva.Quantidade = priGrelhaDocs.GetGRID_GetValorCelula(i, m_colQuantidadeDisponivel) - (dblQtdReserva - dblQtdEncomenda); } objLinhaReserva.QuantidadePendente = objLinhaReserva.Quantidade; objLinhaReserva.ReservadoPor = InvBE100.InvBETipos.EnumReservadoPor.Destino; objReservas.Insere(objLinhaReserva); } } if (dblQtdReserva == 0) { MessageBox.Show("Não exitem reservas a efetuar."); return; } string strIdEncomenda = priGrelhaEncomendas.GetGRID_GetValorCelula(priGrelhaEncomendas.Grelha.ActiveRow, m_colIdDocumento); string strIdLinha = priGrelhaEncomendas.GetGRID_GetValorCelula(priGrelhaEncomendas.Grelha.ActiveRow, m_colIdLinha); VndBEDocumentoVenda objDoc = PriEngine.Engine.Vendas.Documentos.EditaID(strIdEncomenda); VndBELinhaDocumentoVenda objLinha = ((IEnumerable <VndBELinhaDocumentoVenda>)objDoc.Linhas).FirstOrDefault(x => x.IdLinha == strIdLinha); InvBE100.InvBEReserva objReserva = new InvBE100.InvBEReserva(); objReserva.Linhas = objReservas; objLinha.ReservaStock = objReserva; PriEngine.Engine.Vendas.Documentos.Actualiza(objDoc); MessageBox.Show("Reserva criada com sucesso"); } catch (Exception ex) { PriEngine.Platform.Dialogos.MostraErro("Erro ao executar a operação", StdPlatBS100.StdBSTipos.IconId.PRI_Exclama, ex.Message); } }
/// <summary> /// Creates a new invoice. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CmdSave_Click(object sender, EventArgs e) { VndBEDocumentoVenda invoice = new VndBEDocumentoVenda(); string strAvisos = string.Empty; invoice.Tipodoc = txtTipoDoc.Text; invoice.Entidade = txtEntidade.Text; invoice.TipoEntidade = "C"; invoice.Serie = txtSerie.Text; // To save the document as draft set this flag to true //invoice.Rascunho = true ; try { if (checkBox1.Checked) { // Set all the entity related information. PriEngine.Engine.Vendas.Documentos.PreencheDadosRelacionados(invoice); } if (listView1.Items.Count > 0) { foreach (ListViewItem item in listView1.Items) { VndBELinhasDocumentoVenda linhas = new VndBELinhasDocumentoVenda(); double qtd = Convert.ToDouble(item.SubItems[1].Text); // Add new line to the invoice and set all the item related information. PriEngine.Engine.Vendas.Documentos.AdicionaLinha(invoice, item.SubItems[0].Text, ref qtd); linhas = invoice.Linhas; linhas.GetEdita(1).Desconto1 = 10; } if (txtobs.Text.Length > 0) { PriEngine.Engine.Vendas.Documentos.AdicionaLinhaEspecial(invoice, vdTipoLinhaEspecial.vdLinha_Comentario, 0, txtobs.Text); } } else { MessageBox.Show("There are no items."); } PriEngine.Engine.Vendas.Documentos.CalculaValoresTotais(invoice); // Save the document as draft. // PriEngine.Engine.Comercial.Vendas.ActualizaRascunho(invoice, ref strAvisos); PriEngine.Engine.Vendas.Documentos.Actualiza(invoice, ref strAvisos); if (strAvisos.Length > 0) { MessageBox.Show("Error writing document. \n" + strAvisos); } else { MessageBox.Show("Document saved with success."); StringBuilder strAssunto = new StringBuilder(); strAssunto.Append("A new invoice was created - "); strAssunto.Append(invoice.Tipodoc.ToString()); strAssunto.Append("/"); strAssunto.Append(invoice.NumDoc.ToString()); PriEngine.Platform.Mail.Inicializa(); PriEngine.Platform.Mail.EnviaMailEx("*****@*****.**", null, null, strAssunto.ToString(), null, null, false); } } catch (Exception ex) { MessageBox.Show("Unable to save document. \n" + ex.Message); } }
/// <summary> /// Import a purchases document. /// </summary> /// <param name="oERPContext"></param> /// <param name="Company"></param> /// <param name="IdDoc"></param> /// <returns>The reference of the created document or the error text.</returns> internal static Tuple <string, string> ImportPurchasesDocument(ERPContext oERPContext, String Company, String IdDoc) { Tuple <string, string> retValue = new Tuple <string, string>(String.Empty, String.Empty); ErpBS oCompany = new ErpBS(); string strErrWarn = string.Empty; try { oCompany.AbreEmpresaTrabalho( StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial, Company, Properties.Settings.Default.User, Properties.Settings.Default.Password); CmpBEDocumentoCompra sourceDocument = oCompany.Compras.Documentos.EditaID(IdDoc); String targetDocumentType = oCompany.Compras.TabCompras.DaValorAtributo(sourceDocument.Tipodoc, "CDU_DocDestino"); //Error if the target document not exists in the target company if (!oERPContext.BSO.Vendas.TabVendas.Existe(targetDocumentType)) { throw new Exception(String.Format("O tipo de documento {0} não existe na empresa atual.", targetDocumentType)); } VndBETabVenda salesTable = oERPContext.BSO.Vendas.TabVendas.Edita(targetDocumentType); //NEW DOCUMENT VndBEDocumentoVenda targetDocument = new VndBEDocumentoVenda(); targetDocument.Filial = "000"; targetDocument.Serie = oERPContext.BSO.Base.Series.DaSerieDefeito("V", targetDocumentType); targetDocument.Tipodoc = targetDocumentType; targetDocument.TipoEntidade = "C"; //Error if the entity doesnt exists in the target company if (!oERPContext.BSO.Base.Clientes.Existe(Company)) { throw new Exception(String.Format("O cliente {0} não existe na empresa atual.", Company)); } targetDocument.Entidade = Company; targetDocument.DataDoc = sourceDocument.DataDoc; int preencheDadosTodos = (int)BasBETiposGcp.PreencheRelacaoVendas.vdDadosTodos; targetDocument = oERPContext.BSO.Vendas.Documentos.PreencheDadosRelacionados(targetDocument, ref preencheDadosTodos); if (targetDocument.DataVenc == default(DateTime)) { targetDocument.DataVenc = sourceDocument.DataVenc; } if (string.IsNullOrEmpty(targetDocument.CondPag)) { targetDocument.CondPag = sourceDocument.CondPag; } if (string.IsNullOrEmpty(targetDocument.ModoPag)) { targetDocument.ModoPag = sourceDocument.ModoPag; } targetDocument.DescFinanceiro = sourceDocument.DescFinanceiro; targetDocument.DescEntidade = sourceDocument.DescFornecedor; targetDocument.CamposUtil["CDU_Exportado"].Valor = 1; //NEW DOCUMENT DETAILS foreach (CmpBELinhaDocumentoCompra detailSourceDocument in sourceDocument.Linhas) { double quantity = detailSourceDocument.Quantidade; string targetWarehouse = oERPContext.BSO.Base.Artigos.DaValorAtributo(detailSourceDocument.Artigo, "ArmazemSugestao") ?? detailSourceDocument.Armazem; string targetWarehouseLocation = oERPContext.BSO.Base.Artigos.DaValorAtributo(detailSourceDocument.Artigo, "LocalizacaoSugestao") ?? detailSourceDocument.Localizacao; targetDocument = oERPContext.BSO.Vendas.Documentos.AdicionaLinha( targetDocument, detailSourceDocument.Artigo, ref quantity, ref targetWarehouse, ref targetWarehouseLocation, detailSourceDocument.PrecUnit, detailSourceDocument.Desconto1); } //SAVE string settlementSeries = string.Empty; if (!oERPContext.BSO.Vendas.Documentos.ValidaActualizacao(targetDocument, salesTable, ref settlementSeries, ref strErrWarn)) { throw new Exception(strErrWarn); } else { oERPContext.BSO.Vendas.Documentos.Actualiza(targetDocument, ref strErrWarn); retValue = Tuple.Create <string, string>( string.Format("{0} {1}/{2}", targetDocument.Tipodoc, targetDocument.Serie, targetDocument.NumDoc.ToString()), strErrWarn); oCompany.DSO.ExecuteSQL(string.Format("UPDATE CabecCompras SET CDU_Exportado=1 WHERE ID='{0}'", sourceDocument.ID)); //TODO: Eliminar (foi adicionado porque o objeto não estava a gravar os valores dos CDUs) oERPContext.BSO.DSO.ExecuteSQL(string.Format("UPDATE CabecDoc SET CDU_Exportado=1 WHERE ID='{0}'", targetDocument.ID)); } } catch (Exception e) { retValue = Tuple.Create <string, string>("ERRO", e.Message); } finally { if (oCompany != null) { oCompany.FechaEmpresaTrabalho(); } } return(retValue); }