OfflineUploader.cs
1 using sage.ew.db;
2 using sage.ew.ewbase;
3 using sage.ew.ewbase.Clases;
4 using sage.ew.global;
6 using System;
7 using System.Collections.Generic;
8 using System.Data;
9 using System.IO;
10 using System.Linq;
11 using System.Text;
16 using System.Data.SqlClient;
17 using sage.ew.functions;
18 
19 namespace sage.addons.offline.Negocio.Clases
20 {
21  internal class OfflineUploader : OfflineUpAndDown
22  {
23  #region Métodos para el Asistente de Configuración
24 
25  internal static bool Upload_Control_Files(int nTipoCom, bool isCentral, int tnIdConf)
26  {
27  _Porcen_Progreso_Async -= OfflineUploader__Porcen_Progreso_Async;
28  _Mostrar_Progreso_Async -= OfflineUploader__Mostrar_Progreso_Async;
29 
30  _Mostrar_Progreso_Async += OfflineUploader__Mostrar_Progreso_Async;
31  _Porcen_Progreso_Async += OfflineUploader__Porcen_Progreso_Async;
32 
33  OfflineDatosComunicaciones datos = new OfflineDatosComunicaciones();
34 
35  if (!Directory.Exists(TempFolderName))
36  {
37  Directory.CreateDirectory(TempFolderName);
38  }
39 
40  ComprobacionesPrevias(tnIdConf);
41 
42  _cIdLog = _offlineConfig.GenerarRandomId();
43 
44  datos._Log_ComoffID = _cIdLog;
45  datos._IdConf = tnIdConf;
46  datos._MultConf = DB.SQLValor("MULTCONF", "IDCONF", tnIdConf.ToString(), "CODIGO", "OFFLINE").ToString();
47  datos._Usuario = sage.ew.global.EW_GLOBAL._GetVariable("wc_usuario").ToString();
48  datos._BdOffline = clsOfflineUtils.ObtenerNombreBdReal("OFFLINE");
49  datos._Sucursal = string.Empty;
50  datos._PathFolderInicial = TempFolderName;
51  datos._IniServidor = DB._GetVariable("wc_iniservidor").ToString().ToLower();
52  datos._EnvioArticulos = false;
53  datos._FechaInicial = Convert.ToDateTime(EW_GLOBAL._GetVariable("wd_periodoini"));
54  datos._FechaFinal = Convert.ToDateTime(EW_GLOBAL._GetVariable("wd_periodofin"));
55  datos._TipoCom = nTipoCom;
56  datos._IsCentral = isCentral;
57 
58  //• Sucursales->Configuración de todas las sucursales, datos en tablas SUCURSALES, SUCURALM, SUCURCONF y SUCURLET.Ver punto 17.1.1.
59  DataTable tablaDatos = new DataTable();
60  string lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "SUCURSALES");
61  DB.SQLExec(lcSql, ref tablaDatos);
62  ConvertIndividualFile(tablaDatos, TempFolderName, "SUCURSALES", FormatoExportacion.XML);
63 
64  tablaDatos = new DataTable();
65  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "SUCURALM");
66  DB.SQLExec(lcSql, ref tablaDatos);
67  ConvertIndividualFile(tablaDatos, TempFolderName, "SUCURALM", FormatoExportacion.XML);
68 
69  tablaDatos = new DataTable();
70  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "SUCURLET");
71  DB.SQLExec(lcSql, ref tablaDatos);
72  ConvertIndividualFile(tablaDatos, TempFolderName, "SUCURLET", FormatoExportacion.XML);
73 
74  tablaDatos = new DataTable();
75  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "SUCURCAJA");
76  DB.SQLExec(lcSql, ref tablaDatos);
77  ConvertIndividualFile(tablaDatos, TempFolderName, "SUCURCAJA", FormatoExportacion.XML);
78 
79  tablaDatos = new DataTable();
80  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "SUCURCONF");
81  DB.SQLExec(lcSql, ref tablaDatos);
82  ConvertIndividualFile(tablaDatos, TempFolderName, "SUCURCONF", FormatoExportacion.XML);
83 
84  tablaDatos = new DataTable();
85  lcSql = "SELECT * FROM " + DB.SQLDatabase("GESTION", "ALMACEN");
86  DB.SQLExec(lcSql, ref tablaDatos);
87  ConvertIndividualFile(tablaDatos, TempFolderName, "ALMACEN", FormatoExportacion.XML);
88 
89  tablaDatos = new DataTable();
90  lcSql = "SELECT * FROM " + DB.SQLDatabase("COMUNES", "LETRAS");
91  DB.SQLExec(lcSql, ref tablaDatos);
92  ConvertIndividualFile(tablaDatos, TempFolderName, "LETRAS", FormatoExportacion.XML);
93 
94  tablaDatos = new DataTable();
95  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "VARIABLES") + " WHERE VARIABLE = 'ULTIMOLOG' ";
96  DB.SQLExec(lcSql, ref tablaDatos);
97  ConvertIndividualFile(tablaDatos, TempFolderName, "VARIABLES", FormatoExportacion.XML);
98 
99  tablaDatos = new DataTable();
100  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "MULTCONF");
101  DB.SQLExec(lcSql, ref tablaDatos);
102  ConvertIndividualFile(tablaDatos, TempFolderName, "MULTCONF", FormatoExportacion.XML);
103 
104  tablaDatos = new DataTable();
105  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "TABNETCONF");
106  DB.SQLExec(lcSql, ref tablaDatos);
107  ConvertIndividualFile(tablaDatos, TempFolderName, "TABNETCONF", FormatoExportacion.XML);
108 
109  tablaDatos = new DataTable();
110  lcSql = "SELECT * FROM " + DB.SQLDatabase("OFFLINE", "PRIORIDAD");
111  DB.SQLExec(lcSql, ref tablaDatos);
112  ConvertIndividualFile(tablaDatos, TempFolderName, "PRIORIDAD", FormatoExportacion.XML);
113 
115  ILog_comoffRepository logRepository = offlineUnitOfWork.Log_comoffRepository;
116 
117  if (datos._IsCentral)
118  {
119  _TextStepDetalle = "Generando fichero configura_offline.xml";
120  _TextStepProgreso = _TextStepDetalle;
121  _PorcenProgreso = IncrementarBarraProgreso();
122 
123  Subir_Fichero_Configuracion(datos, logRepository);
124  }
125 
126  Eliminar_Carpetas_Temporales(datos, logRepository);
127 
128  offlineUnitOfWork.SaveChanges();
129  offlineUnitOfWork.Dispose();
130 
131  _Porcen_Progreso_Async -= OfflineUploader__Porcen_Progreso_Async;
132  _Mostrar_Progreso_Async -= OfflineUploader__Mostrar_Progreso_Async;
133 
134  return true;
135  }
136 
137 
166  internal static bool Upload_Offline_Files(clsOfflineUtils.ReportProgress progressReporter, DateTime tdFechaConf, DateTime tdFechaMin, DateTime tdFechaMax, string tcSucursal, bool tlImagenes, bool tlAnterior, bool isCentral, int idConf, bool tlInicial = false, Dictionary<int, bool> prioridades = null)
167  {
168  _Mostrar_Progreso_Async -= OfflineUploader__Mostrar_Progreso_Async;
169  _Porcen_Progreso_Async -= OfflineUploader__Porcen_Progreso_Async;
170 
171  _Mostrar_Progreso_Async += OfflineUploader__Mostrar_Progreso_Async;
172  _Porcen_Progreso_Async += OfflineUploader__Porcen_Progreso_Async;
173 
174  _cTempFolderName = string.Empty;
175  _cTempFileName = clsOfflineUtils.CrearNombreFicheroDatos(tcSucursal, idConf);
176 
177  if (!Directory.Exists(TempFolderName))
178  {
179  Directory.CreateDirectory(TempFolderName);
180  }
181 
182  ReestablecerInfoConfig();
183  Generar_Configuracion(progressReporter, tdFechaConf, tdFechaMin, tdFechaMax, isCentral, (tlInicial ? "i" : "e"), prioridades, tcSucursal);
184 
185  // i -> Carga Inicial
186  // e -> Envío de datos
187  bool llOk = GenerarDatosEnvio(tcSucursal, tlImagenes, tdFechaConf, tdFechaMin, tdFechaMax, isCentral, idConf, (tlInicial ? "i" : "e"), prioridades);
188 
189  if (!tlInicial)
190  {
191  AsistenteOffEnvioDatosBizRule negocioOffline = new AsistenteOffEnvioDatosBizRule();
192 
193  if (negocioOffline.ValidacionEjercicioPredet())
194  {
195  string lcEjercicioPredeterminado = negocioOffline.GetEjercicioPredeterminado();
196 
197  DataTable ldtEjercicios = negocioOffline.GetEjerciciosOffline();
198 
199  DataRow[] rows = ldtEjercicios.Select("tipooff = " + DB.SQLString(isCentral ? "CENTRAL" : tcSucursal));
200 
201  foreach (DataRow item in rows)
202  {
203  if (item.Field<DateTime?>("traspejer") == null || item.Field<DateTime>("traspejer") < tdFechaMin || item.Field<DateTime>("traspejer") > tdFechaMax)
204  {
205  continue;
206  }
207 
208  GenerarDatosEnvioEjercicioPosterior(progressReporter, tdFechaConf, tdFechaMin, tdFechaMax, tcSucursal, tlImagenes, isCentral, idConf, tlInicial, prioridades, lcEjercicioPredeterminado, item);
209 
210  GenerarDatosEnvioEjercicioAnterior(progressReporter, tdFechaConf, tdFechaMin, tdFechaMax, tcSucursal, tlImagenes, isCentral, idConf, tlInicial, prioridades, lcEjercicioPredeterminado, item);
211  }
212  }
213  }
214 
215  _Mostrar_Progreso_Async -= OfflineUploader__Mostrar_Progreso_Async;
216  _Porcen_Progreso_Async -= OfflineUploader__Porcen_Progreso_Async;
217 
218  return llOk;
219  }
220 
221  private static void GenerarDatosEnvioEjercicioAnterior(clsOfflineUtils.ReportProgress progressReporter, DateTime tdFechaConf, DateTime tdFechaMin, DateTime tdFechaMax, string tcSucursal, bool tlImagenes, bool isCentral, int idConf, bool tlInicial, Dictionary<int, bool> prioridades, string lcEjercicioPredeterminado, DataRow item)
222  {
223  // Comprobar si existe un ejercicio anterior al predeterminado
224  string lcEjercicioAnterior = item.Field<string>("EJERCICIO");
225 
226  if (!string.IsNullOrWhiteSpace(lcEjercicioAnterior) && Convert.ToInt16(lcEjercicioAnterior) < Convert.ToInt16(lcEjercicioPredeterminado))
227  {
228  if (lcEjercicioAnterior != lcEjercicioPredeterminado)
229  {
230  // Cambiar al ejercicio
231  FUNCTIONS.CambiarEjercicio(lcEjercicioPredeterminado, lcEjercicioAnterior);
232 
233  _cTempFolderName = string.Empty;
234  _cTempFileName = clsOfflineUtils.CrearNombreFicheroDatos(tcSucursal, idConf);
235 
236  if (!Directory.Exists(TempFolderName))
237  {
238  Directory.CreateDirectory(TempFolderName);
239  }
240 
241  ReestablecerInfoConfig();
242  Generar_Configuracion(progressReporter, tdFechaConf, tdFechaMin, tdFechaMax, isCentral, (tlInicial ? "i" : "e"), prioridades, tcSucursal);
243  GenerarDatosEnvio(tcSucursal, tlImagenes, tdFechaConf, tdFechaMin, tdFechaMax, isCentral, idConf, (tlInicial ? "i" : "e"), prioridades);
244 
245  // Restaurar al ejercicio
246  FUNCTIONS.CambiarEjercicio(lcEjercicioAnterior, lcEjercicioPredeterminado);
247  }
248  }
249  }
250 
251  private static void GenerarDatosEnvioEjercicioPosterior(clsOfflineUtils.ReportProgress progressReporter, DateTime tdFechaConf, DateTime tdFechaMin, DateTime tdFechaMax, string tcSucursal, bool tlImagenes, bool isCentral, int idConf, bool tlInicial, Dictionary<int, bool> prioridades, string lcEjercicioPredeterminado, DataRow item)
252  {
253  // Comprobar si existe un ejercicio posterior al predeterminado
254  string lcEjercicioPosterior = item.Field<string>("EJERCICIO");
255 
256  if (!string.IsNullOrWhiteSpace(lcEjercicioPosterior) && Convert.ToInt16(lcEjercicioPosterior) > Convert.ToInt16(lcEjercicioPredeterminado))
257  {
258  if (lcEjercicioPosterior != lcEjercicioPredeterminado)
259  {
260  // Cambiar al ejercicio
261  FUNCTIONS.CambiarEjercicio(lcEjercicioPredeterminado, lcEjercicioPosterior);
262 
263  _cTempFolderName = string.Empty;
264  _cTempFileName = clsOfflineUtils.CrearNombreFicheroDatos(tcSucursal, idConf);
265 
266  if (!Directory.Exists(TempFolderName))
267  {
268  Directory.CreateDirectory(TempFolderName);
269  }
270 
271  ReestablecerInfoConfig();
272  Generar_Configuracion(progressReporter, tdFechaConf, tdFechaMin, tdFechaMax, isCentral, (tlInicial ? "i" : "e"), prioridades, tcSucursal);
273  GenerarDatosEnvio(tcSucursal, tlImagenes, tdFechaConf, tdFechaMin, tdFechaMax, isCentral, idConf, (tlInicial ? "i" : "e"), prioridades);
274 
275  // Restaurar al ejercicio
276  FUNCTIONS.CambiarEjercicio(lcEjercicioPosterior, lcEjercicioPredeterminado);
277  }
278  }
279  }
280 
281  private static void OfflineUploader__Mostrar_Progreso_Async(string message)
282  {
283  try
284  {
285  if(_offBase != null)
286  _offBase._TextStepDetalle = message;
287  }
288  catch (Exception) { }
289  }
290 
291  private static void OfflineUploader__Porcen_Progreso_Async(decimal porcen, string message)
292  {
293  try
294  {
295  if (_offBase != null)
296  {
297  _offBase._TextStepProgreso = message;
298  _offBase._PorcenProgreso = porcen;
299  }
300  }
301  catch (Exception) { }
302  }
303 
304  private static void Generar_Configuracion(clsOfflineUtils.ReportProgress progressReporter, DateTime tdFechaConf, DateTime tdFechaMin, DateTime tdFechaMax, bool isCentral, string cTipoEnvio, Dictionary<int, bool> prioridades, string tcSucursal)
305  {
306  // Los datos que se incluirán en los ficheros de configuración cuando la central realice un envío de datos o carga inicial serán los siguientes:
307  // • Versión de Sage 50
308  // • Año y Fecha inicial y final de ejercicio desde el cual se ejecuta envío.
309  // • Add - ons instalados(que exista base de datos) y Add-ons activos(mismo control que en formulario de aplicaciones y servicios conectados) en el grupo de empresa de Sage 50->Registrar únicamente estado de los siguientes Add-ons: Sage TPV Extra, Series, Trazabilidad, Tallas y colores, Tu eFideliza y Fabricación.
310  // • Prioridades definidas para los datos a traspasar->Ver punto 17.1.2.
311 
312  InicializarBarraProgreso();
313  _TextStepDetalle = "Generando fichero InfoConfig.xml";
314  _TextStepProgreso = _TextStepDetalle;
315  _PorcenProgreso = IncrementarBarraProgreso();
316 
317  PrioridadesBizRule rnPrioridades = DependencyInjector.Instance.Retrieve<PrioridadesBizRule>();//new PrioridadesBizRule();
318  List<int> lstPrioridades = new List<int>();
319 
320  InfoConfig._PrioridadesCentral.Clear();
321  InfoConfig._PrioridadesSucursal.Clear();
322 
323  foreach (KeyValuePair<int, bool> valuePair in prioridades)
324  {
325  lstPrioridades.Clear();
326  rnPrioridades.AddPrioridadesDependientes(valuePair.Key, ref lstPrioridades);
327  foreach (int item in lstPrioridades)
328  {
329  if (valuePair.Value)
330  {
331  InfoConfig._PrioridadesCentral.Add(item);
332  }
333  else
334  {
335  InfoConfig._PrioridadesSucursal.Add(item);
336  }
337  }
338  }
339 
340  // • Fecha inicial y final de los datos que contiene el fichero->Según tipo de envío las fechas serán diferentes.
341  // – Carga inicial: Fecha inicial o final definida por el usuario en el asistente de Carga inicial.
342  // – Envío de datos automático: Serán las mismas fechas que se usarán para seleccionar datos a enviar de las diferentes tablas. Fecha inicial será la fecha y hora del último envío de datos según valor de campo SUCURSALES.ULTFECENV(Tener en cuenta que para cada sucursal la fecha podrá ser diferente) y fecha final será la fecha y hora del sistema en el momento de ejecutar envío de datos.
343  // – Envío de datos personalizado: Fecha inicial o final definida por el usuario en el asistente de Carga inicial o Envío de datos.
344 
345  InfoConfig._FechaEnvioInicial = tdFechaMin;
346  InfoConfig._FechaEnvioFinal = tdFechaMax;
347 
348 
349  string lcInfoConfig = _SerializeOfflineInfoConfig(InfoConfig);
350  byte[] bytes = Encoding.UTF8.GetBytes(lcInfoConfig);
351 
352  string lcPath = Path.Combine(TempFolderName, "InfoConfig.xml");
353 
354  if (!File.Exists(lcPath))
355  {
356  FileStream loStream = File.Create(lcPath);
357 
358  loStream.Write(bytes, 0, bytes.Length);
359 
360  loStream.Close();
361  }
362 
363  if (isCentral)
364  {
365  //• Tamaño de campos en la instalación Central->Se incluirá la longitud que tienen todos los campos ampliables de Sage 50.
366 
367  //Crear fichero CONFIG.DBF
368  _TextStepDetalle = "Generando fichero Config.xml";
369  _TextStepProgreso = _TextStepDetalle;
370  _PorcenProgreso = IncrementarBarraProgreso();
371  clsOfflineUtils.GenerarAmplitudCampos(TempFolderName);
372 
373  //• Sucursales->Configuración de todas las sucursales, datos en tablas SUCURSALES, SUCURALM, SUCURCONF y SUCURLET.Ver punto 17.1.1.
374  TratarConfiguracion("SUCURSALES", tdFechaConf, DateTime.MaxValue);
375  TratarConfiguracion("SUCURALM", tdFechaConf, DateTime.MaxValue);
376  TratarConfiguracion("SUCURLET", tdFechaConf, DateTime.MaxValue);
377  TratarConfiguracion("SUCURART", tdFechaConf, DateTime.MaxValue);
378  TratarConfiguracion("SUCURCAJA", tdFechaConf, DateTime.MaxValue);
379 
380  //• Configuración de comunicaciones->Tablas MULTCONF y TABNETCONF, PRIORIDAD.Ver punto 17.1.3.
381  TratarConfiguracion("MULTCONF", tdFechaConf, DateTime.MaxValue);
382  TratarConfiguracion("SUCURCONF", tdFechaConf, DateTime.MaxValue);
383  TratarConfiguracion("TABNETCONF", tdFechaConf, DateTime.MaxValue);
384 
385  if (cTipoEnvio == "i")
386  {
387  TratarConfiguracion("VARIABLES", tdFechaConf, DateTime.MaxValue, " VARIABLE = 'ULTIMOLOG' ");
388  }
389 
390  TratarConfiguracion("EJERCICIOS", tdFechaConf, DateTime.MaxValue, " TIPOOFF = 'CENTRAL' ");
391 
392  DataTable ldtPrioridades = obtenerDatosEnvio(prioridades, cTipoEnvio);
393  TratarConfiguracion("PRIORIDAD", tdFechaConf, DateTime.MaxValue, TabTmp: ldtPrioridades);
394  }
395  else
396  {
397  // Comentado con Nestor y cuando hacemos envío de datos de sucursal a central sólo debemos mandar la sucursal desde la que enviamos.
398  TratarConfiguracion("SUCURSALES", tdFechaMin, tdFechaMax, " CODIGO = " + DB.SQLString(tcSucursal));
399 
400  TratarConfiguracion("EJERCICIOS", tdFechaConf, DateTime.MaxValue, " TIPOOFF = '" + tcSucursal + "' ");
401  }
402  }
403 
404  private static void TratarConfiguracion(string nombreTabla, DateTime tdFechaMin, DateTime tdFechaMax, string tcWhere = " 1 = 1 ", DataTable TabTmp = null)
405  {
406  DataTable tablaDatos = new DataTable();
407  string lcSql = string.Empty;
408  string lcWhere = string.Empty;
409 
410  _TextStepDetalle = "Generando fichero " + nombreTabla + ".xml";
411  _TextStepProgreso = _TextStepDetalle;
412  _PorcenProgreso = IncrementarBarraProgreso();
413 
414  lcSql += "SELECT * FROM " + DB.SQLDatabase("OFFLINE", nombreTabla.ToUpper()) +
415  " WHERE " + tcWhere + " AND MODIFIED >= " + DB.SQLString(tdFechaMin) + " AND MODIFIED <= " + DB.SQLString(tdFechaMax) +
416  " AND (CREATED < " + DB.SQLString(tdFechaMin) + " OR CREATED > " + DB.SQLString(tdFechaMax) + " ) ";
417 
418  lcSql += " UNION ALL ";
419 
420  lcSql += "SELECT * FROM " + DB.SQLDatabase("OFFLINE", nombreTabla.ToUpper()) +
421  " WHERE " + tcWhere + " AND CREATED >= " + DB.SQLString(tdFechaMin) + " AND CREATED <= " + DB.SQLString(tdFechaMax);
422 
423  DB.SQLExec(lcSql, ref tablaDatos);
424 
425  if (tablaDatos.Rows.Count > 0)
426  {
427  switch (nombreTabla.ToUpper())
428  {
429  case "PRIORIDAD":
430 
431  foreach (DataRow item in tablaDatos.Rows)
432  {
433  // Actualizar la tabla segun las prioridades seleccionadas
434  DataRow[] r = TabTmp.Select("id = " + item["idtabrel"].ToString());
435 
436  if (r.Length > 0)
437  {
438  if (Convert.ToBoolean(r[0]["prioridad"]))
439  {
440  item["prio_datos"] = 1;
441  }
442  else
443  {
444  item["prio_datos"] = 2;
445  }
446  }
447  }
448 
449  break;
450 
451  default:
452 
453  break;
454  }
455 
456  ConvertIndividualFile(tablaDatos, TempFolderName, nombreTabla.ToUpper(), FormatoExportacion.XML);
457  }
458  }
459 
460  private static bool GenerarDatosEnvio(string tcSucursal, bool tlImagenes, DateTime tdFechaConf, DateTime tdFechaMin, DateTime tdFechaMax, bool isCentral, int idConf, string cTipoEnvio, Dictionary<int, bool> prioridades = null)
461  {
463  ILog_comoffRepository logRepository = offlineUnitOfWork.Log_comoffRepository;
464 
465  _cRaizDataBaseTemporal = ObtenerDataBaseName(tcSucursal);
466 
467  Dictionary<string, object> tablaSucursales = DB.SQLREGValor("SUCURSALES", "CODIGO", tcSucursal, "OFFLINE");
468 
469  string lcBdTabla = string.Empty;
470  string lcPrincipal = string.Empty;
471  string lcBd = string.Empty;
472  string lcTabla = string.Empty;
473  string lcClave = string.Empty;
474  string lcVisicond = string.Empty;
475  string lcCondEnv = string.Empty;
476  string lcTitulo = string.Empty;
477 
478  string lcBdReal = string.Empty;
479  string lcBdAnt = string.Empty;
480  string lcTablaControl = string.Empty;
481  string lcTipoDato = string.Empty;
482 
483  bool llOk = true;
484  string lcSql = string.Empty;
485  DataTable tablaDatosNuevos = new DataTable();
486  DataTable tablaDatosModi = new DataTable();
487  DataTable ldtImagenes = new DataTable();
488 
489  // Obtenemos datos en la tabla dependiendo del tipo de envío:
490  // i -> Carga Inicial
491  // e -> Envío de datos
492  string lcTipoEnvio = (cTipoEnvio == "i" ? "la carga inicial" : "envío");
493  OfflineDatosComunicaciones datos = EstablecerConfiguracion(tcSucursal, tdFechaConf, tdFechaMin, tdFechaMax, isCentral, idConf, cTipoEnvio, logRepository);
494 
495  Log_comoffDto logDto = logRepository.GetDto(datos);
496  logDto.TipoDato = "01";
497  logDto.Resultado = 1;
498  logDto.Detalle = "Iniciando " + lcTipoEnvio + " de datos para la sucursal " + tcSucursal + ".";
499  logRepository.Insert(logDto);
500 
501 
502  logDto.Detalle = "Obtener configuración de " + lcTipoEnvio + " de datos para la sucursal " + tcSucursal + ".";
503  logRepository.Insert(logDto);
504 
505  DataTable TabTmp = obtenerDatosEnvio(prioridades, cTipoEnvio);
506 
507  Dictionary<string, bool> dicTablas = new Dictionary<string, bool>();
508  foreach (DataRow row in TabTmp.Rows)
509  {
510  if (!dicTablas.ContainsKey(row[0].ToString()))
511  dicTablas.Add(row[0].ToString(), false);
512  }
513 
514  VaciarUltimoLog(datos, logRepository);
515 
516  // Crear un directorio para la carga inicial/envío de datos
517  if (!Directory.Exists(datos._PathFolderInicial))
518  {
519  Directory.CreateDirectory(datos._PathFolderInicial);
520 
521  logDto.Detalle = "Se ha creado la carpeta temporal " + datos._PathFolderInicial + ".";
522  logRepository.Insert(logDto);
523  }
524 
525  #region Crear_Tablas_temporales
526 
527  // Tablas temporales
528  Dictionary<string, DataTable> dicDt = CrearTablasTemporales();
529 
530 
531  #endregion Crear_Tablas_temporales
532 
533  #region Gestionar Tablas
534 
535  decimal nCociente = (TabTmp != null ? TabTmp.Rows.Count : 99.0M);
536 
537  nCociente = (nCociente == 0 ? 100 : nCociente);
538  InicializarBarraProgreso(Convert.ToInt32(nCociente));
539  bool prioridadUsuarios = false;
540 
541  //Crear les bases de dades temporals a s amb les taules de la càrrega inicial
542  foreach (DataRow itemRow in TabTmp.Rows)
543  {
544  // comprovo si tinc el módul INSTAL·LAT
545  if (!clsOfflineUtils.EvaluarCondicion(itemRow.Field<string>("visicond").TrimEnd().ToLower()))
546  {
547  continue;
548  }
549 
550  if (itemRow.Field<string>("nombre").TrimEnd() == "COMUNES!HISSERIE")
551  {
552  continue;
553  }
554 
555  RegistroTabRel registro = ComprobarFicheros(itemRow);
556 
557  TratarTablasEnvio(itemRow, datos, registro, tcSucursal, tlImagenes, dicTablas, dicDt, ref ldtImagenes, logRepository);
558 
559  // Per la següent iteració
560  lcBdAnt = lcBd;
561 
562  if (itemRow.Field<string>("nombre").TrimEnd() == "EUROWINSYS!UNIUSERS")
563  {
564  prioridadUsuarios = itemRow.Field<bool>("prioridad");
565  }
566  }
567 
568  // Tratamiento especial de tablas
569  foreach (DataRow itemRow in TabTmp.Rows)
570  {
571  // comprovo si tinc el módul INSTAL·LAT
572  if (!clsOfflineUtils.EvaluarCondicion(itemRow.Field<string>("visicond").TrimEnd().ToLower()))
573  {
574  continue;
575  }
576 
577  if (itemRow.Field<string>("nombre").TrimEnd() == "COMUNES!HISSERIE")
578  {
579  RegistroTabRel registro = ComprobarFicheros(itemRow);
580 
581  TratarTablasEnvioEspecial(itemRow, datos, registro, tcSucursal, tlImagenes, dicTablas, dicDt, logRepository);
582  }
583 
584  // Per la següent iteració
585  lcBdAnt = lcBd;
586  }
587 
588  InicializarBarraProgreso();
589 
590  TratamientoFinal_Fabricacion(datos);
591 
592  GenerarRiesgoCliente(datos);
593 
594  GenerarDeletesDeConfiguracion(datos, dicDt, prioridadUsuarios);
595 
596  // Generar fichero XML Series cuando sea envío de datos desde sucursal
597  GenerarFicherosXML_Series(datos, logRepository);
598 
599  // Generar ficheros XML de datos
600  GenerarFicherosXML(datos);
601 
602  #endregion Gestionar Tablas
603 
604  foreach (KeyValuePair<string, bool> entry in dicTablas)
605  {
606  if (!entry.Value)
607  {
608  logDto.Resultado = 2;
609  logDto.TipoDato = clsOfflineUtils.ObtenerTipoDato(entry.Key.ToString().Trim());
610  logDto.Detalle = "No se ha incluido modificaciones de " + entry.Key.ToString().Trim() + " en el fichero, no se ha detectado datos nuevos o modificados.";
611  logRepository.Insert(logDto);
612  }
613  }
614 
615  GestionarXML_TablasTemporales(dicDt, datos, lcBd, logRepository);
616 
617  Procesar_Imagenes_Envio(lcBdTabla, datos, ldtImagenes, logRepository);
618 
619  llOk = Subir_Fichero_DatosEnvio(datos, cTipoEnvio == "e" ? (isCentral ? "c" : "s") : cTipoEnvio, logRepository);
620 
621  Actualizar_Fecha_Envio_Sucursales(datos, cTipoEnvio, logRepository);
622 
623  if (datos._TipoCom == 2) // Envío de datos
624  {
625  Actualizar_Fecha_Envio_Multiconf(datos);
626 
627  string lcBaseFicheroZip = _cTempFileName + (cTipoEnvio == "e" ? (isCentral ? "c" : "s") : cTipoEnvio);
628 
629  offlineUnitOfWork.SaveChanges();
630 
631  EnvioEmailNotificacion(lcBaseFicheroZip, datos, logRepository);
632  }
633 
634  Eliminar_Carpetas_Temporales(datos, logRepository);
635 
636  // Eliminar base de datos temporal
637  EliminarDataBaseTemporal();
638 
639  offlineUnitOfWork.SaveChanges();
640  offlineUnitOfWork.Dispose();
641 
642  return llOk;
643  }
644 
645  private static Dictionary<string, DataTable> CrearTablasTemporales()
646  {
647  Dictionary<string, DataTable> dicDt = new Dictionary<string, DataTable>();
648  DataTable dtAuxiliar = new DataTable();
649 
650  DB.SQLExec("SELECT * FROM " + DB.SQLDatabase("OFFLINE", "DELETENET") + " WHERE 1 = 2 ", ref dtAuxiliar);
651  dicDt.Add("DELETENET", dtAuxiliar);
652 
653  dtAuxiliar = new DataTable();
654  DB.SQLExec("SELECT * FROM " + DB.SQLDatabase("OFFLINE", "ACTRIESGO") + " WHERE 1 = 2 ", ref dtAuxiliar);
655  dicDt.Add("ACTRIESGO", dtAuxiliar);
656 
657  return dicDt;
658  }
659 
660  private static void GenerarDeletesDeConfiguracion(OfflineDatosComunicaciones datos, Dictionary<string, DataTable> dicDt, bool prioridadUsuarios)
661  {
662  DataTable dtDelete = dicDt.FirstOrDefault(x => x.Key == "DELETENET").Value;
663 
664  if (datos._IsCentral)
665  {
666  DateTime ldFechaAux = datos._FechaInicial;
667  datos._FechaInicial = datos._FechaConf;
668 
669  Gestionar_Tabla_DeleteNet(dtDelete, datos, "OFFLINE!MULTCONF", dicDt, new RegistroTabRel());
670  Gestionar_Tabla_DeleteNet(dtDelete, datos, "OFFLINE!TABNETCONF", dicDt, new RegistroTabRel());
671 
672  if (datos._TipoCom == 1 && prioridadUsuarios)
673  {
674  Gestionar_Tabla_DeleteNet(dtDelete, datos, "COMUNES!USUARIOS", dicDt, new RegistroTabRel());
675  }
676 
677  Gestionar_Tabla_DeleteNet(dtDelete, datos, "OFFLINE!SUCURCONF", dicDt, new RegistroTabRel());
678  Gestionar_Tabla_DeleteNet(dtDelete, datos, "OFFLINE!SUCURLET", dicDt, new RegistroTabRel());
679  Gestionar_Tabla_DeleteNet(dtDelete, datos, "OFFLINE!SUCURALM", dicDt, new RegistroTabRel());
680  Gestionar_Tabla_DeleteNet(dtDelete, datos, "OFFLINE!SUCURCAJA", dicDt, new RegistroTabRel());
681 
682  Gestionar_Tabla_DeleteNet(dtDelete, datos, "OFFLINE!SUCURART", dicDt, new RegistroTabRel());
683 
684  datos._FechaInicial = ldFechaAux;
685  }
686  }
687 
688  private static OfflineDatosComunicaciones EstablecerConfiguracion(string tcSucursal, DateTime tdFechaConf, DateTime tdFechaMin, DateTime tdFechaMax, bool isCentral, int idConf, string cTipoEnvio, ILog_comoffRepository logRepository)
689  {
690  OfflineDatosComunicaciones datos = new OfflineDatosComunicaciones();
691  _offlineConfig = DependencyInjector.Instance.Retrieve<OfflineConfig>();
692 
693  datos._Log_ComoffID = _cIdLog;
694  datos._IdConf = idConf;
695  datos._MultConf = DB.SQLValor("MULTCONF", "IDCONF", idConf.ToString(), "CODIGO", "OFFLINE").ToString();
696  datos._Usuario = sage.ew.global.EW_GLOBAL._GetVariable("wc_usuario").ToString();
697  datos._BdOffline = clsOfflineUtils.ObtenerNombreBdReal("OFFLINE");
698  datos._Sucursal = tcSucursal;
699  datos._PathFolderInicial = TempFolderName;
700  datos._IniServidor = DB._GetVariable("wc_iniservidor").ToString().ToLower();
701  datos._EnvioArticulos = _offlineConfig.GetValorVariable(EnumVariables.ENVIOARTICULOS) == ".T.";
702  datos._FechaConf = tdFechaConf;
703  datos._FechaInicial = tdFechaMin;
704  datos._FechaFinal = tdFechaMax;
705  datos._Almacenes = _offlineConfig.ObtenerAlmacenesSucursal(tcSucursal);
706  datos._Series = _offlineConfig.ObtenerSeriesSucursal(tcSucursal);
707  datos._Cajas = _offlineConfig.ObtenerCajasSucursal(tcSucursal);
708  datos._TipoCom = (cTipoEnvio == "i" ? 1 : 2);
709  datos._IsCentral = isCentral;
710 
711  if (isCentral)
712  {
713  datos._Delete_Mantes = _offlineConfig.GetValorVariable(EnumVariables.DELETE_CEN_MANT) == ".T.";
714  datos._Delete_Documentos = _offlineConfig.GetValorVariable(EnumVariables.DELETE_CEN_DOC) == ".T.";
715  }
716  else
717  {
718  datos._Delete_Mantes = _offlineConfig.GetValorVariable(EnumVariables.DELETE_SUC_MANT) == ".T.";
719  datos._Delete_Documentos = _offlineConfig.GetValorVariable(EnumVariables.DELETE_SUC_DOC) == ".T.";
720  }
721 
722  datos._NotificacionEnvio = Convert.ToBoolean(DB.SQLValor("MULTCONF", "IDCONF", idConf.ToString(), "NOTIFICAEN", "OFFLINE"));
723  datos._EmailNotificacionEnvio = Convert.ToString(DB.SQLValor("MULTCONF", "IDCONF", idConf.ToString(), "EMAILNOTEN", "OFFLINE"));
724 
725  datos._NotificacionRecepcion = Convert.ToBoolean(DB.SQLValor("MULTCONF", "IDCONF", idConf.ToString(), "NOTIFICARE", "OFFLINE"));
726  datos._EmailNotificacionRecepcion = Convert.ToString(DB.SQLValor("MULTCONF", "IDCONF", idConf.ToString(), "EMAILNOTRE", "OFFLINE"));
727 
728  try
729  {
730  datos._UltimoLog = Convert.ToInt32(_offlineConfig.GetValorVariable(EnumVariables.ULTIMOLOG));
731  }
732  catch
733  {
734  datos._UltimoLog = 6;
735  }
736 
737 
738 
739  string[] loClaveBackup = _offlineConfig.GetValorVariable(EnumVariables.BACKUP_RECEP).Split('|');
740  if (loClaveBackup.Length == 3)
741  {
742  try
743  {
744  datos._Backup = (loClaveBackup[0].ToUpper() == ".T." ? true : false);
745  datos._BackupPath = loClaveBackup[1].TrimEnd();
746  datos._BackupNumArchivos = Convert.ToInt32(loClaveBackup[2]);
747  }
748  catch
749  {
750  Log_comoffDto logDto = logRepository.GetDto(datos);
751  logDto.TipoDato = "01";
752  logDto.Resultado = 2;
753  logDto.Detalle = "Error al leer la configuración de la variable " + EnumVariables.BACKUP_RECEP.ToString();
754  logRepository.Insert(logDto);
755  }
756  }
757 
758  return datos;
759  }
760 
761  private static void GenerarRiesgoCliente(OfflineDatosComunicaciones datos)
762  {
763  if (!datos._IsCentral)
764  {
765  return;
766  }
767 
768  _TextStepDetalle = "Generando riesgo de clientes";
769  _TextStepProgreso = _TextStepDetalle;
770  _PorcenProgreso = IncrementarBarraProgreso();
771 
772  DataTable tablaDatos = new DataTable();
773  string lcSql = "SELECT * FROM " + DB.SQLDatabase("GESTION", "RIESGO");
774  lcSql += " WHERE 1 = 1 ";
775  lcSql += " AND MODIFIED >= " + DB.SQLString(datos._FechaInicial) + " AND MODIFIED <= " + DB.SQLString(datos._FechaFinal);
776  lcSql += " AND (CREATED < " + DB.SQLString(datos._FechaInicial) + " OR CREATED > " + DB.SQLString(datos._FechaFinal) + ")";
777  lcSql += " UNION ALL ";
778  lcSql += " SELECT * FROM " + DB.SQLDatabase("GESTION", "RIESGO");
779  lcSql += " WHERE 1 = 1 ";
780  lcSql += " AND CREATED >= " + DB.SQLString(datos._FechaInicial) + " AND CREATED <= " + DB.SQLString(datos._FechaFinal);
781 
782  DB.SQLExec(lcSql, ref tablaDatos);
783  ConvertIndividualFile(tablaDatos, TempFolderName, "RIESGO", FormatoExportacion.XML);
784  }
785 
786  private static void TratamientoFinal_Fabricacion(OfflineDatosComunicaciones datos)
787  {
788  _TextStepDetalle = "Ejecutando procesos adicionales";
789  _TextStepProgreso = _TextStepDetalle;
790  _PorcenProgreso = IncrementarBarraProgreso();
791 
792  string lcSql = string.Empty;
793  string[] Sufijos = new string[] { "_CREATED", "_MODIFIED" };
794  DataTable table = new DataTable();
795 
796  foreach (string sufijo in Sufijos)
797  {
798  // Cabecera Partes de costes
799  if (clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PARTES" + sufijo + "]"))
800  {
801  bool llPartes1 = clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_C_PARTES" + sufijo + "]");
802  bool llPartes2 = clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_C_PARTES" + sufijo + "]");
803  bool llCostes = clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_C_PARTES" + sufijo + "]");
804 
805  if (llPartes1 && llPartes2 && llCostes)
806  {
807  lcSql = " SELECT a.* INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PARTES" + sufijo + "] " +
808  " FROM ( " +
809  " SELECT * FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_C_PARTES" + sufijo + "] " +
810  " UNION ALL " +
811  " SELECT * FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_C_PARTES" + sufijo + "] " +
812  " UNION ALL " +
813  " SELECT * FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_C_PARTES" + sufijo + "] " +
814  " ) a ";
815  }
816  else
817  {
818  if (llPartes1)
819  {
820  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PARTES" + sufijo + "] " +
821  "FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_C_PARTES" + sufijo + "] ";
822  }
823 
824  if (llPartes2)
825  {
826  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PARTES" + sufijo + "] " +
827  "FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_C_PARTES" + sufijo + "] ";
828  }
829 
830  if (llCostes)
831  {
832  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PARTES" + sufijo + "] " +
833  "FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_C_PARTES" + sufijo + "] ";
834  }
835  }
836 
837  if (!string.IsNullOrWhiteSpace(lcSql))
838  {
839  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PARTES" + sufijo + "]");
840  DB.SQLExec(lcSql);
841  }
842  }
843 
844  // Lineas Partes de costes
845  if (clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + sufijo + "]"))
846  {
847  bool llPartes1 = clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_D_PARTES" + sufijo + "]");
848  bool llPartes2 = clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_D_PARTES" + sufijo + "]");
849  bool llCostes = clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_D_PARTES" + sufijo + "]");
850 
851  if (llPartes1 && llPartes2 && llCostes)
852  {
853  lcSql = " SELECT a.* INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + sufijo + "] " +
854  " FROM ( " +
855  " SELECT * FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_D_PARTES" + sufijo + "] " +
856  " UNION ALL " +
857  " SELECT * FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_D_PARTES" + sufijo + "] " +
858  " UNION ALL " +
859  " SELECT * FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_D_PARTES" + sufijo + "] " +
860  " ) a ";
861  }
862  else
863  {
864  if (llPartes1)
865  {
866  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + sufijo + "] " +
867  "FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_D_PARTES" + sufijo + "] ";
868  }
869 
870  if (llPartes2)
871  {
872  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + sufijo + "] " +
873  "FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_D_PARTES" + sufijo + "] ";
874  }
875 
876  if (llCostes)
877  {
878  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + sufijo + "] " +
879  "FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_D_PARTES" + sufijo + "] ";
880  }
881  }
882 
883  if (!string.IsNullOrWhiteSpace(lcSql))
884  {
885  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + sufijo + "]");
886  DB.SQLExec(lcSql);
887  }
888  }
889 
890  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_C_PARTES" + sufijo + "]");
891  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_C_PARTES" + sufijo + "]");
892  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_C_PARTES" + sufijo + "]");
893  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES1_D_PARTES" + sufijo + "]");
894  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_PARTES2_D_PARTES" + sufijo + "]");
895  DB.SQLExec("DROP TABLE IF EXISTS [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "_COSTES_D_PARTES" + sufijo + "]");
896  }
897  }
898 
899  private static void GenerarFicherosXML(OfflineDatosComunicaciones datos)
900  {
901  GenerarFicherosDatabaseXML(_cRaizDataBaseTemporal + "COMUNES", datos);
902  GenerarFicherosDatabaseXML(_cRaizDataBaseTemporal + "GESTION", datos);
903 
904  //* *Faig un recorregut per tots els móduls que tinc
905  foreach (KeyValuePair<string, DB._ModuloSchema> entry in DB._dicCacheModulos)
906  {
907  GenerarFicherosDatabaseXML(_cRaizDataBaseTemporal + entry.Value._Nombre, datos);
908  }
909 
910  GenerarFicherosDatabaseXML(_cRaizDataBaseTemporal + "EUROWINSYS", datos);
911  }
912 
913  private static void GenerarFicherosDatabaseXML(string tcDatabase, OfflineDatosComunicaciones datos)
914  {
915  string lcSql = string.Empty;
916  DataTable ldtDatos = new DataTable();
917 
918  if (clsOfflineUtils.ExisteDatabaseOffline(tcDatabase))
919  {
920  int lnPos = tcDatabase.LastIndexOf("_");
921  string lcNombre = tcDatabase.Substring(lnPos + 1);
922  string lcGetDate = " GETDATE() ";
923 
924  _TextStepDetalle = "Generando ficheros XML de la base de datos " + lcNombre.ToUpper();
925  _TextStepProgreso = _TextStepDetalle;
926  _PorcenProgreso = IncrementarBarraProgreso();
927 
928  DataTable table = clsOfflineUtils.ListaTablasDatabaseOffline(tcDatabase);
929 
930  foreach (DataRow item in table.Rows)
931  {
932  string lcCadenaCamps = ObtenerCamposSelect(lcNombre, item["table_name"].ToString().Trim());
933 
934  lcSql = "SELECT DISTINCT " + lcCadenaCamps + ", " + lcGetDate + " as created, " + lcGetDate + " as modified FROM [" + tcDatabase + "].dbo.[" + item["table_name"].ToString().Trim() + "] ";
935  DB.SQLExec(lcSql, ref ldtDatos);
936 
937  ConvertIndividualFile(ldtDatos, Path.Combine(datos._PathFolderInicial, lcNombre), item["table_name"].ToString().Trim(), FormatoExportacion.XML);
938  }
939 
940  }
941  }
942 
943  private static string ObtenerCamposSelect(string tcDBLocal, string tcTablaLocal)
944  {
945  // tcDBLocal->Nombre de la base de datos a la cual pertenece la tabla tcTablaLocal
946  // tcTablaLocal->nombre de la tabla de la cual se debe comparar
947 
948  string lcSelect = string.Empty;
949  string lcComa = string.Empty;
950  DataTable ldtCampos = new DataTable();
951 
952  DB.SQLExec("SELECT column_name, data_type FROM " + _cRaizDataBaseTemporal + tcDBLocal + ".INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tcTablaLocal + "' ", ref ldtCampos);
953 
954  //Creamos estructura vacia
955  foreach (DataRow item in ldtCampos.Rows)
956  {
957  switch (item["column_name"].ToString().ToLower())
958  {
959  case "com_estado":
960  case "com_fecha":
961  case "com_ini":
962  case "sucursal":
963  case "created":
964  case "modified":
965  case "vista":
966 
967  break;
968 
969  default:
970 
971  switch (item["data_type"].ToString().ToLower())
972  {
973  case "text":
974  case "ntext":
975 
976  lcSelect += lcComa + "CONVERT(VARCHAR(MAX), [" + item["column_name"].ToString().ToLower() + "]) as [" + item["column_name"].ToString().ToLower() + "] ";
977  break;
978 
979  default:
980 
981  lcSelect += lcComa + "[" + item["column_name"].ToString().ToLower() + "]";
982 
983  break;
984  }
985 
986  lcComa = ", ";
987 
988  break;
989  }
990  }
991 
992  return lcSelect;
993  }
994 
995  private static void TratarTablasEnvio(DataRow item, OfflineDatosComunicaciones datos, RegistroTabRel registro, string tcSucursal, bool tlImagenes, Dictionary<string, bool> dicTablas, Dictionary<string, DataTable> dicDt, ref DataTable ldtImagenes, ILog_comoffRepository logRepository)
996  {
997  string lcTipoDato = clsOfflineUtils.ObtenerTipoDato(registro._Clave);
998 
999  string lcCampoEmpresa = item.Field<string>("empresa").TrimEnd();
1000  string lcCampoEmpreSecun = item.Field<string>("empresecun").TrimEnd();
1001 
1002  // Obtenir nom real de la bd
1003  string lcBdReal = clsOfflineUtils.ObtenerNombreBdReal(registro._DBSecundaria);
1004 
1005  // Ens saltem les bases de dades que no existeixen
1006  if (string.IsNullOrEmpty(lcBdReal))
1007  {
1008  Log_comoffDto logDto = logRepository.GetDto(datos);
1009  logDto.TipoDato = lcTipoDato;
1010  logDto.Resultado = 3;
1011  logDto.Detalle = "No existe la base de datos " + registro._DBSecundaria + ".";
1012  logRepository.Insert(logDto);
1013  }
1014  else
1015  {
1016  _TextStepDetalle = "Revisando datos tabla " + registro._DBSecundaria + "!" + registro._TablaSecundaria;
1017  _TextStepProgreso = _TextStepDetalle;
1018  _PorcenProgreso = IncrementarBarraProgreso();
1019 
1020  string lcSql = string.Empty;
1021  string lcFiltrePrincipal = string.Empty;
1022  string lcFilterCondCtrl = string.Empty;
1023  string lcFilterCondCtrl_2 = string.Empty;
1024  string lcAny = EW_GLOBAL._GetVariable("wc_any").ToString();
1025 
1026  if (!string.IsNullOrWhiteSpace(registro._CondCtrl))
1027  {
1028  string lcOn = string.Empty;
1029 
1030  lcOn = ObtenerInnerOn(registro._DBPrincipal, registro._DBCondCtrl, registro._TablaPrincipal, registro._TablaCondCtrl, registro._RelaCtrl, registro._Clave, datos, logRepository, true);
1031  lcOn = lcOn + " AND c.EJERCICIO = " + DB.SQLString(lcAny);
1032 
1033  lcFilterCondCtrl = " INNER JOIN [" + clsOfflineUtils.ObtenerNombreBdReal(registro._DBCondCtrl) + "].dbo." + registro._TablaCondCtrl + " c " + " ON " + lcOn;
1034 
1035  lcFilterCondCtrl = lcFilterCondCtrl.Replace("b.", "c.");
1036  lcFilterCondCtrl = lcFilterCondCtrl.Replace("B.", "C.");
1037 
1038  lcFilterCondCtrl_2 = _offlineConfig.ConstruirFiltroCaja(registro._CondCtrl, tcSucursal, datos._Cajas);
1039  lcFilterCondCtrl_2 = lcFilterCondCtrl_2.Replace("{TABLA}", "c.");
1040 
1041  lcFilterCondCtrl = lcFilterCondCtrl + " AND " + lcFilterCondCtrl_2;
1042  }
1043 
1044  lcSql = " FROM [" + lcBdReal + "].dbo." + registro._TablaSecundaria + " b " +
1045  " INNER JOIN [" + clsOfflineUtils.ObtenerNombreBdReal(registro._DBPrincipal) + "].dbo." + registro._TablaPrincipal + " a " +
1046  " ON " + ObtenerInnerOn(registro._DBPrincipal, registro._DBSecundaria, registro._TablaPrincipal, registro._TablaSecundaria, registro._Relacion, registro._Clave, datos, logRepository) +
1047  lcFilterCondCtrl +
1048  " WHERE 1=1 ";
1049 
1050  // Casos especiales
1051  if (datos._EnvioArticulos && ((registro._DBPrincipal + "!" + registro._TablaPrincipal) == "GESTION!ARTICULO" || registro._Clave == "STOCKINI" || registro._Clave == "STOCKS"))
1052  {
1053  lcSql += Envio_Articulos_Sucursal(datos, registro._TablaSecundaria);
1054  }
1055 
1056  if (datos._IsCentral && registro._DBPrincipal + "!" + registro._TablaPrincipal == "COMUNES!LETRAS")
1057  {
1058  lcSql += Envio_Series_Sucursal(datos);
1059  }
1060 
1061  if (datos._IsCentral && registro._DBPrincipal + "!" + registro._TablaPrincipal == "TPV!CAJAS")
1062  {
1063  lcSql += Envio_Cajas_Sucursal(datos);
1064  }
1065 
1066  if (registro._DBPrincipal != registro._DBSecundaria || registro._TablaPrincipal != registro._TablaSecundaria)
1067  {
1068 
1069  if (!string.IsNullOrEmpty(registro._CondSecun))
1070  {
1071  lcFiltrePrincipal = registro._CondSecun;
1072  lcFiltrePrincipal = lcFiltrePrincipal.Replace("{TABLA}", "b.");
1073 
1074  lcSql = lcSql + " AND " + lcFiltrePrincipal;
1075  }
1076  }
1077 
1078  if (!string.IsNullOrWhiteSpace(registro._CondEnv))
1079  {
1080  lcFiltrePrincipal = registro._CondEnv;
1081  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroAlmacen(lcFiltrePrincipal, tcSucursal, datos._Almacenes, registro._TablaSecundaria);
1082  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroLetra(lcFiltrePrincipal, tcSucursal, datos._Series);
1083  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroCaja(lcFiltrePrincipal, tcSucursal, datos._Cajas);
1084 
1085  lcFiltrePrincipal = lcFiltrePrincipal.Replace("{TABLA}", "a.");
1086 
1087  lcSql = lcSql + " AND " + lcFiltrePrincipal;
1088  }
1089 
1090  //Copiar només els registres de les empreses no excloses
1091  clsOfflineUtils.RevisarTablasCampoEmpresa(registro._TablaPrincipal, ref lcCampoEmpresa);
1092  if (!string.IsNullOrWhiteSpace(lcCampoEmpresa))
1093  {
1094  lcSql = lcSql + " AND a." + lcCampoEmpresa + " NOT IN (SELECT empresa FROM [" + datos._BdOffline + "].dbo.empexclu) ";
1095  }
1096 
1097  clsOfflineUtils.RevisarTablasCampoEmpresa(registro._TablaSecundaria, ref lcCampoEmpreSecun);
1098  if (!string.IsNullOrWhiteSpace(lcCampoEmpreSecun))
1099  {
1100  lcSql = lcSql + " AND b." + lcCampoEmpreSecun + " NOT IN (SELECT empresa FROM [" + datos._BdOffline + "].dbo.empexclu) ";
1101  }
1102 
1103  ActualizarDatosEnvio(item, datos, registro, tcSucursal, tlImagenes, dicTablas, dicDt, ref ldtImagenes, lcSql, logRepository);
1104 
1105  // Gestionar la tabla DELETENET
1106  DataTable dtDelete = dicDt.FirstOrDefault(x => x.Key == "DELETENET").Value;
1107 
1108  if (datos._IsCentral ? Convert.ToBoolean(registro._Prioridad) : !Convert.ToBoolean(registro._Prioridad))
1109  {
1110  if (datos._TipoCom == 2 || (datos._TipoCom == 1 && (registro._IdGrupo == 3 || registro._IdGrupo == 4)))
1111  {
1112  Gestionar_Tabla_DeleteNet(dtDelete, datos, registro._Nombre, dicDt, registro);
1113  }
1114  }
1115  }
1116  }
1117 
1118  private static void TratarTablasEnvioEspecial(DataRow item, OfflineDatosComunicaciones datos, RegistroTabRel registro, string tcSucursal, bool tlImagenes, Dictionary<string, bool> dicTablas, Dictionary<string, DataTable> dicDt, ILog_comoffRepository logRepository)
1119  {
1120  string lcTipoDato = clsOfflineUtils.ObtenerTipoDato(registro._Clave);
1121 
1122  string lcCampoEmpresa = item.Field<string>("empresa").TrimEnd();
1123  string lcCampoEmpreSecun = item.Field<string>("empresecun").TrimEnd();
1124 
1125  // Obtenir nom real de la bd
1126  string lcBdReal = clsOfflineUtils.ObtenerNombreBdReal(registro._DBSecundaria);
1127 
1128  // Ens saltem les bases de dades que no existeixen
1129  if (string.IsNullOrEmpty(lcBdReal))
1130  {
1131  Log_comoffDto logDto = logRepository.GetDto(datos);
1132  logDto.TipoDato = lcTipoDato;
1133  logDto.Resultado = 3;
1134  logDto.Detalle = "No existe la base de datos " + registro._DBSecundaria + ".";
1135  logRepository.Insert(logDto);
1136  }
1137  else
1138  {
1139  if (_TextStepDetalle != "Revisando datos tabla " + registro._DBSecundaria + "!" + registro._TablaSecundaria)
1140  {
1141  _TextStepDetalle = "Revisando datos tabla " + registro._DBSecundaria + "!" + registro._TablaSecundaria;
1142  }
1143 
1144  if (clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + registro._DBPrincipal + "].dbo.[" + registro._TablaPrincipal + registro._Sufijo + "]"))
1145  {
1146  string lcSql = string.Empty;
1147  string lcFiltrePrincipal = string.Empty;
1148 
1149  lcSql = " FROM [" + lcBdReal + "].dbo." + registro._TablaSecundaria + " b " +
1150  " INNER JOIN [" + _cRaizDataBaseTemporal + registro._DBPrincipal + "].dbo." + registro._TablaPrincipal + registro._Sufijo + " a " +
1151  " ON " + ObtenerInnerOn(registro._DBPrincipal, registro._DBSecundaria, registro._TablaPrincipal, registro._TablaSecundaria, registro._Relacion, registro._Clave, datos, logRepository) +
1152  " WHERE 1=1 ";
1153 
1154  // Casos especiales
1155  if (datos._EnvioArticulos && ((registro._DBPrincipal + "!" + registro._TablaPrincipal) == "GESTION!ARTICULO" || registro._Clave == "STOCKINI" || registro._Clave == "STOCKS"))
1156  {
1157  lcSql += Envio_Articulos_Sucursal(datos, registro._TablaSecundaria);
1158  }
1159 
1160  if (datos._IsCentral && registro._DBPrincipal + "!" + registro._TablaPrincipal == "COMUNES!LETRAS")
1161  {
1162  lcSql += Envio_Series_Sucursal(datos);
1163  }
1164 
1165  if (datos._IsCentral && registro._DBPrincipal + "!" + registro._TablaPrincipal == "TPV!CAJAS")
1166  {
1167  lcSql += Envio_Cajas_Sucursal(datos);
1168  }
1169 
1170  if (registro._DBPrincipal != registro._DBSecundaria || registro._TablaPrincipal != registro._TablaSecundaria)
1171  {
1172 
1173  if (!string.IsNullOrEmpty(registro._CondSecun))
1174  {
1175  lcFiltrePrincipal = registro._CondSecun;
1176  lcFiltrePrincipal = lcFiltrePrincipal.Replace("{TABLA}", "b.");
1177 
1178  lcSql = lcSql + " AND " + lcFiltrePrincipal;
1179  }
1180  }
1181 
1182  if (!string.IsNullOrWhiteSpace(registro._CondEnv))
1183  {
1184  lcFiltrePrincipal = registro._CondEnv;
1185  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroAlmacen(lcFiltrePrincipal, tcSucursal, datos._Almacenes, registro._TablaSecundaria);
1186  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroLetra(lcFiltrePrincipal, tcSucursal, datos._Series);
1187  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroCaja(lcFiltrePrincipal, tcSucursal, datos._Cajas);
1188 
1189  lcFiltrePrincipal = lcFiltrePrincipal.Replace("{TABLA}", "a.");
1190 
1191  lcSql = lcSql + " AND " + lcFiltrePrincipal;
1192  }
1193 
1194  //Copiar només els registres de les empreses no excloses
1195  clsOfflineUtils.RevisarTablasCampoEmpresa(registro._TablaPrincipal, ref lcCampoEmpresa);
1196  if (!string.IsNullOrWhiteSpace(lcCampoEmpresa))
1197  {
1198  lcSql = lcSql + " AND a." + lcCampoEmpresa + " NOT IN (SELECT empresa FROM [" + datos._BdOffline + "].dbo.empexclu) ";
1199  }
1200 
1201  clsOfflineUtils.RevisarTablasCampoEmpresa(registro._TablaSecundaria, ref lcCampoEmpreSecun);
1202  if (!string.IsNullOrWhiteSpace(lcCampoEmpreSecun))
1203  {
1204  lcSql = lcSql + " AND b." + lcCampoEmpreSecun + " NOT IN (SELECT empresa FROM [" + datos._BdOffline + "].dbo.empexclu) ";
1205  }
1206 
1207  DataTable ldtImagenes = new DataTable();
1208  ActualizarDatosEnvio(item, datos, registro, tcSucursal, tlImagenes, dicTablas, dicDt, ref ldtImagenes, lcSql, logRepository);
1209  }
1210 
1211  // Gestionar la tabla DELETENET
1212  DataTable dtDelete = dicDt.FirstOrDefault(x => x.Key == "DELETENET").Value;
1213 
1214  if (datos._IsCentral ? Convert.ToBoolean(registro._Prioridad) : !Convert.ToBoolean(registro._Prioridad))
1215  {
1216  if (datos._TipoCom == 2 || (datos._TipoCom == 1 && (registro._IdGrupo == 3 || registro._IdGrupo == 4)))
1217  {
1218  Gestionar_Tabla_DeleteNet(dtDelete, datos, registro._Nombre, dicDt, registro);
1219  }
1220  }
1221  }
1222  }
1223 
1224  private static RegistroTabRel ComprobarFicheros(DataRow item)
1225  {
1226  RegistroTabRel registro = new RegistroTabRel();
1227 
1228  registro._DBPrincipal = string.Empty;
1229  registro._TablaPrincipal = string.Empty;
1230 
1231  registro._DBSecundaria = string.Empty;
1232  registro._TablaSecundaria = string.Empty;
1233 
1234  registro._Empresa = item.Field<string>("empresa").TrimEnd();
1235 
1236 
1237  registro._ID = item.Field<int>("id");
1238  registro._IdGrupo = item.Field<int>("idgrupo");
1239  registro._Clave = item.Field<string>("clave").TrimEnd();
1240  registro._Nombre = item.Field<string>("nombre").TrimEnd();
1241  registro._Prioridad = Convert.ToInt32(item.Field<bool>("prioridad"));
1242  registro._Titulo = item.Field<string>("titulo").TrimEnd().ToUpper();
1243 
1244  registro._CondEnv = item.Field<string>("condenv").TrimEnd().ToUpper();
1245  registro._CondSecun = item.Field<string>("condsecun").TrimEnd().ToUpper();
1246  registro._CondCtrl = item.Field<string>("condctrl").TrimEnd().ToUpper();
1247  registro._NombreTablaCtrl = item.Field<string>("tablactrl").TrimEnd().ToUpper();
1248 
1249  if (!string.IsNullOrWhiteSpace(item.Field<string>("principal")))
1250  {
1251  string[] subPos = item.Field<string>("principal").TrimEnd().Split('!');
1252  if (subPos.Length == 2)
1253  {
1254  registro._DBPrincipal = subPos[0].TrimEnd();
1255  registro._TablaPrincipal = subPos[1].TrimEnd();
1256  }
1257  }
1258 
1259  // taula secundaria
1260  if (!string.IsNullOrWhiteSpace(item.Field<string>("nombre")))
1261  {
1262  string[] subPos = item.Field<string>("nombre").TrimEnd().Split('!');
1263  if (subPos.Length == 2)
1264  {
1265  registro._DBSecundaria = subPos[0].TrimEnd();
1266  registro._TablaSecundaria = subPos[1].TrimEnd();
1267  }
1268  }
1269 
1270  if (!string.IsNullOrWhiteSpace(item.Field<string>("tablactrl")))
1271  {
1272  string[] subPos = item.Field<string>("tablactrl").TrimEnd().Split('!');
1273  if (subPos.Length == 2)
1274  {
1275  registro._DBCondCtrl = subPos[0].TrimEnd();
1276  registro._TablaCondCtrl = subPos[1].TrimEnd();
1277  }
1278  }
1279 
1280  registro._Sufijo = "_CREATED";
1281  registro._TipoTabla = item.Field<int>("tipotabla");
1282 
1283  registro._Asientos = item.Field<string>("asientos").TrimEnd();
1284  registro._Otrasien = item.Field<string>("otrasien").TrimEnd();
1285  registro._Eos = item.Field<string>("eos").TrimEnd();
1286  registro._Iva_exen = item.Field<string>("iva_exen").TrimEnd();
1287  registro._Ivasopor = item.Field<string>("ivasopor").TrimEnd();
1288  registro._Ivareper = item.Field<string>("ivareper").TrimEnd();
1289  registro._Retsopor = item.Field<string>("retsopor").TrimEnd();
1290  registro._Retreper = item.Field<string>("retreper").TrimEnd();
1291  registro._Compras = item.Field<string>("compras").TrimEnd();
1292  registro._Relacion = item.Field<string>("relacion").TrimEnd();
1293  registro._RelaCtrl = item.Field<string>("relactrl").TrimEnd();
1294 
1295  return registro;
1296  }
1297 
1298  private static void ActualizarDatosEnvio(DataRow item, OfflineDatosComunicaciones datos, RegistroTabRel registro, string tcSucursal, bool tlImagenes, Dictionary<string, bool> dicTablas, Dictionary<string, DataTable> dicDt, ref DataTable ldtImagenes, string lcSql, ILog_comoffRepository logRepository)
1299  {
1300  bool llPrioridad = (datos._IsCentral && Convert.ToBoolean(registro._Prioridad) || !datos._IsCentral && !Convert.ToBoolean(registro._Prioridad));
1301 
1302  if (llPrioridad || (registro._Clave == "FACTURAS" || registro._Clave == "FACTURAC" || registro._TablaSecundaria == "ENTREGAS"))
1303  {
1304  registro._Sufijo = "_MODIFIED";
1305 
1306  ProcesoActualizarDatos(item, datos, registro, tcSucursal, tlImagenes, dicTablas, dicDt, ref ldtImagenes, lcSql, logRepository);
1307  }
1308 
1309  registro._Sufijo = "_CREATED";
1310 
1311  ProcesoActualizarDatos(item, datos, registro, tcSucursal, tlImagenes, dicTablas, dicDt, ref ldtImagenes, lcSql, logRepository);
1312  }
1313 
1314  private static void ProcesoActualizarDatos(DataRow item, OfflineDatosComunicaciones datos, RegistroTabRel registro, string tcSucursal, bool tlImagenes, Dictionary<string, bool> dicTablas, Dictionary<string, DataTable> dicDt, ref DataTable ldtImagenes, string tcSql, ILog_comoffRepository logRepository)
1315  {
1316  string lcSqlCondicion = string.Empty;
1317  DataTable dtDatos = new DataTable();
1318 
1319  Dictionary<string, object> tablaSucursales = DB.SQLREGValor("SUCURSALES", "CODIGO", tcSucursal, "OFFLINE");
1320 
1321  string lcBdReal = clsOfflineUtils.ObtenerNombreBdReal(registro._DBSecundaria);
1322  string lcTipoDato = clsOfflineUtils.ObtenerTipoDato(registro._Clave);
1323  string lcAlias = ProcesoActualizarDatos_Alias(datos, registro);
1324 
1325  if (registro._Sufijo == "_MODIFIED")
1326  {
1327  string lcSufijo = string.Empty;
1328  string[] subPos = registro._Sufijo.Split('_');
1329 
1330  if (subPos.Length == 2)
1331  {
1332  lcSufijo = subPos[1].TrimEnd();
1333  }
1334 
1335  lcSqlCondicion = " AND " + lcAlias + lcSufijo + " >= " + DB.SQLString(datos._FechaInicial) + " AND " + lcAlias + lcSufijo + " <= " + DB.SQLString(datos._FechaFinal);
1336  lcSqlCondicion += " AND (" + lcAlias + "CREATED < " + DB.SQLString(datos._FechaInicial) + " OR " + lcAlias + "CREATED > " + DB.SQLString(datos._FechaFinal) + ")";
1337  }
1338  else
1339  {
1340  lcSqlCondicion = " AND " + lcAlias + "CREATED >= " + DB.SQLString(datos._FechaInicial) + " AND " + lcAlias + "CREATED <= " + DB.SQLString(datos._FechaFinal);
1341  }
1342 
1343  string lcSql = " SELECT b.* " + tcSql + lcSqlCondicion;
1344 
1345  if (!DB.SQLExec(lcSql, ref dtDatos))
1346  {
1347  Log_comoffDto logDto = logRepository.GetDto(datos);
1348  logDto.TipoDato = lcTipoDato;
1349  logDto.Resultado = 3;
1350  logDto.Detalle = "No se ha podido ejecutar la instrucción " + lcSql + ".";
1351  logRepository.Insert(logDto);
1352  }
1353  else
1354  {
1355  if (dtDatos.Rows.Count > 0)
1356  {
1357  RegistroDatos(datos, item, lcBdReal, registro._DBSecundaria, registro._TablaSecundaria, dtDatos, registro._Sufijo, logRepository);
1358  dicTablas[item[0].ToString()] = true;
1359 
1360  if (clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "]"))
1361  {
1362  InsertarDatosBulkMode(dtDatos, "[" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "]");
1363  }
1364  else
1365  {
1366  if (!clsOfflineUtils.ExisteDatabaseOffline(_cRaizDataBaseTemporal + registro._DBSecundaria))
1367  {
1368  CrearDataTable(registro._DBSecundaria, _cRaizDataBaseTemporal);
1369  }
1370 
1371  lcSql = " SELECT b.* INTO [" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "]" +
1372  tcSql + lcSqlCondicion;
1373  DB.SQLExec(lcSql);
1374  }
1375 
1376  ProcesoActualizarDatosEspecial(registro, datos, dicDt);
1377  }
1378 
1379  if (Revisar_Imagenes_Datos(tlImagenes, tablaSucursales, registro._TablaSecundaria, datos, ref dtDatos))
1380  {
1381  // Actualizar el campo ULTFECENV en TABNETFEC
1382  Actualizar_Ultima_Fecha_Envio(registro._ID);
1383 
1384  // Gestionar la tabla de control
1385  if (registro._Sufijo == "_CREATED")
1386  {
1387  Gestionar_Tabla_Control(dtDatos, datos, registro, Convert.ToBoolean(registro._Prioridad), registro._ID, lcTipoDato, item, dicTablas, logRepository);
1388  }
1389 
1390  // Enviar imagenes??
1391  Seleccionar_Imagenes_Envio(tlImagenes, tablaSucursales, registro._TablaSecundaria, datos, ref ldtImagenes);
1392  }
1393  }
1394  }
1395 
1396  private static string ProcesoActualizarDatos_Alias(OfflineDatosComunicaciones datos, RegistroTabRel registro)
1397  {
1398  string lcAlias = "a.";
1399 
1400  if (datos._IsCentral && Convert.ToBoolean(registro._Prioridad) || !datos._IsCentral && !Convert.ToBoolean(registro._Prioridad))
1401  {
1402  lcAlias = "b.";
1403  }
1404  else
1405  {
1406  // Caso especial para las entregas de clientes
1407  if (registro._TablaPrincipal == "C_ALBVEN" && registro._TablaSecundaria == "ENTRE_CL" && !registro._Sobreescribir)
1408  {
1409  lcAlias = "b.";
1410  }
1411 
1412  // Caso especial para las entregas de pedidos
1413  if (registro._TablaPrincipal == "C_PEDIVE" && registro._TablaSecundaria == "ENTRE_PV" && !registro._Sobreescribir)
1414  {
1415  lcAlias = "b.";
1416  }
1417 
1418  // Caso especial para las entregas de presupuestos
1419  if (registro._TablaPrincipal == "C_PRESUV" && registro._TablaSecundaria == "ENTRE_PR" && !registro._Sobreescribir)
1420  {
1421  lcAlias = "b.";
1422  }
1423  }
1424 
1425  return lcAlias;
1426  }
1427 
1428  private static void TratamientoEspecial_RiesgoCliente(RegistroTabRel registro, OfflineDatosComunicaciones datos, Dictionary<string, DataTable> dicDt)
1429  {
1430  DataTable tablaDatos = new DataTable();
1431  string lcSql = string.Empty;
1432 
1433  DataTable dtActRiesgo = dicDt.FirstOrDefault(x => x.Key == "ACTRIESGO").Value;
1434 
1435  switch (registro._Clave)
1436  {
1437  case "C_PEDIVE":
1438 
1439  if (registro._TablaPrincipal == "C_PEDIVE")
1440  {
1441  lcSql = " SELECT DISTINCT EMPRESA, CLIENTE AS CODIGO FROM [" + _cRaizDataBaseTemporal + registro._DBPrincipal + "].[dbo].[" + registro._TablaPrincipal + registro._Sufijo + "]";
1442  DB.SQLExec(lcSql, ref tablaDatos);
1443  }
1444 
1445  break;
1446 
1447  case "C_ALBVEN":
1448  case "FACTURAS":
1449  case "TPVCONARQUEO":
1450  case "TPVSINARQUEO":
1451 
1452  if (registro._TablaPrincipal == "C_ALBVEN")
1453  {
1454  lcSql = " SELECT DISTINCT EMPRESA, CLIENTE AS CODIGO FROM [" + _cRaizDataBaseTemporal + registro._DBPrincipal + "].[dbo].[" + registro._TablaPrincipal + registro._Sufijo + "]";
1455  DB.SQLExec(lcSql, ref tablaDatos);
1456  }
1457 
1458  break;
1459 
1460  case "CLIENTES":
1461 
1462  if (registro._TablaPrincipal == "CLIENTES")
1463  {
1464  lcSql = " SELECT DISTINCT B.EMPRESA, A.CODIGO " +
1465  " FROM [" + _cRaizDataBaseTemporal + registro._DBPrincipal + "].[dbo].[" + registro._TablaPrincipal + registro._Sufijo + "] A " +
1466  " INNER JOIN " + DB.SQLDatabase("OFFLINE","ACTRIESGO") + " B ON A.CODIGO = B.CODIGO " +
1467  " WHERE B.EMPRESA NOT IN (SELECT EMPRESA FROM " + DB.SQLDatabase("OFFLINE", "EMPEXCLU") + ")";
1468 
1469  DB.SQLExec(lcSql, ref tablaDatos);
1470  }
1471 
1472  break;
1473 
1474  default:
1475 
1476  break;
1477  }
1478 
1479  // Eliminamos la tabla que tenemos salvada en el diccionario y guardamos de nuevo actualizada
1480  if (tablaDatos != null && tablaDatos.Rows.Count > 0)
1481  {
1482  foreach (DataRow item in tablaDatos.Rows)
1483  {
1484  var dataRow = dtActRiesgo.AsEnumerable().Where(dr => dr.Field<string>("empresa") == item.Field<string>("empresa") &&
1485  dr.Field<string>("codigo") == item.Field<string>("codigo"));
1486  if (!dataRow.Any())
1487  {
1488  DataRow newRow = dtActRiesgo.NewRow();
1489 
1490  newRow["empresa"] = item["empresa"];
1491  newRow["codigo"] = item["codigo"];
1492 
1493  dtActRiesgo.Rows.Add(newRow);
1494  }
1495  }
1496 
1497  dicDt.Remove("ACTRIESGO");
1498  dicDt.Add("ACTRIESGO", dtActRiesgo);
1499  }
1500  }
1501 
1502  private static void ProcesoActualizarDatosEspecial(RegistroTabRel registro, OfflineDatosComunicaciones datos, Dictionary<string, DataTable> dicDt)
1503  {
1504  string lcSql = string.Empty;
1505 
1506  // buscar los registros de ASIENTOS afectados
1507  if (!string.IsNullOrWhiteSpace(registro._Asientos))
1508  {
1509  TratamientoEspecial_ASI(registro, "ASIENTOS", registro._Asientos);
1510  TratamientoEspecial_Asientos(registro, datos, true);
1511  }
1512 
1513  // buscar los registros de COMPRAS afectados
1514  if (!string.IsNullOrWhiteSpace(registro._Compras))
1515  {
1516  TratamientoEspecial_Compras(registro, datos);
1517  }
1518 
1519  if (!datos._IsCentral)
1520  {
1521  TratamientoEspecial_RiesgoCliente(registro, datos, dicDt);
1522  }
1523 
1524  // Si la taula secundaria és ASIENTOS, hem d'agafar tots el registres de cada assentament.
1525  switch (registro._TablaSecundaria)
1526  {
1527  case "ASIENTOS":
1528 
1529  TratamientoEspecial_Asientos(registro, datos);
1530 
1531  break;
1532 
1533  case "PREVIS":
1534  case "PREVI_CL":
1535 
1536  TratamientoEspecial_Previsiones(registro, datos);
1537 
1538  break;
1539 
1540  case "IVAREPER":
1541  case "IVASOPOR":
1542 
1543  DataTable ldtDatosEOS = new DataTable();
1544 
1545  lcSql = " SELECT A.* " +
1546  " FROM " + DB.SQLDatabase("GESTION", "EOS") + " A " +
1547  " INNER JOIN [" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "] B ON A.EMPRESA = B.EMPRESA AND A.ASIIVA = B.ASI ";
1548 
1549  if (registro._TablaSecundaria == "IVAREPER")
1550  {
1551  lcSql = lcSql + " AND A.TIPO = 1 ";
1552  }
1553  else
1554  {
1555  lcSql = lcSql + " AND A.TIPO = 0 ";
1556  }
1557 
1558  DB.SQLExec(lcSql, ref ldtDatosEOS);
1559 
1560  if (ldtDatosEOS != null && ldtDatosEOS.Rows.Count > 0)
1561  {
1562  ComprobarTablaTemporalSQL(registro, "GESTION", "EOS");
1563 
1564  InsertarDatosBulkMode(ldtDatosEOS, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "EOS" + registro._Sufijo + "]");
1565  }
1566 
1567  break;
1568 
1569  case "IVACJSOPOR":
1570  case "IVACJREPER":
1571 
1572  TratamientoEspecial_CriterioCaja(registro, datos);
1573 
1574  break;
1575 
1576  case "D_PROD":
1577  case "D_TRANS":
1578  case "D_PARTES":
1579  TratamientoEspecial_EnvioFabricacion(registro, datos);
1580  break;
1581 
1582  case "C_PARTES":
1583  break;
1584 
1585  case "D_PEDIVE":
1586 
1587  TratamientoEspecial_PedidosVenta(registro, datos);
1588  break;
1589 
1590  case "D_PEDICO":
1591 
1592  TratamientoEspecial_PedidosCompra(registro, datos);
1593  break;
1594 
1595  case "D_ALBDEP":
1596 
1597  TratamientoEspecial_DepositosVenta(registro, datos);
1598  break;
1599 
1600  case "D_DEPCOM":
1601 
1602  TratamientoEspecial_DepositosCompra(registro, datos);
1603  break;
1604 
1605  case "D_ALBVEN":
1606 
1607  TratamientoEspecial_AlbaranesVenta(registro, datos);
1608  break;
1609 
1610  case "D_ALBCOM":
1611 
1612  TratamientoEspecial_AlbaranesCompra(registro, datos);
1613  break;
1614 
1615  case "C_FACTUVEN":
1616 
1617  TratamientoEspecial_FacturasVenta(registro, datos);
1618  break;
1619 
1620  case "C_FACTUCOM":
1621 
1622  TratamientoEspecial_FacturasCompra(registro, datos);
1623  break;
1624 
1625  case "ACCESOGRUP":
1626 
1627  TratamientoEspecial_AccesoGrup(registro, datos);
1628  break;
1629 
1630  default:
1631 
1632  break;
1633  }
1634  }
1635 
1636  private static void TratamientoEspecial_AccesoGrup(RegistroTabRel registro, OfflineDatosComunicaciones datos)
1637  {
1638  string lcSql = string.Empty;
1639  string lcGrupo = GrupoEmpresa._CodigoGrupoActual().ToString().Trim();
1640 
1641  lcSql = " Delete From [" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo." + registro._TablaSecundaria + registro._Sufijo + " " +
1642  " Where grupo != " + DB.SQLString(lcGrupo);
1643 
1644  // Executem la consulta
1645  DB.SQLExec(lcSql);
1646  }
1647 
1648  private static void TratamientoEspecial_PedidosVenta(RegistroTabRel registro, OfflineDatosComunicaciones datos)
1649  {
1650  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
1651  // para que enviemos la modificación de datos del documento origen.
1652  if (!registro._Sobreescribir && registro._DBPrincipal == "GESTION")
1653  {
1654  DataTable ldtDatosRelacionados = new DataTable();
1655  string lcSql = string.Empty;
1656 
1657  // buscar documento asociado a la linea del albarán
1658  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1659  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_PEDIVE" + registro._Sufijo + "]" +
1660  " WHERE DOC = 3 ";
1661  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1662 
1663  foreach (DataRow item in ldtDatosRelacionados.Rows)
1664  {
1665  DataTable ldtDatos = new DataTable();
1666  lcSql = " SELECT * " +
1667  " FROM " + DB.SQLDatabase("GESTION", "C_PRESUV") +
1668  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1669  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num"));
1670  DB.SQLExec(lcSql, ref ldtDatos);
1671 
1672  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1673  {
1674  ComprobarTablaTemporalSQL(registro, "GESTION", "C_PRESUV", "_ESPECIAL");
1675 
1676  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PRESUV" + "_ESPECIAL" + "]");
1677  }
1678 
1679  lcSql = " SELECT * " +
1680  " FROM " + DB.SQLDatabase("GESTION", "D_PRESUV") +
1681  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1682  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num")) +
1683  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1684 
1685  DB.SQLExec(lcSql, ref ldtDatos);
1686 
1687  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1688  {
1689  ComprobarTablaTemporalSQL(registro, "GESTION", "D_PRESUV", "_ESPECIAL");
1690 
1691  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PRESUV" + "_ESPECIAL" + "]");
1692  }
1693  }
1694  }
1695  }
1696 
1697  private static void TratamientoEspecial_PedidosCompra(RegistroTabRel registro, OfflineDatosComunicaciones datos)
1698  {
1699  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
1700  // para que enviemos la modificación de datos del documento origen.
1701  if (!registro._Sobreescribir && registro._DBPrincipal == "GESTION")
1702  {
1703  // No hay nada que hacer
1704  }
1705  }
1706 
1707  private static void TratamientoEspecial_DepositosVenta(RegistroTabRel registro, OfflineDatosComunicaciones datos)
1708  {
1709  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
1710  // para que enviemos la modificación de datos del documento origen.
1711  if (!registro._Sobreescribir && registro._DBPrincipal == "GESTION")
1712  {
1713  DataTable ldtDatosRelacionados = new DataTable();
1714  string lcSql = string.Empty;
1715 
1716  // buscar documento asociado a la linea del albarán
1717  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1718  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_ALBDEP" + registro._Sufijo + "]" +
1719  " WHERE DOC = 1 ";
1720  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1721 
1722  foreach (DataRow item in ldtDatosRelacionados.Rows)
1723  {
1724  DataTable ldtDatos = new DataTable();
1725  lcSql = " SELECT * " +
1726  " FROM " + DB.SQLDatabase("GESTION", "C_PEDIVE") +
1727  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1728  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num"));
1729  DB.SQLExec(lcSql, ref ldtDatos);
1730 
1731  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1732  {
1733  ComprobarTablaTemporalSQL(registro, "GESTION", "C_PEDIVE", "_ESPECIAL");
1734 
1735  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PEDIVE" + "_ESPECIAL" + "]");
1736  }
1737 
1738  lcSql = " SELECT * " +
1739  " FROM " + DB.SQLDatabase("GESTION", "D_PEDIVE") +
1740  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1741  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num")) +
1742  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1743 
1744  DB.SQLExec(lcSql, ref ldtDatos);
1745 
1746  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1747  {
1748  ComprobarTablaTemporalSQL(registro, "GESTION", "D_PEDIVE", "_ESPECIAL");
1749 
1750  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PEDIVE" + "_ESPECIAL" + "]");
1751  }
1752  }
1753 
1754  // buscar documento asociado a la linea del albarán
1755  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1756  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_ALBDEP" + registro._Sufijo + "]" +
1757  " WHERE DOC = 2 ";
1758  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1759 
1760  foreach (DataRow item in ldtDatosRelacionados.Rows)
1761  {
1762  DataTable ldtDatos = new DataTable();
1763  lcSql = " SELECT * " +
1764  " FROM " + DB.SQLDatabase("GESTION", "C_ALBDEP") +
1765  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1766  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num"));
1767  DB.SQLExec(lcSql, ref ldtDatos);
1768 
1769  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1770  {
1771  ComprobarTablaTemporalSQL(registro, "GESTION", "C_ALBDEP", "_ESPECIAL");
1772 
1773  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_ALBDEP" + "_ESPECIAL" + "]");
1774  }
1775 
1776  lcSql = " SELECT * " +
1777  " FROM " + DB.SQLDatabase("GESTION", "D_ALBDEP") +
1778  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1779  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num")) +
1780  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1781 
1782  DB.SQLExec(lcSql, ref ldtDatos);
1783 
1784  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1785  {
1786  ComprobarTablaTemporalSQL(registro, "GESTION", "D_ALBDEP", "_ESPECIAL");
1787 
1788  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_ALBDEP" + "_ESPECIAL" + "]");
1789  }
1790  }
1791  }
1792  }
1793 
1794  private static void TratamientoEspecial_DepositosCompra(RegistroTabRel registro, OfflineDatosComunicaciones datos)
1795  {
1796  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
1797  // para que enviemos la modificación de datos del documento origen.
1798  if (!registro._Sobreescribir && registro._DBPrincipal == "GESTION")
1799  {
1800  DataTable ldtDatosRelacionados = new DataTable();
1801  string lcSql = string.Empty;
1802 
1803  // buscar documento asociado a la linea del albarán
1804  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1805  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_DEPCOM" + registro._Sufijo + "]" +
1806  " WHERE DOC = 1 ";
1807  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1808 
1809  foreach (DataRow item in ldtDatosRelacionados.Rows)
1810  {
1811  DataTable ldtDatos = new DataTable();
1812  lcSql = " SELECT * " +
1813  " FROM " + DB.SQLDatabase("GESTION", "C_PEDICO") +
1814  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1815  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num"));
1816  DB.SQLExec(lcSql, ref ldtDatos);
1817 
1818  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1819  {
1820  ComprobarTablaTemporalSQL(registro, "GESTION", "C_PEDICO", "_ESPECIAL");
1821 
1822  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PEDICO" + "_ESPECIAL" + "]");
1823  }
1824 
1825  lcSql = " SELECT * " +
1826  " FROM " + DB.SQLDatabase("GESTION", "D_PEDICO") +
1827  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1828  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num")) +
1829  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1830 
1831  DB.SQLExec(lcSql, ref ldtDatos);
1832 
1833  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1834  {
1835  ComprobarTablaTemporalSQL(registro, "GESTION", "D_PEDICO", "_ESPECIAL");
1836 
1837  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PEDICO" + "_ESPECIAL" + "]");
1838  }
1839  }
1840 
1841  // buscar documento asociado a la linea del albarán
1842  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1843  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_DEPCOM" + registro._Sufijo + "]" +
1844  " WHERE DOC = 3 ";
1845  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1846 
1847  foreach (DataRow item in ldtDatosRelacionados.Rows)
1848  {
1849  DataTable ldtDatos = new DataTable();
1850  lcSql = " SELECT * " +
1851  " FROM " + DB.SQLDatabase("GESTION", "C_DEPCOM") +
1852  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1853  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num"));
1854  DB.SQLExec(lcSql, ref ldtDatos);
1855 
1856  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1857  {
1858  ComprobarTablaTemporalSQL(registro, "GESTION", "C_DEPCOM", "_ESPECIAL");
1859 
1860  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_DEPCOM" + "_ESPECIAL" + "]");
1861  }
1862 
1863  lcSql = " SELECT * " +
1864  " FROM " + DB.SQLDatabase("GESTION", "D_DEPCOM") +
1865  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1866  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num")) +
1867  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1868 
1869  DB.SQLExec(lcSql, ref ldtDatos);
1870 
1871  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1872  {
1873  ComprobarTablaTemporalSQL(registro, "GESTION", "D_DEPCOM", "_ESPECIAL");
1874 
1875  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_DEPCOM" + "_ESPECIAL" + "]");
1876  }
1877  }
1878  }
1879  }
1880 
1881 
1882  private static void TratamientoEspecial_AlbaranesVenta(RegistroTabRel registro, OfflineDatosComunicaciones datos)
1883  {
1884  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
1885  // para que enviemos la modificación de datos del documento origen.
1886  if (!registro._Sobreescribir && registro._DBSecundaria == "GESTION")
1887  {
1888  DataTable ldtDatosRelacionados = new DataTable();
1889  string lcSql = string.Empty;
1890 
1891  // buscar documento asociado a la linea del albarán
1892  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1893  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_ALBVEN" + registro._Sufijo + "]" +
1894  " WHERE DOC = 1 ";
1895  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1896 
1897  foreach (DataRow item in ldtDatosRelacionados.Rows)
1898  {
1899  DataTable ldtDatos = new DataTable();
1900  lcSql = " SELECT * " +
1901  " FROM " + DB.SQLDatabase("GESTION", "C_PEDIVE") +
1902  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1903  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num"));
1904  DB.SQLExec(lcSql, ref ldtDatos);
1905 
1906  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1907  {
1908  ComprobarTablaTemporalSQL(registro, "GESTION", "C_PEDIVE", "_ESPECIAL");
1909 
1910  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PEDIVE" + "_ESPECIAL" + "]");
1911  }
1912 
1913  lcSql = " SELECT * " +
1914  " FROM " + DB.SQLDatabase("GESTION", "D_PEDIVE") +
1915  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1916  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num")) +
1917  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1918 
1919  DB.SQLExec(lcSql, ref ldtDatos);
1920 
1921  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1922  {
1923  ComprobarTablaTemporalSQL(registro, "GESTION", "D_PEDIVE", "_ESPECIAL");
1924 
1925  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PEDIVE" + "_ESPECIAL" + "]");
1926  }
1927  }
1928 
1929  // buscar documento asociado a la linea del albarán
1930  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1931  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_ALBVEN" + registro._Sufijo + "]" +
1932  " WHERE DOC = 2 ";
1933  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1934 
1935  foreach (DataRow item in ldtDatosRelacionados.Rows)
1936  {
1937  DataTable ldtDatos = new DataTable();
1938  lcSql = " SELECT * " +
1939  " FROM " + DB.SQLDatabase("GESTION", "C_ALBDEP") +
1940  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1941  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num"));
1942  DB.SQLExec(lcSql, ref ldtDatos);
1943 
1944  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1945  {
1946  ComprobarTablaTemporalSQL(registro, "GESTION", "C_ALBDEP", "_ESPECIAL");
1947 
1948  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_ALBDEP" + "_ESPECIAL" + "]");
1949  }
1950 
1951  lcSql = " SELECT * " +
1952  " FROM " + DB.SQLDatabase("GESTION", "D_ALBDEP") +
1953  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1954  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num")) +
1955  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1956 
1957  DB.SQLExec(lcSql, ref ldtDatos);
1958 
1959  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1960  {
1961  ComprobarTablaTemporalSQL(registro, "GESTION", "D_ALBDEP", "_ESPECIAL");
1962 
1963  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_ALBDEP" + "_ESPECIAL" + "]");
1964  }
1965  }
1966 
1967  // buscar documento asociado a la linea del albarán
1968  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
1969  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_ALBVEN" + registro._Sufijo + "]" +
1970  " WHERE DOC = 3 ";
1971  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
1972 
1973  foreach (DataRow item in ldtDatosRelacionados.Rows)
1974  {
1975  DataTable ldtDatos = new DataTable();
1976  lcSql = " SELECT * " +
1977  " FROM " + DB.SQLDatabase("GESTION", "C_PRESUV") +
1978  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1979  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num"));
1980  DB.SQLExec(lcSql, ref ldtDatos);
1981 
1982  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1983  {
1984  ComprobarTablaTemporalSQL(registro, "GESTION", "C_PRESUV", "_ESPECIAL");
1985 
1986  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PRESUV" + "_ESPECIAL" + "]");
1987  }
1988 
1989  lcSql = " SELECT * " +
1990  " FROM " + DB.SQLDatabase("GESTION", "D_PRESUV") +
1991  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
1992  " AND NUMERO + LETRA = " + DB.SQLString(item.Field<string>("doc_num")) +
1993  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
1994 
1995  DB.SQLExec(lcSql, ref ldtDatos);
1996 
1997  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
1998  {
1999  ComprobarTablaTemporalSQL(registro, "GESTION", "D_PRESUV", "_ESPECIAL");
2000 
2001  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PRESUV" + "_ESPECIAL" + "]");
2002  }
2003  }
2004  }
2005  }
2006 
2007  private static void TratamientoEspecial_AlbaranesCompra(RegistroTabRel registro, OfflineDatosComunicaciones datos)
2008  {
2009  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
2010  // para que enviemos la modificación de datos del documento origen.
2011  if (!registro._Sobreescribir && registro._DBSecundaria == "GESTION")
2012  {
2013  DataTable ldtDatosRelacionados = new DataTable();
2014  string lcSql = string.Empty;
2015 
2016  // buscar documento asociado a la linea del albarán
2017  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
2018  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_ALBCOM" + registro._Sufijo + "]" +
2019  " WHERE DOC = 1 ";
2020  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
2021 
2022  foreach (DataRow item in ldtDatosRelacionados.Rows)
2023  {
2024  DataTable ldtDatos = new DataTable();
2025  lcSql = " SELECT * " +
2026  " FROM " + DB.SQLDatabase("GESTION", "C_PEDICO") +
2027  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2028  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num"));
2029  DB.SQLExec(lcSql, ref ldtDatos);
2030 
2031  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
2032  {
2033  ComprobarTablaTemporalSQL(registro, "GESTION", "C_PEDICO", "_ESPECIAL");
2034 
2035  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_PEDICO" + "_ESPECIAL" + "]");
2036  }
2037 
2038  lcSql = " SELECT * " +
2039  " FROM " + DB.SQLDatabase("GESTION", "D_PEDICO") +
2040  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2041  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num")) +
2042  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
2043 
2044  DB.SQLExec(lcSql, ref ldtDatos);
2045 
2046  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
2047  {
2048  ComprobarTablaTemporalSQL(registro, "GESTION", "D_PEDICO", "_ESPECIAL");
2049 
2050  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PEDICO" + "_ESPECIAL" + "]");
2051  }
2052  }
2053 
2054  // buscar documento asociado a la linea del albarán
2055  lcSql = " SELECT DISTINCT empresa, doc_num, doc_lin " +
2056  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[D_ALBCOM" + registro._Sufijo + "]" +
2057  " WHERE DOC = 3 ";
2058  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
2059 
2060  foreach (DataRow item in ldtDatosRelacionados.Rows)
2061  {
2062  DataTable ldtDatos = new DataTable();
2063  lcSql = " SELECT * " +
2064  " FROM " + DB.SQLDatabase("GESTION", "C_DEPCOM") +
2065  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2066  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num"));
2067  DB.SQLExec(lcSql, ref ldtDatos);
2068 
2069  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
2070  {
2071  ComprobarTablaTemporalSQL(registro, "GESTION", "C_DEPCOM", "_ESPECIAL");
2072 
2073  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_DEPCOM" + "_ESPECIAL" + "]");
2074  }
2075 
2076  lcSql = " SELECT * " +
2077  " FROM " + DB.SQLDatabase("GESTION", "D_DEPCOM") +
2078  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2079  " AND NUMERO = " + DB.SQLString(item.Field<string>("doc_num")) +
2080  " AND LINIA = " + DB.SQLString(item.Field<int>("doc_lin"));
2081 
2082  DB.SQLExec(lcSql, ref ldtDatos);
2083 
2084  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
2085  {
2086  ComprobarTablaTemporalSQL(registro, "GESTION", "D_DEPCOM", "_ESPECIAL");
2087 
2088  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_DEPCOM" + "_ESPECIAL" + "]");
2089  }
2090  }
2091  }
2092  }
2093 
2094  private static void TratamientoEspecial_FacturasVenta(RegistroTabRel registro, OfflineDatosComunicaciones datos)
2095  {
2096  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
2097  // para que enviemos la modificación de datos del documento origen.
2098  if (!registro._Sobreescribir && registro._DBPrincipal == "GESTION")
2099  {
2100  DataTable ldtDatosRelacionados = new DataTable();
2101  string lcSql = string.Empty;
2102 
2103  // buscar documento asociado a la linea del albarán
2104  lcSql = " SELECT DISTINCT empresa, numero " +
2105  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[C_FACTUVEN" + registro._Sufijo + "]";
2106  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
2107 
2108  foreach (DataRow item in ldtDatosRelacionados.Rows)
2109  {
2110  DataTable ldtDatos = new DataTable();
2111  lcSql = " SELECT * " +
2112  " FROM " + DB.SQLDatabase("GESTION", "C_ALBVEN") +
2113  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2114  " AND FACTURA = " + DB.SQLString(item.Field<string>("numero"));
2115  DB.SQLExec(lcSql, ref ldtDatos);
2116 
2117  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
2118  {
2119  ComprobarTablaTemporalSQL(registro, "GESTION", "C_ALBVEN", "_ESPECIAL");
2120 
2121  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_ALBVEN" + "_ESPECIAL" + "]");
2122  }
2123  }
2124  }
2125  }
2126 
2127  private static void TratamientoEspecial_FacturasCompra(RegistroTabRel registro, OfflineDatosComunicaciones datos)
2128  {
2129  // Se debe modificar el proceso de envío para realizar una excepción cuando se haga envío sin prioridad (solo enviamos datos nuevos)
2130  // para que enviemos la modificación de datos del documento origen.
2131  if (!registro._Sobreescribir && registro._DBPrincipal == "GESTION")
2132  {
2133  DataTable ldtDatosRelacionados = new DataTable();
2134  string lcSql = string.Empty;
2135 
2136  // buscar documento asociado a la linea del albarán
2137  lcSql = " SELECT DISTINCT empresa, proveedor, numero " +
2138  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].[dbo].[C_FACTUCOM" + registro._Sufijo + "]";
2139  DB.SQLExec(lcSql, ref ldtDatosRelacionados);
2140 
2141  foreach (DataRow item in ldtDatosRelacionados.Rows)
2142  {
2143  DataTable ldtDatos = new DataTable();
2144  lcSql = " SELECT * " +
2145  " FROM " + DB.SQLDatabase("GESTION", "C_ALBCOM") +
2146  " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2147  " AND PROVEEDOR = " + DB.SQLString(item.Field<string>("proveedor")) +
2148  " AND FACTURA = " + DB.SQLString(item.Field<string>("numero"));
2149  DB.SQLExec(lcSql, ref ldtDatos);
2150 
2151  if (ldtDatos != null && ldtDatos.Rows.Count > 0)
2152  {
2153  ComprobarTablaTemporalSQL(registro, "GESTION", "C_ALBCOM", "_ESPECIAL");
2154 
2155  InsertarDatosBulkMode(ldtDatos, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "C_ALBCOM" + "_ESPECIAL" + "]");
2156  }
2157  }
2158  }
2159  }
2160 
2161  private static void ComprobarTablaTemporalSQL(RegistroTabRel registro, string tcDb, string tcTable, string tcSufijo = "")
2162  {
2163  if (!clsOfflineUtils.ExisteDatabaseOffline(_cRaizDataBaseTemporal + tcDb))
2164  {
2165  CrearDataTable(tcDb, _cRaizDataBaseTemporal);
2166  }
2167 
2168  string lcSufijo = (!string.IsNullOrWhiteSpace(tcSufijo) ? tcSufijo : registro._Sufijo);
2169 
2170  if (!clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + tcDb + "].dbo.[" + tcTable + lcSufijo + "]"))
2171  {
2172  string lcSql = " Select * INTO [" + _cRaizDataBaseTemporal + tcDb + "].dbo.[" + tcTable + lcSufijo + "]" +
2173  " From " + DB.SQLDatabase(tcDb, tcTable) + " as A Where 1 = 2 ";
2174 
2175  // Executem la consulta
2176  DB.SQLExec(lcSql);
2177  }
2178  }
2179 
2180  private static void TratamientoEspecial_Compras(RegistroTabRel registro, OfflineDatosComunicaciones datos)
2181  {
2182  string lcSql;
2183  DataTable ldtDatosCompras = new DataTable();
2184 
2185  if (clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "]"))
2186  {
2187  ComprobarTablaTemporalSQL(registro, "COMUNES", "COMPRAS");
2188 
2189  // Montem la consulta per agafar les línies dels assentaments
2190  lcSql = " SELECT A.* " +
2191  " FROM " + DB.SQLDatabase("COMUNES", "COMPRAS") + " A " +
2192  " INNER JOIN [" + _cRaizDataBaseTemporal + registro._DBPrincipal + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "] B " +
2193  " ON A.SERIE = B." + registro._Compras;
2194 
2195  // Executem la consulta
2196  DB.SQLExec(lcSql, ref ldtDatosCompras);
2197 
2198  if (ldtDatosCompras != null && ldtDatosCompras.Rows.Count > 0)
2199  {
2200  InsertarDatosBulkMode(ldtDatosCompras, "[" + _cRaizDataBaseTemporal + "COMUNES].dbo.[COMPRAS" + registro._Sufijo + "]");
2201  }
2202  }
2203  }
2204 
2205  private static void TratamientoEspecial_Asientos(RegistroTabRel registro, OfflineDatosComunicaciones datos, bool tlForzar = false)
2206  {
2207  string lcSql;
2208  DataTable ldtDatosAsientos = new DataTable();
2209 
2210  ComprobarTablaTemporalSQL(registro, "GESTION", "ASIENTOS");
2211 
2212  // Montem la consulta per agafar les línies dels assentaments
2213  lcSql = " SELECT DISTINCT A.* " +
2214  " FROM " + DB.SQLDatabase("GESTION", "ASIENTOS") + " A " +
2215  " INNER JOIN [" + _cRaizDataBaseTemporal + "GESTION].dbo.[ASIENTOS" + registro._Sufijo + "] B " +
2216  " ON A.EMPRESA=B.EMPRESA And A.NUMERO=B.NUMERO ";
2217 
2218  // Executem la consulta
2219  DB.SQLExec(lcSql, ref ldtDatosAsientos);
2220 
2221  if (ldtDatosAsientos != null && ldtDatosAsientos.Rows.Count > 0)
2222  {
2223  DB.SQLExec("DELETE FROM [" + _cRaizDataBaseTemporal + "GESTION].dbo.[ASIENTOS" + registro._Sufijo + "] WHERE 1 = 1 ");
2224 
2225  InsertarDatosBulkMode(ldtDatosAsientos, "[" + _cRaizDataBaseTemporal + "GESTION].dbo.[ASIENTOS" + registro._Sufijo + "]");
2226 
2227  if (!clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + "CTRL_ASIEN" + registro._Sufijo + "]"))
2228  {
2229  if (!clsOfflineUtils.ExisteDatabaseOffline(_cRaizDataBaseTemporal + "OFFLINE"))
2230  {
2231  CrearDataTable("OFFLINE", _cRaizDataBaseTemporal);
2232  }
2233 
2234  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + "CTRL_ASIEN" + registro._Sufijo + "]" +
2235  " FROM [" + datos._BdOffline + "].dbo.[" + "CTRL_ASIEN" + "] WHERE 1 = 2";
2236 
2237  DB.SQLExec(lcSql);
2238  }
2239 
2240  // Actualizar tabla de control
2241  Actualizar_Tabla_Control(ldtDatosAsientos, "GESTION!ASIENTOS", "CTRL_ASIEN", registro._ID, datos);
2242 
2243  if (tlForzar)
2244  {
2245  string lcAny = EW_GLOBAL._GetVariable("wc_any").ToString();
2246  string lcSet = " Set ORIGEN = " + (datos._IsCentral ? DB.SQLString("CENTRAL") : DB.SQLString(datos._Sucursal)) + ", MODIFIED = " + DB.SQLString(DateTime.Now);
2247  string lcOrigen = (datos._IsCentral ? "CENTRAL" : datos._Sucursal);
2248 
2249  foreach (DataRow item in ldtDatosAsientos.Rows)
2250  {
2251  string lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2252  " AND NUMERO = " + DB.SQLString(item.Field<int>("numero")) +
2253  " AND LINEA = " + DB.SQLString(item.Field<int>("linea")) +
2254  " AND EJERCICIO = " + DB.SQLString(lcAny);
2255 
2256  string lcInsert = "(EMPRESA, NUMERO, LINEA, EJERCICIO, ORIGEN, IDTABREL, GUID_ID, CREATED, MODIFIED, VISTA) " +
2257  "Values(" +
2258  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<int>("numero")) + ", " + DB.SQLString(item.Field<int>("linea")) + ", " +
2259  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ", " + DB.SQLString(registro._ID) + ", NEWID(), GETDATE(), GETDATE(), cast(1 as bit))";
2260 
2261  ComprobarTablaTemporalSQL(registro, "OFFLINE", "CTRL_ASIEN");
2262 
2263  lcSql = " IF EXISTS " + Environment.NewLine +
2264  " ( SELECT NUMERO FROM [" + _cRaizDataBaseTemporal + "OFFLINE].dbo.[CTRL_ASIEN" + registro._Sufijo + "] " + lcWhere + " ) " + Environment.NewLine +
2265  " BEGIN " + Environment.NewLine +
2266  " Update [" + _cRaizDataBaseTemporal + "OFFLINE].dbo.[CTRL_ASIEN" + registro._Sufijo + "] " + lcSet + lcWhere + Environment.NewLine +
2267  " END " + Environment.NewLine +
2268  " ELSE " + Environment.NewLine +
2269  " BEGIN" + Environment.NewLine +
2270  "Insert Into [" + _cRaizDataBaseTemporal + "OFFLINE].dbo.[CTRL_ASIEN" + registro._Sufijo + "] " + lcInsert +
2271  " END ";
2272 
2273  DB.SQLExec(lcSql);
2274  }
2275  }
2276  }
2277 
2278  TratamientoEspecialTablas(registro);
2279  }
2280 
2281  private static void TratamientoEspecialTablas(RegistroTabRel registro)
2282  {
2283  // buscar ASI en las tablas relacionadas
2284  if (!string.IsNullOrWhiteSpace(registro._Otrasien))
2285  {
2286  TratamientoEspecial_ASI(registro, "OTRASIEN", registro._Otrasien);
2287  }
2288 
2289  if (!string.IsNullOrWhiteSpace(registro._Ivareper))
2290  {
2291  TratamientoEspecial_ASI(registro, "IVAREPER", registro._Ivareper);
2292  }
2293 
2294  if (!string.IsNullOrWhiteSpace(registro._Ivasopor))
2295  {
2296  TratamientoEspecial_ASI(registro, "IVASOPOR", registro._Ivasopor);
2297  }
2298 
2299  if (!string.IsNullOrWhiteSpace(registro._Iva_exen))
2300  {
2301  TratamientoEspecial_ASI(registro, "IVA_EXEN", registro._Iva_exen);
2302  }
2303 
2304  if (!string.IsNullOrWhiteSpace(registro._Retreper))
2305  {
2306  TratamientoEspecial_ASI(registro, "RETREPER", registro._Retreper);
2307  }
2308 
2309  if (!string.IsNullOrWhiteSpace(registro._Retsopor))
2310  {
2311  TratamientoEspecial_ASI(registro, "RETSOPOR", registro._Retsopor);
2312  }
2313 
2314  if (!string.IsNullOrWhiteSpace(registro._Eos))
2315  {
2316  TratamientoEspecial_ASI(registro, "EOS", registro._Eos);
2317  }
2318  }
2319 
2320  private static void ProcesoActualizarControlEspecial(RegistroTabRel registro, string tcTablaControl, OfflineDatosComunicaciones datos)
2321  {
2322  // Si la taula secundaria és ASIENTOS, hem d'agafar tots el registres de cada assentament.
2323  switch (tcTablaControl)
2324  {
2325  case "CTRL_ASIEN":
2326 
2327  DataTable ldtDatosAsientos = new DataTable();
2328  string lcSql = string.Empty;
2329 
2330  ComprobarTablaTemporalSQL(registro, "OFFLINE", tcTablaControl);
2331 
2332  // Montem la consulta per agafar les línies dels assentaments
2333  lcSql = " SELECT DISTINCT A.* " +
2334  " FROM " + DB.SQLDatabase("OFFLINE", tcTablaControl) + " A " +
2335  " INNER JOIN [" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + tcTablaControl + registro._Sufijo + "] B " +
2336  " ON A.EMPRESA=B.EMPRESA And A.NUMERO=B.NUMERO ";
2337 
2338  // Executem la consulta
2339  DB.SQLExec(lcSql, ref ldtDatosAsientos);
2340 
2341  if (ldtDatosAsientos != null && ldtDatosAsientos.Rows.Count > 0)
2342  {
2343  DB.SQLExec("DELETE FROM [" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + tcTablaControl + registro._Sufijo + "] WHERE 1 = 1 ");
2344 
2345  InsertarDatosBulkMode(ldtDatosAsientos, "[" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + tcTablaControl + registro._Sufijo + "]");
2346  }
2347 
2348  break;
2349 
2350  default:
2351 
2352  break;
2353 
2354 
2355  }
2356  }
2357 
2358  private static void TratamientoEspecial_ASI(RegistroTabRel registro, string tcTabla, string tcCampo)
2359  {
2360  DataTable ldtDatosASI = new DataTable();
2361  string lcSql = string.Empty;
2362 
2363  lcSql = " Select A.* " +
2364  " From " + DB.SQLDatabase("GESTION", tcTabla) + " as a " +
2365  " Inner Join ( Select a.empresa, a.asi " +
2366  " From " + DB.SQLDatabase("GESTION", "ASIENTOS") + " as a " +
2367  " Inner Join ( Select b.empresa, b.numero " +
2368  " From [" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo." + registro._TablaSecundaria + registro._Sufijo + " as a " +
2369  " Inner Join " + DB.SQLDatabase("GESTION", "ASIENTOS") + " b ON a.EMPRESA = b.EMPRESA And a." + tcCampo + " = b.ASI " +
2370  " ) b ON a.EMPRESA = b.EMPRESA And a.NUMERO = b.NUMERO " +
2371  " ) b ON a.EMPRESA = b.EMPRESA And a.ASI = b.ASI ";
2372 
2373 
2374  // Executem la consulta
2375  DB.SQLExec(lcSql, ref ldtDatosASI);
2376 
2377  if (ldtDatosASI != null && ldtDatosASI.Rows.Count > 0)
2378  {
2379  ComprobarTablaTemporalSQL(registro, "GESTION", tcTabla);
2380 
2381  InsertarDatosBulkMode(ldtDatosASI, "[" + _cRaizDataBaseTemporal + "GESTION].dbo.[" + tcTabla + registro._Sufijo + "]");
2382  }
2383  }
2384 
2385  private static void TratamientoEspecial_Previsiones(RegistroTabRel registro, OfflineDatosComunicaciones datos)
2386  {
2387  DataTable ldtDatosPrevisiones = new DataTable();
2388  string lcSql = string.Empty;
2389 
2390 
2391  lcSql = " Select DISTINCT A.* " +
2392  " From " + DB.SQLDatabase("GESTION", "ASIENTOS") + " as A " +
2393  " Where Exists ( " +
2394  " Select B.* " +
2395  " From [" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo." + registro._TablaSecundaria + registro._Sufijo + " as B " +
2396  " Where A.EMPRESA=B.EMPRESA And A.ASI=B.ASI )";
2397 
2398  // Executem la consulta
2399  DB.SQLExec(lcSql, ref ldtDatosPrevisiones);
2400 
2401  if (ldtDatosPrevisiones != null && ldtDatosPrevisiones.Rows.Count > 0)
2402  {
2403  ComprobarTablaTemporalSQL(registro, "GESTION", "ASIENTOS");
2404 
2405  InsertarDatosBulkMode(ldtDatosPrevisiones, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "ASIENTOS" + registro._Sufijo + "]");
2406 
2407  TratamientoEspecial_Asientos(registro, datos, true);
2408  }
2409 
2410 
2411  DataTable ldtDatosIva = new DataTable();
2412  string lcTabla = (registro._TablaSecundaria == "PREVIS" ? "IVASOPOR" : "IVAREPER");
2413 
2414  if (clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "GESTION].dbo.[" + lcTabla + registro._Sufijo + "]"))
2415  {
2416  lcSql = " Select A.* " +
2417  " From " + DB.SQLDatabase("GESTION", lcTabla) + " as A " +
2418  " Where Exists ( " +
2419  " Select B.* " +
2420  " From [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo." + lcTabla + registro._Sufijo + " as B " +
2421  " Where A.EMPRESA=B.EMPRESA And A.ASI = B.ASI )";
2422 
2423  // Executem la consulta
2424  DB.SQLExec(lcSql, ref ldtDatosIva);
2425 
2426  if (ldtDatosIva != null && ldtDatosIva.Rows.Count > 0)
2427  {
2428  ComprobarTablaTemporalSQL(registro, "GESTION", lcTabla);
2429 
2430  InsertarDatosBulkMode(ldtDatosIva, "[" + _cRaizDataBaseTemporal + "GESTION].dbo.[" + lcTabla + registro._Sufijo + "]");
2431  }
2432  }
2433  }
2434 
2435  private static void TratamientoEspecial_CriterioCaja(RegistroTabRel registro, OfflineDatosComunicaciones datos)
2436  {
2437  TratamientoEspecial_CriterioCaja(registro, datos, "ASI");
2438  TratamientoEspecial_CriterioCaja(registro, datos, "ASI_IVA");
2439  TratamientoEspecial_CriterioCaja(registro, datos, "ASIRECC");
2440  }
2441 
2442  private static void TratamientoEspecial_CriterioCaja(RegistroTabRel registro, OfflineDatosComunicaciones datos, string lcCampo)
2443  {
2444  DataTable ldtDatosPrevisiones = new DataTable();
2445  string lcSql = string.Empty;
2446 
2447  lcSql = " Select DISTINCT A.* " +
2448  " From " + DB.SQLDatabase("GESTION", "ASIENTOS") + " as A " +
2449  " Where Exists ( " +
2450  " Select B.* " +
2451  " From [" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo." + registro._TablaSecundaria + registro._Sufijo + " as B " +
2452  " Where A.EMPRESA=B.EMPRESA And A.ASI=B." + lcCampo + " )";
2453 
2454  // Executem la consulta
2455  DB.SQLExec(lcSql, ref ldtDatosPrevisiones);
2456 
2457  if (ldtDatosPrevisiones != null && ldtDatosPrevisiones.Rows.Count > 0)
2458  {
2459  ComprobarTablaTemporalSQL(registro, "GESTION", "ASIENTOS");
2460 
2461  InsertarDatosBulkMode(ldtDatosPrevisiones, "[" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "ASIENTOS" + registro._Sufijo + "]");
2462 
2463  TratamientoEspecial_Asientos(registro, datos, true);
2464  }
2465  }
2466 
2467  private static void CrearDataTable(string tcDB, string tcArrelDB)
2468  {
2469  string lcDataBaseTemp = tcArrelDB + tcDB;
2470 
2471  DB._DBCreate(lcDataBaseTemp);
2472  }
2473 
2474  private static void CrearDataTable(string tcDB, string tcArrelDB, RegistroTabRel registro)
2475  {
2476  string lcDataBaseTemp = tcArrelDB + tcDB;
2477  string lcRutaTemp = Path.Combine(TempFolderName, tcDB);
2478 
2479  DB._DBCreate(lcDataBaseTemp);
2480 
2481  string lcBdReal = clsOfflineUtils.ObtenerNombreBdReal(registro._DBSecundaria);
2482 
2483  // tinc que comprovar si existeix
2484  if (Directory.Exists(lcRutaTemp))
2485  {
2486  DB._DBCreate(lcDataBaseTemp);
2487 
2488  DB.SQLExec("DROP TABLE IF EXISTS [" + lcDataBaseTemp + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "]");
2489 
2490 
2491  DB.SQLExec("SELECT * INTO [" + lcDataBaseTemp + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "]" +
2492  " FROM [" + lcBdReal + "].dbo.[" + registro._TablaSecundaria + "] WHERE 1 = 2");
2493  }
2494  }
2495 
2496  private static void InsertarTablaBaseDatosBulk(string tcDB, string tcArrelDB, RegistroTabRel registro, DataTable dtDatos)
2497  {
2498  string lcDataBaseTemp = tcArrelDB + tcDB;
2499  string lcRutaTemp = Path.Combine(TempFolderName, tcDB);
2500 
2501  // tinc que comprovar si existeix
2502  if (Directory.Exists(lcRutaTemp))
2503  {
2504  //Inertamos con BulkCopy
2505  using (System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(DB.Conexion))
2506  {
2507  bulkCopy.DestinationTableName = "[" + lcDataBaseTemp + "].dbo.["+ registro._TablaSecundaria + registro._Sufijo + "]";
2508 
2509  // Write from the source to the destination.
2510  bulkCopy.WriteToServer(dtDatos);
2511  }
2512  }
2513  }
2514 
2515  private static void GestionarXML_TablasTemporales(Dictionary<string, DataTable> dicTablas, OfflineDatosComunicaciones datos, string lcBd, ILog_comoffRepository logRepository)
2516  {
2517  _TextStepDetalle = "Generando ficheros XML adicionales";
2518  _TextStepProgreso = _TextStepDetalle;
2519  _PorcenProgreso = IncrementarBarraProgreso();
2520 
2521  foreach (KeyValuePair<string, DataTable> tabla in dicTablas)
2522  {
2523  if (tabla.Value != null && tabla.Value.Rows.Count > 0)
2524  {
2525  // Convertir el datatable en XML
2526  ConvertIndividualFile(tabla.Value, Path.Combine(datos._PathFolderInicial), tabla.Key, FormatoExportacion.XML);
2527 
2528  Log_comoffDto logDto = logRepository.GetDto(datos);
2529  logDto.TipoDato = "01";
2530  logDto.Resultado = 1;
2531 
2532  if (tabla.Key.Contains("DELETENET"))
2533  {
2534  tabla.Value.DefaultView.Sort = "tabla ASC";
2535  DataTable ldtAux = tabla.Value.DefaultView.ToTable();
2536 
2537  // Gestionar XML de la tabla DELETENET
2538  if (ldtAux.Rows.Count > 0)
2539  {
2540  List<string> lsTabla = new List<string>();
2541 
2542  foreach (DataRow row in ldtAux.Rows)
2543  {
2544  if (!lsTabla.Contains(row["tabla"]))
2545  {
2546  DataRow[] dtRow = ldtAux.Select("tabla =" + DB.SQLString(row["tabla"]));
2547  if (dtRow.Length > 0)
2548  {
2549  logDto.Detalle = "Se han eliminado " + dtRow.Length + " registros en la tabla " + row["tabla"].ToString().Trim() + ". " + Environment.NewLine +
2550  "Dichas eliminaciones se corresponden con datos eliminados en el grupo de empresa origen de los datos.";
2551  logRepository.Insert(logDto);
2552 
2553  lsTabla.Add(row["tabla"].ToString());
2554  }
2555  }
2556  }
2557  }
2558  }
2559  else
2560  {
2561  logDto.Detalle = "Se han incluido datos nuevos en el fichero de comunicaciones. (" + tabla.Key + ")";
2562  logRepository.Insert(logDto);
2563  }
2564  }
2565  }
2566  }
2567 
2577  private static void TratamientoEspecial_EnvioAsientos(RegistroTabRel registro, DataRow itemRow, DataRow row, ref DataTable dtAsientos, ref DataTable dtOtrasien, ref DataTable dtEos)
2578  {
2579  string lcValueAsientos = string.Empty;
2580  string lcValueOtrasien = string.Empty;
2581  string lcValueEos = string.Empty;
2582  string lcSql = string.Empty;
2583  Dictionary<string, string> dcValue = new Dictionary<string, string>();
2584 
2585  switch (registro._Clave)
2586  {
2587  case "C_PRESUV":
2588  case "C_PEDIVE":
2589  case "C_ALBDEP":
2590  case "C_ALBVEN":
2591  case "FACTURAS":
2592  case "C_PEDICO":
2593  case "C_DEPCOM":
2594  case "C_ALBCOM":
2595  case "FACTURAC":
2596  case "C_TRANSDUA":
2597  if (registro._Asientos != "")
2598  {
2599  if (!string.IsNullOrEmpty(itemRow["asientos"].ToString().Trim()))
2600  {
2601  dcValue.Add("Asientos", itemRow["asientos"].ToString().Trim());
2602 
2603  RegistroEspecial_Asientos_Envio(dcValue, "ASIENTOS", row, ref dtAsientos, "Asientos");
2604  }
2605  }
2606  if (registro._Otrasien != "")
2607  {
2608  if (!string.IsNullOrEmpty(itemRow["otrasien"].ToString().Trim()))
2609  {
2610  dcValue.Add("Otrasien", itemRow["otrasien"].ToString().Trim());
2611 
2612  RegistroEspecial_Asientos_Envio(dcValue, "ASIENTOS", row, ref dtOtrasien, "Otrasien");
2613  }
2614  }
2615  if (registro._Eos != "")
2616  {
2617  if (!string.IsNullOrEmpty(itemRow["eos"].ToString().Trim()))
2618  {
2619  dcValue.Add("Eos", itemRow["eos"].ToString().Trim());
2620 
2621  RegistroEspecial_Asientos_Envio(dcValue, "ASIENTOS", row, ref dtEos, "Eos");
2622  }
2623  }
2624 
2625  break;
2626  }
2627  }
2628 
2637  private static void RegistroEspecial_Asientos_Envio(Dictionary<string,string> dcValue, string lcTabla, DataRow row, ref DataTable dtTabla, string lcBusqueda)
2638  {
2639  DataTable dtTemp = new DataTable();
2640  DataTable dtDatos = new DataTable();
2641 
2642  string Value = dcValue.FirstOrDefault(x => x.Key == lcBusqueda).Value;
2643 
2644  if (!string.IsNullOrEmpty(Value))
2645  {
2646  // preparo la taula secundaria
2647  string lcSql = "SELECT * FROM " + DB.SQLDatabase("GESTION", lcTabla) + " WHERE " + Value + " = " + DB.SQLString(row[Value]);
2648 
2649  DB.SQLExec(lcSql, ref dtTemp);
2650 
2651  foreach (DataRow loRow in dtTemp.Rows)
2652  {
2653  lcSql = "SELECT * FROM " + DB.SQLDatabase("GESTION", lcTabla) + " WHERE NUMERO = " + DB.SQLString(loRow["numero"]) + " AND EMPRESA = " + DB.SQLString(loRow["empresa"]);
2654 
2655  DB.SQLExec(lcSql, ref dtDatos);
2656 
2657  string lcValue = string.Empty;
2658  foreach (DataRow item in dtDatos.Rows)
2659  {
2660  dtTabla.ImportRow(item);
2661  }
2662  }
2663  }
2664  }
2665 
2674  private static void RegistroEspecial_OtrasienEos_Envio(string value, string lcTabla, DataRow row, ref DataTable dtTabla, DataRow loRow)
2675  {
2676  DataTable dtDatos = new DataTable();
2677 
2678  string lcSql = "SELECT * FROM " + DB.SQLDatabase("GESTION", lcTabla) + " WHERE ASI = " + DB.SQLString(loRow["asi"]) + " AND EMPRESA = " + DB.SQLString(loRow["empresa"]);
2679 
2680  DB.SQLExec(lcSql, ref dtDatos);
2681 
2682  foreach (DataRow item in dtDatos.Rows)
2683  {
2684  dtTabla.ImportRow(item);
2685  }
2686  }
2687 
2688  private static void RegistroDatosEspecial(OfflineDatosComunicaciones datos, string tcTabla, DataTable ldtDatos, ILog_comoffRepository logRepository)
2689  {
2690  string lcDetalle = string.Empty;
2691 
2692  if (ldtDatos.TableName.Contains("_MODIFIED"))
2693  {
2694  lcDetalle = "Se han incluido los siguientes datos modificados en el fichero de comunicaciones. Dato: " + tcTabla + Environment.NewLine;
2695  }
2696  else
2697  {
2698  lcDetalle = "Se han incluido los siguientes datos nuevos en el fichero de comunicaciones. Dato: " + tcTabla + Environment.NewLine;
2699  }
2700 
2701 
2702  lcDetalle += ConstruirTextoDetalle(ldtDatos, "numero", "ASIENTOS", "GESTION");
2703 
2704  Log_comoffDto logDto = logRepository.GetDto(datos);
2705  logDto.TipoDato = "02";
2706  logDto.Resultado = 1;
2707  logDto.Detalle = lcDetalle;
2708  logRepository.Insert(logDto);
2709  }
2710 
2711  private static void TratamientoEspecial_EnvioFabricacion(RegistroTabRel registro, OfflineDatosComunicaciones datos)
2712  {
2713  string lcSql = string.Empty;
2714 
2715  // Obtenir nom real de la bd
2716  string lcBdReal = clsOfflineUtils.ObtenerNombreBdReal(registro._DBSecundaria);
2717 
2718  //Si son partes de costes sin asignar, se deben eliminar las lineas que estan relacionados con documentos
2719  if (registro._TablaSecundaria == "D_PARTES")
2720  {
2721  lcSql = " SELECT a.* INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[_COSTES_C_PARTES" + registro._Sufijo + "]" +
2722  " FROM [" + lcBdReal + "].dbo.C_PARTES a " +
2723  " INNER JOIN ( " +
2724  " SELECT DISTINCT empresa, numero " +
2725  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + registro._Sufijo + "] " +
2726  " WHERE albaran = 0 " +
2727  " ) b ON a.empresa = b.empresa AND a.numero = b.numero ";
2728  DB.SQLExec(lcSql);
2729 
2730  lcSql = " SELECT * INTO [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[_COSTES_D_PARTES" + registro._Sufijo + "]" +
2731  " FROM [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + "D_PARTES" + registro._Sufijo + "] WHERE albaran = 0 ";
2732  DB.SQLExec(lcSql);
2733  }
2734  else
2735  {
2736  string[] filesTablas = new string[] { "D_PARTES", "C_PARTES" };
2737  DataTable table = new DataTable();
2738 
2739  foreach (string file in filesTablas)
2740  {
2741  ComprobarTablaTemporalSQL(registro, "GESTION", file);
2742 
2743  int tipo_alb = (registro._TablaSecundaria == "D_PROD" ? 1 : 2);
2744 
2745  if (file == "D_PARTES")
2746  {
2747  lcSql = " FROM [" + lcBdReal + "].dbo.[D_PARTES] as A " +
2748  " INNER JOIN [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "] as B " +
2749  " ON A.EMPRESA = B.EMPRESA AND A.ALBARAN = B.NUMERO AND A.LINEA = B.LINEA AND A.TIPO_ALB = " + tipo_alb;
2750  }
2751  else
2752  {
2753  lcSql = " FROM [" + lcBdReal + "].dbo.C_PARTES a " +
2754  " INNER JOIN ( SELECT DISTINCT A.EMPRESA, A.NUMERO " +
2755  " FROM [" + lcBdReal + "].dbo.[D_PARTES] as A " +
2756  " INNER JOIN [" + _cRaizDataBaseTemporal + "GESTION" + "].dbo.[" + registro._TablaSecundaria + registro._Sufijo + "] as B " +
2757  " ON A.EMPRESA = B.EMPRESA AND A.ALBARAN = B.NUMERO AND A.LINEA = B.LINEA AND A.TIPO_ALB = " + tipo_alb +
2758  " ) b on A.EMPRESA = B.EMPRESA And A.NUMERO = B.NUMERO ";
2759  }
2760 
2761  DB.SQLExec(" SELECT a.* " + lcSql, ref table);
2762 
2763  if (table != null & table.Rows.Count > 0)
2764  {
2765  DB.SQLExec(" SELECT A.* INTO [" + _cRaizDataBaseTemporal + registro._DBSecundaria + "].dbo.[_PARTES" + tipo_alb + "_" + file + registro._Sufijo + "] " + lcSql);
2766 
2767  // Actualizar tabla de control
2768  if (file == "D_PARTES")
2769  {
2770  Actualizar_Tabla_Control(table, "GESTION!D_PARTES", "CTRL_PARCO", registro._ID, datos);
2771 
2772  string lcAny = EW_GLOBAL._GetVariable("wc_any").ToString();
2773  string lcSet = " Set ORIGEN = " + (datos._IsCentral ? DB.SQLString("CENTRAL") : DB.SQLString(datos._Sucursal)) + ", MODIFIED = " + DB.SQLString(DateTime.Now);
2774  string lcOrigen = (datos._IsCentral ? "CENTRAL" : datos._Sucursal);
2775 
2776  foreach (DataRow item in table.Rows)
2777  {
2778  string lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
2779  " AND NUMERO = " + DB.SQLString(item.Field<string>("numero")) +
2780  " AND LINIA = " + DB.SQLString(item.Field<int>("linea")) +
2781  " AND EJERCICIO = " + DB.SQLString(lcAny);
2782 
2783  string lcInsert = "(EMPRESA, NUMERO, LINIA, ORIGEN, EJERCICIO, GUID_ID, CREATED, MODIFIED, VISTA, IDTABREL) " +
2784  "Values(" +
2785  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " + DB.SQLString(item.Field<int>("linea")) + ", " +
2786  DB.SQLString(lcOrigen) + ", " + DB.SQLString(lcAny) + ", NEWID(), GETDATE(), GETDATE(), cast(1 as bit), 0)";
2787 
2788  ComprobarTablaTemporalSQL(registro, "OFFLINE", "CTRL_PARCO");
2789 
2790  lcSql = " IF EXISTS " + Environment.NewLine +
2791  " ( SELECT NUMERO FROM [" + _cRaizDataBaseTemporal + "OFFLINE].dbo.[CTRL_PARCO" + registro._Sufijo + "] " + lcWhere + " ) " + Environment.NewLine +
2792  " BEGIN " + Environment.NewLine +
2793  " Update [" + _cRaizDataBaseTemporal + "OFFLINE].dbo.[CTRL_PARCO" + registro._Sufijo + "] " + lcSet + lcWhere + Environment.NewLine +
2794  " END " + Environment.NewLine +
2795  " ELSE " + Environment.NewLine +
2796  " BEGIN" + Environment.NewLine +
2797  "Insert Into [" + _cRaizDataBaseTemporal + "OFFLINE].dbo.[CTRL_PARCO" + registro._Sufijo + "] " + lcInsert +
2798  " END ";
2799 
2800  DB.SQLExec(lcSql);
2801  }
2802  }
2803  }
2804  }
2805  }
2806  }
2807 
2808  private static void RegistroDatos(OfflineDatosComunicaciones datos, DataRow registro, string tcBdReal, string tbDB, string tcTabla, DataTable tdtDatos, string lcSufijo, ILog_comoffRepository logRepository)
2809  {
2810  string lcDetalle = string.Empty;
2811  string lcCampo = string.Empty;
2812 
2813  List<string> lista = new List<string>();
2814 
2815 
2816  if (lcSufijo.Contains("_MODIFIED"))
2817  {
2818  lcDetalle = "Se han incluido los siguientes datos modificados en el fichero de comunicaciones. " + Environment.NewLine;
2819  }
2820  else
2821  {
2822  lcDetalle = "Se han incluido los siguientes datos nuevos en el fichero de comunicaciones. " + Environment.NewLine;
2823  }
2824 
2825  lcDetalle += "Dato: " + (tcTabla.Contains("CTRL_") ? "Información extendida de " : "") + registro.Field<string>("titulo").TrimEnd().ToUpper() + Environment.NewLine + Environment.NewLine;
2826 
2827  int nId = registro.Field<int>("id");
2828  string cClave = registro.Field<string>("clave");
2829 
2830  switch (tcTabla)
2831  {
2832  case "BARRAS":
2833  case "IDI_ART":
2834  case "OFERTAS":
2835  case "PVP":
2836  case "REFERPRO":
2837  case "PVPCOL":
2838  case "ART_COLO":
2839  case "ART_TALL":
2840  case "ESCANDAL":
2841  case "FACTORPTOS":
2842  case "ART_FOTO":
2843  case "ARTLOT":
2844  case "BAREAN":
2845  case "COSTELOT":
2846  case "STOALMMM":
2847  case "EAN_PESO":
2848  case "ART_REST":
2849  case "ART_REG":
2850  case "CMBPVP":
2851 
2852  case "CTRL_OFER":
2853 
2854  lcDetalle += ConstruirTextoDetalle(tdtDatos, "articulo", "ARTICULO", "GESTION");
2855  break;
2856 
2857  case "DESC_FAM":
2858 
2859  lcDetalle += ConstruirTextoDetalle(tdtDatos, "familia", "ARTICULO", "GESTION");
2860  break;
2861 
2862  case "MULTICAM":
2863  case "VALMULTI":
2864  lcDetalle += ConstruirTextoDetalle(tdtDatos, "codigo", "MCAMPOS", "GESTION");
2865  break;
2866 
2867  case "DESC_SUB":
2868 
2869  lcDetalle += ConstruirTextoDetalle(tdtDatos, "subfam", "SUBFAM", "GESTION");
2870  break;
2871 
2872  case "TALLGRUP":
2873 
2874  lcDetalle += ConstruirTextoDetalle(tdtDatos, "talla", "TALLAS", "COMUNES");
2875  break;
2876 
2877  case "COLOGRUP":
2878 
2879  lcDetalle += ConstruirTextoDetalle(tdtDatos, "color", "COLORES", "COMUNES");
2880  break;
2881 
2882  case "COMPRAS":
2883  case "STOCKS2":
2884  case "STOCKLOTES":
2885  case "STOCKS":
2886  case "STOCKINI":
2887  case "ALMA_ANALI":
2888  case "INICIALSER":
2889  case "LTSTINI":
2890  case "CTRL_STINI":
2891  case "REGULARI":
2892  case "LTREGUL":
2893  case "REGULARISER":
2894  case "CTRL_REGUL":
2895 
2896  lcDetalle += ConstruirTextoDetalle(tdtDatos, "almacen", "ALMACEN", "GESTION");
2897  break;
2898 
2899  case "HISSERIE":
2900  switch (cClave)
2901  {
2902  case "STOCKINI":
2903 
2904  lcDetalle += ConstruirTextoDetalle(tdtDatos, "almacen", "ALMACEN", "GESTION");
2905  break;
2906 
2907  case "C_ALBARE":
2908  case "C_ALBATR":
2909  case "PEDINT_C":
2910  case "C_ALBCOM":
2911  case "C_DEPCOM":
2912  case "C_PROD":
2913  case "C_TRANS":
2914 
2915  ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "numero", "", "numero");
2916  break;
2917 
2918  case "C_ALBVEN":
2919  case "C_ALBDEP":
2920 
2921  ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "letra", "numero", "numero");
2922  break;
2923 
2924  case "REGULARI":
2925 
2926  ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "documento", "", "documento");
2927  break;
2928  }
2929  break;
2930 
2931  case "C_FORMUL":
2932  case "D_FORMUL":
2933  case "CTRL_FORMU":
2934 
2935  lcCampo = (tcTabla == "D_FORMUL" ? "formula" : "articulo");
2936  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "C_FORMUL", "LOTES", "ARTICULO");
2937  break;
2938 
2939  case "ART_CLASIF":
2940  case "CTRL_CLASI":
2941 
2942  lcCampo = (tcTabla == "ART_CLASIF" ? "clasif" : "codigo");
2943  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLASIF", "COMUNES");
2944  break;
2945 
2946  case "DESCUEN":
2947  case "ACTI_CLI":
2948  case "BANC_CLI":
2949  case "CONT_CLI":
2950  case "ENV_CLI":
2951  case "GIRO_CLI":
2952  case "TELF_CLI":
2953  case "VACA_CLI":
2954  case "CLITARJFID":
2955  case "MANDATOS":
2956  //case "MANDEMP":
2957  case "CONTLF_CLI":
2958  case "RIESGO":
2959 
2960  lcCampo = (tcTabla == "RIESGO" ? "codigo" : "cliente");
2961  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
2962  break;
2963 
2964  case "TCPS":
2965 
2966  lcDetalle += ConstruirTextoDetalle(tdtDatos, "tcp", "TCP", "COMUNES");
2967  break;
2968 
2969  case "OTRAS":
2970  case "GIRO_CUE":
2971  case "BANC_CUE":
2972 
2973  lcCampo = (tcTabla == "OTRAS" ? "codigo" : "cuenta");
2974  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CUENTAS", "GESTION");
2975  break;
2976 
2977  case "TELF_PRO":
2978  case "GIRO_PRO":
2979  case "CONT_PRO":
2980  case "ACTI_PRO":
2981  case "ENV_PRO":
2982  case "VACA_PRO":
2983  case "BANC_PRO":
2984  case "CONTLF_PRO":
2985  case "DESC_PRO":
2986 
2987  lcCampo = (tcTabla == "DESC_PRO" ? "proveed" : "proveedor");
2988  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "PROVEED", "GESTION");
2989  break;
2990 
2991  case "ENTRE_CL":
2992 
2993  switch (nId)
2994  {
2995  case 113:
2996  // Entregas a cuenta de cliente
2997  lcCampo = (tcTabla == "ENTRE_CL" || tcTabla == "PREVI_CL" ? "cliente" : "cuenta");
2998  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
2999  break;
3000 
3001  case 318:
3002  // Entregas a cuenta de proveedor
3003  lcCampo = (tcTabla == "ENTRE_CL" ? "cliente" : (tcTabla == "PREVIS" ? "proveedor" : "cuenta"));
3004  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "PROVEED", "GESTION");
3005  break;
3006  }
3007 
3008  break;
3009 
3010  case "EOS":
3011  switch (nId)
3012  {
3013  case 68: // Facturas de venta
3014  case 301: // TPV con arqueo
3015  case 326: // TPV sin arqueo
3016 
3017  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "factura");
3018  break;
3019 
3020  case 113:
3021  // Entregas a cuenta de cliente
3022  lcCampo = (tcTabla == "ENTRE_CL" || tcTabla == "PREVI_CL" ? "cliente" : "cuenta");
3023  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
3024  break;
3025 
3026  case 318:
3027  // Entregas a cuenta de proveedor
3028  lcCampo = (tcTabla == "ENTRE_CL" ? "cliente" : (tcTabla == "PREVIS" ? "proveedor" : "cuenta"));
3029  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "PROVEED", "GESTION");
3030  break;
3031 
3032  case 216:
3033  // Facturas de compra
3034  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "cuenta", "factura");
3035 
3036  break;
3037  }
3038 
3039  break;
3040 
3041  case "IVAREPER":
3042 
3043  switch (nId)
3044  {
3045  case 69: // Facturas de venta
3046  case 302: // TPV con arqueo
3047  case 327: // TPV sin arqueo
3048  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "numfra");
3049  break;
3050 
3051  case 113:
3052  // Entregas a cuenta de cliente
3053  lcCampo = (tcTabla == "ENTRE_CL" || tcTabla == "PREVI_CL" ? "cliente" : "cuenta");
3054  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
3055  break;
3056 
3057  case 318:
3058  // Entregas a cuenta de proveedor
3059  lcCampo = (tcTabla == "ENTRE_CL" ? "cliente" : (tcTabla == "PREVIS" ? "proveedor" : "cuenta"));
3060  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "PROVEED", "GESTION");
3061  break;
3062 
3063  case 344:
3064  // Facturas de compra
3065  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "cuenta", "numfra");
3066  break;
3067  }
3068 
3069  break;
3070 
3071  case "IVASOPOR":
3072 
3073  switch (nId)
3074  {
3075  case 318:
3076  // Entregas a cuenta de proveedor
3077  lcDetalle += ConstruirTextoDetalle(tdtDatos, "cuenta", "PROVEED", "GESTION");
3078  break;
3079 
3080  case 217:
3081  // Facturas de compra
3082  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "cuenta", "numfra");
3083  break;
3084  }
3085 
3086  break;
3087 
3088  case "IVA_EXEN":
3089 
3090  switch (nId)
3091  {
3092  case 276: // Facturas de venta
3093  case 308: // TPV con arqueo
3094  case 333: // TPV sin arqueo
3095 
3096  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "factura");
3097  break;
3098 
3099  case 113:
3100  // Entregas a cuenta de cliente
3101  lcDetalle += ConstruirTextoDetalle(tdtDatos, "cuenta", "CLIENTES", "GESTION");
3102  break;
3103 
3104  case 318:
3105  // Entregas a cuenta de proveedor
3106  lcDetalle += ConstruirTextoDetalle(tdtDatos, "cuenta", "PROVEED", "GESTION");
3107  break;
3108 
3109  case 277:
3110  // Facturas de compra
3111  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "cuenta", "factura");
3112 
3113  break;
3114  }
3115 
3116  break;
3117 
3118  case "RETREPER":
3119  // Factura de compra
3120  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "numfra");
3121 
3122  break;
3123 
3124  case "RETSOPOR":
3125 
3126  switch (nId)
3127  {
3128  case 393: // Facturas de venta
3129  case 395: // TPV con arqueo
3130  case 396: // TPV sin arqueo
3131 
3132  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "numfra");
3133  break;
3134  }
3135 
3136  break;
3137 
3138  case "PREVI_CL":
3139  case "CTRL_PREVV":
3140 
3141  switch (nId)
3142  {
3143  case 67: // Facturas de venta
3144  case 300: // TPV con arqueo
3145  case 325: // TPV sin arqueo
3146  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "factura");
3147  break;
3148 
3149  case 360:
3150  // Entregas a cuenta de cliente
3151  lcDetalle += ConstruirTextoDetalle(tdtDatos, "cliente", "CLIENTES", "GESTION");
3152  break;
3153  }
3154 
3155  break;
3156 
3157  case "PREVIS":
3158  case "CTRL_PREVC":
3159 
3160  switch (nId)
3161  {
3162  case 361:
3163  // Entregas a cuenta de proveedor
3164  lcDetalle += ConstruirTextoDetalle(tdtDatos, "proveedor", "PROVEED", "GESTION");
3165  break;
3166 
3167  case 245:
3168  // Facturas de compra
3169  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "proveedor", "factura");
3170  break;
3171  }
3172 
3173  break;
3174 
3175  case "CTRL_ASIEN":
3176 
3177  lcDetalle += tdtDatos.Rows.Count.ToString() + " registros.";
3178  break;
3179 
3180  case "ASIENTOS":
3181  case "OTRASIEN":
3182  //case "CTRL_ASIEN":
3183 
3184  switch (nId)
3185  {
3186  case 336:
3187  // Presupuestos de venta
3188  lcCampo = (tcTabla == "OTRASIEN" ? "codcuen" : "cuenta");
3189  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
3190  break;
3191 
3192  case 72:
3193  // Pedidos de venta
3194  lcCampo = (tcTabla == "OTRASIEN" ? "codcuen" : "cuenta");
3195  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
3196  break;
3197 
3198  case 5:
3199  // Albaranes de venta
3200  lcCampo = (tcTabla == "OTRASIEN" ? "codcuen" : "cuenta");
3201  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
3202  break;
3203 
3204  case 67:
3205  case 68:
3206  case 222:
3207  case 348:
3208  // Facturas de venta
3209  lcCampo = (tcTabla == "OTRASIEN" ? "codcuen" : "cuenta");
3210  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
3211  break;
3212 
3213  case 216:
3214  case 245:
3215  case 221:
3216  // Facturas de compra
3217  lcCampo = (tcTabla == "OTRASIEN" ? "codcuen" : "cuenta");
3218  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "PROVEED", "GESTION");
3219  break;
3220 
3221  case 360:
3222  // Clientes
3223  lcCampo = (tcTabla == "OTRASIEN" ? "codcuen" : "cuenta");
3224  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "CLIENTES", "GESTION");
3225  break;
3226 
3227  case 361:
3228  // Proveedores
3229  lcCampo = (tcTabla == "OTRASIEN" ? "codcuen" : "cuenta");
3230  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo, "PROVEED", "GESTION");
3231  break;
3232  }
3233  break;
3234 
3235  case "C_FACTUVEN":
3236 
3237  switch (nId)
3238  {
3239  case 288: // Facturas de venta
3240  case 310: // TPV con arqueo
3241  case 335: // TPV sin arqueo
3242 
3243  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "numero");
3244 
3245  break;
3246  }
3247  break;
3248 
3249  case "C_FACTUCOM":
3250 
3251  switch (nId)
3252  {
3253  case 289: // Facturas de compra
3254 
3255  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "proveedor", "numero");
3256 
3257  break;
3258  }
3259  break;
3260 
3261  case "FINTECHFAC":
3262 
3263  switch (nId)
3264  {
3265  case 293: // Facturas de venta
3266  case 311: // TPV con arqueo
3267  case 252: // TPV sin arqueo
3268 
3269  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "numfra");
3270 
3271 
3272  break;
3273  }
3274  break;
3275 
3276  case "FCFACTUVEN":
3277 
3278  switch (nId)
3279  {
3280  case 400: // Facturas de venta
3281  case 408: // TPV con arqueo
3282  case 407: // TPV sin arqueo
3283 
3284  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "borrador");
3285 
3286 
3287  break;
3288  }
3289  break;
3290 
3291  case "FCREGCERT":
3292 
3293  switch (nId)
3294  {
3295  case 403: // Facturas de venta
3296  case 405: // TPV con arqueo
3297  case 404: // TPV sin arqueo
3298 
3299  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "borrador");
3300 
3301 
3302  break;
3303  }
3304  break;
3305  case "FPAG_GIR":
3306 
3307  lcDetalle += ConstruirTextoDetalle(tdtDatos, "fpag", "FPAG", "GESTION");
3308  break;
3309 
3310  case "LIN_DESC":
3311 
3312  lcDetalle += ConstruirTextoDetalle(tdtDatos, "codigo", "LINEAS", "GESTION");
3313  break;
3314 
3315  case "ZONAS":
3316 
3317  lcDetalle += ConstruirTextoDetalle(tdtDatos, "ruta", "RUTAS", "GESTION");
3318  break;
3319 
3320  case "ART_COMI":
3321 
3322  lcDetalle += ConstruirTextoDetalle(tdtDatos, "vendedor", "VENDEDOR", "GESTION");
3323  break;
3324 
3325  case "CONIRPF":
3326 
3327  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "conirpf", "nombre");
3328 
3329  break;
3330 
3331  case "FCLETRAS":
3332 
3333  lcDetalle += ConstruirTextoDetalle(tdtDatos, "letra", "LETRAS", "COMUNES");
3334  break;
3335 
3336  case "CAJ_FCOB":
3337 
3338  lcDetalle += ConstruirTextoDetalle(tdtDatos, "caja", "CAJAS", "TPV");
3339  break;
3340 
3341  case "PLAN_D":
3342 
3343  lcDetalle += ConstruirTextoDetalle(tdtDatos, "plancont", "PLANS", "GESTION");
3344  break;
3345 
3346  case "MODCONFI":
3347  case "CFGFACT":
3348  case "CODIGOS":
3349  case "FACTUCNF":
3350  case "FLAGS":
3351  case "OPCEMP":
3352  case "CONTACNF":
3353  case "ESCALADO":
3354  case "CONTADOR":
3355  case "SERIES":
3356  case "ACCESOS":
3357  case "MENUS":
3358  case "CONFIGURA":
3359  case "CONFTPV":
3360  case "CONFVAL":
3361  case "CONFTICK":
3362 
3363  lcDetalle += ConstruirTextoDetalle(tdtDatos, "empresa", "EMPRESA", "GESTION");
3364  break;
3365 
3366  case "OPC_USER":
3367 
3368  lcDetalle += ConstruirTextoDetalle(tdtDatos, "operario", "OPERARIO", "COMUNES");
3369  break;
3370 
3371  case "ACCE_MON":
3372  case "OPCESPUS":
3373 
3374  lcDetalle += ConstruirTextoDetalle(tdtDatos, "usuario", "USUARIOS", "COMUNES");
3375  break;
3376 
3377 
3378  case "OPCFLAG":
3379  case "CASH":
3380  case "PERFILES":
3381  case "PRCLIENT":
3382 
3383  foreach (DataRow item in tdtDatos.Rows)
3384  {
3385  lcDetalle += item.Field<int>("codigo").ToString().TrimEnd() + " - " + item.Field<string>("nombre").TrimEnd() + Environment.NewLine;
3386  }
3387 
3388  break;
3389 
3390  case "ARQUEOS":
3391  case "D_ARQUEO":
3392  case "CTRL_ARQUE":
3393 
3394  lcCampo = (tcTabla == "D_ARQUEO" ? "arqueo" : "numero");
3395 
3396  foreach (DataRow item in tdtDatos.Rows)
3397  {
3398  if (!lista.Contains(item.Field<string>("empresa").ToString().TrimEnd() + " - " + item.Field<int>(lcCampo).ToString().TrimEnd()))
3399  {
3400  lcDetalle += item.Field<string>("empresa").ToString().TrimEnd() + " - " + item.Field<int>(lcCampo).ToString().TrimEnd() + Environment.NewLine;
3401  lista.Add(item.Field<string>("empresa").ToString().TrimEnd() + " - " + item.Field<int>(lcCampo).ToString().TrimEnd());
3402  }
3403  }
3404 
3405  break;
3406 
3407  case "C_ALBATR":
3408  case "D_ALBATR":
3409  case "LTALBTR":
3410  case "TRASPSER":
3411  case "CTRL_ALBTR":
3412 
3413  case "C_ALBARE":
3414  case "D_ALBARE":
3415  case "LTALBRE":
3416  case "REGUSER":
3417  case "CTRL_ALBRE":
3418 
3419  case "PEDINT_C":
3420  case "PEDINT_D":
3421  case "PEDINT_LIN":
3422  case "PEDINT_REG":
3423  case "CTRL_PEDIN":
3424 
3425  case "CTRL_FACV":
3426 
3427  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "numero");
3428 
3429  break;
3430 
3431  case "MULTICA2":
3432 
3433  switch (cClave)
3434  {
3435  case "C_PRESUV":
3436  case "C_PEDIVE":
3437  case "C_ALBDEP":
3438  case "C_ALBVEN":
3439  case "FACTURAS":
3440  case "TPVCONARQUEO":
3441  case "TPVSINARQUEO":
3442 
3443  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "letra", "numero");
3444 
3445  break;
3446  }
3447  break;
3448 
3449  case "MULTICA3":
3450 
3451  switch (cClave)
3452  {
3453  case "C_PEDICO":
3454  case "C_DEPCOM":
3455  case "C_ALBCOM":
3456  case "FACTURAC":
3457 
3458  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "proveedor", "numero");
3459 
3460  break;
3461  }
3462  break;
3463 
3464  case "CONTADO":
3465 
3466  switch (cClave)
3467  {
3468  case "C_PEDIVE":
3469  case "C_ALBDEP":
3470  case "C_ALBVEN":
3471  case "CONTADO":
3472 
3473  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "letra", "numero");
3474 
3475  break;
3476  }
3477  break;
3478 
3479  case "C_PRESUV":
3480  case "D_PRESUV":
3481  case "PORTES_PRV":
3482  case "ENTRE_PR":
3483  case "PRES_ADI":
3484 
3485  case "C_PEDIVE":
3486  case "D_PEDIVE":
3487  case "D_PEDIVEES":
3488  case "PORTES_PDV":
3489  case "ENTRE_PV":
3490  case "PEDV_ADI":
3491 
3492  case "C_ALBDEP":
3493  case "D_ALBDEP":
3494  case "LTDEPVE":
3495  case "DEPSER":
3496  case "PORTES_DPV":
3497  case "DEPV_ADI":
3498 
3499  case "C_ALBVEN":
3500  case "D_ALBVEN":
3501  case "LTALBVE":
3502  case "VENSER":
3503  case "PORTES":
3504  case "ENTREGAS":
3505  case "ALBV_ADI":
3506  case "REFALBCLI":
3507  case "CAB_AV":
3508  case "LIN_AV":
3509  case "ALB_FPAG":
3510  case "VALES":
3511 
3512  case "CTRL_PRESV":
3513  case "CTRL_PEDV":
3514  case "CTRL_DEPV":
3515  case "CTRL_ALBV":
3516 
3517 
3518  lcCampo = (tcTabla == "PORTES" || tcTabla == "ENTREGAS" ? "albaran" : (tcTabla == "VALES" ? "ticket" : "numero"));
3519  if (cClave == "FACTURAS")
3520  {
3521  lcCampo = (tcTabla == "C_ALBVEN" && tcBdReal == "GESTION" ? "factura" : lcCampo);
3522  }
3523 
3524  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "letra", lcCampo);
3525  break;
3526 
3527 
3528  case "C_PEDICO":
3529  case "D_PEDICO":
3530  case "D_PEDICOES":
3531 
3532  case "C_DEPCOM":
3533  case "D_DEPCOM":
3534  case "LTDEPCO":
3535  case "DEPCSER":
3536 
3537  case "C_PROD":
3538  case "D_PROD":
3539  case "LTCPROD":
3540  case "LTDPROD":
3541  case "PRODUSER":
3542  case "PRODUSERC":
3543 
3544  case "C_TRANS":
3545  case "D_TRANS":
3546  case "LTCTRAN":
3547  case "LTDTRAN":
3548  case "TRANSER":
3549  case "TRANSSER":
3550 
3551  case "C_PARTES":
3552  case "D_PARTES":
3553 
3554  case "CTRL_PEDC":
3555  case "CTRL_DEPC":
3556  case "CTRL_PROD":
3557  case "CTRL_PARCO":
3558  case "CTRL_TRANS":
3559 
3560  lcCampo = (tcTabla == "PRODUSER" || tcTabla == "PRODUSERC" || tcTabla == "TRANSER" || tcTabla == "TRANSSER" ? "albaran" : "numero");
3561 
3562  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", lcCampo);
3563  break;
3564 
3565  case "C_ALBCOM":
3566  case "D_ALBCOM":
3567  case "LTALBCO":
3568  case "COMSER":
3569  case "PORTESC":
3570  case "ALB_FPA2":
3571 
3572  case "CTRL_ALBC":
3573  case "CTRL_FACC":
3574  case "CTRL_TRDUA":
3575 
3576  lcCampo = (tcTabla == "PORTESC" ? "albaran" : "numero");
3577  if (cClave == "FACTURAC")
3578  {
3579  lcCampo = (tcTabla == "C_ALBCOM" ? "factura" : lcCampo);
3580  }
3581 
3582  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "empresa", "proveedor", lcCampo);
3583  break;
3584 
3585  case "TIKETS":
3586  case "REPOSI":
3587  case "COB_PAGO":
3588  case "CTRL_REPOS":
3589  case "CTRL_RETIR":
3590 
3591  lcDetalle += tdtDatos.Rows.Count.ToString() + " registros.";
3592  break;
3593 
3594  case "ESTILOS":
3595  case "PERF_OBLIG":
3596  case "PERF_USERS":
3597 
3598  // No hacer nada, de momento
3599  break;
3600 
3601  default:
3602 
3603  if (tcTabla.Contains("CTRL_"))
3604  {
3605  string[] loDatos = _offlineConfig.ObtenerTablaOriginalRelacionada(tcTabla).Split('!');
3606  lcCampo = "CODIGO";
3607 
3608  if (loDatos.Length == 2)
3609  {
3610  switch (tcTabla)
3611  {
3612  case "CTRL_FORMU":
3613 
3614  lcCampo = "ARTICULO";
3615  break;
3616 
3617  case "CTRL_STINI":
3618 
3619  lcCampo = "ALMACEN";
3620  break;
3621 
3622  case "CTRL_CIRPF":
3623 
3624  lcCampo = "CONIRPF";
3625  break;
3626 
3627  default:
3628 
3629  lcCampo = "CODIGO";
3630  break;
3631 
3632  }
3633 
3634  if (tcTabla == "CTRL_PRCLI")
3635  {
3636  lcDetalle += ConstruirTextoDetalleEntero(tdtDatos, lcCampo.ToLower(), loDatos[1], loDatos[0], lcCampo);
3637  }
3638  else
3639  {
3640  lcDetalle += ConstruirTextoDetalle(tdtDatos, lcCampo.ToLower(), loDatos[1], loDatos[0], lcCampo);
3641  }
3642  }
3643  }
3644  else
3645  {
3646  if (tdtDatos.Columns.Contains("codigo") && tdtDatos.Columns.Contains("nombre"))
3647  {
3648  lcDetalle += ConstruirTextoDetalleEspecial(tdtDatos, "codigo", "nombre");
3649 
3650  }
3651  }
3652  break;
3653  }
3654 
3655  Log_comoffDto logDto = logRepository.GetDto(datos);
3656  logDto.TipoDato = clsOfflineUtils.ObtenerTipoDato(registro.Field<string>("clave").TrimEnd().ToUpper());
3657  logDto.Resultado = 1;
3658  logDto.Detalle = lcDetalle;
3659  logRepository.Insert(logDto);
3660 
3661  }
3662 
3663 
3667  public static void EnvioEmailNotificacion(string tcFicheroZip, OfflineDatosComunicaciones datos, ILog_comoffRepository logRepository)
3668  {
3669  if (datos._NotificacionEnvio && !string.IsNullOrEmpty(datos._EmailNotificacionEnvio))
3670  {
3671  // Comprobamos resultado del envío
3672  DataTable table = new DataTable();
3673 
3674  AsistenteOffEnvioDatosBizRule loAsist = new AsistenteOffEnvioDatosBizRule();
3675  Dictionary<string, int> loDic = loAsist.Result_LogComunicaciones_IdLog(ref table, datos._Log_ComoffID);
3676  int nResultado = 0;
3677  if (loDic.Count > 0)
3678  {
3679  KeyValuePair<string, int> itemFirst = loDic.First();
3680  nResultado = itemFirst.Value;
3681  }
3682 
3683  string lcAsunto = string.Empty;
3684  string lcMensajeEnvio = string.Empty;
3685 
3686  switch (nResultado)
3687  {
3688  case 3:
3689  lcAsunto = "Sage 50 – Errores en el envío de datos";
3690  lcMensajeEnvio = " Se han producido errores en el proceso de envío de datos de fecha " + clsOfflineUtils.ObtenerFechaFicheroDatos(tcFicheroZip) + ", fichero " + tcFicheroZip + "<br><br>" +
3691  " Revise el documento adjunto donde se incluye detalle del registro de comunicaciones, en el cual podrá ver los errores detectadas durante el proceso de envío de datos. ";
3692  break;
3693  case 2:
3694  lcAsunto = "Sage 50 – Incidencias en el envío de datos";
3695  lcMensajeEnvio = " Ha finalizado el envío de datos de fecha " + clsOfflineUtils.ObtenerFechaFicheroDatos(tcFicheroZip) + ", fichero " + tcFicheroZip + " con incidencias." + "<br><br>" + " Revise el documento adjunto donde se incluye detalle del registro de comunicaciones, en el cual podrá ver las incidencias detectadas durante el proceso de envío de datos. ";
3696  break;
3697  default:
3698  lcAsunto = "Sage 50 – Envío de datos";
3699  lcMensajeEnvio = " Ha finalizado el envío de datos de fecha " + clsOfflineUtils.ObtenerFechaFicheroDatos(tcFicheroZip) + ", fichero " + tcFicheroZip + " correctamente. " + "<br><br>" + " Revise documento adjunto donde se incluye detalle del registro de comunicaciones en el cual podrá ver los datos enviados. ";
3700  break;
3701 
3702  }
3703 
3704  _TextStepDetalle = "Enviando email de notificación";
3705  _TextStepProgreso = _TextStepDetalle;
3706  _PorcenProgreso = IncrementarBarraProgreso();
3707 
3708 
3709  SendMail loSendMail = new SendMail("SUPERVISOR");
3710  loSendMail._Emails = datos._EmailNotificacionEnvio.Split(';').ToList();
3711  loSendMail._Subject = lcAsunto;
3712 
3713  string lcGrupoActual = GrupoEmpresa._CodigoGrupoActual();
3714  GrupoEmpresa _oGrupoEmpresa = new GrupoEmpresa(lcGrupoActual);
3715 
3716  string lcBody = " Grupo de empresa: " + GrupoEmpresa._CodigoGrupoActual() + " - " + _oGrupoEmpresa._Nombre.ToString().Trim() + "<br>" +
3717  (datos._IsCentral ? "Sucursal destino: " + datos._Sucursal + " - " + DB.SQLValor("SUCURSALES", "CODIGO", datos._Sucursal, "NOMBRE", "OFFLINE").ToString() : "Central") + "<br><br>" +
3718  lcMensajeEnvio;
3719 
3720  loSendMail._Body = lcBody;
3721 
3722  loSendMail._EnvioDirecto = true;
3723  loSendMail._ShowEmailForm = false;
3724  loSendMail._CCOUsuarioActivo = false;
3725 
3726  _ObtenerConfiguracionEmail(loSendMail); //Task 202603
3727 
3728  // Adjuntar fichero Comunicaciones
3729  string cRuta = TempFolderName;
3730 
3731  Log_comoffDto logDto = logRepository.GetDto(datos);
3732  logDto.TipoDato = "01";
3733 
3734  try
3735  {
3736  using (RegistroComunicaciones loLogCom = new RegistroComunicaciones(datos._Log_ComoffID))
3737  {
3738 
3739  cRuta = Path.Combine(cRuta, loLogCom._NombreFicheroExportar);
3740  loLogCom._Exportar(ew.listados.Clases.Listados.ExportType.pdf, cRuta, false, "REG_COMU");
3741 
3742  loSendMail._AddAttachment(cRuta + ".pdf");
3743  }
3744  }
3745  catch (Exception)
3746  {
3747  logDto.Resultado = 2;
3748  logDto.Detalle = "No se ha podido adjuntar el fichero PDF.";
3749  logRepository.Insert(logDto);
3750  }
3751 
3752  if (!loSendMail._Send() && !string.IsNullOrWhiteSpace(loSendMail._Error_Message))
3753  {
3754  //En caso de que haya dado un error en el envío del email y estemos en modo de tarea programada, guardamos una notificación de Sage 50
3755  //FUNCTIONS._Notificacion("Sage 50 – Envío de datos", "Incidencia en envío de email del envío de datos.",
3756  //"No se ha enviado correctamente el email de el envío de datos del grupo " + GrupoEmpresa._CodigoGrupoActual(), tcIcono: "warning");
3757  logDto.Resultado = 3;
3758  logDto.Detalle = "Fallo al realizar envío de mail de notificación de envío de datos. Revise en el mantenimiento de grupos de empresa, los datos de configuración en pestaña Configuración notificaciones del Add-on Comunicaciones offline.";
3759  }
3760  else
3761  {
3762  logDto.Resultado = 1;
3763  logDto.Detalle = "Enviado email de notificación de envío correctamente.";
3764  }
3765  logRepository.Insert(logDto);
3766 
3767  if (loSendMail._EnvioDirecto && File.Exists(cRuta + ".pdf"))
3768  {
3769  File.Delete(cRuta + ".pdf");
3770  }
3771  }
3772  }
3773 
3774  private static string Envio_Articulos_Sucursal(OfflineDatosComunicaciones datos, string lcTabla)
3775  {
3776  string lcCampo = string.Empty;
3777 
3778  switch (lcTabla)
3779  {
3780  case "ARTICULO":
3781  case "MULTICAM":
3782  lcCampo = "CODIGO";
3783  break;
3784 
3785  case "HISSERIE":
3786  // No existe el campo artículo en la tabla HISSERIE
3787  return "";
3788 
3789  default:
3790  lcCampo = "ARTICULO";
3791  break;
3792  }
3793 
3794  return " AND b." + lcCampo + " IN (SELECT ARTICULO FROM [" + datos._BdOffline + "].dbo.sucurart WHERE SUCURSAL = " + DB.SQLString(datos._Sucursal) + ") ";
3795  }
3796 
3797  private static string Envio_Series_Sucursal(OfflineDatosComunicaciones datos)
3798  {
3799  return " AND a.codigo IN (SELECT LETRA FROM [" + datos._BdOffline + "].dbo.sucurlet WHERE SUCURSAL = " + DB.SQLString(datos._Sucursal) + ") ";
3800  }
3801 
3802  private static string Envio_Cajas_Sucursal(OfflineDatosComunicaciones datos)
3803  {
3804  return " AND a.codigo IN (SELECT CAJA FROM [" + datos._BdOffline + "].dbo.sucurcaja WHERE SUCURSAL = " + DB.SQLString(datos._Sucursal) + ") ";
3805  }
3806 
3807  private static void Actualizar_Fecha_Envio_Sucursales(OfflineDatosComunicaciones datos, string cTipoEnvio, ILog_comoffRepository logRepository)
3808  {
3809  // i -> Carga Inicial
3810  // e -> Envío de datos
3811  string lcCampo = (cTipoEnvio == "i" ? "CARGAINI" : "ULTFECENV");
3812  string lcTipoEnvio = (cTipoEnvio == "i" ? "la carga inicial" : "datos");
3813 
3814  _TextStepDetalle = "Actualizando la fecha de envío de las sucursales";
3815  _TextStepProgreso = _TextStepDetalle;
3816  _PorcenProgreso = IncrementarBarraProgreso();
3817 
3818  DB.SQLExec("UPDATE " + DB.SQLDatabase("OFFLINE", "SUCURSALES") +
3819  " SET " + lcCampo + " = " + DB.SQLString(DateTime.Now) + ", MODIFIED = MODIFIED " +
3820  " WHERE CODIGO = " + DB.SQLString(datos._Sucursal));
3821 
3822  Log_comoffDto logDto = logRepository.GetDto(datos);
3823  logDto.TipoDato = "01";
3824  logDto.Resultado = 1;
3825  logDto.Detalle = "Envío de " + lcTipoEnvio + " finalizado correctamente.";
3826  logRepository.Insert(logDto);
3827  }
3828 
3829 
3830 
3835  private static void Actualizar_Fecha_Envio_Multiconf(OfflineDatosComunicaciones datos)
3836  {
3837  string lcCampo = "ULTFECENV";
3838 
3839  DB.SQLExec("UPDATE " + DB.SQLDatabase("OFFLINE", "MULTCONF") +
3840  " SET " + lcCampo + " = " + DB.SQLString(DateTime.Now) + ", MODIFIED = MODIFIED " +
3841  " WHERE IDCONF = " + DB.SQLString(datos._IdConf));
3842  }
3843 
3844 
3845 
3846 
3847 
3848 
3849  private static void Actualizar_Ultima_Fecha_Envio(int tnId)
3850  {
3851  DateTime dtUltFecEnv = DateTime.Now;
3852  string lcWhere = " WHERE ID = " + DB.SQLString(tnId);
3853 
3854  string lcSql = " IF EXISTS " + Environment.NewLine +
3855  " ( SELECT ID FROM " + DB.SQLDatabase("OFFLINE", "TABNETFEC") + lcWhere + " ) " + Environment.NewLine +
3856  " BEGIN " + Environment.NewLine +
3857  " UPDATE " + DB.SQLDatabase("OFFLINE", "TABNETFEC") +
3858  " SET ULTFECENV = " + DB.SQLString(dtUltFecEnv) +
3859  lcWhere + Environment.NewLine +
3860  " AND ULTFECENV < " + DB.SQLString(dtUltFecEnv) + Environment.NewLine +
3861  " END " + Environment.NewLine +
3862  " ELSE " + Environment.NewLine +
3863  " BEGIN" + Environment.NewLine +
3864  "Insert Into " + DB.SQLDatabase("OFFLINE", "TABNETFEC") +
3865  "(ID, ULTFECENV) " +
3866  "Values(" +
3867  DB.SQLString(tnId) + ", " + DB.SQLString(dtUltFecEnv) + ")" +
3868  " END ";
3869 
3870  DB.SQLExec(lcSql);
3871 
3872  }
3873 
3874  private static void Gestionar_Tabla_Control(DataTable table, OfflineDatosComunicaciones datos, RegistroTabRel registro, bool tlPrioridad, int tnId, string tcTipoDato, DataRow itemRow, Dictionary<string, bool> dicTablas, ILog_comoffRepository logRepository)
3875  {
3876  DataTable tablaDatosNuevos = new DataTable();
3877  DataTable tablaDatosModi = new DataTable();
3878 
3879  string lcTablaControl = _offlineConfig.ObtenerTablaControlRelacionada(registro._DBSecundaria + "!" + registro._TablaSecundaria);
3880 
3881  if (!string.IsNullOrWhiteSpace(lcTablaControl))
3882  {
3883  // Actualizar tabla de control
3884  string lcInnerJoin = Actualizar_Tabla_Control(table, registro._DBSecundaria + "!" + registro._TablaSecundaria, lcTablaControl, tnId, datos);
3885 
3886  //* Copiar tabla de la bd de offline a la bd temporal
3887  string lcSql = " FROM [" + datos._BdOffline + "].dbo." + lcTablaControl + " a " + lcInnerJoin + " WHERE 1=1 ";
3888 
3889  string lcCampoEmpresa = registro._Empresa;
3890 
3891  clsOfflineUtils.RevisarTablasCampoEmpresa(registro._TablaSecundaria, ref lcCampoEmpresa);
3892 
3893  // Casos especiales
3894  if (datos._EnvioArticulos && ((registro._DBSecundaria + "!" + registro._TablaSecundaria) == "GESTION!ARTICULO" || registro._Clave == "STOCKINI" || registro._Clave == "STOCKS"))
3895  {
3896  lcSql += Envio_Articulos_Sucursal(datos, registro._TablaSecundaria);
3897  }
3898 
3899  if (datos._IsCentral && registro._DBPrincipal + "!" + registro._TablaPrincipal == "COMUNES!LETRAS")
3900  {
3901  lcSql += Envio_Series_Sucursal(datos);
3902  }
3903 
3904  string lcFiltrePrincipal = string.Empty;
3905  if (!string.IsNullOrWhiteSpace(registro._CondEnv))
3906  {
3907  if (registro._TablaPrincipal == registro._TablaSecundaria)
3908  {
3909  lcFiltrePrincipal = registro._CondEnv;
3910  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroAlmacen(lcFiltrePrincipal, datos._Sucursal, datos._Almacenes, registro._TablaSecundaria);
3911  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroLetra(lcFiltrePrincipal, datos._Sucursal, datos._Series);
3912  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroCaja(lcFiltrePrincipal, datos._Sucursal, datos._Cajas);
3913 
3914  lcFiltrePrincipal = lcFiltrePrincipal.Replace("{TABLA}", "b.");
3915 
3916  lcSql = lcSql + " AND " + lcFiltrePrincipal;
3917  }
3918  }
3919 
3920  if (!string.IsNullOrWhiteSpace(registro._CondSecun))
3921  {
3922  if (registro._TablaPrincipal != registro._TablaSecundaria)
3923  {
3924  lcFiltrePrincipal = registro._CondSecun;
3925  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroAlmacen(lcFiltrePrincipal, datos._Sucursal, datos._Almacenes, registro._TablaSecundaria);
3926  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroLetra(lcFiltrePrincipal, datos._Sucursal, datos._Series);
3927  lcFiltrePrincipal = _offlineConfig.ConstruirFiltroCaja(lcFiltrePrincipal, datos._Sucursal, datos._Cajas);
3928 
3929  lcFiltrePrincipal = lcFiltrePrincipal.Replace("{TABLA}", "b.");
3930 
3931  lcSql = lcSql + " AND " + lcFiltrePrincipal;
3932  }
3933  }
3934 
3935  //Copiar només els registres de les empreses no excloses
3936  if (!string.IsNullOrWhiteSpace(lcCampoEmpresa))
3937  {
3938  lcSql = lcSql + " AND a." + lcCampoEmpresa + " NOT IN (SELECT empresa FROM [" + datos._BdOffline + "].dbo.empexclu) ";
3939  }
3940 
3941  // No se van a enviar tablas de control con los ficheros _MODIFIED.
3942  //if (Convert.ToBoolean(registro._Prioridad))
3943  //{
3944  // registro._Sufijo = "_MODIFIED";
3945 
3946  // ProcesoActualizarCtrl(itemRow, datos, registro, dicTablas, lcSql, lcTablaControl, logRepository);
3947  //}
3948 
3949  //registro._Sufijo = "_CREATED";
3950 
3951  ProcesoActualizarCtrl(itemRow, datos, registro, dicTablas, lcSql, lcTablaControl, logRepository);
3952  }
3953  }
3954 
3955  private static void ProcesoActualizarCtrl(DataRow itemRow, OfflineDatosComunicaciones datos, RegistroTabRel registro, Dictionary<string, bool> dicTablas, string tcSql, string lcTablaControl, ILog_comoffRepository logRepository)
3956  {
3957  DataTable dtDatos = new DataTable();
3958  string lcTipoDato = clsOfflineUtils.ObtenerTipoDato(registro._Clave);
3959  string lcSqlCondicion = string.Empty;
3960 
3961  // No se van a enviar tablas de control con los ficheros _MODIFIED.
3962  //if (registro._Sufijo == "_MODIFIED")
3963  //{
3964  // string lcSufijo = string.Empty;
3965  // string[] subPos = registro._Sufijo.Split('_');
3966  // if (subPos.Length == 2)
3967  // lcSufijo = subPos[1].TrimEnd();
3968 
3969  // lcSqlCondicion = " AND a." + lcSufijo + " >= " + DB.SQLString(datos._FechaInicial) + " AND a." + lcSufijo + " <= " + DB.SQLString(datos._FechaFinal);
3970  // lcSqlCondicion += " AND (a.CREATED < " + DB.SQLString(datos._FechaInicial) + " OR a.CREATED > " + DB.SQLString(datos._FechaFinal) + ")";
3971  //}
3972  //else
3973  //{
3974 
3975  //}
3976 
3977  lcSqlCondicion = " AND a.CREATED >= " + DB.SQLString(datos._FechaInicial) + " AND a.CREATED <= " + DB.SQLString(datos._FechaFinal);
3978 
3979  string lcSql = " SELECT a.* " + tcSql + lcSqlCondicion;
3980 
3981  if (!DB.SQLExec(lcSql, ref dtDatos))
3982  {
3983  Log_comoffDto logDto = logRepository.GetDto(datos);
3984  logDto.TipoDato = lcTipoDato;
3985  logDto.Resultado = 3;
3986  logDto.Detalle = "No se ha podido ejecutar la instrucción " + lcSql + ".";
3987  logRepository.Insert(logDto);
3988  }
3989 
3990  if (dtDatos.Rows.Count > 0)
3991  {
3992  if (clsOfflineUtils.ExisteTablaOffline("[" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + lcTablaControl + registro._Sufijo + "]"))
3993  {
3994  using (SqlBulkCopy bulkCopy = new SqlBulkCopy(DB.Conexion))
3995  {
3996  bulkCopy.DestinationTableName = "[" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + lcTablaControl + registro._Sufijo + "]";
3997 
3998  foreach (DataColumn column in dtDatos.Columns)
3999  {
4000  bulkCopy.ColumnMappings.Add(column.ColumnName.ToUpper(), column.ColumnName.ToUpper());
4001  }
4002 
4003  // Write from the source to the destination.
4004  try
4005  {
4006  bulkCopy.WriteToServer(dtDatos);
4007  }
4008  catch (Exception)
4009  {
4010  bulkCopy.ColumnMappings.Clear();
4011  bulkCopy.WriteToServer(dtDatos);
4012  }
4013  }
4014  }
4015  else
4016  {
4017  if (!clsOfflineUtils.ExisteDatabaseOffline(_cRaizDataBaseTemporal + "OFFLINE"))
4018  {
4019  CrearDataTable("OFFLINE", _cRaizDataBaseTemporal);
4020  }
4021 
4022  lcSql = " SELECT a.* INTO [" + _cRaizDataBaseTemporal + "OFFLINE" + "].dbo.[" + lcTablaControl + registro._Sufijo + "]" +
4023  tcSql + lcSqlCondicion;
4024  DB.SQLExec(lcSql);
4025  }
4026 
4027  ProcesoActualizarControlEspecial(registro, lcTablaControl, datos);
4028 
4029  RegistroDatos(datos, itemRow, datos._BdOffline, registro._TablaSecundaria, lcTablaControl, dtDatos, registro._Sufijo, logRepository);
4030  dicTablas[itemRow[0].ToString()] = true;
4031  }
4032  }
4033 
4042  private static void Gestionar_Tabla_DeleteNet(DataTable dtDeleteNet, OfflineDatosComunicaciones datos, string tcBdTabla, Dictionary<string, DataTable> dicDt, RegistroTabRel registro)
4043  {
4044  if (!datos._Delete_Mantes && registro._TipoTabla == 1)
4045  {
4046  return;
4047  }
4048 
4049  if (!datos._Delete_Documentos && registro._TipoTabla == 2)
4050  {
4051  return;
4052  }
4053 
4054  DataTable tablaDatos = new DataTable();
4055 
4056  string lcAny = EW_GLOBAL._GetVariable("wc_any").ToString();
4057 
4058  string lcBd = string.Empty;
4059  string lcTabla = string.Empty;
4060 
4061  string[] subPos = tcBdTabla.Split('!');
4062  if (subPos.Length == 2)
4063  {
4064  lcBd = subPos[0].TrimEnd();
4065  lcTabla = subPos[1].TrimEnd();
4066  }
4067 
4068  string lcSql = " SELECT * FROM [" + datos._BdOffline + "].dbo." + "DELETENET" +
4069  " WHERE DB = " + DB.SQLString(lcBd) + " AND TABLA = " + DB.SQLString(lcTabla) + " AND EJERCICIO = " + DB.SQLString(lcAny) +
4070  (!string.IsNullOrWhiteSpace(registro._Clave) ? " AND CLAVETAB = " + DB.SQLString(registro._Clave) : " ") +
4071  " AND CREATED >= " + DB.SQLString(datos._FechaInicial) + " AND CREATED <= " + DB.SQLString(datos._FechaFinal);
4072 
4073  if (DB.SQLExec(lcSql, ref tablaDatos))
4074  {
4075  foreach (DataRow loRow in tablaDatos.Rows)
4076  {
4077  DataRow newRow = dtDeleteNet.NewRow();
4078  newRow["id"] = loRow["id"];
4079  newRow["clavetab"] = loRow["clavetab"];
4080  newRow["db"] = loRow["db"];
4081  newRow["tabla"] = loRow["tabla"];
4082  newRow["ejercicio"] = loRow["ejercicio"];
4083  newRow["orden"] = loRow["orden"];
4084  newRow["tipo"] = loRow["tipo"];
4085  newRow["sql"] = loRow["sql"];
4086  newRow["guid_id"] = loRow["guid_id"];
4087  newRow["created"] = loRow["created"];
4088  newRow["modified"] = loRow["modified"];
4089  newRow["vista"] = loRow["vista"];
4090  newRow["checksum"] = loRow["checksum"];
4091  dtDeleteNet.Rows.Add(newRow);
4092 
4093  if (!string.IsNullOrWhiteSpace(registro._Compras))
4094  {
4095  // Parsear la query del delete
4096  string lcSerie = string.Empty;
4097  string lcQuery = loRow["sql"].ToString();
4098  int lnPos = lcQuery.ToUpper().IndexOf(registro._Compras);
4099  DataTable ldtDatosCompras = new DataTable();
4100 
4101 
4102  if (lnPos > 0)
4103  {
4104  lcQuery = lcQuery.Substring(lnPos);
4105 
4106  string[] stringSerie = lcQuery.Split('\'');
4107  if (stringSerie.Length >= 2)
4108  {
4109  lcSerie = stringSerie[1];
4110 
4111  ComprobarTablaTemporalSQL(registro, "COMUNES", "COMPRAS");
4112 
4113  // Montem la consulta per agafar les línies dels assentaments
4114  lcSql = " SELECT A.* " +
4115  " FROM " + DB.SQLDatabase("COMUNES", "COMPRAS") + " A " +
4116  " WHERE A.SERIE = " + DB.SQLString(lcSerie);
4117 
4118  // Executem la consulta
4119  DB.SQLExec(lcSql, ref ldtDatosCompras);
4120 
4121  if (ldtDatosCompras != null && ldtDatosCompras.Rows.Count > 0)
4122  {
4123  InsertarDatosBulkMode(ldtDatosCompras, "[" + _cRaizDataBaseTemporal + "COMUNES].dbo.[COMPRAS" + registro._Sufijo + "]");
4124  }
4125  }
4126  }
4127  }
4128  }
4129 
4130  // Eliminamos la tabla que tenemos salvada en el diccionario y guardamos de nuevo actualizada
4131  if (tablaDatos != null && tablaDatos.Rows.Count > 0)
4132  {
4133  dicDt.Remove("DELETENET");
4134  dicDt.Add("DELETENET", dtDeleteNet);
4135  }
4136  }
4137  }
4138 
4139  private static void GenerarFicherosXML_Series(OfflineDatosComunicaciones datos, ILog_comoffRepository logRepository)
4140  {
4141  // Add-on Comunicaciones Offline – Release 7730 y 7740
4142  // 17.2.1 Contadores de documento configuradas en la sucursal
4143  // Según series configuradas en la sucursal que realiza el envío de datos(Registros en tabla SUCURLET) enviar los contadores de dichas series:
4144  // Registros de tabla SERIES de todas las series de documento configuradas en la sucursal. SUCURLET.LETRA = SERIES.SERIE.
4145 
4146  if (!datos._IsCentral) // Sucursal
4147  {
4148  DataTable tablaDatos = new DataTable();
4149  string lcSql = string.Empty;
4150 
4151  _TextStepDetalle = "Generando fichero Series.xml";
4152  _TextStepProgreso = _TextStepDetalle;
4153  _PorcenProgreso = IncrementarBarraProgreso();
4154 
4155  Log_comoffDto logDto = logRepository.GetDto(datos);
4156  logDto.TipoDato = "01";
4157  logDto.Resultado = 1;
4158  logDto.Detalle = "Actualizados contadores de series de documentos de la sucursal " + datos._Sucursal + ".";
4159  logRepository.Insert(logDto);
4160 
4161  lcSql += " SELECT * FROM " + DB.SQLDatabase("GESTION", "SERIES") +
4162  " WHERE SERIE IN ( SELECT LETRA FROM " + DB.SQLDatabase("OFFLINE","SUCURLET") + " WHERE SUCURSAL = " + DB.SQLString(datos._Sucursal) + " ) " +
4163  " AND MODIFIED >= " + DB.SQLString(datos._FechaInicial) + " AND MODIFIED <= " + DB.SQLString(datos._FechaFinal) +
4164  " AND (CREATED < " + DB.SQLString(datos._FechaInicial) + " OR CREATED > " + DB.SQLString(datos._FechaFinal) + " ) ";
4165 
4166  lcSql += " UNION ALL ";
4167 
4168  lcSql += " SELECT * FROM " + DB.SQLDatabase("GESTION", "SERIES") +
4169  " WHERE SERIE IN ( SELECT LETRA FROM " + DB.SQLDatabase("OFFLINE", "SUCURLET") + " WHERE SUCURSAL = " + DB.SQLString(datos._Sucursal) + " ) " +
4170  " AND CREATED >= " + DB.SQLString(datos._FechaInicial) + " AND CREATED <= " + DB.SQLString(datos._FechaFinal);
4171 
4172  DB.SQLExec(lcSql, ref tablaDatos);
4173 
4174  if (tablaDatos.Rows.Count > 0)
4175  {
4176  ConvertIndividualFile(tablaDatos, TempFolderName, "SERIES", FormatoExportacion.XML);
4177  }
4178  }
4179  }
4180 
4181  private static string Actualizar_Tabla_Control(DataTable table, string tcBdTabla, string tcTablaControl, int tnId, OfflineDatosComunicaciones datos)
4182  {
4183  string lcSql = string.Empty;
4184  string lcWhere = string.Empty;
4185  string lcInsert = string.Empty;
4186  string lcAux = string.Empty;
4187  string lcAny = EW_GLOBAL._GetVariable("wc_any").ToString();
4188  string lcSet = " Set ORIGEN = " + (datos._IsCentral ? DB.SQLString("CENTRAL") : DB.SQLString(datos._Sucursal)) + ", MODIFIED = " + DB.SQLString(DateTime.Now);
4189  string lcOrigen = (datos._IsCentral ? "CENTRAL" : datos._Sucursal);
4190 
4191  string lcInnerJoin = string.Empty;
4192  string lcBd = string.Empty;
4193  string lcTabla = string.Empty;
4194 
4195  string[] subPos = tcBdTabla.Split('!');
4196  if (subPos.Length == 2)
4197  {
4198  lcBd = subPos[0].TrimEnd();
4199  lcTabla = subPos[1].TrimEnd();
4200  }
4201 
4202  foreach (DataRow item in table.Rows)
4203  {
4204  switch (lcTabla)
4205  {
4206  case "COLORES":
4207  case "TALLAS":
4208  case "GRUPCOLO":
4209  case "GRUPTALL":
4210  case "TCP":
4211  case "CLASIF":
4212  case "LETRAS":
4213  case "OBRA":
4214  case "SUPLIDOS":
4215  case "CAJAS":
4216  case "DEFVALES":
4217  case "CONCEP":
4218  case "EMPLEADO":
4219  case "MAND_CONCE":
4220  case "F_COBROS":
4221  case "TIPO_REG":
4222 
4223  lcWhere = " WHERE CODIGO = " + DB.SQLString(item.Field<string>("codigo"));
4224 
4225  lcInsert = "(CODIGO, ORIGEN) " +
4226  "Values(" +
4227  DB.SQLString(item.Field<string>("codigo")) + ", " + DB.SQLString(lcOrigen) + ")";
4228 
4229  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.CODIGO = B.CODIGO ";
4230 
4231  break;
4232 
4233  case "G_CONTRI":
4234  case "MODREFEC":
4235 
4236  lcWhere = " WHERE CODIGO = " + DB.SQLString(item.Field<string>("codigo"));
4237 
4238  lcInsert = "(CODIGO, EJERCICIO, ORIGEN) " +
4239  "Values(" +
4240  DB.SQLString(item.Field<string>("codigo")) + ", " + DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4241 
4242 
4243  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.CODIGO = B.CODIGO ";
4244 
4245  break;
4246 
4247  case "FACTORPTOS":
4248  lcWhere = " WHERE CLIENTE = " + DB.SQLString(item.Field<string>("cliente")) +
4249  " AND ARTICULO = " + DB.SQLString(item.Field<string>("articulo")) +
4250  " AND FAMILIA = " + DB.SQLString(item.Field<string>("familia")) +
4251  " AND SUBFAMILIA = " + DB.SQLString(item.Field<string>("subfamilia")) +
4252  " AND MARCA = " + DB.SQLString(item.Field<string>("marca")) +
4253  " AND ACTIVIDAD = " + DB.SQLString(item.Field<string>("actividad")) +
4254  " AND TARIFA = " + DB.SQLString(item.Field<string>("tarifa")) +
4255  " AND CATALOGO = " + item.Field<int>("catalogo") +
4256  " AND LINEA = " + item.Field<int>("linea");
4257 
4258  lcInsert = "(CLIENTE, ARTICULO, FAMILIA, SUBFAMILIA, MARCA, ACTIVIDAD, TARIFA, CATALOGO, LINEA, ORIGEN, IDTABREL) " +
4259  "Values(" +
4260  DB.SQLString(item.Field<string>("cliente")) + ", " + DB.SQLString(item.Field<string>("articulo")) + ", " +
4261  DB.SQLString(item.Field<string>("familia")) + ", " + DB.SQLString(item.Field<string>("subfamilia")) + ", " +
4262  DB.SQLString(item.Field<string>("marca")) + ", " + DB.SQLString(item.Field<string>("actividad")) + ", " +
4263  DB.SQLString(item.Field<string>("tarifa")) + ", " + item.Field<int>("catalogo") + ", " +
4264  item.Field<int>("linea") + ", " + DB.SQLString(lcOrigen) + ", " + DB.SQLString(tnId) + ")";
4265 
4266  break;
4267 
4268  case "ASIENTOS":
4269 
4270  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4271  " AND NUMERO = " + DB.SQLString(item.Field<int>("numero")) +
4272  " AND LINEA = " + DB.SQLString(item.Field<int>("linea")) +
4273  " AND EJERCICIO = " + DB.SQLString(lcAny);
4274 
4275  lcInsert = "(EMPRESA, NUMERO, LINEA, EJERCICIO, ORIGEN, IDTABREL) " +
4276  "Values(" +
4277  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<int>("numero")) + ", " + DB.SQLString(item.Field<int>("linea")) + ", " +
4278  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ", " + DB.SQLString(tnId) + ")";
4279 
4280  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.NUMERO = B.NUMERO AND A.LINEA = B.LINEA ";
4281 
4282  switch (tnId)
4283  {
4284  case 7:
4285  case 96:
4286  // COBROS, PAGOS Y ASIENTOS RELACIONADOS
4287  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("TPV", "TIKETS") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI ";
4288  break;
4289 
4290  case 9:
4291  case 98:
4292  // REPOSICIONES Y ASIENTOS RELACIONADOS
4293  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("TPV", "REPOSI") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI ";
4294  break;
4295 
4296  case 68:
4297  case 301:
4298  case 326:
4299  // ASIENTO DE FACTURA DE VENDA
4300  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("GESTION", "C_ALBVEN") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI ";
4301  break;
4302 
4303  case 74:
4304  case 99:
4305  // RETIROS DE CAJA Y ASIENTOS RELACIONADOS
4306  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("TPV", "COB_PAGO") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI ";
4307  break;
4308 
4309  case 113:
4310  case 318:
4311  // ENTREGAS A CUENTA DE CLIENTES/PROVEEDORES
4312  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("GESTION", "ENTRE_CL") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI ";
4313  break;
4314 
4315  case 216:
4316  // ASIENTO DE FACTURA DE COMPRA
4317  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("GESTION", "C_ALBCOM") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI ";
4318  break;
4319 
4320  case 285:
4321  // ASIENTO DE FACTURA TRANSITARIO
4322  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("GESTION", "C_TRANSDUA") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI_TRANS ";
4323  break;
4324 
4325  case 286:
4326  // ASIENTO DE FACTURA DUA
4327  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("GESTION", "C_TRANSDUA") + " C ON B.EMPRESA = C.EMPRESA AND B.ASI = C.ASI_DUA ";
4328  break;
4329 
4330  }
4331 
4332  break;
4333 
4334  case "C_FORMUL":
4335 
4336  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4337  " AND ARTICULO = " + DB.SQLString(item.Field<string>("articulo"));
4338 
4339  lcInsert = "(EMPRESA, ARTICULO, ORIGEN) " +
4340  "Values(" +
4341  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("articulo")) + ", " +
4342  DB.SQLString(lcOrigen) + ")";
4343 
4344  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.ARTICULO = B.ARTICULO ";
4345 
4346  break;
4347 
4348  case "CANALES":
4349 
4350  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4351  " AND CODIGO = " + DB.SQLString(item.Field<string>("codigo"));
4352 
4353  lcInsert = "(EMPRESA, CODIGO, ORIGEN) " +
4354  "Values(" +
4355  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("codigo")) + ", " +
4356  DB.SQLString(lcOrigen) + ")";
4357 
4358  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.CODIGO = B.CODIGO ";
4359 
4360  break;
4361 
4362  case "PLEFACT_C":
4363 
4364  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4365  " AND CODIGO = " + DB.SQLString(item.Field<string>("codigo"));
4366 
4367  lcInsert = "(EMPRESA, CODIGO, EJERCICIO, ORIGEN) " +
4368  "Values(" +
4369  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("codigo")) + ", " +
4370  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4371 
4372  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.CODIGO = B.CODIGO ";
4373 
4374  break;
4375 
4376  case "IDIOMA":
4377 
4378  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4379  " AND CODIGO = " + DB.SQLString(item.Field<string>("codigo")) +
4380  " AND EJERCICIO = " + DB.SQLString(lcAny);
4381 
4382  lcInsert = "(EMPRESA, CODIGO, EJERCICIO, ORIGEN) " +
4383  "Values(" +
4384  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("codigo")) + ", " +
4385  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4386 
4387  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.CODIGO = B.CODIGO ";
4388 
4389  break;
4390 
4391  case "CONIRPF":
4392 
4393  lcWhere = " WHERE CONIRPF = " + DB.SQLString(item.Field<string>("conirpf")) +
4394  " AND CONGASING = " + DB.SQLString(item.Field<string>("congasing")) +
4395  " AND EJERCICIO = " + DB.SQLString(lcAny);
4396 
4397  lcInsert = "(CONIRPF, CONGASING, EJERCICIO, ORIGEN) " +
4398  "Values(" +
4399  DB.SQLString(item.Field<string>("conirpf")) + ", " + DB.SQLString(item.Field<string>("congasing")) + ", " +
4400  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4401 
4402  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.CONIRPF = B.CONIRPF AND A.CONGASING = B.CONGASING ";
4403 
4404  break;
4405 
4406  case "OFERTAS":
4407 
4408  lcWhere = " WHERE ARTICULO = " + DB.SQLString(item.Field<string>("articulo")) +
4409  " AND CLIENTE = " + DB.SQLString(item.Field<string>("cliente")) +
4410  " AND LINEA = " + DB.SQLString(item.Field<int>("linea")) +
4411  " AND EJERCICIO = " + DB.SQLString(lcAny);
4412 
4413  lcInsert = "(ARTICULO, CLIENTE, LINEA, EJERCICIO, ORIGEN) " +
4414  "Values(" +
4415  DB.SQLString(item.Field<string>("articulo")) + ", " + DB.SQLString(item.Field<string>("cliente")) + ", " +
4416  DB.SQLString(item.Field<int>("linea")) + ", " + DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4417 
4418  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.ARTICULO = B.ARTICULO AND A.CLIENTE = B.CLIENTE AND A.LINEA = B.LINEA ";
4419 
4420  break;
4421 
4422  case "PREVI_CL":
4423 
4424  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4425  " AND PERIODO = " + DB.SQLString(item.Field<int>("periodo")) +
4426  " AND FACTURA = " + DB.SQLString(item.Field<string>("factura")) +
4427  " AND ORDEN = " + DB.SQLString(item.Field<int>("orden")) +
4428  " AND IMPAGADO = " + DB.SQLString(item.Field<int>("impagado")) +
4429  " AND PENDIENTE = " + DB.SQLString(item.Field<decimal>("pendiente"));
4430 
4431  lcInsert = "(EMPRESA, PERIODO, FACTURA, ORDEN, IMPAGADO, PENDIENTE, ORIGEN, IDTABREL) " +
4432  "Values(" +
4433  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<int>("periodo")) + ", " +
4434  DB.SQLString(item.Field<string>("factura")) + ", " + DB.SQLString(item.Field<int>("orden")) + ", " +
4435  DB.SQLString(item.Field<int>("impagado")) + ", " + DB.SQLString(item.Field<decimal>("pendiente")) + ", " +
4436  DB.SQLString(lcOrigen) + ", " + DB.SQLString(tnId) + ")";
4437 
4438  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.PERIODO = B.PERIODO " +
4439  " AND A.FACTURA = B.FACTURA AND A.ORDEN = B.ORDEN AND A.IMPAGADO = B.IMPAGADO AND A.PENDIENTE = B.PENDIENTE ";
4440 
4441  break;
4442 
4443  case "PREVIS":
4444 
4445  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4446  " AND YEAR(EMISION) = " + DB.SQLString(item.Field<int>("periodo")) +
4447  " AND PROVEEDOR = " + DB.SQLString(item.Field<string>("proveedor")) +
4448  " AND FACTURA = " + DB.SQLString(item.Field<string>("factura")) +
4449  " AND NUMEREB = " + DB.SQLString(item.Field<int>("numereb")) +
4450  " AND PENDIENTE = " + DB.SQLString(item.Field<int>("pendiente"));
4451 
4452  lcInsert = "(EMPRESA, EMISION, PROVEEDOR, FACTURA, NUMEREB, PENDIENTE, ORIGEN, IDTABREL) " +
4453  "Values(" +
4454  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<DateTime>("emision")) + ", " +
4455  DB.SQLString(item.Field<string>("proveedor")) + ", " + DB.SQLString(item.Field<string>("factura")) + ", " +
4456  DB.SQLString(item.Field<int>("numereb")) + ", " + DB.SQLString(item.Field<int>("pendiente")) + ", " +
4457  DB.SQLString(lcOrigen) + ", " + DB.SQLString(tnId) + ")";
4458 
4459  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.EMISION = B.EMISION " +
4460  " AND A.PROVEEDOR = B.PROVEEDOR AND A.FACTURA = B.FACTURA AND A.NUMEREB = B.NUMEREB AND A.PENDIENTE = B.PENDIENTE ";
4461 
4462  break;
4463 
4464  case "STOCKINI":
4465 
4466  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4467  " AND FECHA = " + DB.SQLString(item.Field<DateTime>("fecha")) +
4468  " AND ALMACEN = " + DB.SQLString(item.Field<string>("almacen")) +
4469  " AND ARTICULO = " + DB.SQLString(item.Field<string>("articulo")) +
4470  " AND LINIA = " + DB.SQLString(item.Field<int>("linia")) +
4471  " AND EJERCICIO = " + DB.SQLString(lcAny);
4472 
4473  lcInsert = "(EMPRESA, FECHA, ALMACEN, ARTICULO, LINIA, EJERCICIO, ORIGEN) " +
4474  "Values(" +
4475  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<DateTime>("fecha")) + ", " +
4476  DB.SQLString(item.Field<string>("almacen")) + ", " + DB.SQLString(item.Field<string>("articulo")) + ", " +
4477  DB.SQLString(item.Field<int>("linia")) + ", " + DB.SQLString(lcAny) + ", " +
4478  DB.SQLString(lcOrigen) + ")";
4479 
4480  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.FECHA = B.FECHA " +
4481  " AND A.ALMACEN = B.ALMACEN AND A.ARTICULO = B.ARTICULO AND A.LINIA = B.LINIA ";
4482 
4483  break;
4484 
4485  case "C_PLANT":
4486  case "SECCIONES":
4487 
4488  lcWhere = " WHERE CODIGO = " + DB.SQLString(item.Field<string>("codigo")) + " AND EJERCICIO = " + DB.SQLString(lcAny);
4489 
4490  lcInsert = "(CODIGO, EJERCICIO, ORIGEN, IDTABREL) " +
4491  "Values(" +
4492  DB.SQLString(item.Field<string>("codigo")) + ", " + DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ", " + DB.SQLString(tnId) + ")";
4493 
4494 
4495  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.CODIGO = B.CODIGO ";
4496 
4497  break;
4498 
4499  case "C_ALBVEN":
4500  case "C_ALBDEP":
4501  case "C_PEDIVE":
4502  case "C_PRESUV":
4503 
4504  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4505  " AND NUMERO = " + DB.SQLString(item.Field<string>("numero")) +
4506  " AND LETRA = " + DB.SQLString(item.Field<string>("letra")) +
4507  " AND EJERCICIO = " + DB.SQLString(lcAny);
4508 
4509  if (lcTabla == "C_ALBVEN")
4510  {
4511  lcInsert = "(EMPRESA, NUMERO, LETRA, EJERCICIO, ORIGEN, IDTABREL) " +
4512  "Values(" +
4513  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " +
4514  DB.SQLString(item.Field<string>("letra")) + ", " + DB.SQLString(lcAny) + ", " +
4515  DB.SQLString(lcOrigen) + ", " + DB.SQLString(tnId) + ")";
4516  }
4517  else
4518  {
4519  lcInsert = "(EMPRESA, NUMERO, LETRA, EJERCICIO, ORIGEN) " +
4520  "Values(" +
4521  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " +
4522  DB.SQLString(item.Field<string>("letra")) + ", " + DB.SQLString(lcAny) + ", " +
4523  DB.SQLString(lcOrigen) + ")";
4524  }
4525 
4526  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.NUMERO = B.NUMERO AND A.LETRA = B.LETRA ";
4527 
4528  break;
4529 
4530  case "C_FACTUVEN":
4531  case "C_ALBARE":
4532  case "C_ALBATR":
4533  case "C_DEPCOM":
4534  case "C_PEDICO":
4535  case "C_PRECOM":
4536  case "C_PROD":
4537  case "C_TRANS":
4538 
4539  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4540  " AND NUMERO = " + DB.SQLString(item.Field<string>("numero")) +
4541  " AND EJERCICIO = " + DB.SQLString(lcAny);
4542 
4543  if (lcTabla == "C_FACTUVEN")
4544  {
4545  lcInsert = "(EMPRESA, NUMERO, EJERCICIO, ORIGEN, IDTABREL) " +
4546  "Values(" +
4547  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " +
4548  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ", " + DB.SQLString(tnId) + ")";
4549  }
4550  else
4551  {
4552  lcInsert = "(EMPRESA, NUMERO, EJERCICIO, ORIGEN) " +
4553  "Values(" +
4554  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " +
4555  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4556  }
4557 
4558  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.NUMERO = B.NUMERO ";
4559 
4560  if (lcTabla == "C_FACTUVEN")
4561  {
4562  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("GESTION", "C_ALBVEN") + " C ON B.EMPRESA = C.EMPRESA AND B.NUMERO = C.FACTURA ";
4563  }
4564 
4565  break;
4566 
4567  case "C_ALBCOM":
4568  case "C_FACTUCOM":
4569  case "C_TRANSDUA":
4570 
4571  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4572  " AND NUMERO = " + DB.SQLString(item.Field<string>("numero")) +
4573  " AND PROVEEDOR = " + DB.SQLString(item.Field<string>("proveedor")) +
4574  " AND EJERCICIO = " + DB.SQLString(lcAny);
4575 
4576  lcInsert = "(EMPRESA, NUMERO, PROVEEDOR, EJERCICIO, ORIGEN) " +
4577  "Values(" +
4578  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " +
4579  DB.SQLString(item.Field<string>("proveedor")) + ", " + DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4580 
4581  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.NUMERO = B.NUMERO AND A.PROVEEDOR = B.PROVEEDOR ";
4582 
4583  if (lcTabla == "C_FACTUCOM")
4584  {
4585  lcInnerJoin += " INNER JOIN " + DB.SQLDatabase("GESTION", "C_ALBCOM") + " C ON B.EMPRESA = C.EMPRESA AND B.NUMERO = C.FACTURA AND B.PROVEEDOR = C.PROVEEDOR ";
4586  }
4587 
4588  break;
4589 
4590  case "ARQUEOS":
4591 
4592  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4593  " AND NUMERO = " + DB.SQLString(item.Field<int>("numero"));
4594 
4595  lcInsert = "(EMPRESA, NUMERO, EJERCICIO, ORIGEN) " +
4596  "Values(" +
4597  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<int>("numero")) + ", " +
4598  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4599 
4600  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.NUMERO = B.NUMERO ";
4601 
4602  break;
4603 
4604  case "PEDINT_C":
4605 
4606  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4607  " AND NUMERO = " + DB.SQLString(item.Field<string>("numero"));
4608 
4609  lcInsert = "(EMPRESA, NUMERO, ORIGEN) " +
4610  "Values(" +
4611  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " +
4612  DB.SQLString(lcOrigen) + ")";
4613 
4614  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.NUMERO = B.NUMERO ";
4615 
4616  break;
4617 
4618  case "D_PARTES":
4619 
4620  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4621  " AND NUMERO = " + DB.SQLString(item.Field<string>("numero")) +
4622  " AND LINIA = " + DB.SQLString(item.Field<int>("linea")) +
4623  " AND EJERCICIO = " + DB.SQLString(lcAny);
4624 
4625  lcInsert = "(EMPRESA, NUMERO, LINIA, EJERCICIO, ORIGEN) " +
4626  "Values(" +
4627  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("numero")) + ", " +
4628  DB.SQLString(item.Field<int>("linea")) + ", " + DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4629 
4630  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.NUMERO = B.NUMERO AND A.LINIA = B.LINEA ";
4631 
4632  break;
4633 
4634  case "REGULARI":
4635 
4636  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4637  " AND ALMACEN = " + DB.SQLString(item.Field<string>("almacen")) +
4638  " AND FECHA = " + DB.SQLString(item.Field<DateTime>("fecha")) +
4639  " AND DOCUMENTO = " + DB.SQLString(item.Field<string>("documento")) +
4640  " AND LINIA = " + DB.SQLString(item.Field<int>("linia")) +
4641  " AND EJERCICIO = " + DB.SQLString(lcAny);
4642 
4643  lcInsert = "(EMPRESA, ALMACEN, FECHA, LINIA, DOCUMENTO, EJERCICIO, ORIGEN) " +
4644  "Values(" +
4645  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("almacen")) + ", " +
4646  DB.SQLString(item.Field<DateTime>("fecha")) + ", " + DB.SQLString(item.Field<int>("linia")) + ", " + DB.SQLString(item.Field<string>("documento")) + ", " +
4647  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4648 
4649  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.ALMACEN = B.ALMACEN " +
4650  " AND A.FECHA = B.FECHA AND A.DOCUMENTO = B.DOCUMENTO AND A.LINIA = B.LINIA ";
4651 
4652  break;
4653 
4654  case "VALES":
4655 
4656  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4657  " AND LETRA = " + DB.SQLString(item.Field<string>("letra")) +
4658  " AND TICKET = " + DB.SQLString(item.Field<string>("ticket")) +
4659  " AND ORDEN = " + DB.SQLString(item.Field<int>("orden"));
4660 
4661  lcInsert = "(EMPRESA, LETRA, TICKET, ORDEN, EJERCICIO, ORIGEN) " +
4662  "Values(" +
4663  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("letra")) + ", " +
4664  DB.SQLString(item.Field<string>("ticket")) + ", " + DB.SQLString(item.Field<int>("orden")) + ", " +
4665  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4666 
4667  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.LETRA = B.LETRA AND A.TICKET = B.TICKET " +
4668  " AND A.ORDEN = B.ORDEN ";
4669 
4670  break;
4671 
4672  case "REPOSI":
4673 
4674  lcAux = ", ARQUEO = " + DB.SQLString(item.Field<int>("arqueo"));
4675 
4676  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4677  " AND CAJA = " + DB.SQLString(item.Field<string>("caja")) +
4678  " AND MONEDA = " + DB.SQLString(item.Field<string>("moneda")) +
4679  " AND FECHA = " + DB.SQLString(item.Field<DateTime>("fecha")) +
4680  " AND OPERARIO = " + DB.SQLString(item.Field<string>("operario")) +
4681  //" AND ARQUEO = " + DB.SQLString(item.Field<int>("arqueo")) +
4682  " AND LINEA = " + DB.SQLString(item.Field<int>("linea"));
4683 
4684  lcInsert = "(EMPRESA, CAJA, MONEDA, FECHA, OPERARIO, ARQUEO, LINEA, ORIGEN) " +
4685  "Values(" +
4686  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("caja")) + ", " +
4687  DB.SQLString(item.Field<string>("moneda")) + ", " + DB.SQLString(item.Field<DateTime>("fecha")) + ", " +
4688  DB.SQLString(item.Field<string>("operario")) + ", " + DB.SQLString(item.Field<int>("arqueo")) + ", " +
4689  DB.SQLString(item.Field<int>("linea")) + ", " + DB.SQLString(lcOrigen) + ")";
4690 
4691  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.CAJA = B.CAJA AND A.MONEDA = B.MONEDA " +
4692  " AND A.FECHA = B.FECHA AND A.OPERARIO = B.OPERARIO AND A.LINEA = B.LINEA ";
4693 
4694  break;
4695 
4696  case "COB_PAGO":
4697 
4698  lcAux = ", ARQUEO = " + DB.SQLString(item.Field<int>("arqueo"));
4699 
4700  lcWhere = " WHERE EMPRESA = " + DB.SQLString(item.Field<string>("empresa")) +
4701  " AND CAJA = " + DB.SQLString(item.Field<string>("caja")) +
4702  " AND FECHA = " + DB.SQLString(item.Field<DateTime>("fecha")) +
4703  " AND OPERARIO = " + DB.SQLString(item.Field<string>("operario")) +
4704  //" AND ARQUEO = " + DB.SQLString(item.Field<int>("arqueo")) +
4705  " AND LINEA = " + DB.SQLString(item.Field<int>("linea"));
4706 
4707  lcInsert = "(EMPRESA, CAJA, FECHA, OPERARIO, ARQUEO, LINEA, ORIGEN) " +
4708  "Values(" +
4709  DB.SQLString(item.Field<string>("empresa")) + ", " + DB.SQLString(item.Field<string>("caja")) + ", " +
4710  DB.SQLString(item.Field<DateTime>("fecha")) + ", " + DB.SQLString(item.Field<string>("operario")) + ", " +
4711  DB.SQLString(item.Field<int>("arqueo")) + ", " + DB.SQLString(item.Field<int>("linea")) + ", " + DB.SQLString(lcOrigen) + ")";
4712 
4713  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.EMPRESA = B.EMPRESA AND A.CAJA = B.CAJA " +
4714  " AND A.FECHA = B.FECHA AND A.OPERARIO = B.OPERARIO AND A.LINEA = B.LINEA ";
4715 
4716  break;
4717 
4718  case "PRCLIENT":
4719 
4720  lcWhere = " WHERE CODIGO = " + DB.SQLString(item.Field<int>("codigo")) +
4721  " AND EJERCICIO = " + DB.SQLString(lcAny);
4722 
4723  lcInsert = "(CODIGO, EJERCICIO, ORIGEN) " +
4724  "Values(" +
4725  DB.SQLString(item.Field<int>("codigo")) + ", " +
4726  DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4727 
4728  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.CODIGO = B.CODIGO ";
4729 
4730  break;
4731 
4732 
4733  default:
4734 
4735  if (lcBd == "LOTES" && lcTabla == "MCAMPOS")
4736  {
4737  lcWhere = " WHERE CODIGO = " + DB.SQLString(item.Field<string>("codigo"));
4738  }
4739  else
4740  {
4741  lcWhere = " WHERE CODIGO = " + DB.SQLString(item.Field<string>("codigo")) + " AND EJERCICIO = " + DB.SQLString(lcAny);
4742  }
4743 
4744  lcInsert = "(CODIGO, EJERCICIO, ORIGEN) " +
4745  "Values(" +
4746  DB.SQLString(item.Field<string>("codigo")) + ", " + DB.SQLString(lcAny) + ", " + DB.SQLString(lcOrigen) + ")";
4747 
4748 
4749  lcInnerJoin = " INNER JOIN " + DB.SQLDatabase(lcBd, lcTabla) + " B ON A.CODIGO = B.CODIGO ";
4750 
4751  break;
4752  }
4753 
4754  lcSql = " IF EXISTS " + Environment.NewLine +
4755  " ( SELECT ORIGEN FROM " + DB.SQLDatabase("OFFLINE", tcTablaControl) + lcWhere + " ) " + Environment.NewLine +
4756  " BEGIN " + Environment.NewLine +
4757  " Update " + DB.SQLDatabase("OFFLINE", tcTablaControl) + lcSet + lcAux + lcWhere + Environment.NewLine +
4758  " END " + Environment.NewLine +
4759  " ELSE " + Environment.NewLine +
4760  " BEGIN" + Environment.NewLine +
4761  "Insert Into " + DB.SQLDatabase("OFFLINE", tcTablaControl) + lcInsert +
4762  " END ";
4763 
4764  DB.SQLExec(lcSql);
4765  }
4766 
4767  return lcInnerJoin;
4768  }
4769 
4770  private static bool Subir_Fichero_DatosEnvio(OfflineDatosComunicaciones datos, string cTipoEnvio, ILog_comoffRepository logRepository)
4771  {
4772  // i -> Carga Inicial
4773  // e -> Envío de datos
4774  string lcTipoEnvio = (cTipoEnvio == "i" ? "la carga inicial " : "envío ");
4775 
4776  string lcBaseFicheroZip = _cTempFileName + cTipoEnvio;
4777  bool llOk = true;
4778 
4779  if (!string.IsNullOrWhiteSpace(lcBaseFicheroZip) && Directory.Exists(datos._PathFolderInicial))
4780  {
4781  _TextStepDetalle = "Subiendo el fichero de " + lcTipoEnvio + lcBaseFicheroZip + ".zip ";
4782  _TextStepProgreso = _TextStepDetalle;
4783  _PorcenProgreso = IncrementarBarraProgreso();
4784 
4785  clsOffLine utilsOffline = new clsOffLine();
4786  string pathArchivoComprimido = utilsOffline.Fichero_Comprimir(datos._PathFolderInicial, lcBaseFicheroZip);
4787 
4788  //IOfflineUnitOfWork offlineUnitOfWork = DependencyInjector.Instance.Retrieve<IOfflineUnitOfWork>();
4789  //ILog_comoffRepository logRepository = offlineUnitOfWork.Log_comoffRepository;
4790 
4791  Log_comoffDto logDto = logRepository.GetDto(datos);
4792  logDto.TipoDato = "01";
4793  if (string.IsNullOrWhiteSpace(pathArchivoComprimido))
4794  {
4795  logDto.Resultado = 3;
4796  logDto.Detalle = "El fichero de " + lcTipoEnvio + lcBaseFicheroZip + ".zip no se ha podido generar.";
4797  logRepository.Insert(logDto);
4798  }
4799  else
4800  {
4801  logDto.Resultado = 1;
4802  logDto.Detalle = "El fichero de " + lcTipoEnvio + lcBaseFicheroZip + ".zip se ha generado con éxito.";
4803  logRepository.Insert(logDto);
4804 
4805  string lcZipFile = Path.Combine(datos._PathFolderInicial, pathArchivoComprimido);
4806  lcZipFile = Path.Combine(lcZipFile, lcBaseFicheroZip);
4807  lcZipFile = lcZipFile + ".zip";
4808 
4809  long uploadedFileSize = 0;
4810 
4811  var carpetaserv = "SUCURNET" + datos._Sucursal + "/";
4812 
4813 
4814  llOk = UploadManager.Subir_Fichero(lcZipFile, "", carpetaserv, datos._IdConf, ref uploadedFileSize);
4815 
4816  int conexion = TipoConexion(datos);
4817  string lcDescrip = (conexion == 0 ? "FTP" : "OneDrive");
4818 
4819  if (llOk)
4820  {
4821  logDto.Resultado = 1;
4822  logDto.Detalle = "El fichero de " + lcTipoEnvio + lcBaseFicheroZip + ".zip se ha subido a la carpeta " + carpetaserv + " del " + lcDescrip + ".";
4823  }
4824  else
4825  {
4826  logDto.Resultado = 3;
4827  logDto.Detalle = "No se ha podido subir fichero de " + lcTipoEnvio + lcBaseFicheroZip + ".zip a carpeta " + lcDescrip + " , revise si el usuario " + lcDescrip + " configurado tiene permisos en la carpeta indicada.";
4828  }
4829 
4830  logRepository.Insert(logDto);
4831  }
4832  }
4833 
4834  return llOk;
4835  }
4836 
4837 
4838  private static int TipoConexion(OfflineDatosComunicaciones datos)
4839  {
4840  int tipoConexion = 0;
4841 
4842  DataTable ldtDatos = new DataTable();
4843  DB.SQLExec("SELECT CONEXION FROM " + DB.SQLDatabase("OFFLINE", "MULTCONF") + " WHERE IDCONF = " + DB.SQLString(datos._IdConf), ref ldtDatos);
4844 
4845  if (ldtDatos != null || ldtDatos.Rows.Count > 0)
4846  {
4847  return Convert.ToInt16(ldtDatos.Rows[0]["conexion"]);
4848  }
4849 
4850  return tipoConexion;
4851  }
4852 
4853  private static bool Subir_Fichero_Configuracion(OfflineDatosComunicaciones datos, ILog_comoffRepository logRepository)
4854  {
4855  string lcBaseFicheroZip = "configura_offline";
4856  bool llOk = true;
4857 
4858  if (!string.IsNullOrWhiteSpace(lcBaseFicheroZip) && Directory.Exists(datos._PathFolderInicial))
4859  {
4860  clsOffLine utilsOffline = new clsOffLine();
4861  string pathArchivoComprimido = utilsOffline.Fichero_Comprimir(datos._PathFolderInicial, lcBaseFicheroZip);
4862 
4863  Log_comoffDto logDto = logRepository.GetDto(datos);
4864  logDto.TipoDato = "01";
4865  if (string.IsNullOrWhiteSpace(pathArchivoComprimido))
4866  {
4867  logDto.Resultado = 3;
4868  logDto.Detalle = "El fichero de configuración offline " + lcBaseFicheroZip + ".zip no se ha podido generar.";
4869  logRepository.Insert(logDto);
4870  }
4871  else
4872  {
4873  logDto.Resultado = 1;
4874  logDto.Detalle = "El fichero de configuración offline " + lcBaseFicheroZip + ".zip se ha generado con éxito.";
4875  logRepository.Insert(logDto);
4876 
4877  string lcZipFile = Path.Combine(datos._PathFolderInicial, pathArchivoComprimido);
4878  lcZipFile = Path.Combine(lcZipFile, lcBaseFicheroZip);
4879  lcZipFile = lcZipFile + ".zip";
4880 
4881  long uploadedFileSize = 0;
4882  var carpetaserv = "/";
4883 
4884  llOk = UploadManager.Subir_Fichero(lcZipFile, "", carpetaserv, datos._IdConf, ref uploadedFileSize);
4885 
4886  int conexion = TipoConexion(datos);
4887  string lcDescrip = (conexion == 0 ? "FTP" : "OneDrive");
4888 
4889  if (llOk)
4890  {
4891  logDto.Resultado = 1;
4892  logDto.Detalle = "El fichero de configuración offline " + lcBaseFicheroZip + ".zip se ha subido a la carpeta " + carpetaserv + " del " + lcDescrip + ".";
4893  }
4894  else
4895  {
4896  logDto.Resultado = 3;
4897  logDto.Detalle = "No se ha podido subir fichero de configuración offline " + lcBaseFicheroZip + ".zip a carpeta FTP, revise si el usuario FTP configurado tiene permisos en la carpeta indicada.";
4898  }
4899 
4900  logRepository.Insert(logDto);
4901 
4902  }
4903  }
4904 
4905  return llOk;
4906  }
4907 
4908  private static void Procesar_Imagenes_Envio(string tcNombre, OfflineDatosComunicaciones datos, DataTable tdtImagenes, ILog_comoffRepository logRepository)
4909  {
4910  if (tdtImagenes.Rows.Count > 0)
4911  {
4912  _TextStepDetalle = "Procesando imagenes a enviar";
4913  _TextStepProgreso = _TextStepDetalle;
4914  _PorcenProgreso = IncrementarBarraProgreso();
4915 
4916  DataTable _ldtImgOff = new DataTable();
4917 
4918  //Obtenir imatges OFFLINE
4919  DB.SQLExec("SELECT * FROM " + DB.SQLDatabase("OFFLINE", "IMAGENES") + " ORDER BY TIPO, NOMBRE ", ref _ldtImgOff);
4920 
4921  // Obtenir últim número pel comtpador d'imatges
4922  int lnId = 0;
4923  if (_ldtImgOff.Rows.Count > 0)
4924  {
4925  lnId = Convert.ToInt32(_ldtImgOff.Compute("MAX(ID)", ""));
4926  }
4927 
4928  DB.SQLExec("SELECT * FROM " + DB.SQLDatabase("OFFLINE", "IMAGENES") + " WHERE SUCURSAL = " + DB.SQLString(datos._Sucursal) + " ORDER BY TIPO, NOMBRE ", ref _ldtImgOff);
4929 
4930  Log_comoffDto logDto = logRepository.GetDto(datos);
4931  logDto.TipoDato = "01";
4932  //Revisar imatges noves i modificades.
4933  foreach (DataRow item in tdtImagenes.Rows)
4934  {
4935  int lnTipo = item.Field<int>("Tipo");
4936  string lcRutaImagen = Path.GetDirectoryName(item.Field<string>("Imagen"));
4937  string lcNombreImagen = Path.GetFileName(item.Field<string>("Imagen"));
4938 
4939  string lcBuscar = "tipo = " + lnTipo.ToString().TrimEnd() + " and nombre = '" + lcNombreImagen + "'";
4940 
4941  DateTime ldData = DateTime.Today;
4942 
4943  bool llAfegir = false;
4944 
4945  // Únicament acceptem imatges que estiguis guardades al servidor d'Eurowin,
4946  // ja que és quan podrem garantir la seva correcta recepció
4947  if (!string.IsNullOrWhiteSpace(lcRutaImagen) && lcRutaImagen.ToLower().IndexOf(datos._IniServidor.ToLower()) < 0)
4948  {
4949  logDto.Resultado = 3;
4950  logDto.Detalle = "La imagen asociada al código '" + item.Field<string>("codigo") + "' de la tabla '" + Definicion_Tipo_Imagen(lnTipo) + "' no está almacenada en una carpeta dentro del servidor de Sage50. (" + lcRutaImagen + "\\" + lcNombreImagen + ")";
4951  logRepository.Insert(logDto);
4952  //continue;
4953  }
4954 
4955  // Ens saltem les imatges que no existeixen físicament.Si no s'indica ruta suposem que està a COMUNES\FOTOS
4956  string lcOrigen = (string.IsNullOrWhiteSpace(lcRutaImagen) ? datos._IniServidor + "COMUNES\\FOTOS\\" : lcRutaImagen + "\\") + lcNombreImagen;
4957 
4958  if (!File.Exists(lcOrigen))
4959  {
4960  logDto.Resultado = 3;
4961  logDto.Detalle = "La imagen " + lcNombreImagen + " no está almacenada en la carpeta especificada del servidor de Sage50.";
4962  logRepository.Insert(logDto);
4963  continue;
4964  }
4965 
4966  // Obtenim el MD5 de la imatge actual
4967 
4968  string lcNewControl = "";
4969 
4970  var plainTextBytes = Encoding.UTF8.GetBytes(lcOrigen);
4971  string lcValor = System.Convert.ToBase64String(plainTextBytes);
4972 
4973  try
4974  {
4975  DataRow[] ldrs = _ldtImgOff.Select(lcBuscar);
4976 
4977  DataTable _curMd5 = new DataTable();
4978  DB.SQLExec("select master.dbo.md5('" + lcValor + "') as control", ref _curMd5);
4979 
4980  if (_curMd5 != null && _curMd5.Rows.Count > 0)
4981  {
4982  lcNewControl = _curMd5.Rows[0]["control"].ToString();
4983  }
4984 
4985  if (ldrs.Length == 0)
4986  {
4987  // La imatge NO existeix, per tant l'afegim a la taula IMAGENES de la bd del OFFLINE
4988  llAfegir = true;
4989  lnId = lnId + 1;
4990 
4991  // Treiem de la ruta la part del servidor, ja que a cada instal.lació pot ser diferent
4992  string lcRutaDest = lcRutaImagen.Replace(datos._IniServidor, "");
4993 
4994  DataRow newRow = _ldtImgOff.NewRow();
4995  newRow["id"] = lnId;
4996  newRow["nombre"] = lcNombreImagen;
4997  newRow["control"] = lcNewControl;
4998  newRow["ruta"] = lcRutaDest;
4999  newRow["tipo"] = lnTipo;
5000  newRow["fecha"] = ldData;
5001  newRow["sucursal"] = datos._Sucursal;
5002  _ldtImgOff.Rows.Add(newRow);
5003 
5004  // Afegir també la imatge a la taula OFFLINE!IMAGENES
5005  DB.SQLExec("INSERT INTO " + DB.SQLDatabase("OFFLINE", "IMAGENES") + " (id,nombre,control,ruta,tipo,fecha,sucursal) " +
5006  " VALUES (" + DB.SQLString(lnId) + ", " + DB.SQLString(lcNombreImagen) + ", " + DB.SQLString(lcNewControl) + ", " +
5007  DB.SQLString(lcRutaDest) + ", " + DB.SQLString(lnTipo) + ", " + DB.SQLString(ldData) + ", " + DB.SQLString(datos._Sucursal) + ")");
5008  }
5009  else
5010  {
5011  // La imatge ja existeix, comprobar si ha canviat
5012  string lcControl = ldrs[0]["Control"].ToString();
5013 
5014  if (lcControl != lcNewControl)
5015  {
5016  llAfegir = true;
5017 
5018  ldrs[0]["Control"] = lcNewControl;
5019  ldrs[0]["Fecha"] = ldData;
5020 
5021  // Actualitzar també la imatge a la taula OFFLINE!IMAGENES
5022  DB.SQLExec("UPDATE " + DB.SQLDatabase("OFFLINE", "IMAGENES") + " SET control = " + DB.SQLString(lcNewControl) + ", fecha = " + DB.SQLString(ldData) +
5023  " WHERE tipo = " + DB.SQLString(lnTipo) + " AND nombre = " + DB.SQLString(lcNombreImagen) + " AND sucursal = " + DB.SQLString(datos._Sucursal));
5024 
5025  }
5026  }
5027  }
5028  catch (Exception)
5029  {
5030  throw;
5031  }
5032 
5033  // Anem afegint les imatges noves o modificades a la carpeta temporal
5034  if (llAfegir)
5035  {
5036  string lcDestino = Path.Combine(datos._PathFolderInicial, "IMAGENES");
5037 
5038  if (!Directory.Exists(lcDestino))
5039  Directory.CreateDirectory(lcDestino);
5040 
5041  lcDestino = Path.Combine(lcDestino, lcNombreImagen);
5042 
5043  try
5044  {
5045  File.Copy(lcOrigen, lcDestino, true);
5046 
5047  string lcTipoDato = clsOfflineUtils.ObtenerTipoDatoImagen(lnTipo);
5048 
5049  logDto.Resultado = 1;
5050  logDto.Detalle = "Imagen en la carpeta especificada del servidor de Sage50. (" + lcNombreImagen + ")";
5051  logRepository.Insert(logDto);
5052  }
5053  catch (Exception)
5054  {
5055  logDto.Resultado = 3;
5056  logDto.Detalle = "No ha sido posible copiar la imagen " + lcNombreImagen + ".";
5057  logRepository.Insert(logDto);
5058  }
5059  }
5060  }
5061 
5062  // Crear la taula lliure a enviar en la carpeta temporal
5063  ConvertIndividualFile(_ldtImgOff, Path.Combine(datos._PathFolderInicial, "IMAGENES"), "IMAGENES", FormatoExportacion.XML);
5064  }
5065  }
5066 
5067  private static void Seleccionar_Imagenes_Envio(bool tlImagenes, Dictionary<string, object> tablaSucursales, string lcTabla, OfflineDatosComunicaciones datos, ref DataTable ldtImagenes)
5068  {
5069  if (tlImagenes && tablaSucursales.ContainsKey("env_foto") && Convert.ToBoolean(tablaSucursales["env_foto"]))
5070  {
5071  DataTable temporal = new DataTable();
5072  string lcSql = string.Empty;
5073 
5074  // Obtenir imatges EUROWIN
5075  switch (lcTabla)
5076  {
5077  case "FAMILIAS":
5078  lcSql = "SELECT 1 as tipo, LTRIM(RTRIM(b.foto)) as imagen, b.codigo FROM " + DB.SQLDatabase("GESTION", lcTabla) + " b WHERE LTRIM(RTRIM(b.foto)) != '' ";
5079  break;
5080 
5081  case "MARCAS":
5082  lcSql = "SELECT 2 as tipo, LTRIM(RTRIM(b.foto)) as imagen, b.codigo FROM " + DB.SQLDatabase("GESTION", lcTabla) + " b WHERE LTRIM(RTRIM(b.foto)) != '' ";
5083  break;
5084 
5085  case "ART_FOTO":
5086  lcSql = "SELECT 3 as tipo, LTRIM(RTRIM(b.imagen)) as imagen, b.articulo as codigo FROM " + DB.SQLDatabase("GESTION", lcTabla) + " b WHERE LTRIM(RTRIM(b.imagen)) != '' ";
5087 
5088  // Casos especiales
5089  if (datos._EnvioArticulos)
5090  {
5091  lcSql += Envio_Articulos_Sucursal(datos, lcTabla);
5092  }
5093 
5094  break;
5095 
5096  case "COLORES":
5097  lcSql = "SELECT 4 as tipo, LTRIM(RTRIM(b.imagen)) as imagen, b.codigo FROM " + DB.SQLDatabase("COMUNES", lcTabla) + " b WHERE LTRIM(RTRIM(b.imagen)) != '' ";
5098  break;
5099 
5100  case "EMPRESA":
5101  lcSql = "SELECT 5 as tipo, LTRIM(RTRIM(b.foto)) as imagen, b.codigo FROM " + DB.SQLDatabase("GESTION", lcTabla) + " b WHERE LTRIM(RTRIM(b.foto)) != '' ";
5102  break;
5103 
5104  case "USUARIOS":
5105  lcSql = "SELECT 6 as tipo, LTRIM(RTRIM(b.foto)) as imagen, b.codigo FROM " + DB.SQLDatabase("COMUNES", lcTabla) + " b WHERE LTRIM(RTRIM(b.foto)) != '' ";
5106  break;
5107 
5108  case "SUBFAM":
5109  lcSql = "SELECT 7 as tipo, LTRIM(RTRIM(b.foto)) as imagen, b.codigo FROM " + DB.SQLDatabase("GESTION", lcTabla) + " b WHERE LTRIM(RTRIM(b.foto)) != '' ";
5110  break;
5111 
5112  case "VENDEDOR":
5113  lcSql = "SELECT 8 as tipo, LTRIM(RTRIM(b.foto)) as imagen, b.codigo FROM " + DB.SQLDatabase("GESTION", lcTabla) + " b WHERE LTRIM(RTRIM(b.foto)) != '' ";
5114  break;
5115 
5116  case "CLASIF":
5117  lcSql = "SELECT 9 as tipo, LTRIM(RTRIM(b.foto)) as imagen, b.codigo FROM " + DB.SQLDatabase("COMUNES", lcTabla) + " b WHERE LTRIM(RTRIM(b.foto)) != '' ";
5118  break;
5119  }
5120 
5121  if (DB.SQLExec(lcSql, ref temporal))
5122  {
5123  if (ldtImagenes.Rows.Count == 0)
5124  {
5125  ldtImagenes = temporal;
5126  }
5127  else
5128  {
5129  DBfunctions.SQLUnionDatatable(ref ldtImagenes, temporal);
5130  }
5131  }
5132  }
5133  }
5134 
5135  private static bool Revisar_Imagenes_Datos(bool tlImagenes, Dictionary<string, object> tablaSucursales, string lcTabla, OfflineDatosComunicaciones datos, ref DataTable ldtDatos)
5136  {
5137  if (ldtDatos.Rows.Count == 0)
5138  {
5139  return false;
5140  }
5141 
5142  if (!tlImagenes || (tablaSucursales.ContainsKey("env_foto") && !Convert.ToBoolean(tablaSucursales["env_foto"])))
5143  {
5144  DataTable temporal = new DataTable();
5145  string lcSql = string.Empty;
5146 
5147  // Obtenir imatges EUROWIN
5148  switch (lcTabla)
5149  {
5150  case "FAMILIAS":
5151  case "MARCAS":
5152  case "EMPRESA":
5153  case "USUARIOS":
5154  case "SUBFAM":
5155  case "VENDEDOR":
5156  case "CLASIF":
5157  foreach (DataRow item in ldtDatos.Rows)
5158  {
5159  item["foto"] = string.Empty;
5160  }
5161  break;
5162 
5163  case "COLORES":
5164  foreach (DataRow item in ldtDatos.Rows)
5165  {
5166  item["imagen"] = string.Empty;
5167  }
5168  break;
5169 
5170  case "ART_FOTO":
5171  ldtDatos.Clear();
5172  ldtDatos.AcceptChanges();
5173 
5174  return false;
5175  }
5176  }
5177 
5178  return true;
5179  }
5180 
5181  private static DataTable obtenerDatosEnvio(Dictionary<int, bool> prioridades, string cTipoEnvio)
5182  {
5183  string lcSql = string.Empty;
5184  string lcWhereCentral = string.Empty;
5185  string lcWhereSucur = string.Empty;
5186  string lcOrCentral = string.Empty;
5187  string lcOrSucur = string.Empty;
5188 
5189  foreach (KeyValuePair<int, bool> item in prioridades)
5190  {
5191  if (item.Value)
5192  {
5193  lcWhereCentral += lcOrCentral + " ID = " + DB.SQLString(item.Key);
5194  lcOrCentral = " OR ";
5195  }
5196  else
5197  {
5198  lcWhereSucur += lcOrSucur + " ID = " + DB.SQLString(item.Key);
5199  lcOrSucur = " OR ";
5200  }
5201  }
5202 
5203  // Task 190661: Envío de datos - Addons Fabricación
5204  if (cTipoEnvio == "e" && (prioridades.ContainsKey(159) && !prioridades.ContainsKey(292)))
5205  {
5206  if (!string.IsNullOrEmpty(lcWhereCentral))
5207  {
5208  lcWhereCentral += lcOrCentral + " ID = " + DB.SQLString(292);
5209  lcOrCentral = " OR ";
5210  }
5211  else
5212  {
5213  lcWhereSucur += lcOrSucur + " ID = " + DB.SQLString(292);
5214  lcOrSucur = " OR ";
5215  }
5216  }
5217 
5218  if (!string.IsNullOrWhiteSpace(lcOrCentral))
5219  {
5220  lcWhereCentral = " AND (" + lcWhereCentral + ")";
5221  }
5222  else
5223  {
5224  lcWhereCentral = " AND ( 1=2 )";
5225  }
5226 
5227  if (!string.IsNullOrWhiteSpace(lcOrSucur))
5228  {
5229  lcWhereSucur = " AND (" + lcWhereSucur + ")";
5230  }
5231  else
5232  {
5233  lcWhereSucur = " AND ( 1=2 )";
5234  }
5235 
5236  // Obtenemos datos en la tabla dependiendo del tipo de envío:
5237  // i -> Carga Inicial
5238  // e -> Envío de datos
5239  string lcCampoWhere = (cTipoEnvio == "i" ? "visicarga" : "visible");
5240 
5241  DataTable TabTmp = new DataTable();
5242 
5243  //Obtenir totes les taules del Tabrel a enviar en la càrrega inicial
5244  lcSql += " SELECT clave, (CASE WHEN secundaria = '' THEN principal ELSE secundaria END) as nombre, " +
5245  " empresa, id, idgrupo, principal, cast(1 as bit) as prioridad, visicond, UPPER(nombre) as titulo, tipotabla, " +
5246  " cast(condenv as varchar(max)) as condenv, cast(condsecun as varchar(max)) as condsecun, " +
5247  " asientos, otrasien, eos, iva_exen, ivasopor, ivareper, retsopor, retreper, compras, relacion, empresecun, visible, condctrl, tablactrl, relactrl " + Environment.NewLine +
5248  " FROM " + DB.SQLDatabase("OFFLINE", "TABRELNET") + Environment.NewLine +
5249  " WHERE 1=1 " +
5250  " AND clave IN (SELECT DISTINCT CLAVE FROM " + DB.SQLDatabase("OFFLINE", "TABRELNET") + " WHERE " + lcCampoWhere + " = 1 " + lcWhereCentral + ") " + Environment.NewLine;
5251 
5252  lcSql += " UNION ALL " + Environment.NewLine;
5253 
5254  lcSql += " SELECT clave, (CASE WHEN secundaria = '' THEN principal ELSE secundaria END) as nombre, " +
5255  " empresa, id, idgrupo,principal, cast(0 as bit) as prioridad, visicond, UPPER(nombre) as titulo, tipotabla, " +
5256  " cast(condenv as varchar(max)) as condenv, cast(condsecun as varchar(max)) as condsecun, " +
5257  " asientos, otrasien, eos, iva_exen, ivasopor, ivareper, retsopor, retreper, compras, relacion, empresecun, visible, condctrl, tablactrl, relactrl " + Environment.NewLine +
5258  " FROM " + DB.SQLDatabase("OFFLINE", "TABRELNET") + Environment.NewLine +
5259  " WHERE 1=1 " +
5260  " AND clave IN (SELECT DISTINCT CLAVE FROM " + DB.SQLDatabase("OFFLINE", "TABRELNET") + " WHERE " + lcCampoWhere + " = 1 " + lcWhereSucur + ") " + Environment.NewLine;
5261 
5262  DB.SQLExec(lcSql, ref TabTmp);
5263 
5264  TabTmp.DefaultView.Sort = " CLAVE ASC, VISIBLE DESC, PRINCIPAL ASC, PRIORIDAD DESC ";
5265  TabTmp = TabTmp.DefaultView.ToTable();
5266 
5267  // Addons Fabricación
5268  if (TabTmp != null && TabTmp.Rows.Count > 0 && (cTipoEnvio == "e" && (prioridades.ContainsKey(159) && !prioridades.ContainsKey(292))))
5269  {
5270  DataRow[] ldrDelete = TabTmp.Select("id = 292");
5271  if (ldrDelete != null && ldrDelete.Length == 1)
5272  {
5273  ldrDelete[0].Delete();
5274  }
5275  TabTmp.AcceptChanges();
5276  }
5277 
5278  // Riesgo de clientes
5279  bool _lEsSucursal = Convert.ToBoolean(EW_GLOBAL._ModuloActivo("OFFLINE")) && !Convert.ToBoolean(EW_GLOBAL._GetVariable("wl_TipoOffline"));
5280  if (TabTmp != null && TabTmp.Rows.Count > 0 && prioridades.ContainsKey(47) && _lEsSucursal)
5281  {
5282  DataRow[] ldrDelete = TabTmp.Select("id = 287");
5283  if (ldrDelete != null && ldrDelete.Length == 1)
5284  {
5285  ldrDelete[0].Delete();
5286  }
5287  TabTmp.AcceptChanges();
5288  }
5289 
5290  DataTable dtTemp = new DataTable();
5291 
5292  if (TabTmp != null && TabTmp.Rows.Count > 0)
5293  dtTemp = TabTmp.Clone();
5294 
5295  foreach (DataRow item in TabTmp.Rows)
5296  {
5297  if (item.Field<string>("nombre").TrimEnd() != item.Field<string>("principal").TrimEnd())
5298  {
5299  // descarto los historicos de series
5300  if (item.Field<string>("nombre").TrimEnd() == "COMUNES!HISSERIE")
5301  {
5302  continue;
5303  }
5304 
5305  // busco si existe el principal en otro registro como nombre
5306  DataRow[] ldrs = TabTmp.Select("nombre = '" + item.Field<string>("principal").TrimEnd() + "' and principal = '" + item.Field<string>("principal").TrimEnd() + "' and clave ='" + item.Field<string>("clave").TrimEnd() + "' ");
5307  if (ldrs.Length == 0)
5308  {
5309  // busco si existe el principal en tabla temporal
5310  DataRow[] ldrTemp = dtTemp.Select("nombre = '" + item.Field<string>("principal").TrimEnd() + "' and principal = '" + item.Field<string>("principal").TrimEnd() + "'and clave ='" + item.Field<string>("clave").TrimEnd() + "' ");
5311  if (ldrTemp.Length == 0)
5312  {
5313  // Copio el registro en la tabla temporal
5314  DataRow dataRow = dtTemp.NewRow();
5315 
5316  dataRow.ItemArray = item.ItemArray.Clone() as object[];
5317  dataRow["nombre"] = dataRow["principal"];
5318  dataRow["asientos"] = "";
5319  dataRow["otrasien"] = "";
5320  dataRow["eos"] = "";
5321  dataRow["relacion"] = "";
5322  dataRow["iva_exen"] = "";
5323  dataRow["ivasopor"] = "";
5324  dataRow["ivareper"] = "";
5325  dataRow["retreper"] = "";
5326  dataRow["retsopor"] = "";
5327  dataRow["compras"] = "";
5328 
5329  dtTemp.Rows.Add(dataRow);
5330  }
5331  }
5332  }
5333  }
5334 
5335  if (dtTemp != null && dtTemp.Rows.Count > 0)
5336  TabTmp.Merge(dtTemp);
5337 
5338  TabTmp.DefaultView.Sort = " CLAVE ASC, VISIBLE DESC, PRINCIPAL ASC, RELACION ASC ";
5339  TabTmp = TabTmp.DefaultView.ToTable();
5340 
5341  return TabTmp;
5342  }
5343 
5344  private static bool UploadIndividualFile(DataTable datos, string path, string nombreTabla, int idConf, FormatoExportacion formatoExportacion, ref long uploadedFileSize, string carpeta)
5345  {
5346  //Prueba temporal con la tabla de sucursales
5347  string uploadFile = Path.Combine(path, nombreTabla + "." + formatoExportacion.ToString());
5348 
5349  ConvertIndividualFile(datos, path, nombreTabla, formatoExportacion);
5350 
5351  string zippedName = Path.GetFileName(uploadFile) + ".zip";
5352 
5353  if (!UploadManager.Subir_Fichero(uploadFile, zippedName, carpeta, idConf, ref uploadedFileSize))
5354  return false;
5355 
5356  return true;
5357  }
5358 
5359  #endregion Métodos para el Asistente de Configuración
5360  }
5361 }
5362 
bool _Send(string tcCliente="", string tcProveedor="", string tcResumen="")
Envia el correo
Definition: SendMail.cs:198
Clase para el envío de emails
Definition: SendMail.cs:21
Log_comoffDto GetDto(OfflineDatosComunicaciones datos)
Obtiene un dto a partir de DAtos de comunicaciones
bool _EnvioDirecto
Utilizar el correo predeterminado de Windows o el envío directo de Sage50 false : envio mediante clie...
Definition: SendMail.cs:37
object Retrieve(Type T)
Resuelve objeto de tipo T
Es como el tipo de entrada asientos pero por negocio, sin formulario, pq quiero que me haga las propu...
override string _NombreFicheroExportar
Sobreescribir la propiedad de _NombreFicheroExportar para que tenga el valor del nombre de fichero se...
string _Error_Message
Mensaje de error
Definition: SendMail.cs:167
Clase EW_GLOBAL para gestionar las variables públicas de Eurowin, variables de empresa, variables de anchuras de campo, variables de mascaras, etc.
Definition: EW_GLOBAL.cs:46
virtual string _Nombre
Campo nombre del mantenimiento. En este hay que basar los demás campos en las clases heredadas ...
Definition: clsEwBase.cs:2655
void _AddAttachment(string tcFileName)
Añade un fichero adjunto
Definition: SendMail.cs:332
string _Subject
Asunto del correo
Definition: SendMail.cs:94
List< string > _Emails
Dirección de correo electrónico a la que se enviará el correo
Definition: SendMail.cs:79
ILog_comoffRepository Log_comoffRepository
Repositorio de log_comoff
static string _CodigoGrupoActual()
Obtención del código de grupo actual
Definition: GruposEmp.cs:1744
Clase para el control de grupos de empresa (nuevo enfoque en Sage50, desaparece el multiempresa...
Definition: GruposEmp.cs:40
bool _CCOUsuarioActivo
India si tenemos que añadir CCO a los emails definidos en el usuario
Definition: SendMail.cs:104
Dto para inserciones en log log_comoff
string _Body
Cuerpo del mensaje
Definition: SendMail.cs:99
TipoConexion
Tipo de conexión
bool _ShowEmailForm
Para mostrar el formulario del correo en envío directo true : presenta el formulario false : envia si...
Definition: SendMail.cs:30
Clase Inyector de dependencias para resolver las dependencias
bool _Exportar(ExportType toTipoDocumento, string tcRutaFichero, bool tlAbrirFichero=false, string tcPantalla="")
Nos exportará el listado hacia una ruta especificada. Se podra abrir tras su exportación.