ImportacionClientes.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data;
6 using System.Windows.Forms;
7 using System.IO;
8 using System.Collections;
9 using System.ComponentModel;
10 
11 using sage.ew.db;
12 using sage.ew.global;
13 using sage.ew.cliente;
14 using sage.ew.articulo;
15 
16 using sage.ew.functions;
17 using static sage.ew.cliente.Cliente;
18 using sage.ew.contabilidad;
20 
21 namespace sage.addons.idatos.Negocio.Clases
22 {
27  {
28 
29  #region PROPIEDADES
30 
34  private DataTable dtAuxClientes = null;
35  private DataTable dtAuxAgencia = null;
36  private DataTable dtAuxCanal = null;
37  private DataTable dtAuxFormaPago = null;
38  private DataTable dtAuxRuta = null;
39  private DataTable dtAuxTipoFacturacion = null;
40  private DataTable dtAuxVendedor = null;
41  private DataTable dtAuxZona = null;
42  private DataTable dtAuxCatastral = null;
43 
47  private readonly int lnLenCliente = Convert.ToInt32(EW_GLOBAL._GetLenCampo(KeyDiccionarioLenCampos.wn_digitos));
48  private readonly int lnLenFormaPago = Convert.ToInt32(EW_GLOBAL._GetLenCampo(KeyDiccionarioLenCampos.wn_fpag));
49  private readonly int lnLenRuta = Convert.ToInt32(EW_GLOBAL._GetLenCampo(KeyDiccionarioLenCampos.wn_ruta));
50  private readonly int lnLenVendedor = Convert.ToInt32(EW_GLOBAL._GetLenCampo(KeyDiccionarioLenCampos.wn_vendedor));
51  private readonly int lnLenDigitos = Convert.ToInt32(EW_GLOBAL._GetLenCampo(KeyDiccionarioLenCampos.wn_digitos));
52  private readonly int lnLenAgencia = 3;
53  //private readonly int lnLenCanal = 10;
54  private readonly int lnLenZona = Convert.ToInt32(EW_GLOBAL._GetLenCampo(KeyDiccionarioLenCampos.wn_zona));
55 
56 
60  private bool cuentaIBAN = false;
61  // private bool girosCliente = false;
62  private bool lbMandatos = false;
63  private bool lbDireccFac = false;
64  private bool lbDireccAdi = false;
65  private bool lbTelefPre = false;
66  private bool lbTelefAdi = false;
67 
68 
69 
70  #endregion PROPIEDADES
71 
72  #region CONSTRUCTORES
73 
78  {
79 
80  }
84  public ImportacionClientes(DataTable dtcsv, string codigoGuia, List<CargarDatos.stInfoFields> _infoFields, DataTable dtcsvlines, string tcFichero, int tnModo = 0, sage.ew.objetos.ewprogressbar bar = null)
85  {
86  string clave = "CodigoCliente%";
87  int idCampoCli = 18;
88  int idCampoNombreCli = 76;
89  List<Int32> noProcesar = new List<Int32>();
90  // girosCliente = false;
91  //noProcesar.Add(1378);
92 
93  //dtFamilia = new DataTable();
94  //dtStock = new DataTable();
95  //dtTallaYColor = new DataTable();
96  //dtURLAdic = new DataTable();
97  //dtTallaColorID = new DataTable();
98 
99  dtAuxClientes = PrepararDtAux("CLIENTES");
100  dtAuxAgencia = PrepararDtAux("AGENCIA");
101  dtAuxCanal = PrepararDtAux("CANALES", "TPV");
102  dtAuxFormaPago = PrepararDtAux("FPAG");
103  dtAuxRuta = PrepararDtAux("RUTAS");
104  dtAuxTipoFacturacion = PrepararDtAux("TIPO_FAC");
105  dtAuxVendedor = PrepararDtAux("VENDEDOR");
106  dtAuxZona = PrepararDtAux("ZONAS", "COMUNES", "ZONA", "DESCRIPCIO");
107  dtAuxCatastral = PrepararDtAux("MODREFEC", "COMUNES");
108 
109  ewprogressbar = bar;
110 
111  PrepararDtColumns();
112 
113  base.Importar(dtcsv, codigoGuia, _infoFields, dtcsvlines, tcFichero, clave, idCampoCli, idCampoNombreCli, noProcesar, tnModo);
114 
115 
116  }
117 
118  #endregion CONSTRUCTORES
119 
120  #region METODOS PRIVADOS
121 
125  private void PrepararDtColumns()
126  {
128  //dtURLAdic.Columns.Add("codigo", typeof(string));
129  //dtURLAdic.Columns.Add("imagen", typeof(string));
130 
132  //dtTallaColorID.Columns.Add("codigo", typeof(string));
133  //dtTallaColorID.Columns.Add("talla", typeof(string));
134  //dtTallaColorID.Columns.Add("color", typeof(string));
135  //dtTallaColorID.Columns.Add("id", typeof(string));
136  }
137 
143  private bool ExisteCliente(string codigo)
144  {
145  DataTable tmp = new DataTable();
146  string lcSql = "SELECT COUNT(*) AS TOTAL FROM " + DB.SQLDatabase("GESTION", "CLIENTES") +
147  " WHERE CODIGO = " + DB.SQLString(codigo);
148  DB.SQLExec(lcSql, ref tmp);
149 
150  return tmp.Rows.Count > 0 && Convert.ToInt32(tmp.Rows[0]["total"]) > 0;
151  }
152 
153  private void CrearCuentaIBAN()
154  {
155  DataTable ldPlid = new DataTable();
156  DataTable ldPlid_D1 = new DataTable();
157 
158  string lcSql = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D") +
159  " WHERE CODIGO = " + DB.SQLString(codigoGuia);
160  DB.SQLExec(lcSql, ref ldPlid);
161 
162  if (ldPlid != null || ldPlid.Rows.Count > 0)
163  {
164  string nombreColumnaCodigo = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDCAMPO"]) == 18).First()["COLUMNA"].ToString().Trim();
165  string nombreColumnaNombre = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDCAMPO"]) == 76).First()["COLUMNA"].ToString().Trim();
166  string columnaIBAN = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDTABLA"]) == 64).First()["COLUMNA"].ToString().Trim();
167 
168  if (columnaIBAN != null)
169  {
170  string lcSql_D1 = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D1") +
171  " WHERE CODIGO = " + DB.SQLString(codigoGuia);
172  DB.SQLExec(lcSql_D1, ref ldPlid_D1);
173 
174  if (ldPlid_D1 == null || ldPlid_D1.Rows.Count == 0)
175  {
176  return;
177  }
178 
179  List<string> idColumnaIBAN = new List<string>();
180  try
181  {
182  idColumnaIBAN = ldPlid_D1.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDCAMPO"]) == 50006)
183  .Select(dr => dr.Field<string>("ID_D").Trim()).ToList();
184  }
185  catch
186  {
187  // No hay campo "IBAN" en la guia
188  }
189 
190  List<string> nombreColumnaIBAN = new List<string>();
191  if (idColumnaIBAN.Count() > 0)
192  {
193  foreach (string loColumnBarras in idColumnaIBAN)
194  {
195  nombreColumnaIBAN.Add(ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToString(F["ID_RELA"]).Trim() == loColumnBarras).First()["COLUMNA"].ToString().Trim().ToString());
196  }
197  }
198 
199  if (nombreColumnaIBAN.Count == 0)
200  return;
201 
202  foreach (System.Data.DataRow filaCliente in dtCSV.Rows)
203  {
204  Int32 cont = 0;
205  int posic = 0;
206  string codigoCliente = string.Empty;
207  string nombreCliente = string.Empty;
208 
209  //Primero sacamos codigo de cliente
210  posic = posicionColumna(nombreColumnaCodigo);
211  codigoCliente = filaCliente.ItemArray[posic].ToString();
212 
213  try
214  {
215  cont = dtImportar.Rows.OfType<DataRow>().Where(dr => dr.Field<string>("CODIGO").Trim().ToUpper() == codigoCliente.Trim().ToUpper())
216  .Select(dr => dr.Field<string>("CODIGO").Trim()).ToList().FirstOrDefault().Count();
217  }
218  catch
219  {
220  //Si no viene rellena no pasa nada
221  }
222 
223  //Primero sacamos nombre de articulo
224  if (!string.IsNullOrWhiteSpace(nombreColumnaCodigo))
225  {
226  int posic2 = posicionColumna(nombreColumnaNombre);
227  nombreCliente = filaCliente.ItemArray[posic2].ToString();
228  }
229 
230  if (string.IsNullOrEmpty(codigoCliente) || cont == 0)
231  {
232  string codigo = string.Empty;
233  codigo = dtCodigos.AsEnumerable().Where(g => g.Field<Int32>("idtabla") == idTablaNegocio
234  && g.Field<string>("idpropuesto") == codigoCliente.Trim()
235  && g.Field<string>("nombrepropuesto") == nombreCliente.Trim()).Select(g => g.Field<string>("idasignado")).FirstOrDefault();
236  codigoCliente = codigo;
237  if (!string.IsNullOrEmpty(codigo))
238  cont = 1;
239  }
240 
241  if (cont > 0)
242  {
243  Cliente loCliente = new Cliente(codigoCliente);
244 
245  if (nombreColumnaIBAN.Count > 0)
246  {
247  foreach (string loColumnRela in nombreColumnaIBAN)
248  {
249  int posicR = posicionColumna(loColumnRela);
250  string codIBAN = filaCliente.ItemArray[posicR].ToString().Trim();
251 
252  if (codIBAN.Length >= 24)
253  {
255  //buscar si existe la cuenta bancaria que viene del csv
256  bool bExiste = false;
257  bool bPreder = false;
258  int num = 0;
259  foreach (Cliente.DatosBancarios.DatoBancario banco in loBancos)
260  {
261  if (banco._CtaCuenta.Trim() == codIBAN.Substring(14, 10))
262  {
263  bExiste = true;
264  bPreder = banco._Orden;
265  break;
266  }
267  num++;
268  }
269  Cliente.DatosBancarios.DatoBancario loBanco = null;
270 
271  if (bExiste)
272  {
273  loBanco = loBancos[num];
274  }
275  else
276  {
277  loBanco = loCliente._TRelDatosBancarios._NewItem();
278  loBanco._TipoCta = "IBAN";
279  }
280 
281  loBanco._Iban = codIBAN.Substring(0, 4);
282  loBanco._CtaBanco = codIBAN.Substring(4, 4);
283  loBanco._CtaSucur = codIBAN.Substring(8, 4);
284  loBanco._DigCon = codIBAN.Substring(12, 2);
285  loBanco._CtaCuenta = codIBAN.Substring(14, 10);
286  loBanco._CuentaIban = codIBAN.Substring(4, 20);
287  loBanco._Orden = loBancos.Count == 0 || bPreder;
288  loBanco._Direccion = "";
289 
290  loCliente._TRelDatosBancarios._Save();
291 
292 
293  }
294  else
295  {
296  if (codIBAN.Length != 0)
297  {
298  incidenc = "La cuenta bancaria IBAN " + codIBAN.ToString() + " indicada para el cliente " + codigoCliente + " no tiene el formato correcto. " + Environment.NewLine;
299 
300  GestionIncidencias();
301  }
302  }
303  }
304  }
305  }
306  }
307  }
308  }
309  }
310 
311 
316  protected void CrearTelefonoContactoCliente2(bool tlAdicional = false)
317  {
318 
319  int lnTablaVir = (tlAdicional ? 60003 : 60002);
320 
321  ImportManager im = new ImportManager(this, codigoGuia, "CONTLF_CLI");
322  ImportManager imC = new ImportManager(this, codigoGuia, "CLIENTES");
323 
324  if (im.Empty())
325  {
326  return;
327  }
328 
329  foreach (System.Data.DataRow filaCliente in dtCSV.Rows)
330  {
331  im.SetDataRow(filaCliente);
332  imC.SetDataRow(filaCliente);
333 
334  string codigoCliente = imC.getValue("CODIGO", "");
335  string lcTelefono = im.getValue("TELEFONO", lnTablaVir, "");
336  string lcCargo = im.getValue("CARGO", lnTablaVir, "");
337  string lcObserva = im.getValue("OBSERVA", lnTablaVir, "");
338  string lcEmail = im.getValue("EMAIL", lnTablaVir, "");
339  string lcFacebook = im.getValue("FACEBOOK", lnTablaVir, "");
340  string lcSkype = im.getValue("SKYPE", lnTablaVir, "");
341  string lcTwitter = im.getValue("TWITTER", lnTablaVir, "");
342  string lcPersona = im.getValue("PERSONA", lnTablaVir, "");
343 
344  Cliente loCliente = new Cliente(codigoCliente);
345  loCliente._TRelContacTelefs._Load();
346 
348 
349  bool bFind = false;
350  int num = 0;
351  foreach (Cliente.ContacTelefs.ContacTelef loCon in loContactos)
352  {
353 
354  if (loCon._Telefono.Trim() == lcTelefono.Trim() && loCon._Persona.Trim() == lcPersona.Trim())
355  {
356  bFind = true;
357  break;
358  }
359  num++;
360  }
361 
362  Cliente.ContacTelefs.ContacTelef loContacTelef = null;
363 
364  int linea = 1;
365 
366  if (bFind)
367  {
368  loContacTelef = loContactos[num];
369  linea = loContacTelef._Linia;
370  }
371  else
372  {
373  loContacTelef = loCliente._TRelContacTelefs._NewItem();
374  linea = loContactos.Count + 1;
375 
376  if (lbActualizar && lnTablaVir != 60003 && loContactos.Count > 0)
377  {
378  incidenc = " Se ha dado de alta un nuevo teléfono y/o contacto para el cliente " + codigoCliente + ", pero no se ha podido definir como predeterminado porque ya tenía un teléfono o contacto definido como predeterminado. Revise los teléfonos y contactos del cliente para modificarlo manualmente si lo desea." + Environment.NewLine;
379 
380  GestionIncidencias();
381  }
382 
383  }
384 
385  loContacTelef._Cliente = codigoCliente;
386  loContacTelef._Cargo = lcCargo;
387  loContacTelef._Email = lcEmail;
388  loContacTelef._Facebook = lcFacebook;
389  loContacTelef._Observa = lcObserva;
390  loContacTelef._Persona = lcPersona;
391  loContacTelef._Skype = lcSkype;
392  loContacTelef._Telefono = lcTelefono;
393  loContacTelef._Twitter = lcTwitter;
394  loContacTelef._Linia = linea;
395 
396  if (!bFind)
397  {
398  loContacTelef._Predet = !tlAdicional;
399  }
400 
401  loCliente._TRelContacTelefs._Save();
402 
403  }
404  }
405 
409  protected void CrearTelefonoContactoCliente(bool tlAdicional = false)
410  {
411  CrearTelefonoContactoCliente2(tlAdicional);
412  return;
413  }
414 
419  protected void CodigoDeCliente()
420  {
421  bool esCuenta = true;
422 
423  DataTable ldPlid = new DataTable();
424  DataTable ldPlid_D1 = new DataTable();
425 
426  string lcSql = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D") +
427  " WHERE CODIGO = " + DB.SQLString(codigoGuia);
428 
429  DB.SQLExec(lcSql, ref ldPlid);
430 
431  if (ldPlid != null || ldPlid.Rows.Count > 0)
432  {
433  DataTable ldtTemp = new DataTable();
434 
435  string nombreColumnaCodigo = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDCAMPO"]) == 18).First()["COLUMNA"].ToString().Trim();
436  string incidenc = string.Empty;
437  string codigoCliente = string.Empty;
438 
439  Int32 fila = 0;
440  List<DataRow> vacios = new List<DataRow>();
441  List<String> codigos = new List<string>();
442 
443  int posic = posicionColumna(nombreColumnaCodigo);
444 
445  foreach (System.Data.DataRow filaCliente in dtCSV.Rows)
446  {
447  //Primero sacamos codigo de cliente
448 
449  codigoCliente = filaCliente.ItemArray[posic].ToString();
450 
451 
452  if (string.IsNullOrWhiteSpace(codigoCliente))
453  {
454  vacios.Add(filaCliente);
455  continue;
456  }
457 
458  string cuenta = codigoCliente.Substring(0, 3);
459 
460  ldtTemp.Clear();
461 
462  lcSql = "SELECT CODIGO, CLIENTE " +
463  " FROM " + DB.SQLDatabase("gestion", "nivel3") +
464  " WHERE CLIENTE=1 AND CODIGO=" + DB.SQLString(cuenta) +
465  " ORDER BY 1";
466 
467  DB.SQLExec(lcSql, ref ldtTemp);
468 
469  if (ldtTemp.Rows.Count == 0)
470  {
471  esCuenta = false;
472  }
473 
474  int lenCodigo = codigoCliente.Length;
475 
476  if (esCuenta) // Es cuenta contable
477  {
478  // revisar si la longitud del "codigo" sea igual a la longitud del campo destino
479  if (lenCodigo < lnLenCliente)
480  {
481  codigoCliente = codigoCliente.Substring(0, 3) + new String('0', lnLenCliente - lenCodigo) + codigoCliente.Substring(3);
482  filaCliente.ItemArray[posic] = codigoCliente;
483  codigos.Add(codigoCliente);
484  }
485  else
486  {
487  if (lenCodigo < lnLenCliente)
488  {
489  incidenc = MensajeIncidencia(fila.ToString(), posic.ToString(), codigoCliente, "La longitud del campo es mayor del tamaño que la del campo destino. Campo ampliable mediante configuración de " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")));
490  RegistrarIncidencia(fila, incidenc, 2);
491  GestionIncidencias();
492  }
493  }
494  }
495  else // no es cuenta contable
496  {
497  if (lenCodigo + 3 < lnLenCliente)
498  {
499  codigoCliente = "430" + new String('0', lnLenCliente - lenCodigo + 3) + codigoCliente;
500  filaCliente.ItemArray[posic] = codigoCliente;
501  codigos.Add(codigoCliente);
502  }
503  else
504  {
505  if (lenCodigo < lnLenCliente)
506  {
507  incidenc = MensajeIncidencia(fila.ToString(), posic.ToString(), codigoCliente, "La longitud del campo es mayor del tamaño que la del campo destino.Campo ampliable mediante configuración de " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")));
508  RegistrarIncidencia(fila, incidenc, 2);
509  GestionIncidencias();
510  }
511  }
512  }
513  }
514 
515  foreach (DataRow filaCliente in vacios)
516  {
517  codigoCliente = CrearCodigo(107, codigos);
518  filaCliente.ItemArray[posic] = codigoCliente;
519  codigos.Add(codigoCliente);
520  }
521  }
522  }
523 
524 
525 
529  private List<string> Direccion_old(Int32 fila)
530  {
531 
532  List<string> CodClienteIncid = new List<string>();
533 
534  string codigoCliente = string.Empty;
535  string nombreColumnaCodigo = string.Empty;
536  string nombreColumnaNombre = string.Empty;
537 
538  DataTable ldTemp = new DataTable();
539  DataTable ldPlid = new DataTable();
540  DataTable ldPlid_D1 = new DataTable();
541  DataTable ldCampos = new DataTable();
542  CargarDatos c = new CargarDatos(true);
543 
544  string lcSql = "SELECT * FROM " + DB.SQLDatabase("COMUNES", "CAMPOS");
545  DB.SQLExec(lcSql, ref ldCampos);
546  Dictionary<Int32, DataRow> campos = new Dictionary<Int32, DataRow>();
547  foreach (DataRow row in ldCampos.Rows)
548  {
549  Int32 idcampo = Convert.ToInt32(row["idcampo"]);
550  if (!campos.ContainsKey(idcampo))
551  {
552  campos.Add(Convert.ToInt32(row["idcampo"]), row);
553  }
554  }
555 
556  lcSql = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D") + " WHERE CODIGO = " + DB.SQLString(codigoGuia);
557  DB.SQLExec(lcSql, ref ldPlid);
558 
559  if (ldPlid != null || ldPlid.Rows.Count > 0)
560  {
561  nombreColumnaCodigo = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDCAMPO"]) == 18).First()["COLUMNA"].ToString().Trim();
562  nombreColumnaNombre = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDCAMPO"]) == 76).First()["COLUMNA"].ToString().Trim();
563 
564  string lcSql_D1 = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D1") + " WHERE CODIGO = " + DB.SQLString(codigoGuia) +
565  " AND (IDTABLA = 60000 OR IDTABLA = 60001)";
566 
567  DB.SQLExec(lcSql_D1, ref ldPlid_D1);
568  if (ldPlid_D1 == null || ldPlid_D1.Rows.Count == 0)
569  {
570  return CodClienteIncid;
571  }
572 
573  Int32[] tablas = new Int32[] { 60000, 60001 };
574 
575  foreach (Int32 table in tablas)
576  {
577  DataView view = new DataView(ldPlid_D1);
578  view.RowFilter = "idtabla = " + table;
579 
580  Dictionary<string, ArrayList> nombresCampos = new Dictionary<string, ArrayList>();
581 
582  foreach (DataRowView rowView in view)
583  {
584  Int32 idcampo = Convert.ToInt32(rowView["idcampo"]);
585  Int32 idtabla = c.idTablaVirtual(Convert.ToInt32(rowView["idtabla"]));
586  string fieldname = Convert.ToString(campos[idcampo]["campo"]).Trim();
587  string tipocampo = c.obtenerTipoColumna(idtabla, fieldname);
588  string id_d = rowView["ID_D"].ToString().Trim();
589  string nombreColumnaEnCSV = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToString(F["ID_RELA"]).Trim() == id_d).First()["COLUMNA"].ToString().Trim().ToString();
590  ArrayList x = new ArrayList();
591  x.Add(tipocampo);
592  x.Add(nombreColumnaEnCSV);
593  x.Add(fieldname);
594  nombresCampos.Add(fieldname, x);
595  }
596 
597  Dictionary<string, object> valores = new Dictionary<string, object>();
598 
599  Int32 nfila = 0;
600 
601  foreach (DataRow row in dtCSV.Rows)
602  {
603  Int32 cont = 0;
604  int posic = 0;
605  string nombreCliente = string.Empty;
606 
607  posic = posicionColumna(nombreColumnaCodigo);
608  codigoCliente = row.ItemArray[posic].ToString();
609 
610  try
611  {
612  cont = dtImportar.Rows.OfType<DataRow>().Where(dr => dr.Field<string>("CODIGO").Trim().ToUpper() == codigoCliente.Trim().ToUpper())
613  .Select(dr => dr.Field<string>("CODIGO").Trim()).ToList().FirstOrDefault().Count();
614  }
615  catch
616  {
617  //Si no viene rellena no pasa nada
618  }
619 
620  //Primero sacamos nombre de articulo
621  if (!string.IsNullOrWhiteSpace(nombreColumnaCodigo))
622  {
623  int posic2 = posicionColumna(nombreColumnaNombre);
624  nombreCliente = row.ItemArray[posic2].ToString();
625  }
626 
627  if (string.IsNullOrEmpty(codigoCliente) || cont == 0)
628  {
629  string codigo = string.Empty;
630  codigo = dtCodigos.AsEnumerable().Where(g => g.Field<Int32>("idtabla") == idTablaNegocio
631  && g.Field<string>("idpropuesto") == codigoCliente.Trim()
632  && g.Field<string>("nombrepropuesto") == nombreCliente.Trim()).Select(g => g.Field<string>("idasignado")).FirstOrDefault();
633  codigoCliente = codigo;
634  if (!string.IsNullOrEmpty(codigo))
635  cont = 1;
636  }
637 
638  if (cont > 0)
639  {
640  valores.Clear();
641 
642  foreach (KeyValuePair<string, ArrayList> entry in nombresCampos)
643  {
644  string tipocampo = entry.Value[0].ToString(); // tipocampo
645  object valorEnCSV = row[posicionColumna(entry.Value[1].ToString())]; // nombreColumnaEnCSV
646  string fieldname = entry.Value[2].ToString(); // fieldname
647 
648  switch (tipocampo)
649  {
650  case "memo":
651  case "caracter":
652  valores.Add(fieldname, Convert.ChangeType(valorEnCSV, typeof(string)));
653  break;
654  case "logico":
655  valores.Add(fieldname, Convert.ChangeType(valorEnCSV, typeof(bool)));
656  break;
657  case "entero":
658  valores.Add(fieldname, Convert.ChangeType(valorEnCSV, typeof(Int32)));
659  break;
660  case "fecha":
661  valores.Add(fieldname, Convert.ChangeType(valorEnCSV, typeof(DateTime)));
662  break;
663  case "numerico":
664  valores.Add(fieldname, Convert.ChangeType(valorEnCSV, typeof(double)));
665  break;
666  default:
667  break;
668  }
669  }
670 
671  if (valores.ContainsKey("PAIS"))
672  {
673  string pais = string.Empty;
674  string tcPais = (string)(valores.ContainsKey("PAIS") ? valores["PAIS"] : string.Empty);
675 
676  if (!string.IsNullOrEmpty(tcPais))
677  {
678  pais = ValidarRegla(PaisCta(tcPais));
679  if (pais == "-1")
680  {
681  CodClienteIncid.Add(codigoCliente);
682 
683  incidenc = "El cliente " + codigoCliente + " no ha sido traspasado porque el país informado " + tcPais + " no se encuentra en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")) + ". Debe crearlo en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")) + " antes de realizar la importación. " + Environment.NewLine;
684  GestionIncidencias();
685  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
686  continue;
687  }
688  }
689 
690  if (!dtImportar.Columns.Contains("PAIS"))
691  dtImportar.Columns.Add("PAIS");
692 
693  if (table == 60000)
694  dtImportar.Rows[nfila]["PAIS"] = pais;
695 
696  }
697 
698  if (valores.ContainsKey("CODPOS"))
699  {
700  string tcCodPos = (string)(valores.ContainsKey("CODPOS") ? valores["CODPOS"] : string.Empty);
701  string tcPoblacion = (string)(valores.ContainsKey("POBLACION") ? valores["POBLACION"] : string.Empty);
702  string tcProvincia = (string)(valores.ContainsKey("PROVINCIA") ? valores["PROVINCIA"] : string.Empty);
703 
704  CodigoPostal(tcCodPos, tcPoblacion, tcProvincia);
705  }
706 
707  if (valores.ContainsKey("DIRECCION"))
708  {
709  int tipo = 2;
710  int linea = 1;
711  if (table == 60001)
712  {
713  tipo = 3;
714  }
715  lcSql = "SELECT * FROM " + DB.SQLDatabase("GESTION", "ENV_CLI") + " WHERE CLIENTE = " + DB.SQLString(codigoCliente);
716  DB.SQLExec(lcSql, ref ldTemp);
717  if (ldTemp != null)
718  {
719  linea = Convert.ToInt32(ldTemp.Rows.Count) + 1;
720  }
721 
722  string lcCliente = codigoCliente;
723 
724  string tcDireccion = (string)(valores.ContainsKey("DIRECCION") ? valores["DIRECCION"] : string.Empty);
725  string tcCodPos = (string)(valores.ContainsKey("CODPOS") ? valores["CODPOS"] : string.Empty);
726  string tcPoblacion = (string)(valores.ContainsKey("POBLACION") ? valores["POBLACION"] : string.Empty);
727  string tcProvincia = (string)(valores.ContainsKey("PROVINCIA") ? valores["PROVINCIA"] : string.Empty);
728  string tcHorario = (string)(valores.ContainsKey("HORARIO") ? valores["HORARIO"] : string.Empty);
729  string tcPais = (string)(valores.ContainsKey("PAIS") ? valores["PAIS"] : string.Empty);
730 
731  // Si existe la dirección, se actualiza
732 
733  bool bExiste = false;
734  if (lbActualizar)
735  {
736  List<DataRow> row0 = ldTemp.Rows.OfType<DataRow>().Where(F => Convert.ToString(F["DIRECCION"]).Trim() == tcDireccion &&
737  Convert.ToString(F["CODPOS"]).Trim() == tcCodPos &&
738  Convert.ToString(F["POBLACION"]).Trim() == tcPoblacion &&
739  Convert.ToString(F["PROVINCIA"]).Trim() == tcProvincia &&
740  Convert.ToString(F["PAIS"]).Trim() == tcPais).ToList();
741  bExiste = row0.Count > 0;
742 
743  if (bExiste)
744  {
745  lcSql = "UPDATE " + DB.SQLDatabase("env_cli") + " SET cliente = " + DB.SQLString(lcCliente) +
746  ", direccion = " + DB.SQLString(tcDireccion) +
747  ", codpos = " + DB.SQLString(tcCodPos) +
748  ", poblacion = " + DB.SQLString(tcPoblacion) +
749  ", provincia = " + DB.SQLString(tcProvincia) +
750  ", pais = " + DB.SQLString(tcPais) +
751  ", tipo = " + DB.SQLString(tipo);
752  DB.SQLExec(lcSql);
753  }
754  }
755 
756  if (!bExiste)
757  {
758  if (lbActualizar && table == 60000)
759  {
760  tipo = 0;
761  }
762 
763  try
764  {
765  lcSql = "INSERT INTO " + DB.SQLDatabase("env_cli") + "(cliente, linea, direccion, codpos, poblacion, provincia, horario, pais, tipo ) " +
766  "VALUES(" + DB.SQLString(lcCliente) + ", " +
767  DB.SQLString(linea) + ", " +
768  DB.SQLString(tcDireccion) + ", " +
769  DB.SQLString(tcCodPos) + ", " +
770  DB.SQLString(tcPoblacion) + ", " +
771  DB.SQLString(tcProvincia) + ", " +
772  DB.SQLString(tcHorario) + ", " +
773  DB.SQLString(tcPais) + ", " +
774  DB.SQLString(tipo) + ")";
775 
776  DB.SQLExec(lcSql);
777 
778  if (lbActualizar && table == 60000)
779  {
780  incidenc = "Se ha dado de alta nueva dirección para el cliente, pero no se ha podido definir como tipo facturación porque ya tenía una dirección definida con ese tipo. Revise las direcciones del cliente para modificarlo manualmente si lo desea." + Environment.NewLine;
781  GestionIncidencias();
782 
783  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
784  continue;
785  }
786  }
787  catch
788  {
789 
790  }
791  nfila++;
792  }
793  }
794  }
795  }
796  }
797  }
798 
799  return CodClienteIncid;
800 
801  }
802 
803 
804 
805  #endregion METODOS PRIVADOS
806 
807  #region METODOS PROTECTED
808 
817  protected override DataTable PrepararDtImportar(int idTablaCampo, bool linfadi, Int32 idCampo, string nombre)
818  {
819  switch (idTablaCampo)
820  {
821  case 107:
822  // Añadimos columnas a dtClientes
823  if (!dtImportar.Columns.Contains(nombre))
824  dtImportar.Columns.Add(nombre);
825 
826  if (idCampo == 54)
827  {
828  DataTable dtPlinter_D1 = new DataTable();
829 
830  string lcSql = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D1") + " WHERE codigo = " + DB.SQLString(codigoGuia) +
831  " AND IDCAMPO = 50007";
832 
833  DB.SQLExec(lcSql, ref dtPlinter_D1);
834 
835  if (dtPlinter_D1 != null && dtPlinter_D1.Rows.Count > 0)
836  {
837  nombre = "FPAG_GIRO";
838  lbGiros = true;
839  }
840  }
841 
842  if (idCampo == 100 || idCampo == 117) // Ruta o Zona
843  {
844  DataTable dtPlinter_D1 = new DataTable();
845 
846  string lcSql = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D1") + " WHERE codigo = " + DB.SQLString(codigoGuia) +
847  " AND IDCAMPO = 669 OR IDCAMPO = 451";
848 
849  DB.SQLExec(lcSql, ref dtPlinter_D1);
850 
851  if (dtPlinter_D1 != null && dtPlinter_D1.Rows.Count == 2)
852  {
853  nombre = "ZONARUTA";
854  lbRutaZona = true;
855  }
856  }
857 
858  break;
859 
860  default:
861  if (idCampo == 50006)
862  {
863  nombre = "CTAIBAN";
864  cuentaIBAN = true;
865  }
866 
867  if (idCampo == 50007)
868  {
869  nombre = "FPAG_GIRO";
870  lbGiros = true;
871  }
872 
873  if (idCampo == 1534)
874  {
875  nombre = "MANDATO";
876  lbMandatos = true;
877  }
878 
879  if (idCampo == 60000 || idCampo == 60001 || idCampo == 60002 || idCampo == 60003)
880  {
881  nombre = "TAB_VIR"; // Activa el tratamiento direcciones y teléfonos del cliente
882  }
883 
884  break;
885  }
886 
887  return base.PrepararDtImportar(idTablaCampo, linfadi, idCampo, nombre);
888  }
889 
893  protected override void InicializarVariables(DataTable dtPlinter_D)
894  {
895  // si tenemos clientes que van relacionados con tablas relacionadas
896  cuentaIBAN = false;
897  lbMandatos = false;
898  lbDireccFac = false;
899  lbDireccAdi = false;
900  lbTelefPre = false;
901  lbTelefAdi = false;
902  }
903 
904 
908  protected override bool ComprobarExiste(string codigo)
909  {
910  bool lbOk = false;
911  List<string> valoresCodigo = null;
912 
913  valoresCodigo = dtAuxClientes.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("CODIGO").Trim()).ToList();
914 
915  if (!valoresCodigo.Contains(codigo))
916  {
917  valoresCodigo = dtImportar.Rows.OfType<DataRow>().Where(dr => !string.IsNullOrEmpty(dr.Field<string>("CODIGO")))
918  .Select(dr => dr.Field<string>("CODIGO").Trim()).ToList();
919 
920  if (valoresCodigo.Contains(codigo))
921  {
922  // Existe el artículo en los registros de CSV que hemos procesado
923  lbOk = true;
924  }
925  }
926  else
927  {
928  // Existe el artículo en Sage 50
929  lbOk = true;
930  lbExiste_S50 = true;
931  }
932 
933  return lbOk;
934  }
935 
936 
946  protected override void RegistroTablaRelacionada(RegistroPlinter_D registroD, ref Int32 fila, ref string codImportar, ref string valorColumnaCSV, ref bool ltablaImportar, ref Int32 colDt)
947  {
948  switch (registroD._Idtabla)
949  {
950  case 64:
951  cuentaIBAN = true;
952  lbGiros = true;
953  break;
954 
955  case 1534:
956  lbMandatos = true;
957  break;
958 
959  case 60000:
960  lbDireccFac = true;
961  break;
962 
963  case 60001:
964  lbDireccAdi = true;
965  break;
966 
967  case 60002:
968  lbTelefPre = true;
969  break;
970 
971  case 60003:
972  lbTelefAdi = true;
973  break;
974  }
975 
976  fila++;
977  ltablaImportar = false;
978  }
979 
986  protected override DataTable ValoresDtAux(string nombreTabla, ref DataTable dtMomen)
987  {
988  switch (nombreTabla)
989  {
990  case "CLIENTES":
991  {
992  dtMomen = dtAuxClientes;
993  break;
994  }
995  case "AGENCIA":
996  {
997  dtMomen = dtAuxAgencia;
998  break;
999  }
1000  case "CANALES":
1001  {
1002  dtMomen = dtAuxCanal;
1003  break;
1004  }
1005  case "FPAG":
1006  {
1007  dtMomen = dtAuxFormaPago;
1008  break;
1009  }
1010  case "RUTAS":
1011  {
1012  dtMomen = dtAuxRuta;
1013  break;
1014  }
1015  case "TIPO_FAC":
1016  {
1017  dtMomen = dtAuxTipoFacturacion;
1018  break;
1019  }
1020  case "VENDEDOR":
1021  {
1022  dtMomen = dtAuxVendedor;
1023  break;
1024  }
1025  case "ZONAS":
1026  {
1027  dtMomen = dtAuxZona;
1028  break;
1029  }
1030  case "MODREFEC":
1031  {
1032  dtMomen = dtAuxCatastral;
1033  break;
1034  }
1035  }
1036  return base.ValoresDtAux(nombreTabla, ref dtMomen);
1037  }
1038 
1042  protected override int AsignoTextosLongitud(Dictionary<int, string> textos, int idMante)
1043  {
1044  int iLen2 = 0;
1045 
1046  textos.Add(70, "Formas de pago");
1047  textos.Add(18, "Rutas");
1048  textos.Add(4, "Vendedores");
1049  textos.Add(107, "Clientes");
1050  textos.Add(129, "Agencias");
1051  textos.Add(1538, "Canal");
1052  textos.Add(291, "Letras");
1053  textos.Add(356, "Referencias catastrales de inmuebles");
1054 
1055  switch (idMante)
1056  {
1057  case 70:
1058  iLen2 = lnLenFormaPago;
1059  break;
1060  case 18:
1061  iLen2 = lnLenRuta;
1062  break;
1063  case 4:
1064  iLen2 = lnLenVendedor;
1065  break;
1066  case 107:
1067  iLen2 = lnLenCliente;
1068  break;
1069  case 129:
1070  iLen2 = lnLenAgencia;
1071  break;
1072  case 1538:
1073  // iLen2 = lnLenCanal;
1074  break;
1075  case 291:
1076  iLen2 = 2;
1077  break;
1078  case 356:
1079  iLen2 = 25;
1080  break;
1081  case 286:
1082  iLen2 = lnLenZona;
1083  break;
1084  }
1085 
1086  return iLen2;
1087  }
1088 
1089 
1090 
1106  protected override string ValidarRegla(string regla, Int32 idTabla = 0, List<string> valorespreexistentes = null, string codigo = "", string valor = "", DataTable dtImportar = null, string nombreNegocio = "", bool nombreValDef = false, string valor2 = "", string valor3 = "", Int32 fila = 0)
1107  {
1108  string valret = string.Empty;
1109 
1110  switch (regla.Trim())
1111  {
1112  case "CodigoCliente":
1113  case "CodigoTercero":
1114  valorespreexistentes = this.valorespreexistentes;
1115  valret = CrearCodigo(idTabla, valorespreexistentes, true, "", false, true, nombreNegocio, nombreValDef);
1116  break;
1117 
1118  case "CrearMandato":
1119  CrearMandato();
1120  break;
1121 
1122  default:
1123  valret = base.ValidarRegla(regla, idTabla, valorespreexistentes, codigo, valor, dtImportar, nombreNegocio, nombreValDef, valor2, valor3, fila);
1124  break;
1125  }
1126  return valret;
1127  }
1128 
1132  protected void CrearMandato()
1133  {
1134  ImportManager im = new ImportManager(this, codigoGuia, "MANDATOS");
1135 
1136 
1137  if (im.ldPlid_D != null || im.ldPlid_D.Rows.Count > 0)
1138  {
1139  string nombreColumnaCodigo = im.nombreColumna(18);
1140  string nombreColumnaNombre = im.nombreColumna(76);
1141  string columnaMandato = im.nombreColumna(1534);
1142 
1143  if (columnaMandato != null)
1144  {
1145  if (im.ldPlid_D1 == null || im.ldPlid_D1.Rows.Count == 0)
1146  {
1147  return;
1148  }
1149 
1150  im.AddItem("MANDATO", 217);
1151  im.AddItem("DEFECTO", 220);
1152  im.AddItem("FECHA_FIN", 218);
1153  im.AddItem("TIPO_PAGO", 233);
1154  im.AddItem("TIPO", 225);
1155  im.AddItem("CLI_IBAN", 50006);
1156  im.AddItem("FECHA_CART", 221);
1157  im.AddItem("FECHA_FIR", 224);
1158  im.AddItem("POBLAC_FIR", 236);
1159  im.AddItem("PERSPAGO", 243);
1160  im.AddItem("NUMEFPRO", 238);
1161  im.AddItem("NUMEFE", 237);
1162  im.AddItem("ESTPRO", 239);
1163  im.AddItem("MANDATORIG", 234);
1164 
1165 
1166  foreach (System.Data.DataRow filaCliente in dtCSV.Rows)
1167  {
1168  Int32 cont = 0;
1169 
1170  string codigoCliente = string.Empty;
1171  string nombreCliente = string.Empty;
1172 
1173  codigoCliente = valorEnCSV(filaCliente, nombreColumnaCodigo);
1174 
1175  try
1176  {
1177  cont = dtImportar.Rows.OfType<DataRow>().Where(dr => dr.Field<string>("CODIGO").Trim().ToUpper() == codigoCliente.Trim().ToUpper())
1178  .Select(dr => dr.Field<string>("CODIGO").Trim()).ToList().FirstOrDefault().Count();
1179  }
1180  catch
1181  {
1182  //Si no viene rellena no pasa nada
1183  }
1184 
1185  nombreCliente = valorEnCSV(filaCliente, nombreColumnaNombre);
1186 
1187  if (string.IsNullOrEmpty(codigoCliente) || cont == 0)
1188  {
1189  string codigo = string.Empty;
1190  codigo = dtCodigos.AsEnumerable().Where(g => g.Field<Int32>("idtabla") == idTablaNegocio
1191  && g.Field<string>("idpropuesto") == codigoCliente.Trim()
1192  && g.Field<string>("nombrepropuesto") == nombreCliente.Trim()).Select(g => g.Field<string>("idasignado")).FirstOrDefault();
1193  codigoCliente = codigo;
1194  if (!string.IsNullOrEmpty(codigo))
1195  cont = 1;
1196  }
1197 
1198  if (cont > 0)
1199  {
1200  foreach (KeyValuePair<string, actItem> o in im.campos)
1201  {
1202  im.SetDataRow(filaCliente);
1203  }
1204 
1205  string codigoMandato = im.campos["MANDATO"].ToString();
1206  bool MandatoDefecto = im.campos["DEFECTO"].ToBoolean(true);
1207  DateTime FechaFinMandato = im.campos["FECHA_FIN"].ToDateTime();
1208  DateTime FechaFirma = im.campos["FECHA_FIR"].ToDateTime();
1209  DateTime FechaEnv = im.campos["FECHA_CART"].ToDateTime();
1210  string codigoMandatoOrigen = im.campos["MANDATORIG"].ToString();
1211  string codigoPoblacFirma = im.campos["POBLAC_FIR"].ToString();
1212  string codigoPersonaPago = im.campos["PERSPAGO"].ToString();
1213  Int32 TipoPago = im.campos["TIPO_PAGO"].ToInt32(1);
1214  Int32 TipoMandato = im.campos["TIPO"].ToInt32(1);
1215  string cli_IBAN = im.campos["CLI_IBAN"].ToString();
1216  Int32 NumEfecProc = im.campos["NUMEFE"].ToInt32();
1217  Int32 NumEfecMax = im.campos["NUMEFPRO"].ToInt32();
1218  bool MandatoProc = im.campos["ESTPRO"].ToBoolean();
1219 
1220  // buscar en banc_cli
1221 
1222  if (!string.IsNullOrEmpty(codigoMandato))
1223  {
1224  DataTable ldtTemp = new DataTable();
1225 
1226  string sql = "SELECT CODIGO FROM " + DB.SQLDatabase("GESTION", "BANC_CLI") +
1227  " WHERE CLIENTE = " + DB.SQLString(codigoCliente) + " AND (IBAN + CUENTAIBAN) = " + DB.SQLString(cli_IBAN);
1228 
1229  DB.SQLExec(sql, ref ldtTemp);
1230  Int32 banc_cli = 0;
1231  if (ldtTemp != null && ldtTemp.Rows.Count > 0)
1232  {
1233  banc_cli = Convert.ToInt32(ldtTemp.Rows[0]["CODIGO"]);
1234  }
1235 
1236  DataTable ldtMandato = new DataTable();
1237 
1238  string lcSql = "SELECT * FROM " + DB.SQLDatabase("COMUNES", "MANDATOS") +
1239  " WHERE CLIENTE = " + DB.SQLString(codigoCliente) + " And MANDATO = " + DB.SQLString(codigoMandato.ToString().Trim());
1240 
1241 
1242  DB.SQLExec(lcSql, ref ldtMandato);
1243 
1244  if (ldtMandato == null || ldtMandato.Rows.Count == 0)
1245  {
1246  DB.SQLExec("Insert Into " + DB.SQLDatabase("COMUNES", "MANDATOS") +
1247  "(CLIENTE, LINIA, MANDATO, DEFECTO, FECHA_FIN, FECHA_CART, FECHA_FIR," +
1248  " MANDATORIG, POBLAC_FIR, PERSPAGO, TIPO, CLI_IBAN, TIPO_PAGO, NUMEFE, NUMEFPRO, ESTPRO, BANC_CLI) " +
1249  "Values (" + DB.SQLString(codigoCliente) + "," + 1 + "," + DB.SQLString(codigoMandato) + "," + DB.SQLString(MandatoDefecto) + "," +
1250  DB.SQLString(FechaFinMandato) + "," + DB.SQLString(FechaEnv) + "," + DB.SQLString(FechaFirma) + "," +
1251  DB.SQLString(codigoMandatoOrigen) + "," + DB.SQLString(codigoPoblacFirma) + "," + DB.SQLString(codigoPersonaPago) + "," +
1252  DB.SQLString(TipoMandato) + "," + DB.SQLString(cli_IBAN) + "," + DB.SQLString(TipoPago) + "," +
1253  DB.SQLString(NumEfecProc) + "," + DB.SQLString(NumEfecMax) + "," + DB.SQLString(MandatoProc) + ", " +
1254  DB.SQLString(banc_cli) + ")");
1255  }
1256  else
1257  {
1258  DB.SQLExec("Update " + DB.SQLDatabase("COMUNES", "MANDATOS") + " " +
1259  "Set FECHA_FIN = " + DB.SQLString(FechaFinMandato) + ", DEFECTO = " + DB.SQLString(MandatoDefecto) + ", FECHA_CART = " + DB.SQLString(FechaEnv) +
1260  ", FECHA_FIR = " + DB.SQLString(FechaFirma) + ", MANDATORIG = " + DB.SQLString(codigoMandatoOrigen) +
1261  ", POBLAC_FIR = " + DB.SQLString(codigoPoblacFirma) + ", PERSPAGO = " + DB.SQLString(codigoPersonaPago) +
1262  ", TIPO = " + DB.SQLString(TipoMandato) + ", CLI_IBAN = " + DB.SQLString(cli_IBAN) + ", TIPO_PAGO = " + DB.SQLString(TipoPago) +
1263  ", NUMEFE = " + DB.SQLString(NumEfecProc) + ", NUMEFPRO = " + DB.SQLString(NumEfecMax) + ", ESTPRO = " + DB.SQLString(MandatoProc) +
1264  " WHERE CLIENTE = " + DB.SQLString(codigoCliente) + " AND MANDATO = " + DB.SQLString(codigoMandato) + " AND BANC_CLI = " + DB.SQLString(banc_cli));
1265  }
1266  }
1267  }
1268  }
1269  }
1270  }
1271  }
1272 
1273 
1277  protected override void ImportarNegocio()
1278  {
1279  base.ImportarNegocio();
1280 
1281  List<string> lImportados = new List<string>();
1282 
1283  // posición (columna del campo en el fichero CSV-EXCEL)
1284  int posic = PosColumna(107, 18);
1285 
1286  // Comprobamos si la tabla dtImportar tiene campo IDIOMA y si la divisa no existe en Sage50 no traspasamos el cliente y
1287  // mostramos mensaje de incidencia indicando que debe crear antes la divisa en Sage50
1288  int fila = -1;
1289  if (dtImportar != null && dtImportar.Rows.Count > 0)
1290  {
1291  fila++;
1292  int lnRows = dtImportar.Rows.Count;
1293  bool llUpdate = false;
1294 
1295  if (lnRows > 0)
1296  {
1297  while (lnRows > 0)
1298  {
1299  lnRows--;
1300  DataRow ldr = dtImportar.Rows[lnRows];
1301 
1302  string lcCodigo = Convert.ToString(ldr["CODIGO"]).Trim();
1303  string lcIdioma = Convert.ToString(ldr["IDIOMA"]).Trim();
1304  Int32 filaenproceso = Convert.ToInt32(ldr["filafichero"]);
1305 
1306  string divisa = string.Empty;
1307 
1308  if (!string.IsNullOrEmpty(lcIdioma) && lcIdioma != "000")
1309  {
1310  divisa = ValidarRegla("Divisa", 0, null, null, lcIdioma);
1311  }
1312  if (string.IsNullOrEmpty(divisa))
1313  {
1314  incidenc = MensajeIncidencia(filaenproceso.ToString(), (posic + 1).ToString(), lcCodigo, "No ha sido traspasado porque la divisa informada " + lcIdioma + " no se encuentra en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")) + ". Debe crear las divisas en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")) + " antes de realizar la importación. ");
1315  RegistrarIncidencia(filaenproceso, incidenc, 3);
1316  GestionIncidencias();
1317  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
1318 
1319  if (!lstNoImportados.Contains(lcCodigo))
1320  lstNoImportados.Add(lcCodigo);
1321 
1322  ldr.Delete();
1323  llUpdate = true;
1324 
1325  continue;
1326  }
1327 
1328  }
1329  }
1330 
1331  if (llUpdate)
1332  dtImportar.AcceptChanges();
1333  }
1334 
1335  // Recorremos registro de Direccion (Tablas_Vir)
1336  // Si hay dirección y no pais no grabamos el cliente y
1337  // mostramos mensaje de incidencia indicando que debe crear antes la PAIS en Sage50
1338  fila = -1;
1339  if (lbDireccFac || lbDireccAdi)
1340  {
1341  if (dtImportar != null && dtImportar.Rows.Count > 0)
1342  {
1343  fila = -1;
1344  foreach (DataRow lnRows in dtImportar.Rows)
1345  {
1346  fila++;
1347 
1348  List<string> codCliInc = CrearDireccion(lstNoImportados, fila);
1349  }
1350  }
1351  }
1352 
1353  // Campos cuenta contrapartida y banco (comprobamos antes de importar si existe cuenta y sino creamos)
1354  if (lbCrearCuenta)
1355  {
1356  ValidarRegla("CrearCuentaContable");
1357  }
1358 
1359  fila = -1;
1360 
1361  ewprogressbar.Maximum = dtImportar.Rows.Count;
1362 
1363  if (lbFormaPago) ewprogressbar.Maximum++;
1364  if (lbVendedor) ewprogressbar.Maximum++;
1365  if (lbTelefPre || lbTelefAdi) ewprogressbar.Maximum++;
1366  if (cuentaIBAN) ewprogressbar.Maximum++;
1367  if (lbGiros) ewprogressbar.Maximum++;
1368  if (lbMandatos) ewprogressbar.Maximum++;
1369  if (lbCatastral) ewprogressbar.Maximum++;
1370 
1371  foreach (DataRow row in dtImportar.Rows)
1372  {
1373  fila++;
1374 
1375  ewprogressbar.PerformStep();
1376 
1377  string valor = row["CODIGO"].ToString();
1378  string valornombre = row["NOMBRE"].ToString().Trim();
1379  Int32 filaenproceso = Convert.ToInt32(row["filafichero"]);
1380 
1381  if (lImportados.Contains(valor))
1382  continue;
1383 
1384  if (ExisteCliente(valor) && !lbActualizar)
1385  {
1386  incidenc = MensajeIncidencia(filaenproceso.ToString(), (posic + 1).ToString(), valor, "El cliente no ha sido traspasado porque ya existe en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")));
1387 
1388  if (!lstNoImportados.Contains(valor))
1389  lstNoImportados.Add(valor);
1390 
1391  RegistrarIncidencia(filaenproceso, incidenc, 3);
1392  GestionIncidencias();
1393  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
1394  continue;
1395  }
1396 
1397  if (!ExisteCliente(valor) && !lbInsertar)
1398  {
1399  incidenc = MensajeIncidencia(filaenproceso.ToString(), (posic + 1).ToString(), valor, "El cliente no ha sido actualizado porque no existe en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")));
1400 
1401  if (!lstNoImportados.Contains(valor))
1402  lstNoImportados.Add(valor);
1403 
1404  RegistrarIncidencia(filaenproceso, incidenc, 3);
1405  GestionIncidencias();
1406  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
1407  continue;
1408  }
1409 
1410  using (Cliente rnCliente = new Cliente())
1411  {
1412  rnCliente._Codigo = valor;
1413  rnCliente._Load();
1414 
1415  if (rnCliente._Estado == sage.ew.ewbase.ewMante._EstadosMantenimiento.EntrandoNuevo)
1416  {
1417  rnCliente._Codigo = "";
1418  rnCliente._Estado = sage.ew.ewbase.ewMante._EstadosMantenimiento.EsperandoCodigo;
1419  historicoGuia._Importados++;
1420  }
1421  else
1422  {
1423  rnCliente._Codigo = valor;
1424  rnCliente._Estado = sage.ew.ewbase.ewMante._EstadosMantenimiento.EditandoRegistro;
1425  historicoGuia._Actualizados++;
1426  }
1427 
1428  sage.ew.ewbase.ewMante._EstadosMantenimiento loEstado = rnCliente._Estado;
1429 
1430  foreach (DataColumn columna in dtImportar.Columns)
1431  {
1432  switch (columna.ColumnName.Trim())
1433  {
1434  case "CODIGO":
1435  if (string.IsNullOrEmpty(rnCliente._Codigo))
1436  rnCliente._Codigo = valor;
1437  break;
1438  case "NOMBRE":
1439  if (ImportarCampo(row["NOMBRE"].ToString(), "NOMBRE", loEstado))
1440  rnCliente._Nombre = row["NOMBRE"].ToString();
1441  break;
1442  case "IDIOMA":
1443  if (ImportarCampo(row["IDIOMA"].ToString(), "IDIOMA", loEstado))
1444  {
1445  string valCSV = row["IDIOMA"].ToString();
1446  string divisa = "000";
1447  if (!string.IsNullOrEmpty(valCSV) && valCSV != "000")
1448  divisa = ValidarRegla("Divisa", 0, null, null, valCSV);
1449 
1450  rnCliente._Moneda = divisa;
1451  }
1452  break;
1453  case "PAIS":
1454  {
1455  string pais = row["PAIS"].ToString().Trim();
1456  string codPais = " ";
1457  if (!string.IsNullOrEmpty(pais))
1458  codPais = ValidarRegla("Pais", 0, null, null, pais);
1459 
1460  if (codPais == "-1")
1461  {
1462  incidenc = MensajeIncidencia(filaenproceso.ToString(), "", valor, "El código ISO del país " + pais + " no ha sido traspasado porque no se encuentra en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")) + ". Debe crearlo en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")) + " y asignar al proveedor. ");
1463  RegistrarIncidencia(filaenproceso, incidenc, 2);
1464  GestionIncidencias();
1465  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
1466  }
1467  else
1468  {
1469  rnCliente._Pais = codPais;
1470  }
1471  }
1472  break;
1473  case "CIF":
1474  rnCliente._NIF = row["CIF"].ToString();
1475  break;
1476  case "NOMBRE2":
1477  rnCliente._RazonComercial = row["NOMBRE2"].ToString();
1478  break;
1479  case "EMAIL":
1480  rnCliente._Email = row["EMAIL"].ToString();
1481  break;
1482  case "FRAESI":
1483  if (row["FRAESI"].ToString().Trim() == ".T." || row["FRAESI"].ToString().Trim().ToUpper() == cs._BooleanoTrue.ToUpper())
1484  rnCliente._ImprimirFacturaElectronica = true;
1485  break;
1486  case "EMAIL_F":
1487  rnCliente._EmailFacturacion = row["EMAIL_F"].ToString();
1488  break;
1489  case "FPAG":
1490  rnCliente._FormaPago = row["FPAG"].ToString();
1491  break;
1492  case "DIAPAG":
1493  string dpago = row["DIAPAG"].ToString().Trim();
1494  if (!string.IsNullOrEmpty(dpago))
1495  {
1496  rnCliente._DiaPago1 = Convert.ToInt32(row["DIAPAG"].ToString());
1497  }
1498  else
1499  {
1500  rnCliente._DiaPago1 = 0;
1501  }
1502  break;
1503  case "DIAPAG2":
1504  string dpago2 = row["DIAPAG2"].ToString().Trim();
1505  if (!string.IsNullOrEmpty(dpago2))
1506  {
1507  rnCliente._DiaPago2 = Convert.ToInt32(row["DIAPAG2"].ToString());
1508  }
1509  else
1510  {
1511  rnCliente._DiaPago2 = 0;
1512  }
1513  break;
1514  case "F_ALTA":
1515  string fecha = row["F_ALTA"].ToString().Trim();
1516  if (string.IsNullOrEmpty(fecha) || fecha == "DATE()")
1517  {
1518  sage.addons.idatos.Visual.UserControls.FormatosFecha formatoFecha = (sage.addons.idatos.Visual.UserControls.FormatosFecha)cs._FormatoFechas;
1519  string fmtFecha = sage.ew.functions.FUNCTIONS._GetEnumDescription(formatoFecha).ToString().Replace("a", "y").Replace("m", "M");
1520  fecha = DateTime.Now.ToString(fmtFecha);
1521  }
1522  rnCliente._FechaAlta = Convert.ToDateTime(fecha);
1523  break;
1524  case "DESCU1":
1525  string dto1 = row["DESCU1"].ToString().Trim();
1526  if (!string.IsNullOrEmpty(dto1))
1527  {
1528  rnCliente._Dto1 = Convert.ToDecimal(row["DESCU1"].ToString());
1529  }
1530  else
1531  {
1532  rnCliente._Dto1 = 0;
1533  }
1534 
1535  break;
1536  case "DESCU2":
1537  string dto2 = row["DESCU2"].ToString().Trim();
1538  if (!string.IsNullOrEmpty(dto2))
1539  {
1540  rnCliente._Dto2 = Convert.ToDecimal(row["DESCU2"].ToString());
1541  }
1542  else
1543  {
1544  rnCliente._Dto2 = 0;
1545  }
1546  break;
1547  case "PRONTO":
1548  string pronto = row["PRONTO"].ToString().Trim();
1549  if (!string.IsNullOrEmpty(pronto))
1550  {
1551  rnCliente._ProntoPago = Convert.ToDecimal(row["PRONTO"].ToString());
1552  }
1553  else
1554  {
1555  rnCliente._ProntoPago = 0;
1556  }
1557  break;
1558  case "AGENCIA":
1559  rnCliente._Agencia = row["AGENCIA"].ToString();
1560  break;
1561  case "VENDEDOR":
1562  rnCliente._Vendedor = row["VENDEDOR"].ToString();
1563  break;
1564  case "RUTA":
1565  rnCliente._Ruta = row["RUTA"].ToString();
1566  break;
1567  case "ZONA":
1568  rnCliente._Zona = row["ZONA"].ToString();
1569  break;
1570  case "CANAL":
1571  rnCliente._Canal = row["CANAL"].ToString();
1572  break;
1573  case "CONTADO":
1574  if (row["CONTADO"].ToString().Trim() == ".T." || row["CONTADO"].ToString().Trim().ToUpper() == cs._BooleanoTrue.ToUpper())
1575  {
1576  rnCliente._ClienteContado = true;
1577  }
1578  else
1579  {
1580  rnCliente._ClienteContado = false;
1581  }
1582  break;
1583  case "OBSERVACIO":
1584  rnCliente._Observaciones = row["OBSERVACIO"].ToString();
1585  break;
1586  case "TIPOFAC":
1587  rnCliente._TipoFacturacion = row["TIPOFAC"].ToString();
1588  break;
1589  case "CONTRAPAR":
1590  rnCliente._Contrapartida = row["CONTRAPAR"].ToString();
1591  break;
1592  case "COPIA_FRA":
1593  string nCopias = row["COPIA_FRA"].ToString().Trim();
1594  if (!string.IsNullOrEmpty(nCopias))
1595  {
1596  rnCliente._ImprimirCopiasFRA = Convert.ToInt32(row["COPIA_FRA"].ToString());
1597  }
1598  else
1599  {
1600  rnCliente._ImprimirCopiasFRA = 0;
1601  }
1602  break;
1603  case "BANCO_PREV":
1604  rnCliente._BancoPrevisto = row["BANCO_PREV"].ToString();
1605  break;
1606  case "TIPO_IVA":
1607  rnCliente._TipoIVA = row["TIPO_IVA"].ToString();
1608  break;
1609  case "IVAPORCEN":
1610  rnCliente._TipoIVA = row["IVAPORCEN"].ToString();
1611  break;
1612  case "RECARGO":
1613  if (row["RECARGO"].ToString().Trim() == ".T." || row["RECARGO"].ToString().Trim().ToUpper() == cs._BooleanoTrue.ToUpper())
1614  {
1615  rnCliente._Recargo = true;
1616  }
1617  else
1618  {
1619  rnCliente._Recargo = false;
1620  }
1621  break;
1622  case "RECC":
1623  if (row["RECC"].ToString().Trim() == ".T." || row["RECC"].ToString().Trim().ToUpper() == cs._BooleanoTrue.ToUpper())
1624  {
1625  rnCliente._RECC = true;
1626  }
1627  else
1628  {
1629  rnCliente._RECC = false;
1630  }
1631  break;
1632  case "RECARFIN":
1633  rnCliente._RecargoFinanciero = Convert.ToDecimal(row["RECARFIN"].ToString());
1634  break;
1635  case "PVERDE":
1636  if (row["PVERDE"].ToString().Trim() == ".T." || row["PVERDE"].ToString().Trim().ToUpper() == cs._BooleanoTrue.ToUpper())
1637  {
1638  rnCliente._NoApli_Impuesto_Artic = true;
1639  }
1640  else
1641  {
1642  rnCliente._NoApli_Impuesto_Artic = false;
1643  }
1644  break;
1645  case "CREDITO":
1646  string nCredito = row["CREDITO"].ToString().Trim();
1647  if (!string.IsNullOrEmpty(nCredito))
1648  {
1649  rnCliente._Credito = Convert.ToDecimal(row["CREDITO"].ToString());
1650  }
1651  else
1652  {
1653  rnCliente._Credito = 0;
1654  }
1655  break;
1656  case "FACEBOOK":
1657  rnCliente._Facebook = row["FACEBOOK"].ToString();
1658  break;
1659  case "SKYPE":
1660  rnCliente._Skype = row["SKYPE"].ToString();
1661  break;
1662  case "TWITTER":
1663  rnCliente._Twitter = row["TWITTER"].ToString();
1664  break;
1665  case "HTTP":
1666  rnCliente._PaginaWeb = row["HTTP"].ToString();
1667  break;
1668  case "GUID_ID":
1669  rnCliente._Guid_Id = row["GUID_ID"].ToString();
1670  break;
1671  case "DIRECCION":
1672  if (!lbActualizar || (lbActualizar && string.IsNullOrEmpty(rnCliente._Direccion)))
1673  rnCliente._Direccion = row["DIRECCION"].ToString();
1674  break;
1675  case "POBLACION":
1676  if (!lbActualizar || (lbActualizar && string.IsNullOrEmpty(rnCliente._Poblacion)))
1677  rnCliente._Poblacion = row["POBLACION"].ToString();
1678  break;
1679  case "PROVINCIA":
1680  if (!lbActualizar || (lbActualizar && string.IsNullOrEmpty(rnCliente._Provincia)))
1681  rnCliente._Provincia = row["PROVINCIA"].ToString();
1682  break;
1683  case "CODPOST":
1684  if (!lbActualizar || (lbActualizar && string.IsNullOrEmpty(rnCliente._CodPost)))
1685  rnCliente._CodPost = row["CODPOST"].ToString();
1686  break;
1687  case "TELEFONO":
1688  rnCliente._Telefono = row["TELEFONO"].ToString();
1689  break;
1690  case "REFER_CAT":
1691  if (!string.IsNullOrWhiteSpace(row["REFER_CAT"].ToString()))
1692  {
1693  rnCliente._ReferCatastral = DB.SQLValor("MODREFEC", "REFERENCIA", row["REFER_CAT"].ToString().TrimEnd(), "CODIGO", "COMUNES").ToString();
1694  }
1695  break;
1696  case "TIPO_RET":
1697  rnCliente._RetencionFiscal = false;
1698  if (!string.IsNullOrWhiteSpace(row["TIPO_RET"].ToString()))
1699  {
1700  rnCliente._RetencionTipo = row["TIPO_RET"].ToString();
1701  rnCliente._RetencionFiscal = true;
1702 
1703  DataTable ldPlid_D2 = new DataTable();
1704  string lcSql_D2 = "SELECT a.val_def FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D2") + " a " +
1705  " WHERE a.CODIGO = " + DB.SQLString(codigoGuia) +
1706  " AND a.IDTABLA = " + DB.SQLString(107) +
1707  " AND a.IDCAMPO = " + DB.SQLString(70);
1708  DB.SQLExec(lcSql_D2, ref ldPlid_D2);
1709 
1710  if (ldPlid_D2 != null && ldPlid_D2.Rows.Count == 1)
1711  {
1712  if (ldPlid_D2.Rows[0]["VAL_DEF"].ToString().Trim() == ".T." || ldPlid_D2.Rows[0]["VAL_DEF"].ToString().Trim().ToUpper() == cs._BooleanoTrue.ToUpper())
1713  {
1714  rnCliente._RetencionBaseFactura = Cliente.TipoRetencion.SobreBase;
1715  }
1716  else
1717  {
1718  rnCliente._RetencionBaseFactura = Cliente.TipoRetencion.SobreFactura;
1719  }
1720  }
1721  }
1722  break;
1723  case "RETPORCEN":
1724  rnCliente._RetencionFiscal = false;
1725  if (!string.IsNullOrWhiteSpace(row["RETPORCEN"].ToString()))
1726  {
1727  rnCliente._RetencionTipo = row["RETPORCEN"].ToString();
1728  rnCliente._RetencionFiscal = true;
1729 
1730  DataTable ldPlid_D2 = new DataTable();
1731  string lcSql_D2 = "SELECT a.val_def FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D2") + " a " +
1732  " WHERE a.CODIGO = " + DB.SQLString(codigoGuia) +
1733  " AND a.IDTABLA = " + DB.SQLString(107) +
1734  " AND a.IDCAMPO = " + DB.SQLString(70);
1735  DB.SQLExec(lcSql_D2, ref ldPlid_D2);
1736 
1737  if (ldPlid_D2 != null && ldPlid_D2.Rows.Count == 1)
1738  {
1739  if (ldPlid_D2.Rows[0]["VAL_DEF"].ToString().Trim() == ".T." || ldPlid_D2.Rows[0]["VAL_DEF"].ToString().Trim().ToUpper() == cs._BooleanoTrue.ToUpper())
1740  {
1741  rnCliente._RetencionBaseFactura = Cliente.TipoRetencion.SobreBase;
1742  }
1743  else
1744  {
1745  rnCliente._RetencionBaseFactura = Cliente.TipoRetencion.SobreFactura;
1746  }
1747  }
1748  }
1749  break;
1750  case "LETDEFVEN":
1751  rnCliente._SerieDefecto = row["LETDEFVEN"].ToString();
1752  break;
1753  case "LETDEFRECT":
1754  rnCliente._SerieRectificativaDefecto = row["LETDEFRECT"].ToString();
1755  break;
1756  default:
1757  break;
1758  }
1759  }
1760 
1761  string guidid = string.Empty;
1762  if (lbActualizar)
1763  {
1764  bImportar = true;
1765  }
1766  else
1767  {
1768  if (!string.IsNullOrEmpty(rnCliente._Guid_Id) && !string.IsNullOrEmpty((guidid = DB.SQLValor("CLIENTES", "GUID_ID", rnCliente._Guid_Id.ToString().Trim(), "GUID_ID", "GESTION").ToString().Trim())))
1769  {
1770  incidenc = MensajeIncidencia(filaenproceso.ToString(), (posic + 1).ToString(), rnCliente._Codigo, "El cliente no ha sido traspasado porque su GUID_ID: " + rnCliente._Guid_Id + ", ya existe.");
1771 
1772  RegistrarIncidencia(filaenproceso, incidenc, 3);
1773  GestionIncidencias();
1774  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
1775 
1776  if (!lstNoImportados.Contains(rnCliente._Codigo))
1777  lstNoImportados.Add(rnCliente._Codigo);
1778 
1779  continue;
1780  }
1781  }
1782 
1783  if (rnCliente._Save())
1784  {
1785  bImportar = true;
1786  }
1787  else
1788  {
1789  incidenc = MensajeIncidencia(filaenproceso.ToString(), (posic + 1).ToString(), rnCliente._Codigo, "El cliente no ha sido traspasado. Error al salvar.");
1790 
1791  RegistrarIncidencia(filaenproceso, incidenc, 3);
1792  GestionIncidencias();
1793  WriteCSVOut(dtCSVLines.Rows[fila]["LINE"].ToString());
1794 
1795  if (!lstNoImportados.Contains(rnCliente._Codigo))
1796  lstNoImportados.Add(rnCliente._Codigo);
1797  }
1798  }
1799  }
1800 
1801  if (lbFormaPago)
1802  {
1803  ValidarRegla("FormaPago");
1804  ewprogressbar.PerformStep();
1805  }
1806 
1807  if (lbVendedor)
1808  {
1809  ValidarRegla("Vendedor");
1810  ewprogressbar.PerformStep();
1811  }
1812 
1813  if (lbCatastral)
1814  {
1815  ValidarRegla("ReferenciaCatastral");
1816  ewprogressbar.PerformStep();
1817  }
1818 
1819  if (lbTelefPre || lbTelefAdi)
1820  {
1821  ValidarRegla("CrearTelefonoContacto", 0, lstNoImportados);
1822  ewprogressbar.PerformStep();
1823  }
1824  if (cuentaIBAN)
1825  {
1826  ValidarRegla("CuentaBancaria");
1827  ewprogressbar.PerformStep();
1828  }
1829 
1830  if (lbGiros)
1831  {
1832  ValidarRegla("CrearGiros", 0, lstNoImportados);
1833  ewprogressbar.PerformStep();
1834  }
1835 
1836  if (lbMandatos)
1837  {
1838  ValidarRegla("CrearMandato");
1839  ewprogressbar.PerformStep();
1840  }
1841  }
1842 
1846  protected override void NoImportarNegocio()
1847  {
1848  incidenc = MensajeIncidencia("", "", "", "Los clientes ya existen en " + Convert.ToString(EW_GLOBAL._GetVariable("wc_nameproducto")));
1849  RegistrarIncidencia(0, incidenc, 3);
1850  GestionIncidencias();
1851  historicoGuia._Resultado = 2;
1852  }
1853 
1861  protected override bool ImportarCampo(string valor, string nombre, sage.ew.ewbase.ewMante._EstadosMantenimiento loEstado)
1862  {
1863  return base.ImportarCampo(valor, nombre, loEstado);
1864  }
1865 
1866  #endregion METODOS PROTECTED
1867 
1868  #region METODOS PRIVADOS
1869 
1870  private void RegistrosTablasVir(Int32 IdCampoVir)
1871  {
1872  DataTable ldPlid = new DataTable();
1873  DataTable ldPlid_D1 = new DataTable();
1874 
1875  string lcSql = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D") +
1876  " WHERE CODIGO = " + DB.SQLString(codigoGuia);
1877 
1878  DB.SQLExec(lcSql, ref ldPlid);
1879 
1880  if (ldPlid != null || ldPlid.Rows.Count > 0)
1881  {
1882  string nombreColumnaCodigo = ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToInt32(F["IDCAMPO"]) == 18).First()["COLUMNA"].ToString().Trim();
1883 
1884  string lcSql_D1 = "SELECT * FROM " + DB.SQLDatabase("IDATOS", "PLINTER_D1") +
1885  " WHERE CODIGO = " + DB.SQLString(codigoGuia);
1886 
1887  DB.SQLExec(lcSql_D1, ref ldPlid_D1);
1888 
1889  if (ldPlid_D1 == null || ldPlid_D1.Rows.Count == 0)
1890  {
1891  return;
1892  }
1893 
1894  List<string> idColumnas = new List<string>();
1895  try
1896  {
1897  idColumnas = ldPlid_D1.Rows.OfType<DataRow>().Where(F => Convert.ToString(F["IDTABLA"]) == Convert.ToString(IdCampoVir))
1898  .Select(dr => dr.Field<string>("ID_D").Trim()).ToList();
1899  }
1900  catch
1901  {
1902  // No hay campo de tablas virtuales en la guia (60000, 60001, 60002, 60004)
1903  }
1904 
1905  List<string> nombreColumnaTablaVir = new List<string>();
1906  List<string> idColumnaTablaVir = new List<string>();
1907 
1908  if (idColumnas.Count() > 0)
1909  {
1910  foreach (string loColumn in idColumnas)
1911  {
1912  nombreColumnaTablaVir.Add(ldPlid.Rows.OfType<DataRow>().Where(F => Convert.ToString(F["ID_RELA"]).Trim() == loColumn).First()["COLUMNA"].ToString().Trim().ToString());
1913  idColumnaTablaVir.Add(ldPlid_D1.Rows.OfType<DataRow>().Where(F => Convert.ToString(F["ID_D"]).Trim() == loColumn).First()["IDCAMPO"].ToString().Trim().ToString());
1914  }
1915  }
1916 
1917 
1918  if (nombreColumnaTablaVir.Count == 0 && nombreColumnaTablaVir == null)
1919  return;
1920 
1921  foreach (System.Data.DataRow filaCliente in dtCSV.Rows)
1922  {
1923 
1924 
1925  }
1926  }
1927  }
1928 
1929  #endregion METODOS PRIVADOS
1930  }
1931 }
1932 
decimal _Dto1
Nos permitirá asignar un primer descuento en % El valor entrado debe ser un valor entre 0 y 100 ...
Definir la estructura de las líneas de contactos-teléfonos de clientes
Definition: clsCliente.cs:454
Clase de negocio base para mantenimientos
Definition: clsEwBase.cs:1643
string _Telefono
Teléfono predeterminado de la ficha del cliente, sera el que tenga el campo PREDET.
Datos bancarios de clientes
Definition: clsCliente.cs:8149
string _Observaciones
Observaciones
string _Skype
Skype del cliente
override int AsignoTextosLongitud(Dictionary< int, string > textos, int idMante)
AsignoTextosLongitud
string obtenerTipoColumna(int idtabla, string campo)
Obtener el tipo de columna accediendo por el idtabla y el nombre del campo
string _SerieRectificativaDefecto
Serie rectificativa por defecto
Decimal _Credito
Retorna el límite de credito del cliente
TipoRetencion _RetencionBaseFactura
Nos permitirá asignar el tipo de retención al cliente Ojo: el campo MOD_RET =.T. –> es retención sob...
Clase para manejar los campos del CSV en la importación
DataTable ldPlid_D1
Datos de plinterD1 para la plantilla en curso
override void ImportarNegocio()
Importamos el negocio según tipo de guía (Artículos, Clientes, ...)
override string _Codigo
PE-102491: override de _Codigo para que en el Set podamos convertir el número que nos llega a código ...
override bool _Save()
Al guardar todos los registros de CONTLF_CLI, se debe actualizar todos los registros de CONT_CLI y TE...
Definition: clsCliente.cs:138
string _RetencionTipo
Nos permitirá aplicar el código de retención al cliente. En caso que se le aplique un código de reten...
bool _NoApli_Impuesto_Artic
No aplicar impuesto articulo
decimal _Dto2
Nos permitirá asignar un segundo descuento en % El valor entrado debe ser un valor entre 0 y 100 ...
string _ReferCatastral
Referencia catastral
bool _ImprimirFacturaElectronica
Nos permite indicar si el cliente permite generar factura electrónica
Clase sage.ew.objetos.ewprogressbar
string _Provincia
Provincia del cliente
string _Twitter
Url de Twitter del cliente
override void InicializarVariables(DataTable dtPlinter_D)
Inicializar variables para proceso de importación
string _Agencia
Nos permitirá asignar el código del agencia al cliente.
override bool ImportarCampo(string valor, string nombre, sage.ew.ewbase.ewMante._EstadosMantenimiento loEstado)
override bool ComprobarExiste(string codigo)
Comprobamos si existe el artículo en Sage 50 o en los registros de CSV que hemos validado ...
override string _Nombre
Nombre del cliente a partir del campo NOMBRE de la tabla CLIENTES de la base de datos de GESTION de E...
Es como el tipo de entrada asientos pero por negocio, sin formulario, pq quiero que me haga las propu...
string _TipoIVA
Nos permitirá indicar el código de TIPO DE IVA aplicado a este cliente
string _CodPost
Código postal del cliente
BindingList< _LinTRel > _Items
Lista bindable de todos los items de la tabla relacionada
_LinTRel _NewItem(int tnInsertLinea=-1)
Añade un nuevo item a la colección Items y rellena los valores de la claves
string getValue(string nombreCampo, string def)
Obtener valor cadena
override void _Load()
Al cargar los datos ponemos la propiedad interna _llModificado a false. Solo propagaremos cambios a T...
Definition: clsCliente.cs:117
KeyDiccionarioLenCampos
Clave del diccionario LenCampos
Definition: Diccionarios.cs:11
_EstadosMantenimiento _Estado
Estado en que se encuentra el registro
Definition: clsEwBase.cs:2968
override DataTable ValoresDtAux(string nombreTabla, ref DataTable dtMomen)
bool _RetencionFiscal
Nos indicará si el cliente tiene retención fiscal o no.
string _Facebook
Url de Facebook del cliente
override void _Load()
Load
override string ValidarRegla(string regla, Int32 idTabla=0, List< string > valorespreexistentes=null, string codigo="", string valor="", DataTable dtImportar=null, string nombreNegocio="", bool nombreValDef=false, string valor2="", string valor3="", Int32 fila=0)
ValidarRegla
string _Guid_Id
Ens retorna el valor que hi ha al camp GUID_ID de la taula
Definition: clsEwBase.cs:2709
string nombreColumna(Int32 idCampo, Int32 idVirtual=0)
nombreColumna
string _TipoFacturacion
Código de tipo de facturación que se establece al cliente
void CrearTelefonoContactoCliente(bool tlAdicional=false)
Crear telefonos y contactos al cliente
Clase para uso de funciones genéricas
Definition: functions.cs:146
string _Contrapartida
Código de la contrapartida asociada al cliente
string _Zona
Nos permitirá asignar el código del zona asignado al cliente
Definir la estructura de las direcciones de clientes
Definition: clsCliente.cs:8448
bool _ClienteContado
Nos indicará si el cliente es contado
string _Direccion
Dirección del cliente
string _Poblacion
Población del cliente
void CrearTelefonoContactoCliente2(bool tlAdicional=false)
CrearTelefonoContactoCliente2
DateTime _FechaAlta
Nos permitirá indicar la fecha de Alta del cliente Cada vez que se cree un nuevo cliente, esta propiedad deberá tener la fecha del día
ImportacionClientes(DataTable dtcsv, string codigoGuia, List< CargarDatos.stInfoFields > _infoFields, DataTable dtcsvlines, string tcFichero, int tnModo=0, sage.ew.objetos.ewprogressbar bar=null)
Constructor sobrecargado
string _Ruta
Nos permitirá asignar el código del ruta al cliente.
override bool _Save()
Save
string _Moneda
Nos indicará la moneda del cliente
DataTable ldPlid_D
Datos de plinterD para la plantilla en curso
override bool _Save()
Actualización de los datos bancarios del cliente y actualización de los bancos de los mandatos ...
Definition: clsCliente.cs:8314
Dictionary< string, actItem > campos
Obsoleta. Acumula la información de los campos accediendo por el nombre de campo. Sólo utilizado para...
_EstadosMantenimiento
Declaro un enum para los estados del mantenimiento.
Definition: clsEwBase.cs:1671
string _FormaPago
Nos permitirá asignar el código de forma de pago al cliente
bool _Recargo
Nos permitirá asignar si un cliente permite trabajar con retención fiscal
override DataTable PrepararDtImportar(int idTablaCampo, bool linfadi, Int32 idCampo, string nombre)
Rellenamos el datatable de trabajo dtImportar con columnas a importar
TipoRetencion
Posibles tipos de retencion
Definition: clsCliente.cs:9979
string _RazonComercial
Razón comercial del cliente a partir del campo NOMBRE2 de la tabla CLIENTES de la base de datos de GE...
int _ImprimirCopiasFRA
Nos permitirá establecer el número de copias de Facturas
override void RegistroTablaRelacionada(RegistroPlinter_D registroD, ref Int32 fila, ref string codImportar, ref string valorColumnaCSV, ref bool ltablaImportar, ref Int32 colDt)
Registros de tabla relacionada (no pertenecen a tablas principales: 68, 107, ...) ...
string _NIF
CIF del cliente
int idTablaVirtual(Int32 idtabla)
Obtener el idtabla virtual correspondiente a un idtabla
Clase para la importación de datos
Definition: CargarDatos.cs:27
string _Vendedor
Código de vendedor del cliente
int _DiaPago2
Nos indicará el primer dia de pago del cliente El dia de Pago2 nunca podrá tener un valor inferior al...
ContacTelefs _TRelContacTelefs
ManteTRel de teléfonos y contactos de cliente.
DatosBancarios _TRelDatosBancarios
ManteTRel de datos bancarios de cliente.
string _PaginaWeb
Pagina web que tiene asociada el cliente
int _DiaPago1
Nos indicará el primer dia de pago del cliente
string _Canal
Nos permitirá asignar el código del canal asignado al cliente
decimal _ProntoPago
Nos permitirá asignar un % de descuento de pronto pago El valor entrado debe ser un valor entre 0 y 1...
decimal _RecargoFinanciero
Nos permite indicar el recargo financiero para este cliente El valor entrado nunca podrá ser negativo...
string _Email
Email predeterminado de la ficha del cliente
bool _RECC
Nos indica si al cliente se le aplica el criterio de caja en ventas Si el cliente no es nacional ento...
string _SerieDefecto
Serie por defecto
override void NoImportarNegocio()
No hay registros para importar en negocio según tipo de guía (Artículos, Clientes, ...)
string _Pais
Código de país que se establece al cliente
string _EmailFacturacion
Email que tiene asignado el cliente para la facturación
Contactos y teléfonos de clientes, clase de negocio de la nueva tabla GESTION!CONTLF_CLI resultado de...
Definition: clsCliente.cs:53
string _BancoPrevisto
Banco previsto para el cliente, se utiliza en las previsiones de cobro