public static string Finalizar(TRegistro_ProcEtapa val, TRegistro_Pedido rPed, BancoDados.TObjetoBanco banco) { bool st_transacao = false; TCD_ProcEtapa cd = new TCD_ProcEtapa(); try { if (banco == null) { st_transacao = cd.CriarBanco_Dados(true); } else { cd.Banco_Dados = banco; } val.Dt_processo = CamadaDados.UtilData.Data_Servidor(); val.Login = Utils.Parametros.pubLogin; string retorno = cd.Gravar(val); //Verificar se etapa pode ser finalizada cd.executarSql("update TB_FAT_Pedido_Etapa set ST_Registro = 'F', DT_Fin = GETDATE(), DT_Alt = GETDATE() " + "FROM TB_FAT_Pedido_Etapa a " + "where a.nr_pedido = " + val.Nr_pedidostr + " " + "and a.id_etapa = " + val.Id_etapastr + " " + "and not exists(select 1 from TB_FAT_Pedido_ProcEtapa x " + "where x.nr_pedido = a.nr_pedido " + "and x.id_etapa = a.ID_Etapa " + "and x.DT_Processo is null) " + //Verificar se pedido pode ser fechado "update tb_fat_pedido set ST_Pedido = 'F', ST_Registro = 'F', DT_Alt = GETDATE() " + "FROM TB_FAT_PEDIDO a " + "where a.nr_pedido = " + val.Nr_pedidostr + " " + "and not exists(select 1 from TB_FAT_Pedido_Etapa x " + "where x.Nr_Pedido = a.Nr_Pedido " + "and ISNULL(x.ST_Registro, 'A') <> 'F' " + "and isnull(x.ST_Registro, 'A') <> 'C') ", null); if (st_transacao) { cd.Banco_Dados.Commit_Tran(); } return(retorno); } catch (Exception ex) { if (st_transacao) { cd.Banco_Dados.RollBack_Tran(); } throw new Exception("Erro gravar processo: " + ex.Message.Trim()); } finally { if (st_transacao) { cd.deletarBanco_Dados(); } } }
private void BB_Gravar_Click(object sender, EventArgs e) { string ped; dataGridNavegador.Enabled = true; TRegistro_Pedido rgped = (bindingSource_PedidoCab.DataSource as TList_Pedido)[dataGridNavegador.CurrentRow.Index]; if (TPModo == TTpModo.tm_Insert) { rgped.ST_Pedido = 'A'; } rgped.ST_Registro = 'A'; ped = TCN_Pedido.GravaPedido(rgped, null); HabilitarPaineis(false); Nr_Pedido.Value = Convert.ToDecimal(Querys.TDataQuery.getPubVariavel(ped, "@P_NR_PEDIDO")); PreparaBotoes(TTpModo.tm_Standby); }
public static string Gravar(TRegistro_Pedido rPed, TObjetoBanco banco) { bool st_transacao = false; TCD_EntregaPedido qtb_entrega = new TCD_EntregaPedido(); try { if (banco == null) { st_transacao = qtb_entrega.CriarBanco_Dados(true); } else { qtb_entrega.Banco_Dados = banco; } string retorno = Gravar(rPed.lEntregaPedido, qtb_entrega.Banco_Dados); //Alterar dados do pedido TCN_Pedido.Grava_Pedido(rPed, qtb_entrega.Banco_Dados); if (st_transacao) { qtb_entrega.Banco_Dados.Commit_Tran(); } return(retorno); } catch (Exception ex) { if (st_transacao) { qtb_entrega.Banco_Dados.RollBack_Tran(); } throw new Exception("Erro gravar entrega: " + ex.Message.Trim()); } finally { if (st_transacao) { qtb_entrega.deletarBanco_Dados(); } } }
private void CFG_Fiscal(string vCFG_pedido) { TDatCFG_PedidoFiscal QTB_CFGFiscal = new TDatCFG_PedidoFiscal(); DataTable tbfis = new DataTable(); TpBusca[] busca = new TpBusca[1]; TRegistro_Pedido rgped = (bindingSource_PedidoCab.DataSource as TList_Pedido)[dataGridNavegador.CurrentRow.Index]; busca[0].vNM_Campo = "a.CFG_Pedido"; busca[0].vOperador = "="; busca[0].vVL_Busca = "'" + vCFG_pedido + "'"; tbfis = QTB_CFGFiscal.Buscar(busca, 0); if (tbfis.Rows.Count > 0) { if (bindingSource_Fiscal.Count > 0) { for (int x = 0; x < bindingSource_Fiscal.Count; x++) { bindingSource_Fiscal.RemoveAt(x); } } for (int x = 0; x < tbfis.Rows.Count; x++) { bindingSource_Fiscal.AddNew(); rgped.Pedido_Fiscal[x].Nr_pedido = Nr_Pedido.Value; rgped.Pedido_Fiscal[x].Cd_cmistring = tbfis.Rows[x]["CD_CMI"].ToString(); rgped.Pedido_Fiscal[x].ds_cmi = tbfis.Rows[0]["DS_CMI"].ToString(); rgped.Pedido_Fiscal[x].Cd_movtostring = tbfis.Rows[x]["CD_Movto"].ToString(); rgped.Pedido_Fiscal[x].ds_movimentacao = tbfis.Rows[x]["DS_CMI"].ToString(); rgped.Pedido_Fiscal[x].Nr_serie = tbfis.Rows[x]["Nr_Serie"].ToString(); rgped.Pedido_Fiscal[x].Ds_SerieNf = tbfis.Rows[x]["Ds_Movimentacao"].ToString(); rgped.Pedido_Fiscal[x].St_registro = "A"; rgped.Pedido_Fiscal[x].Tp_fiscal = tbfis.Rows[x]["TP_Fiscal"].ToString(); } } }
public static void ProcessarEntregaPedido(TRegistro_Pedido rPed, BancoDados.TObjetoBanco banco) { bool st_transacao = false; TCD_EntregaPedido qtb_entrega = new TCD_EntregaPedido(); try { if (banco == null) { st_transacao = qtb_entrega.CriarBanco_Dados(true); } else { qtb_entrega.Banco_Dados = banco; } ProcessarEntregaPedido(rPed.lEntregaPedido, qtb_entrega.Banco_Dados); TCN_Pedido.Grava_Pedido(rPed, qtb_entrega.Banco_Dados); if (st_transacao) { qtb_entrega.Banco_Dados.Commit_Tran(); } } catch (Exception ex) { if (st_transacao) { qtb_entrega.Banco_Dados.RollBack_Tran(); } throw new Exception("Erro processar entrega: " + ex.Message.Trim()); } finally { if (st_transacao) { qtb_entrega.deletarBanco_Dados(); } } }
public static TRegistro_LanFaturamento ProcessarNF(TRegistro_Pedido rPedido) { //Buscar Configuração Fiscal Pedido TList_CadCFGPedidoFiscal lCfgPed = new TCD_CadCFGPedidoFiscal().Select( new TpBusca[] { new TpBusca() { vNM_Campo = "a.cfg_pedido", vOperador = "=", vVL_Busca = "'" + rPedido.CFG_Pedido + "'" }, new TpBusca() { vNM_Campo = "a.tp_fiscal", vOperador = "=", vVL_Busca = "'RT'" } }, 1, string.Empty); if (lCfgPed.Count > 0) { //Buscar Notas Vendas Sem Remessa TList_RegLanFaturamento lNFV = new TCD_LanFaturamento().Select( new TpBusca[] { new TpBusca() { vNM_Campo = "a.nr_pedido", vOperador = "=", vVL_Busca = rPedido.Nr_pedido.ToString() }, new TpBusca() { vNM_Campo = "isnull(a.st_registro, 'A')", vOperador = "<>", vVL_Busca = "'C'" }, new TpBusca() { vNM_Campo = "isnull(cmi.st_remessatransp, 'N')", vOperador = "<>", vVL_Busca = "'S'" }, new TpBusca() { vNM_Campo = "a.nr_lanctofiscalRT", vOperador = "is", vVL_Busca = "null" } }, 0, string.Empty); if (lNFV.Count.Equals(0)) { throw new Exception("Pedido não possui nota venda disponivel para gerar REMESSA TRANSPORTE."); } TRegistro_LanFaturamento rNF = null; if (lNFV.Count > 1) { using (TFListaNF fNF = new TFListaNF()) { fNF.lFat = lNFV; if (fNF.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (fNF.rFat != null) { rNF = fNF.rFat; } } } } else { rNF = lNFV[0]; } if (rNF == null) { throw new Exception("Obrigório selecionar nota fiscal para gerar REMESSA TRANSPORTE."); } TRegistro_LanFaturamento ret = new TRegistro_LanFaturamento(); ret.Cd_empresa = rNF.Cd_empresa; ret.Cd_clifor = !string.IsNullOrEmpty(rPedido.Cd_cliforent) ? rPedido.Cd_cliforent : rNF.Cd_clifor; ret.Nm_clifor = !string.IsNullOrEmpty(rPedido.Nm_cliforent) ? rPedido.Nm_cliforent : rNF.Nm_clifor; ret.Cd_endereco = !string.IsNullOrEmpty(rPedido.Cd_enderecoent) ? rPedido.Cd_enderecoent : rNF.Cd_endereco; ret.Cd_cmi = lCfgPed[0].Cd_cmi; ret.Cd_movimentacao = lCfgPed[0].Cd_movto; ret.lCFGFiscal = lCfgPed; ret.Cd_uf_empresa = rNF.Cd_uf_empresa; ret.Uf_empresa = rNF.Uf_empresa; ret.Uf_clifor = rNF.Uf_clifor; ret.Cd_condfiscal_clifor = !string.IsNullOrEmpty(rPedido.Cd_cliforent) ? rPedido.Cd_condfiscalent : rNF.Cd_condfiscal_clifor; ret.Cd_uf_clifor = !string.IsNullOrEmpty(rPedido.Cd_cliforent) ? rPedido.Cd_uf_ent : rNF.Cd_uf_clifor; ret.Nr_pedido = rNF.Nr_pedido; ret.Tp_movimento = rNF.Tp_movimento; ret.Tp_pessoa = rNF.Tp_pessoa; ret.Tp_nota = rNF.Tp_nota; ret.Nr_serie = lCfgPed[0].Nr_serie; ret.Cd_modelo = lCfgPed[0].Cd_modelo; ret.St_sequenciaauto = lCfgPed[0].ST_SequenciaAuto.Trim().ToUpper().Equals("S"); ret.Dt_emissao = CamadaDados.UtilData.Data_Servidor(); ret.Dt_saient = ret.Dt_emissao; ret.Dadosadicionais = ProcessaAplicacao.BuscarObsMov("D", ret.Cd_movimentacaostring, rNF.Uf_clifor.Trim().Equals(rNF.Uf_empresa.Trim())); ret.Obsfiscal = ProcessaAplicacao.BuscarObsMov("F", ret.Cd_movimentacaostring, rNF.Uf_clifor.Trim().Equals(rNF.Uf_empresa.Trim())); ret.Freteporconta = rNF.Tp_frete; ret.Cd_transportadora = rNF.Cd_transportadora; ret.Nm_razaosocialtransp = rNF.Nm_razaosocialtransp; ret.Cpf_transp = rNF.Cpf_transp; ret.Placaveiculo = rNF.Placaveiculo; //Abrir tela para capturar dados da nota fiscal using (NumeroNota.TFNumero_Nota fNumero = new NumeroNota.TFNumero_Nota()) { fNumero.pCd_empresa = ret.Cd_empresa; fNumero.pNm_empresa = ret.Nm_empresa; fNumero.pCd_clifor = ret.Cd_clifor; fNumero.pNm_clifor = ret.Nm_clifor; fNumero.pTp_pessoa = ret.Tp_pessoa; fNumero.pTp_movimento = ret.Tp_movimento; fNumero.pTp_nota = ret.Tp_nota; fNumero.pChave_Acesso_NFe = ret.Chave_acesso_nfe; fNumero.pNr_serie = ret.Nr_serie; fNumero.pDs_serie = ret.Ds_serienf; fNumero.pCd_modelo = ret.Cd_modelo; fNumero.pDt_emissao = ret.Dt_emissao; fNumero.pST_NotaUnica = false; fNumero.pNr_notafiscal = ret.Nr_notafiscal.HasValue ? ret.Nr_notafiscal.Value.ToString() : string.Empty; fNumero.pDt_saient = ret.Dt_saient; fNumero.pDs_dadosadic = ret.Dadosadicionais; fNumero.pDs_obsfiscal = ret.Obsfiscal; fNumero.pSt_sequenciaauto = ret.St_sequenciaauto; fNumero.pCd_movto = ret.Cd_movimentacaostring; fNumero.pCd_cmi = ret.Cd_cmistring; fNumero.pSt_servico = lCfgPed.Count > 0 ? lCfgPed[0].St_servico : false; if (ret.Tp_nota.Trim().ToUpper().Equals("T")) { //Buscar inscricao estadual do clifor da nota object obj_insc = new TCD_CadEndereco().BuscarEscalar( new TpBusca[] { new TpBusca() { vNM_Campo = "a.cd_clifor", vOperador = "=", vVL_Busca = "'" + ret.Cd_clifor.Trim() + "'" }, new TpBusca() { vNM_Campo = "a.cd_endereco", vOperador = "=", vVL_Busca = "'" + ret.Cd_endereco.Trim() + "'" } }, "a.insc_estadual"); fNumero.pInsc_estadual = obj_insc == null ? string.Empty : obj_insc.ToString(); } fNumero.pTp_frete = ret.Freteporconta; fNumero.pCd_transportadora = ret.Cd_transportadora; fNumero.pNm_transportadora = ret.Nm_razaosocialtransp; fNumero.pCnpjCpfTransp = ret.Cpf_transp; fNumero.pPlacaVeiculo = ret.Placaveiculo; fNumero.pVl_frete = rNF.ItensNota.Sum(p => p.Vl_freteitem); if (fNumero.ShowDialog() == System.Windows.Forms.DialogResult.OK) { ret.Chave_acesso_nfe = fNumero.pChave_Acesso_NFe; if (!string.IsNullOrEmpty(fNumero.pNr_notafiscal)) { ret.Nr_notafiscal = decimal.Parse(fNumero.pNr_notafiscal); } else { ret.Nr_notafiscal = null; } ret.Nr_serie = fNumero.pNr_serie; ret.Cd_modelo = fNumero.pCd_modelo; ret.Dt_emissao = fNumero.pDt_emissao; ret.Dt_saient = fNumero.pDt_saient; ret.Obsfiscal = fNumero.pDs_obsfiscal; ret.Dadosadicionais = fNumero.pDs_dadosadic; ret.Cd_transportadora = fNumero.pCd_transportadora; ret.Cd_enderecotransp = fNumero.pCd_endtransportadora; ret.Nm_razaosocialtransp = fNumero.pNm_transportadora; ret.Cpf_transp = fNumero.pCnpjCpfTransp; ret.Placaveiculo = fNumero.pPlacaVeiculo; ret.Freteporconta = fNumero.pTp_frete; ret.Especie = fNumero.pEspecie; ret.Quantidade = fNumero.pQuantidade; ret.Pesobruto = fNumero.pPsbruto; ret.Pesoliquido = fNumero.pPsliquido; ret.Vl_frete = fNumero.pVl_frete; ret.Cd_municipioexecservico = fNumero.pCd_municipioexecservico; ret.Ds_municipioexecservico = fNumero.pNm_municipioexecservico; //Preencher objeto CMI CamadaDados.Fiscal.TRegistro_CadCMI rCmi = CamadaNegocio.Fiscal.TCN_CadCMI.Busca(fNumero.pCd_cmi, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, false, false, false, false, false, false, false, null)[0]; ret.Cminf.Add(new TRegistro_LanFaturamento_CMI() { St_compdevimposto = rCmi.St_compdevimposto, St_complementar = rCmi.St_complementar, St_devolucao = rCmi.St_devolucao, St_geraestoque = rCmi.St_geraestoque, St_mestra = rCmi.St_mestra, St_simplesremessa = rCmi.St_simplesremessa, St_retorno = rCmi.St_retorno, St_remessatransp = "S" }); ret.Cd_cmistring = fNumero.pCd_cmi; ret.Ds_cmi = rCmi.Ds_cmi; ret.Tp_duplicata = rCmi.Tp_duplicata; ret.Ds_tpduplicata = rCmi.ds_tpduplicata; } else { throw new Exception("Obrigatorio informar numero da nota fiscal."); } } if (ret.Nr_notafiscal.HasValue) { TRegistro_LanFaturamento rFat = TCN_LanFaturamento.existeNumeroNota(ret.Nr_notafiscal.ToString(), ret.Nr_serie, ret.Cd_empresa, ret.Cd_clifor, string.Empty, ret.Tp_nota, null); if (rFat != null) { if (rFat.St_registro.Trim().ToUpper().Equals("C")) { throw new Exception("Nota Fiscal Nº " + rFat.Nr_notafiscal.ToString() + " ja existe no sistema e se encontra cancelada.\r\n" + "Para poder utilizar o mesmo numero e necessario excluir a nota fiscal cancelada.\r\n" + "Dica: Menu FATURAMENTO->Emissão de Notas Fiscais / NFe, localize a nota fiscal cancelada e exclua a mesma.\r\n" + "Obs.: Para excluir a nota fiscal cancelada é necessario que o usuario tenha permissão."); } else { throw new Exception("Nota Fiscal Nº " + rFat.Nr_notafiscal.ToString() + " ja existe no sistema e se encontra ativa.\r\n" + "Não é permitido gerar nota fiscal com mesmo numero."); } } } TCN_LanFaturamento_Item.Busca(rNF.Cd_empresa, rNF.Nr_lanctofiscal.Value.ToString(), string.Empty, null).ForEach(item => { TRegistro_LanFaturamento_Item rItem = new TRegistro_LanFaturamento_Item(); rItem.Cd_empresa = rNF.Cd_empresa; rItem.Cd_produto = item.Cd_produto; rItem.Cd_local = item.Cd_local; rItem.Cd_condfiscal_produto = item.Cd_condfiscal_produto; rItem.Cd_unidade = item.Cd_unidade; rItem.Cd_unidEst = item.Cd_unidEst; rItem.Nr_pedido = item.Nr_pedido; rItem.Id_pedidoitem = item.Id_pedidoitem; rItem.Quantidade = item.Quantidade; rItem.Quantidade_estoque = item.Quantidade; rItem.Vl_subtotal = item.Vl_subtotal; rItem.Vl_subtotal_estoque = item.Vl_subtotal; rItem.Vl_unitario = item.Vl_unitario; rItem.Pc_desconto = item.Pc_desconto; rItem.Vl_desconto = item.Vl_desconto; rItem.Vl_freteitem = item.Vl_freteitem; rItem.Pc_juro_fin = item.Pc_juro_fin; rItem.Vl_juro_fin = item.Vl_juro_fin; rItem.Vl_outrasdesp = item.Vl_outrasdesp; rItem.Pc_imposto_Aprox = item.Pc_imposto_Aprox; rItem.Observacao_item = item.Observacao_item; //Buscar cfop do item TRegistro_CadCFOP rCfop = null; if (TCN_Mov_X_CFOP.BuscarCFOP(ret.Cd_movimentacaostring, item.Cd_condfiscal_produto, ret.Cd_uf_clifor.Trim().Equals("99") ? "I" : ret.Cd_uf_clifor.Trim().Equals(ret.Cd_uf_empresa.Trim()) ? "D" : "F", (ret.Tp_movimento.Trim().ToUpper().Equals("E") ? ret.Cd_uf_clifor : ret.Cd_uf_empresa), (ret.Tp_movimento.Trim().ToUpper().Equals("E") ? ret.Cd_uf_empresa : ret.Cd_uf_clifor), ret.Tp_movimento, ret.Cd_condfiscal_clifor, ret.Cd_empresa, ref rCfop, null)) { rItem.Cd_cfop = rCfop.CD_CFOP; rItem.Ds_cfop = rCfop.DS_CFOP; rItem.St_bonificacao = rCfop.St_bonificacaobool; } else { throw new Exception("Não existe CFOP " + (ret.Cd_uf_clifor.Trim().Equals("99") ? "I" : ret.Cd_uf_clifor.Trim().Equals(ret.Cd_uf_empresa.Trim()) ? "dentro estado" : "fora estado") + " configurado para a Movimentação " + ret.Cd_movimentacaostring + " condição fiscal do produto " + item.Cd_condfiscal_produto); } //Procurar Impostos Estaduais para o Item string vObsFiscal = string.Empty; TList_ImpostosNF lImpUf = TCN_LanFaturamento_Item.procuraImpostosPorUf(ret.Cd_empresa, (ret.Tp_movimento.Trim().ToUpper().Equals("E") ? ret.Cd_uf_clifor : ret.Cd_uf_empresa), (ret.Tp_movimento.Trim().ToUpper().Equals("E") ? ret.Cd_uf_empresa : ret.Cd_uf_clifor), ret.Cd_movimentacaostring, ret.Tp_movimento, ret.Cd_condfiscal_clifor, rItem.Cd_condfiscal_produto, rItem.Vl_subtotal, rItem.Quantidade, ref vObsFiscal, ret.Dt_emissao, rItem.Cd_produto, ret.Tp_nota, ret.Nr_serie, null); if (lImpUf.Exists(v => v.Imposto.St_ICMS)) { TCN_LanFaturamento_Item.PreencherICMS(lImpUf.Find(v => v.Imposto.St_ICMS), rItem); ret.Obsfiscal += vObsFiscal.Trim(); } else if (TCN_LanFaturamento_Item.ObrigImformarICMS(rItem.Cd_produto, ret.Nr_serie, null)) { throw new Exception("Erro: Não existe condição fiscal do ICMS.\r\n" + "Tipo Movimento: " + ret.Tipo_movimento.Trim() + "\r\n" + "Movimentação: " + ret.Cd_movimentacao.ToString() + "\r\n" + "Cond. Fiscal Clifor: " + ret.Cd_condfiscal_clifor.Trim() + "\r\n" + "Cond. Fiscal Produto: " + rItem.Cd_condfiscal_produto.Trim() + "\r\n" + "UF Origem: " + (ret.Tp_movimento.Trim().ToUpper().Equals("E") ? ret.Uf_clifor.Trim() : ret.Uf_empresa.Trim()) + "\r\n" + "UF Destino: " + (ret.Tp_movimento.Trim().ToUpper().Equals("E") ? ret.Uf_empresa.Trim() : ret.Uf_clifor.Trim())); } //Procurar impostos sobre os itens da nota fiscal de destino TCN_LanFaturamento_Item.PreencherOutrosImpostos( TCN_LanFaturamento_Item.procuraCondicaoFiscalImpostos(ret.Cd_condfiscal_clifor, rItem.Cd_condfiscal_produto, ret.Cd_movimentacaostring, ret.Tp_movimento, ret.Tp_pessoa, ret.Cd_empresa, ret.Nr_serie, ret.Cd_clifor, rItem.Cd_unidEst, ret.Dt_emissao, rItem.Quantidade, rItem.Vl_subtotal, ret.Tp_nota, ret.Cd_municipioexecservico, null), rItem, ret.Tp_movimento); string obs_ret = string.Empty; string linha = string.Empty; if (rItem.Vl_ICMSRetido > decimal.Zero) { obs_ret += linha + "ICMS RETIDO " + rItem.Vl_ICMSRetido.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (rItem.Vl_retidoCofins > decimal.Zero) { obs_ret += linha + "COFINS RETIDO " + rItem.Vl_retidoCofins.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (rItem.Vl_retidoCSLL > decimal.Zero) { obs_ret += linha + "CSLL RETIDO " + rItem.Vl_retidoCSLL.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (rItem.Vl_retidoFunrural > decimal.Zero) { obs_ret += linha + "FUNRURAL RETIDO " + rItem.Vl_retidoFunrural.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (rItem.Vl_retidoINSS > decimal.Zero) { obs_ret += linha + "INSS RETIDO " + rItem.Vl_retidoINSS.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (rItem.Vl_retidoIRRF > decimal.Zero) { obs_ret += linha + "IRFF RETIDO " + rItem.Vl_retidoIRRF.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (rItem.Vl_retidoPIS > decimal.Zero) { obs_ret += linha + "PIS RETIDO " + rItem.Vl_retidoPIS.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (rItem.Vl_retidoSenar > decimal.Zero) { obs_ret += linha + "SENAR RETIDO " + rItem.Vl_retidoSenar.ToString("C2", new System.Globalization.CultureInfo("pt-BR")); linha = "\r\n"; } if (!string.IsNullOrEmpty(obs_ret)) { ret.Obsfiscal += (string.IsNullOrEmpty(ret.Obsfiscal) ? string.Empty : "\r\n") + obs_ret.Trim(); } ret.ItensNota.Add(rItem); }); ret.rNFVendaRT = rNF; return(ret); } else { throw new Exception("Não existe configuração fiscal pedido para gerar REMESSA TRANSPORTE."); } }
private void bbImportar_Click(object sender, EventArgs e) { //071.548.686-19 if (bsPedLoja.Current != null) { if ((bsPedLoja.Current as TRegistro_Pedido).Nr_pedido.ToString().Trim() != "0") { MessageBox.Show("Não é permitido IMPORTAR pedido novamente.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if ((bsPedLoja.Current as TRegistro_Pedido).StatusMagento.Trim().ToUpper().Equals("CANCELADO")) { MessageBox.Show("Não é permitido IMPORTAR pedido CANCELADO.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (rCfg == null) { MessageBox.Show("Não existe configuração E-commerce para loja selecionada.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } MagentoService api = new MagentoService(); string sessao = string.Empty; try { sessao = api.login((cbLoja.SelectedItem as TRegistro_LojaVirtual).UserName, (cbLoja.SelectedItem as TRegistro_LojaVirtual).ApiKey); salesOrderEntity ePed = api.salesOrderInfo(sessao, (bsPedLoja.Current as TRegistro_Pedido).Nr_PedidoOrigem); if (ePed != null) { TRegistro_Pedido rPedido = new TRegistro_Pedido(); //Buscar Cliente customerCustomerEntity eCliente = api.customerCustomerInfo(sessao, int.Parse(ePed.customer_id), null); //Verificar se cliente existe no Aliance TList_CadClifor lCliente = new TCD_CadClifor().Select( new TpBusca[] { new TpBusca() { vNM_Campo = string.Empty, vOperador = string.Empty, vVL_Busca = "dbo.FVALIDA_NUMEROS(a.nr_cgc) = '" + eCliente.taxvat.Trim() + "' " + "or dbo.FVALIDA_NUMEROS(a.nr_cpf) = '" + eCliente.taxvat.Trim() + "'" } }, 1, string.Empty); if (lCliente.Count > 0) { rPedido.CD_Clifor = lCliente[0].Cd_clifor; rPedido.NM_Clifor = lCliente[0].Nm_clifor; //Buscar endereco cliente TList_CadEndereco lEnd = new TCD_CadEndereco().Select( new TpBusca[] { new TpBusca() { vNM_Campo = "a.cd_clifor", vOperador = "=", vVL_Busca = "'" + lCliente[0].Cd_clifor.Trim() + "'" } }, 1, string.Empty); if (lEnd.Count > 0) { rPedido.CD_Endereco = lEnd[0].Cd_endereco; rPedido.DS_Endereco = lEnd[0].Ds_endereco; numero.Text = lEnd[0].Numero; bairro.Text = lEnd[0].Bairro; ds_cidade.Text = lEnd[0].DS_Cidade; uf.Text = lEnd[0].UF; } } else { TRegistro_CadClifor rClifor = new TRegistro_CadClifor(); rClifor.Nm_clifor = eCliente.firstname.Trim().ToUpper() + " " + eCliente.lastname.Trim().ToUpper(); rClifor.Email = eCliente.email.Trim(); rClifor.Tp_pessoa = eCliente.taxvat.Trim().Length.Equals(14) ? "J" : "F"; rClifor.Nr_cgc = eCliente.taxvat.Trim().Length.Equals(14) ? eCliente.taxvat.Trim() : string.Empty; rClifor.Nr_cpf = !eCliente.taxvat.Trim().Length.Equals(14) ? eCliente.taxvat.Trim() : string.Empty; rClifor.Id_categoriaclifor = rCfg.Id_categoriaclifor; rClifor.Cd_condfiscal_clifor = rCfg.Cd_condfiscal_clifor; TRegistro_CadEndereco rEndereco = new TRegistro_CadEndereco(); rEndereco.Cep = ePed.billing_address.postcode; //Buscar Endereco Rest TEndereco_CEPRest eRest = ServiceRest.DataService.BuscarEndCEPRest(rEndereco.Cep); if (eRest != null) { rEndereco.Ds_endereco = eRest.logradouro; rEndereco.Ds_complemento = eRest.complemento; rEndereco.Bairro = eRest.bairro; rEndereco.Cd_cidade = eRest.ibge; string[] str = ePed.billing_address.street.Split(new char[] { '\n' }); if (str.Length >= 2) { rEndereco.Numero = str[1]; } } else { string[] str = ePed.billing_address.street.Split(new char[] { '\n' }); if (str.Length >= 4) { rEndereco.Ds_endereco = str[0]; rEndereco.Bairro = str[3]; rEndereco.Numero = str[1]; } } rClifor.lEndereco.Add(rEndereco); using (Financeiro.Cadastros.TFCadCliforResumido fClifor = new Financeiro.Cadastros.TFCadCliforResumido()) { fClifor.rClifor = rClifor; if (fClifor.ShowDialog() == DialogResult.OK) { try { TCN_CadClifor.Gravar(fClifor.rClifor, null); MessageBox.Show("Cliente cadastrado com sucesso.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); rPedido.CD_Clifor = fClifor.rClifor.Cd_clifor; rPedido.NM_Clifor = fClifor.rClifor.Nm_clifor; rPedido.CD_Endereco = fClifor.rClifor.lEndereco[0].Cd_endereco; rPedido.DS_Endereco = fClifor.rClifor.lEndereco[0].Ds_endereco; numero.Text = fClifor.rClifor.lEndereco[0].Numero; bairro.Text = fClifor.rClifor.lEndereco[0].Bairro; ds_cidade.Text = fClifor.rClifor.lEndereco[0].DS_Cidade; uf.Text = fClifor.rClifor.lEndereco[0].UF; } catch (Exception ex) { MessageBox.Show(ex.Message.Trim(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { MessageBox.Show("Obrigatório cadastrar cliente para importar pedido.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } } rPedido.cd_empresa = (cbLoja.SelectedItem as TRegistro_LojaVirtual).Cd_empresa; rPedido.Nm_Empresa = (cbLoja.SelectedItem as TRegistro_LojaVirtual).Nm_empresa; rPedido.Nr_PedidoOrigem = (bsPedLoja.Current as TRegistro_Pedido).Nr_PedidoOrigem; rPedido.CFG_Pedido = rCfg.Cfg_pedido; rPedido.TP_Movimento = "S";//Venda rPedido.DT_Pedido = CamadaDados.UtilData.Data_Servidor(); rPedido.ST_Pedido = "F"; rPedido.St_registro = "F"; rPedido.Cd_moeda = rCfg.Cd_moeda; rPedido.Tp_frete = decimal.Divide(decimal.Parse(ePed.shipping_amount.SoNumero()), 10000) > 0 ? "1" : "9"; rPedido.QUANTIDADENF = decimal.Divide(decimal.Parse(ePed.total_qty_ordered.SoNumero()), 10000); //Endereco Entrega TEndereco_CEPRest endRest = ServiceRest.DataService.BuscarEndCEPRest(ePed.shipping_address.postcode.Trim()); if (endRest != null) { rPedido.Logradouroent = endRest.logradouro; rPedido.Complementoent = endRest.complemento; rPedido.Bairroent = endRest.bairro; rPedido.Cd_cidadeent = endRest.ibge; } string[] eEnt = ePed.shipping_address.street.Split(new char[] { '\n' }); if (eEnt.Length >= 4) { rPedido.Logradouroent = eEnt[0]; rPedido.Numeroent = eEnt[1]; rPedido.Complementoent = eEnt[2]; rPedido.Bairroent = eEnt[3]; } //Itens do pedido foreach (salesOrderItemEntity item in ePed.items) { foreach (salesOrderItemEntity nitem in ePed.items) { if (item.sku.ToString().Equals(nitem.sku.ToString()) && decimal.Divide(decimal.Parse(nitem.price.SoNumero()), 10000) == decimal.Zero) { item.name = nitem.name; item.product_id = nitem.product_id; break; } } if (decimal.Divide(decimal.Parse(item.price.SoNumero()), 10000) > decimal.Zero) { TRegistro_LanPedido_Item rItem = new TRegistro_LanPedido_Item(); rItem.Cd_referencia = item.product_id; //Buscar Produto CamadaDados.Estoque.Cadastros.TList_CadProduto lProd = new CamadaDados.Estoque.Cadastros.TCD_CadProduto().Select( new TpBusca[] { new TpBusca() { vNM_Campo = "a.codigo_alternativo", vOperador = "=", vVL_Busca = "'" + item.product_id.Trim() + "'" }, new TpBusca() { vNM_Campo = "isnull(a.st_registro, 'A')", vOperador = "<>", vVL_Busca = "'C'" } }, 1, string.Empty, string.Empty, string.Empty); if (lProd.Count > 0) { rItem.Cd_produto = lProd[0].CD_Produto; rItem.Ds_produto = lProd[0].DS_Produto; rItem.Cd_unidade_est = lProd[0].CD_Unidade; rItem.Ds_unidade_est = lProd[0].DS_Unidade; rItem.Sg_unidade_est = lProd[0].Sigla_unidade; rItem.Cd_unidade_valor = lProd[0].CD_Unidade; rItem.Ds_unidade_valor = lProd[0].DS_Unidade; rItem.Sg_unidade_valor = lProd[0].Sigla_unidade; } else { rItem.Ds_produto = item.name.Trim().ToUpper(); } rItem.Quantidade = decimal.Divide(decimal.Parse(item.qty_ordered.SoNumero()), 10000); rItem.Vl_unitario = decimal.Divide(decimal.Parse(item.price.SoNumero()), 10000); rItem.Vl_subtotal = decimal.Divide(decimal.Parse(item.row_total.SoNumero()), 10000); rItem.Vl_desc = decimal.Divide(decimal.Parse(item.discount_amount.SoNumero()), 10000); rItem.Cd_local = rCfg.Cd_local; rPedido.Pedido_Itens.Add(rItem); } //Ratear Frete rPedido.Vl_frete = decimal.Divide(decimal.Parse(ePed.shipping_amount.SoNumero()), 10000); if (rPedido.Vl_frete > decimal.Zero) { CamadaNegocio.Faturamento.Pedido.TCN_Pedido.Rateia_Frete(rPedido); } bsPedido.DataSource = new TList_Pedido { rPedido }; } } gPedido.Enabled = false; bbImportar.Enabled = false; tlpPedido.ColumnStyles[1].Width = 623; } catch (Exception ex) { MessageBox.Show(ex.Message.Trim(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { api.endSession(sessao); } } }