AsientoApertura.cs
2 using sage.ew.db;
3 using sage.ew.empresa;
4 using sage.ew.ewbase;
5 using sage.ew.ewbase.Clases;
6 using sage.ew.formul.Classes;
7 using sage.ew.functions;
8 using sage.ew.global;
9 using sage.ew.interficies;
10 using sage.ew.listados.Clases;
11 using sage.ew.listados.Procesos;
13 using System;
14 using System.Collections.Generic;
15 using System.Data;
16 using System.Linq;
17 using System.Text;
18 using System.Windows.Forms;
19 
20 namespace sage.ew.contabilidad.Clases
21 {
25  public class AsientoApertura
26  {
27  private String _cErrorMessage;
28  private String _cInfoMessage;
29  private Boolean _bGenerarAsientoAplicacionPerdidasGanancias = true;
30  private Boolean _bGenerAsientoApertura = true;
31 
32  private DateTime? _oDateIni = null;
33  private DataTable _oDatosCierre = null;
34  private DataTable _oDatosEjercicioAnterior = null;
35  private Asientos _oAsientoAntiguo;
36  private ProcessBar _oProcess;
37 
38  private string _cCuentaResultados = "";
39  private string _cCuentaRemanenteAcreedor = "";
40  private string _cCuentaRemanenteDeudor = "";
41 
42  private string _cNombreCuentaResultados = "";
43  private string _cNombreCuentaRemanenteAcreedor = "";
44  private string _cNombreCuentaRemanenteDeudor = "";
45 
46  private String _cMonedaEmpresa = EW_GLOBAL._Moneda._Codigo;
47 
48 
49  private enum TipoAsiento
50  {
51  Apertura,
52  Aplicacion
53  }
54 
55  private String _CuentaResultados
56  {
57  get
58  {
59  if (String.IsNullOrEmpty(_cCuentaResultados)) _cCuentaResultados = Convert.ToString(EW_GLOBAL._GetVariable("wc_perdi"));
60 
61  return _cCuentaResultados;
62  }
63  }
64 
65  private String _NombreCuentaResultados
66  {
67  get
68  {
69  if(String.IsNullOrEmpty(_cNombreCuentaResultados)) _ObtenerCuentasRemanentes();
70 
71  return _cNombreCuentaResultados;
72  }
73  }
74 
78  private String _CuentaRemanenteAcreedor
79  {
80  get
81  {
82  if (String.IsNullOrEmpty(_cCuentaRemanenteAcreedor)) _ObtenerCuentasRemanentes();
83 
84  return _cCuentaRemanenteAcreedor;
85  }
86  }
87 
88  private String _NombreCuentaRemanenteAcreedor
89  {
90  get
91  {
92  if (String.IsNullOrEmpty(_cNombreCuentaRemanenteAcreedor)) _ObtenerCuentasRemanentes();
93 
94  return _cNombreCuentaRemanenteAcreedor;
95  }
96  }
97 
101  private String _CuentaRemanenteDeudor
102  {
103  get
104  {
105  if (String.IsNullOrEmpty(_cCuentaRemanenteDeudor)) _ObtenerCuentasRemanentes();
106 
107  return _cCuentaRemanenteDeudor;
108  }
109  }
110 
111  private String _NombreCuentaRemanenteDeudor
112  {
113  get
114  {
115  if (String.IsNullOrEmpty(_cNombreCuentaRemanenteDeudor)) _ObtenerCuentasRemanentes();
116 
117  return _cNombreCuentaRemanenteDeudor;
118  }
119  }
120 
124  public Boolean _GenerAsientoApertura
125  {
126  get
127  {
128  return _bGenerAsientoApertura;
129  }
130  set
131  {
132  _bGenerAsientoApertura = value;
133  }
134  }
135 
139  public Boolean _GenerarAsientoAplicacionPerdidasGanancias
140  {
141  get
142  {
143  return _bGenerarAsientoAplicacionPerdidasGanancias;
144  }
145  set
146  {
147  _bGenerarAsientoAplicacionPerdidasGanancias = value;
148  }
149  }
150 
154  private ProcessBar _ProcessBar
155  {
156  get
157  {
158  if (_oProcess == null) _oProcess = new ProcessBar(false, "");
159  return _oProcess;
160  }
161  set
162  {
163  _oProcess = value;
164  }
165  }
166 
167  private Asientos _AsientoAntiguo
168  {
169  get
170  {
171  if (_oAsientoAntiguo == null) _oAsientoAntiguo = new Asientos();
172  return _oAsientoAntiguo;
173  }
174  }
175 
176  private String _CodigoEmpresa
177  {
178  get
179  {
180  return EW_GLOBAL._Empresa._Codigo;
181  }
182  }
183 
187  public String _ErrorMessage
188  {
189  get
190  {
191  return _cErrorMessage;
192  }
193  }
194 
198  public String _InfoMessage
199  {
200  get
201  {
202  return _cInfoMessage;
203  }
204  }
205 
209  public DateTime _Fecha
210  {
211  get
212  {
213  if(_oDateIni == null)
214  {
215  _oDateIni =((DateTime)ew.global.EW_GLOBAL._GetVariable("wd_periodoini", DateTime.Today));
216  }
217  return Convert.ToDateTime(_oDateIni);
218  }
219  }
220 
224  public Boolean _IsProvisional
225  {
226  get
227  {
228  return _DatosCierre.Rows.Count == 0;
229  }
230  }
231 
232  private DataTable _DatosCierre
233  {
234  get
235  {
236  if (_oDatosCierre == null)
237  {
238  String lcSql, lcCon;
239 
240  _oDatosCierre = new DataTable();
241 
242  if (_ConfigEjercicioAnterior.Rows.Count > 0)
243  {
244  lcCon = DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "ASIENTOS");
245 
246  lcSql = String.Format("SELECT * FROM {0} WHERE EMPRESA = '{1}' AND TIPO = '{2}' ORDER BY CUENTA", lcCon, _CodigoEmpresa, Convert.ToInt32(eTipoMovimientoAsiento.Cierre));
247  DB.SQLExec(lcSql, ref _oDatosCierre);
248  }
249  }
250 
251  return _oDatosCierre;
252  }
253  }
254 
258  private DataTable _ConfigEjercicioAnterior
259  {
260  get
261  {
262  if(_oDatosEjercicioAnterior == null)
263  {
264  String lcSql;
265  Int32 lnEjercicio;
266  _oDatosEjercicioAnterior = new DataTable();
267 
268  lnEjercicio = Convert.ToInt32(DB.Ejercicio_EW) - 1;
269  lcSql = String.Format("SELECT * FROM {0} WHERE [ANY] = {1} ", DB.SQLDatabase("COMUNES", "EJERCICI"), DB.SQLString(lnEjercicio));
270  DB.SQLExec(lcSql, ref _oDatosEjercicioAnterior);
271  }
272 
273  return _oDatosEjercicioAnterior;
274  }
275  }
276 
277  private void _ObtenerCuentasRemanentes()
278  {
279  String lcSql;
280  DataTable loDt = new DataTable();
281 
282  lcSql = String.Format("SELECT CODIGO, NOMBRE FROM {0} asi WHERE LEFT(asi.codigo, 3) = '120' OR LEFT(asi.codigo, 3) = '121' OR CODIGO = '{1}' ORDER BY CODIGO ", DB.SQLDatabase("GESTION", "CUENTAS"), _CuentaResultados);
283  DB.SQLExec(lcSql, ref loDt);
284 
285  if (loDt.Rows.Count > 0)
286  {
287  List<DataRow> loRows = (from loRow in loDt.AsEnumerable()
288  where Convert.ToString(loRow["CODIGO"]).Substring(0, 3) == "120"
289  orderby Convert.ToString(loRow["CODIGO"])
290  select loRow).ToList();
291 
292  if (loRows.Count > 0)
293  {
294  _cCuentaRemanenteAcreedor = Convert.ToString(loRows.First()["CODIGO"]);
295  _cNombreCuentaRemanenteAcreedor = Convert.ToString(loRows.First()["NOMBRE"]);
296  }
297 
298  loRows = (from loRow in loDt.AsEnumerable()
299  where Convert.ToString(loRow["CODIGO"]).Substring(0, 3) == "121"
300  orderby Convert.ToString(loRow["CODIGO"])
301  select loRow).ToList();
302 
303  if (loRows.Count > 0)
304  {
305  _cCuentaRemanenteDeudor = Convert.ToString(loRows.First()["CODIGO"]);
306  _cNombreCuentaRemanenteDeudor = Convert.ToString(loRows.First()["NOMBRE"]);
307  }
308 
309  loRows = (from loRow in loDt.AsEnumerable()
310  where Convert.ToString(loRow["CODIGO"]) == _CuentaResultados
311  select loRow).ToList();
312  if (loRows.Count > 0)
313  {
314  _cNombreCuentaResultados = Convert.ToString(loRows.First()["NOMBRE"]);
315  }
316  }
317  }
318 
319  private String _FiltroFecha(String lcAlias = "")
320  {
321  String lcSql = "";
322  DateTime loPerIniAnt, loPerFinAnt;
323 
324  lcAlias = lcAlias.Trim();
325  if (!String.IsNullOrEmpty(lcAlias) && !lcAlias.EndsWith(".")) lcAlias = String.Format("{0}.", lcAlias.Trim());
326 
327  if (_ConfigEjercicioAnterior.Rows.Count > 0)
328  {
329  loPerIniAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0]["PERIODOINI"]);
330  loPerFinAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0]["PERIODOFIN"]);
331 
332  lcSql = String.Format("AND {0}fecha >= {1} AND {0}fecha <= {2} ", lcAlias, DB.SQLString(loPerIniAnt), DB.SQLString(loPerFinAnt));
333  }
334 
335  return lcSql;
336  }
337 
343  public Boolean _AsientoAperturaProvisional(ref Asientos toAsiento)
344  {
345  return _AsientoAperturaProvisional(ref toAsiento, false);
346  }
347 
355  public Boolean _AsientoAperturaProvisional(ref Asientos toAsiento, bool tlRenumerar)
356  {
357  DataTable loDt;
358 
359  _cErrorMessage = "";
360 
361  _ProcessBar.InitGauge(1, 100, String.Format("Obteniendo datos del ejercicio anterior"));
362 
363  loDt = _ObtenerSaldos();
364 
365  bool llOk = _CreaAsientoApertura(ref toAsiento, loDt);
366 
367  if (llOk && tlRenumerar)
368  RenumerarAsientos(2, 0, out string _cErrorMessage);
369 
370  return llOk;
371 
372  }
373 
374  private Boolean _ObtenerAsiento(ref Asientos toAsiento, TipoAsiento totipo)
375  {
376  Int32 lnNumTipo, lnNum = 0;
377 
378  toAsiento._Empresa = _CodigoEmpresa;
379  toAsiento._Fecha = _Fecha;
380 
381  _oAsientoAntiguo = new Asientos();
382 
383  if (totipo == TipoAsiento.Apertura)
384  {
385  lnNum = _ExisteAsientoApertura();
386  lnNumTipo = 1;
387  toAsiento._Tipo = "1";
388  }
389  else
390  {
391  toAsiento._Tipo = "4";
392  lnNum = _ExisteAsientoAplicacion();
393  lnNumTipo = 2;
394  }
395 
396  toAsiento._Numero = lnNum == 0 && !_ExisteNumAsiento(lnNumTipo) ? lnNumTipo : lnNum;
397 
398  if (lnNum > 0)
399  {
400  Asientos loAsientoAper = new Asientos();
401  loAsientoAper._Empresa = _CodigoEmpresa;
402  loAsientoAper._Numero = lnNum;
403  loAsientoAper._Load();
404  _oAsientoAntiguo._Clonar(loAsientoAper);
405 
406  if (!loAsientoAper._Delete())
407  {
408  _cErrorMessage = String.Format("No se ha podido eliminar el asiento {0}", lnNum);
409  return false;
410  }
411  }
412 
413  return true;
414  }
415 
416  private Boolean _AsientoAplicacionPerdidasGanancias(ref Asientos toAsiento)
417  {
418  Int32 lnNum;
419 
420  _ProcessBar.InitGauge(1, 10, String.Format("Creando asiento de aplicación de pérdidas o ganancias "));
421 
422  lnNum = _ExisteAsientoApertura();
423 
424  Asientos loAsientoApertura = new Asientos();
425  loAsientoApertura._Empresa = _CodigoEmpresa;
426  loAsientoApertura._Numero = lnNum;
427  loAsientoApertura._Load();
428 
429  List<IAsientosLinea> loLinResultados = (from loLin in loAsientoApertura._Lineas
430  where loLin._Cuenta == _CuentaResultados
431  select loLin).ToList();
432 
433  if(loLinResultados.Count > 0)
434  {
435  if (_ObtenerAsiento(ref toAsiento, TipoAsiento.Aplicacion))
436  {
437  if (loLinResultados.First()._Haber != 0 || loLinResultados.First()._Debe != 0)
438  {
439  _ProcessBar.Step();
440 
441  IAsientosLinea lineaResultados = toAsiento._AddLinea();
442 
443  lineaResultados._Cuenta = _CuentaResultados;
444  lineaResultados._Definicion = _NombreCuentaResultados;
445 
446  IAsientosLinea lineaRemanente = toAsiento._AddLinea();
447 
448  if (loLinResultados.First()._Haber > 0)
449  {
450  lineaResultados._Debe = loLinResultados.First()._Haber;
451 
452  lineaRemanente._Cuenta = _CuentaRemanenteAcreedor;
453  lineaRemanente._Definicion = _NombreCuentaRemanenteAcreedor;
454  lineaRemanente._Haber = lineaResultados._Debe;
455  }
456  else if (loLinResultados.First()._Haber < 0)
457  {
458  lineaResultados._Debe = loLinResultados.First()._Haber;
459 
460  lineaRemanente._Cuenta = _CuentaRemanenteDeudor;
461  lineaRemanente._Definicion = _NombreCuentaRemanenteDeudor;
462  lineaRemanente._Haber = lineaResultados._Debe;
463  }
464  else if (loLinResultados.First()._Debe > 0)
465  {
466  lineaResultados._Debe = loLinResultados.First()._Debe * -1;
467 
468  lineaRemanente._Cuenta = _CuentaRemanenteDeudor;
469  lineaRemanente._Definicion = _NombreCuentaRemanenteDeudor;
470  lineaRemanente._Haber = lineaResultados._Debe;
471  }
472  else if (loLinResultados.First()._Debe < 0)
473  {
474  lineaResultados._Debe = loLinResultados.First()._Debe;
475 
476  lineaRemanente._Cuenta = _CuentaRemanenteDeudor;
477  lineaRemanente._Definicion = _NombreCuentaRemanenteDeudor;
478  lineaRemanente._Haber = lineaResultados._Debe;
479  }
480 
481  if (!toAsiento._Save())
482  {
483  if (_oAsientoAntiguo is Asientos) _oAsientoAntiguo._Save();
484  _cErrorMessage = String.Format("No se ha podido crear el asiento de aplicación: {0}", toAsiento._Mensaje_Error);
485  }
486  }
487  else
488  {
489  _cInfoMessage = "No se ha podido crear el asiento de aplicación ya que el resultado del ejercicio es cero.";
490  }
491 
492  _ProcessBar.InitGauge(10, 10, string.Format("Creando asiento de aplicación de pérdidas o ganancias "));
493  }
494  }
495  else
496  {
497  _cErrorMessage = string.Format("No se ha podido crear el asiento de aplicación: No se ha encontrado ninguna linea en el asiento de apertura de la cuenta {0}", _CuentaResultados);
498  }
499 
500  return string.IsNullOrEmpty(_cErrorMessage) && string.IsNullOrEmpty(_cInfoMessage);
501  }
502 
503  private Boolean _ExisteNumAsiento(Int32 tnNum)
504  {
505  String lcSql;
506  DataTable loDt = new DataTable();
507 
508  lcSql = String.Format("SELECT * FROM {0} WHERE EMPRESA = '{1}' AND TIPO != 1 AND TIPO != 4 AND NUMERO = {2} ", DB.SQLDatabase("GESTION", "ASIENTOS"), _CodigoEmpresa, tnNum);
509  DB.SQLExec(lcSql, ref loDt);
510 
511  return loDt.Rows.Count > 0;
512  }
513 
514  private DataTable _ObtenerSaldos()
515  {
516  DataTable loDtDebe = new DataTable();
517  DataTable loDtHaber = new DataTable();
518  DataTable loDt = new DataTable();
519  String lcCompra, lcVenta, lcSql, lcCon;
520  Boolean llNoDivisa;
521  DateTime loPerIniAnt, loPerFinAnt;
522 
523  lcCompra = Convert.ToString(EW_GLOBAL._GetVariable("wc_compra")).Substring(0, 1); // Primer caracter de la cuenta de compras.
524  lcVenta = Convert.ToString(EW_GLOBAL._GetVariable("wc_venta")).Substring(0, 1); // Primer caracter de la cuenta de ventas.
525 
526  lcCon = Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]);
527 
528  //Asiento agrupado en una sola divisa
529  llNoDivisa = Convert.ToBoolean(EW_GLOBAL._GetVariable("wl_asicierrediv"));
530 
531  loPerIniAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0]["PERIODOINI"]);
532  loPerFinAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0]["PERIODOFIN"]);
533 
534 
535  //Obtinc els saldos dels comptes
536  if(llNoDivisa)
537  {
538  lcSql = String.Format("SELECT asi.cuenta, cue.nombre, SUM(asi.debe) as debe, SUM(asi.debediv) as debediv, 0.0 as haber, 0.0 as haberDiv, {0} as divisa ", llNoDivisa ? String.Format("'{0}'", EW_GLOBAL._Moneda._Codigo) : "asi.divisa");
539  }
540  else
541  {
542  lcSql = String.Format("SELECT asi.cuenta, cue.nombre, asi.debe as debe, asi.debediv as debediv, 0.0 as haber, 0.0 as haberDiv, {0} as divisa, asi.tipo_mov ", llNoDivisa ? String.Format("'{0}'", EW_GLOBAL._Moneda._Codigo) : "asi.divisa");
543  }
544 
545  lcSql += String.Format("FROM {0} cue LEFT JOIN {1} asi ON cue.codigo = asi.cuenta ", DB.SQLDatabaseReal(lcCon, "CUENTAS"), DB.SQLDatabaseReal(lcCon, "ASIENTOS"));
546  lcSql += String.Format("WHERE empresa = '{0}' AND haber = 0 AND tipo != '3' {1}", _CodigoEmpresa, _FiltroFecha("asi"));
547  lcSql += String.Format("AND LEFT(asi.cuenta, 1) != '{0}' AND LEFT(asi.cuenta, 1) != '{1}' ", lcCompra, lcVenta);
548 
549  if (llNoDivisa) lcSql += String.Format("GROUP BY asi.cuenta, cue.nombre {0} ", llNoDivisa ? "" : ", asi.divisa");
550  lcSql += "ORDER BY asi.CUENTA ";
551 
552  if(!DB.SQLExec(lcSql, ref loDtDebe))
553  {
554  throw new Exception("No se ha podido obtener los saldos de las cuentas. Imposible realizar els asiento de apertura provisional.");
555  }
556 
557  //Obtinc els saldos dels comptes al DEURE
558  if (llNoDivisa)
559  {
560  lcSql = String.Format("SELECT asi.cuenta, cue.nombre, SUM(asi.haber) as haber, SUM(asi.haberdiv) as haberDiv, 0.0 as debe, 0.0 as debediv, {0} as divisa ", llNoDivisa ? String.Format("'{0}'", _cMonedaEmpresa) : "asi.divisa");
561  }
562  else
563  {
564  lcSql = String.Format("SELECT asi.cuenta, cue.nombre, asi.haber as haber, asi.haberdiv as haberDiv, 0.0 as debe, 0.0 as debediv, {0} as divisa, asi.tipo_mov ", llNoDivisa ? String.Format("'{0}'", _cMonedaEmpresa) : "asi.divisa");
565  }
566 
567  lcSql += String.Format("FROM {0} cue LEFT JOIN {1} asi ON cue.codigo = asi.cuenta ", DB.SQLDatabaseReal(lcCon, "CUENTAS"), DB.SQLDatabaseReal(lcCon, "ASIENTOS"));
568  lcSql += String.Format("WHERE empresa = '{0}' AND debe = 0 AND tipo != '3' ", _CodigoEmpresa);
569  lcSql += String.Format("AND asi.fecha >= {0} AND asi.fecha <= {1} ", DB.SQLString(loPerIniAnt), DB.SQLString(loPerFinAnt));
570  lcSql += String.Format("AND LEFT(asi.cuenta, 1) != '{0}' AND LEFT(asi.cuenta, 1) != '{1}' ", lcCompra, lcVenta);
571  if (llNoDivisa) lcSql += String.Format("GROUP BY asi.cuenta, cue.nombre {0} ", llNoDivisa ? "" : ", asi.divisa");
572  lcSql += "ORDER BY asi.CUENTA ";
573 
574  if (!DB.SQLExec(lcSql, ref loDtHaber))
575  {
576  throw new Exception("No se ha podido obtener los saldos de las cuentas. Imposible realizar els asiento de apertura provisional.");
577  }
578 
579  loDt = loDtDebe.Clone();
580 
581  _AddRows(ref loDt, loDtDebe);
582  _AddRows(ref loDt, loDtHaber);
583 
584 
585  if (!llNoDivisa)
586  {
587  var loGroups = (from loRow in loDt.AsEnumerable()
588  where _EsDiferenciaCambio(Convert.ToInt32(loRow["tipo_mov"]), Convert.ToString(loRow["cuenta"]))
589  group loRow by new { Cuenta = Convert.ToString(loRow["cuenta"]) } into g
590  select new
591  {
592  Cuenta = g.Key.Cuenta,
593  Rows = g.ToList().Where(f => Convert.ToString(f["divisa"]) != _cMonedaEmpresa).ToList()
594  }).ToList();
595 
596 
597  loGroups.Where(f => f.Rows.Count > 0).ToList().ForEach(f =>
598  {
599  var loDiv = (from loRowDiv in loDt.AsEnumerable()
600  where Convert.ToString(loRowDiv["divisa"]).Trim() != _cMonedaEmpresa && f.Cuenta == Convert.ToString(loRowDiv["cuenta"]).Trim()
601  select new { Divisa = Convert.ToString(loRowDiv["divisa"]) }).FirstOrDefault();
602 
603  if (loDiv != null)
604  {
605  f.Rows.ForEach(loRow =>
606  {
607  loRow["divisa"] = loDiv.Divisa;
608  loRow["tipo_mov"] = 0;
609  loRow["haberdiv"] = 0;
610  loRow["debediv"] = 0;
611  });
612  }
613  });
614  }
615 
616 
617  loDt = (from loRow in loDt.AsEnumerable()
618  group loRow by new { Cuenta = loRow["CUENTA"], Nombre = loRow["NOMBRE"], Divisa = loRow["DIVISA"] } into g
619  where g.Sum(t => Convert.ToDecimal(t["HABERDIV"])) - g.Sum(t => Convert.ToDecimal(t["DEBEDIV"])) != 0
620  orderby g.Key.Cuenta
621  select new
622  {
623  Cuenta = g.Key.Cuenta,
624  Nombre = g.Key.Nombre,
625  Divisa = g.Key.Divisa,
626  Debe = g.Sum(t => Convert.ToDecimal(t["DEBE"])),
627  Haber = g.Sum(t => Convert.ToDecimal(t["HABER"])),
628  DebeDiv = g.Sum(t => Convert.ToDecimal(t["DEBEDIV"])),
629  HaberDiv = g.Sum(t => Convert.ToDecimal(t["HABERDIV"])),
630  ImporteDiv = 0,
631  Cambio = 0.0
632  }).__CopyToDataTable();
633 
634 
635  _TratarMonedaEmpresa(loDt);
636 
637  for (Int32 lnI = 0; lnI < loDt.Rows.Count; lnI++)
638  {
639  DataRow loRowTmp = loDt.Rows[lnI];
640 
641  _TrataLinea(ref loRowTmp);
642  }
643 
644  //Añadimos la linea de perdidas y ganancias
645  DataRow loRowPerdidadGanancias = loDt.NewRow();
646  loRowPerdidadGanancias["CUENTA"] = _CuentaResultados;
647  loRowPerdidadGanancias["NOMBRE"] = _NombreCuentaResultados;
648  loRowPerdidadGanancias["DIVISA"] = _cMonedaEmpresa;
649  loRowPerdidadGanancias["DEBE"] = loDt.AsEnumerable().Sum(f=>Convert.ToDecimal(f["DEBE"]));
650  loRowPerdidadGanancias["HABER"] = loDt.AsEnumerable().Sum(f => Convert.ToDecimal(f["HABER"]));
651  loRowPerdidadGanancias["DEBEDIV"] = loDt.AsEnumerable().Sum(f => Convert.ToDecimal(f["DEBEDIV"]));
652  loRowPerdidadGanancias["HABERDIV"] = loDt.AsEnumerable().Sum(f => Convert.ToDecimal(f["HABERDIV"]));
653 
654  _TrataLinea(ref loRowPerdidadGanancias);
655  loDt.Rows.Add(loRowPerdidadGanancias);
656 
657  loDt = (from loRow in loDt.AsEnumerable()
658  where Convert.ToDecimal(loRow["DEBE"]) + Convert.ToDecimal(loRow["HABER"]) != 0
659  orderby loRow["CUENTA"]
660  select loRow).__CopyToDataTable();
661 
662  return loDt;
663  }
664 
665  private void _AddRows(ref DataTable loDtTo, DataTable loDtFrom)
666  {
667  foreach (DataRow loRow in loDtFrom.Rows)
668  {
669  loDtTo.ImportRow(loRow);
670  }
671  }
672 
673  private bool _EsDiferenciaCambio(int tnTipoMov, string tcCuenta)
674  {
675  AsientoTipoMov toTipoMov;
676 
677  if (Enum.IsDefined(typeof(AsientoTipoMov), tnTipoMov))
678  {
679  toTipoMov = (AsientoTipoMov)tnTipoMov;
680 
681  switch (toTipoMov)
682  {
683  case AsientoTipoMov.DiferenciasCambioCobro:
684  case AsientoTipoMov.DiferenciasCambioCierreCobro:
685  return CONTABILIDAD._EsCliente(tcCuenta);
686  case AsientoTipoMov.DiferenciasCambioPago:
687  case AsientoTipoMov.DiferenciasCambioCierrePago:
688  return CONTABILIDAD._EsProveedor(tcCuenta);
689  case AsientoTipoMov.DiferenciasCambioBancoCaja:
690  case AsientoTipoMov.DiferenciasCambioBancoCajaCierre:
691  return _EsBanco(tcCuenta);
692  }
693  }
694  return false;
695 
696  }
697 
698  private void _TratarMonedaEmpresa(DataTable dtDatos)
699  {
700 
701  var loGroups = (from loRow in dtDatos.AsEnumerable()
702  group loRow by new { Cuenta = Convert.ToString(loRow["cuenta"]) } into g
703  where !CONTABILIDAD._EsCliente(g.Key.Cuenta) && !CONTABILIDAD._EsProveedor(g.Key.Cuenta) && !_EsBanco(g.Key.Cuenta)
704  select new
705  {
706  Cuenta = g.Key.Cuenta,
707  Rows = g.ToList().Where(f => Convert.ToString(f["divisa"]) != _cMonedaEmpresa).ToList()
708  });
709 
710  loGroups.Where(f => f.Rows.Count > 0).ToList().ForEach(f => f.Rows.ForEach(loRow =>
711  {
712  loRow["divisa"] = _cMonedaEmpresa;
713  loRow["debediv"] = loRow["debe"];
714  loRow["haberdiv"] = loRow["haber"];
715  }));
716  }
717 
718  private bool _EsBanco(string tcCuenta)
719  {
720  return tcCuenta.Length > 2 ? CONTABILIDAD._EsBancoCajaDivisa(tcCuenta.Substring(0, 3)) : false;
721  }
722 
723  private void _TrataLinea(ref DataRow loRow)
724  {
725  Decimal lnDebe, lnHaber, lnDebeDiv, lnHaverDiv, lnCambio;
726 
727  lnDebe = Convert.ToDecimal(loRow["DEBE"]);
728  lnHaber = Convert.ToDecimal(loRow["HABER"]);
729  lnDebeDiv = Convert.ToDecimal(loRow["DEBEDIV"]);
730  lnHaverDiv = Convert.ToDecimal(loRow["HABERDIV"]);
731  lnCambio = 1;
732 
733  if (lnDebe > lnHaber)
734  {
735  loRow["DEBE"] = loRow["DEBEDIV"] = 0;
736  loRow["HABER"] = lnDebe - lnHaber;
737 
738  if (Convert.ToString(loRow["DIVISA"]) == _cMonedaEmpresa)
739  {
740  loRow["HABERDIV"] = loRow["HABER"];
741  }
742  else
743  {
744  loRow["HABERDIV"] = lnDebeDiv - lnHaverDiv;
745  lnCambio = Convert.ToDecimal(loRow["HABERDIV"]) == 0 ? 1 : Convert.ToDecimal(loRow["HABER"]) / Convert.ToDecimal(loRow["HABERDIV"]);
746 
747  }
748  loRow["CAMBIO"] = lnCambio;
749  }
750  else if (lnHaber > lnDebe)
751  {
752  loRow["DEBE"] = lnHaber - lnDebe;
753  loRow["HABERDIV"] = loRow["HABER"] = 0;
754 
755  if (Convert.ToString(loRow["DIVISA"]) ==_cMonedaEmpresa)
756  {
757  loRow["DEBEDIV"] = loRow["DEBE"];
758  }
759  else
760  {
761  loRow["DEBEDIV"] = lnHaverDiv - lnDebeDiv;
762  lnCambio = Convert.ToDecimal(loRow["DEBEDIV"]) == 0 ? 1 : Convert.ToDecimal(loRow["DEBE"]) / Convert.ToDecimal(loRow["DEBEDIV"]);
763  }
764  }
765  else
766  {
767  loRow["DEBE"] = 0;
768  loRow["HABER"] = 0;
769  }
770 
771  loRow["CAMBIO"] = lnCambio;
772  }
773 
778  public Boolean _AsientoApertura(ref Asientos toAsiento)
779  {
780  return _CreaAsientoApertura(ref toAsiento, _DatosCierre);
781  }
782 
789  public ResultadoOperacion CrearAsientoApertura(string ejercicio, List<AsientoCierreRegularizacion.SaldoCierre> lineasParaApertura)
790  {
791 
792  List<String> loMesesCerrados = new List<String>();
793 
794  try
795  {
796  //Comprobaciones iniciales
797  if (string.IsNullOrWhiteSpace(ejercicio))
798  return new ResultadoOperacion(false, "No se ha especificado ejercicio.");
799 
800  if (lineasParaApertura == null || lineasParaApertura.Count() == 0)
801  return new ResultadoOperacion(false, "No se han especificado lineas para el asiento de apertura.");
802 
803  //Empezamos la ejecución
804 
805  //1.- Borrar apertura preexistente
806  bool hayAperturaPrevia = Asientos.ContieneAsientoApertura(ejercicio) == true;
807  bool aperturaCorrecta = true;
808  bool aplicacionCorrecta = true;
809 
810  string mensajeEjecucion = "Proceso realizado con éxito";
811 
812  //Abro los meses para operar
813  loMesesCerrados = MesesCerrados.ObtenerMesesCerrados();
815 
816  //2.- Crear el asiento con las líneas recibidas
817  Asientos asientoApertura = new Asientos();
818  Asientos asientoAplicacion = new Asientos();
819 
820  List<AsientoCierreGenerado> asientosGenerados = new List<AsientoCierreGenerado>();
821 
822  Int32 lnNumApertura = _ExisteAsientoApertura();
823  Int32 lnNumAplicacion = _ExisteAsientoAplicacion();
824 
825  Boolean lRenumerar = (lnNumApertura == 0 || lnNumAplicacion == 0);
826 
827  if (_ObtenerAsiento(ref asientoApertura, TipoAsiento.Apertura))
828  {
829  foreach (var lineaSaldo in lineasParaApertura)
830  {
831  IAsientosLinea loLin = asientoApertura._AddLinea();
832  lineaSaldo.InvertirDebeHaber().ToAsientosLinea(loLin);
833  loLin._Definicion = "ASIENTO APERTURA";
834  }
835 
836  if (hayAperturaPrevia)
837  {
838  if (!Asientos.DeleteAsientoApertura(ejercicio))
839  {
840  return new ResultadoOperacion(false, "No se ha podido borrar el asiento de apertura previo.");
841  }
842  }
843 
844  if (aperturaCorrecta = asientoApertura._Save())
845  {
846  if (aplicacionCorrecta = _AsientoAplicacionPerdidasGanancias(ref asientoAplicacion))
847  {
848  if (lRenumerar)
849  {
850  if (RenumerarAsientos(asientoApertura._Numero, asientoAplicacion._Numero, out string errorRenumeracion))
851  {
852  asientoApertura._Numero = 1;
853  asientoAplicacion._Numero = 2;
854  }
855  else
856  {
857  //Un fallo en la renumeración no lo consideramos suficientemente grave para retroceder el proceso pero propago su mensaje
858  mensajeEjecucion = errorRenumeracion;
859  }
860  }
861  }
862  else
863  {
864  mensajeEjecucion = asientoAplicacion._Mensaje_Error;
865  }
866  }
867  else
868  {
869  mensajeEjecucion = asientoApertura._Mensaje_Error;
870 
871  }
872 
873  if (aperturaCorrecta)
874  {
875  //Creo información de retorno
876  AsientoCierreGenerado asientoGenerado = new AsientoCierreGenerado(asientoApertura, ejercicio)
877  {
878  Categoria = "Asiento de apertura",
879  Descripcion = "Asiento de apertura"
880  };
881  asientosGenerados.Add(asientoGenerado);
882  }
883 
884  if(aplicacionCorrecta)
885  {
886  //Creo información de retorno
887  AsientoCierreGenerado asientoGenerado = new AsientoCierreGenerado(asientoAplicacion, ejercicio)
888  {
889  Categoria = "Asiento de apertura",
890  Descripcion = "Asiento de aplicación de pérdidas o ganancias"
891  };
892  asientosGenerados.Add(asientoGenerado);
893  }
894  }
895 
896  var resultado = new ResultadoOperacion(aperturaCorrecta, mensajeEjecucion)
897  {
898  Datos = asientosGenerados
899  };
900 
901  return resultado;
902  }
903  finally
904  {
905  MesesCerrados.Cerrar(loMesesCerrados);
906  }
907  }
908 
909  private bool _CreaAsientoApertura(ref Asientos toAsiento, DataTable toDatos)
910  {
911  if (toDatos is DataTable && toDatos.Rows.Count > 0)
912  {
913  _cErrorMessage = "";
914 
915  _ProcessBar.InitGauge(1, 100, String.Format("Creación automática del asiento de apertura"));
916 
917  if (_ObtenerAsiento(ref toAsiento, TipoAsiento.Apertura))
918  {
919  _ProcessBar.InitGauge(1, toDatos.Rows.Count + 1, String.Format("Creando lineas del asiento apertura "));
920 
921  foreach (DataRow loRow in toDatos.Rows)
922  {
923  IAsientosLinea loLin = toAsiento._AddLinea();
924 
925  loLin._Cuenta = Convert.ToString(loRow["CUENTA"]);
926  loLin._Definicion = "ASIENTO DE APERTURA";
927  loLin._Divisa = Convert.ToString(loRow["DIVISA"]);
928  loLin._Cambio = Convert.ToDecimal(loRow["CAMBIO"]);
929  loLin._Debe = Convert.ToDecimal(loRow["HABER"]);
930  loLin._DebeDiv = Convert.ToDecimal(loRow["HABERDIV"]);
931  loLin._Haber = Convert.ToDecimal(loRow["DEBE"]);
932  loLin._HaberDiv = Convert.ToDecimal(loRow["DEBEDIV"]);
933 
934  _ProcessBar.Step(String.Format("Apertura de la cuenta {0} ", loLin._Cuenta));
935  }
936 
937  _ProcessBar.Step(String.Format("Guardando asiento apertura ", toAsiento._Numero));
938 
939  if (!toAsiento._Save())
940  {
941  if (_oAsientoAntiguo is Asientos) _oAsientoAntiguo._Save();
942  _cErrorMessage = String.Format("No se ha podido crear el asiento de apertura: {0}", toAsiento._Mensaje_Error);
943  }
944  }
945  }
946  else
947  {
948  _cErrorMessage = "No hay datos para generar el asiento de apertura";
949  }
950 
951  return String.IsNullOrEmpty(_cErrorMessage);
952  }
953 
958  public void _Generar(ProcessBar _oProcess = null)
959  {
960 
961  Boolean lOk = true;
962  Boolean lRenumerar = true;
963  Asientos loAsientosApertura = new Asientos();
964  Asientos loAsientosAplicacion = new Asientos();
965  List<Asientos> loList = new List<Asientos>();
966  List<String> loMesesCerrados = new List<String>();
967  Int32 lnNumApertura, lnNumAplicacion;
968 
969  //Abro los meses para operar
970  loMesesCerrados = MesesCerrados.ObtenerMesesCerrados();
972 
973  _cInfoMessage = "";
974  _ProcessBar = _oProcess;
975 
976  try
977  {
978  lnNumApertura = _ExisteAsientoApertura();
979  lnNumAplicacion = _ExisteAsientoAplicacion();
980 
981  lRenumerar = (lnNumApertura == 0 || lnNumAplicacion == 0);
982 
983  if (_GenerAsientoApertura)
984  {
985  if (_IsProvisional)
986  {
987  lOk = _AsientoAperturaProvisional(ref loAsientosApertura);
988  }
989  else
990  {
991  lOk = _AsientoApertura(ref loAsientosApertura);
992  }
993 
994  if (lOk) loList.Add(loAsientosApertura);
995  }
996 
997  if (_GenerarAsientoAplicacionPerdidasGanancias && lOk)
998  {
999  lOk = _AsientoAplicacionPerdidasGanancias(ref loAsientosAplicacion);
1000  if (lOk) loList.Add(loAsientosAplicacion);
1001  }
1002 
1003  if (loList.Count > 0)
1004  {
1005  _ProcessBar._Result = loList;
1006 
1007  //Proceso de renumeración
1008  if (lRenumerar && (loAsientosApertura._Numero > 1 || loAsientosAplicacion._Numero > 2))
1009  {
1010  _ProcessBar.InitGauge(1, 3, String.Format("Ejecutado proceso de renumeración"));
1011 
1012  if (RenumerarAsientos(loAsientosApertura._Numero, loAsientosAplicacion._Numero, out string mensaje))
1013  {
1014  loAsientosApertura._Numero = 1;
1015  loAsientosAplicacion._Numero = 2;
1016 
1017  _ProcessBar.Step();
1018  }
1019  else
1020  {
1021  _cInfoMessage = mensaje;
1022  }
1023  _ProcessBar.Step();
1024  }
1025  }
1026  }
1027  finally
1028  {
1029  //Dejo como estaban los meses
1030  MesesCerrados.Cerrar(loMesesCerrados);
1031  }
1032  }
1033 
1041  private bool RenumerarAsientos(int numeroAsientoApertura, int numeroAsientoAplicacion, out string mensaje)
1042  {
1043  mensaje = string.Empty;
1044  if (numeroAsientoApertura > 1 || numeroAsientoAplicacion > 2) //Si hace falta renumerar
1045  {
1046  _ProcessBar.Step();
1047 
1048  RenumeracionAsientos loProcess = new RenumeracionAsientos();
1049 
1050  if (!loProcess._Execute_Process())
1051  {
1052  //Detallo la numeración de los asientos en caso de error
1053 
1054  string soloApertura = $"El asiento de apertura se ha creado con el número {numeroAsientoApertura}";
1055  string soloAplicacion = $"El asiento de aplicación se ha creado con el número {numeroAsientoAplicacion}";
1056  string ambosAsientos = $"El asiento de apertura se ha creado con el número {numeroAsientoApertura} y el asiento de aplicación se ha creado con el número {numeroAsientoAplicacion}";
1057 
1058  mensaje = _GenerAsientoApertura ? (_GenerarAsientoAplicacionPerdidasGanancias ? ambosAsientos : soloApertura) : soloAplicacion;
1059 
1060  mensaje = $"{mensaje}, ya que no se ha podido ejecutar el proceso de renumeración.{Environment.NewLine}({loProcess._Error_Message}) ";
1061 
1062  return false;
1063  }
1064  }
1065 
1066  return true;
1067  }
1068 
1069 
1073  public void _Show()
1074  {
1075  frmAsientoApertura loForm = new frmAsientoApertura(this);
1076  loForm._ShowDialog();
1077  }
1078 
1083  public bool _Valida()
1084  {
1085  Int32 lnResult = 0;
1086  Boolean lOk = true;
1087  DataTable loDtCuentas;
1088 
1089  _cErrorMessage = "";
1090 
1091  if (((Empresa)EW_GLOBAL._Empresa)._EsConsolidada)
1092  {
1093  _cErrorMessage = " en empresas consolidadas.";
1094  }
1095  //else if (_MesCerrado(_Fecha))
1096  //{
1097  // _cErrorMessage = ". El mes de la fecha inicial del periodo esta cerrado.";
1098  //}
1099  else if (!_ExisteEjercicioAnterior())
1100  {
1101  _cErrorMessage = ". No existe ningún ejercicio anterior del que recuperar los datos.";
1102  }
1103  else if (_GenerAsientoApertura && _IsProvisional && (lnResult = _AsientosDescuadrados()) > 0)
1104  {
1105  _cErrorMessage = lnResult > 1 ? String.Format(". Se han localizado {0} asientos descuadrados", lnResult) : ". Se ha localizado 1 asiento descuadrado";
1106  _cErrorMessage = String.Format("{0} en el ejercicio anterior. Imposible realizar el asiento de apertura provisional.{1}Utilice la opción de revisión de asientos en el ejercicio anterior para comprobar los posibles errores. ", _cErrorMessage, Environment.NewLine);
1107  }
1108  else if (!_GenerAsientoApertura && _GenerarAsientoAplicacionPerdidasGanancias && _ExisteAsientoApertura() == 0)
1109  {
1110  _cErrorMessage = " porque no existe asiento de apertura";
1111  }
1112 
1113  if (String.IsNullOrEmpty(_cErrorMessage))
1114  {
1115  loDtCuentas = _ValidarCuentasPorEjercicio();
1116 
1117  if (_GenerAsientoApertura && loDtCuentas.Rows.Count > 0)
1118  {
1119  List<String> loCuentas = (from loRow in loDtCuentas.AsEnumerable()
1120  select Convert.ToString(loRow["CODIGO"]).Trim()).Distinct().ToList();
1121 
1122  _cErrorMessage = String.Format(" porque hay cuentas del ejercicio {0} ({2}) necesarias para la apertura que no existen en el ejercicio {1}.{3}{3}Antes de crear la apertura debe traspasar dichas cuentas en el ejercicio {1}.", Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["ANY"]).Trim(), DB.Ejercicio_EW, string.Join(", ", loCuentas), Environment.NewLine);
1123  }
1124  }
1125 
1126  if (String.IsNullOrEmpty(_cErrorMessage))
1127  {
1128  loDtCuentas = _ValidarLongitudCuentas();
1129 
1130  if (_GenerAsientoApertura && loDtCuentas.Rows.Count > 0)
1131  {
1132  List<String> loCuentas = (from loRow in loDtCuentas.AsEnumerable()
1133  select Convert.ToString(loRow["CODIGO"]).Trim()).Distinct().ToList();
1134 
1135  _cErrorMessage = String.Format(" porque hay cuentas del ejercicio {0} ({2}) necesarias para la apertura que no tienen la longitud correcta.{3}{3}Antes de crear la apertura debe revisar las cuentas en el ejercicio {0}.", Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["ANY"]).Trim(), DB.Ejercicio_EW, string.Join(", ", loCuentas), Environment.NewLine);
1136  }
1137  }
1138 
1139  if (String.IsNullOrEmpty(_cErrorMessage))
1140  {
1141  lOk = _ValidarCuentasAplicacion();
1142  lOk = lOk && _ExistenAsientosAperturaAplicacion();
1143  }
1144 
1145 
1146  if (!String.IsNullOrEmpty(_cErrorMessage))
1147  {
1148  String lcCadenaAsientos;
1149 
1150  if(_GenerarAsientoAplicacionPerdidasGanancias && _GenerAsientoApertura)
1151  {
1152  lcCadenaAsientos = String.Format("No se puede crear el asiento de apertura {0} ni el asiento de aplicación de pérdidas o ganancias", _IsProvisional ? "provisional" : "definitivo");
1153  }
1154  else if (_GenerAsientoApertura)
1155  {
1156  lcCadenaAsientos = String.Format("No se puede crear el asiento de apertura {0}", _IsProvisional ? "provisional" : "definitivo");
1157  }
1158  else
1159  {
1160  lcCadenaAsientos = "No se puede crear el asiento de aplicación de pérdidas o ganancias";
1161  }
1162  _cErrorMessage = String.Format("{0}{1}", lcCadenaAsientos, _cErrorMessage);
1163  }
1164 
1165  lOk &= String.IsNullOrEmpty(_cErrorMessage);
1166 
1167  return lOk;
1168  }
1169 
1170  private DataTable _ValidarLongitudCuentas()
1171  {
1172 
1173  String lcSql;
1174  DataTable loDt = new DataTable();
1175  Int32 lnLen = EW_GLOBAL._GetLenCampo(KeyDiccionarioLenCampos.wn_digitos);
1176 
1177  if (_IsProvisional)
1178  {
1179  lcSql = String.Format("SELECT CODIGO FROM {0} INNER JOIN ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "CUENTAS"));
1180  lcSql += String.Format("(SELECT CUENTA FROM {0} asi WHERE EMPRESA = {1} {2} GROUP BY CUENTA HAVING SUM(asi.debediv) - SUM(asi.haberDiv) <> 0) e ON e.CUENTA = CODIGO ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "ASIENTOS"), DB.SQLString(_CodigoEmpresa), _FiltroFecha("asi"));
1181  lcSql += String.Format("WHERE LEN(CODIGO) <> {0} ", lnLen);
1182  }
1183  else
1184  {
1185  lcSql = String.Format("SELECT CODIGO FROM {0} INNER JOIN ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "CUENTAS"));
1186  lcSql += String.Format("(SELECT CUENTA FROM {0} asi WHERE EMPRESA = {1} AND TIPO = '{2}' ) e ON e.CUENTA = CODIGO ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "ASIENTOS"), DB.SQLString(_CodigoEmpresa), Convert.ToInt32(eTipoMovimientoAsiento.Cierre));
1187  lcSql += String.Format("WHERE LEN(CODIGO) <> {0} ", lnLen);
1188  }
1189  DB.SQLExec(lcSql, ref loDt);
1190 
1191  return loDt;
1192 
1193  }
1194 
1195 
1196  private DataTable _ValidarCuentasPorEjercicio()
1197  {
1198  String lcSql;
1199  DataTable loDt = new DataTable();
1200 
1201  if (_ConfigEjercicioAnterior.Rows.Count > 0)
1202  {
1203  if (_IsProvisional)
1204  {
1205  lcSql = String.Format("SELECT CODIGO FROM {0} INNER JOIN ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "CUENTAS"));
1206  lcSql += String.Format("(SELECT CUENTA FROM {0} asi WHERE EMPRESA = {1} {2} GROUP BY CUENTA HAVING SUM(asi.debediv) - SUM(asi.haberDiv) <> 0) e ON e.CUENTA = CODIGO ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "ASIENTOS"), DB.SQLString(_CodigoEmpresa), _FiltroFecha("asi"));
1207  lcSql += String.Format("WHERE CUENTA NOT IN (SELECT CODIGO FROM {0})", DB.SQLDatabase("GESTION", "CUENTAS"));
1208  }
1209  else
1210  {
1211  lcSql = String.Format("SELECT CODIGO FROM {0} INNER JOIN ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "CUENTAS"));
1212  lcSql += String.Format("(SELECT CUENTA FROM {0} asi WHERE EMPRESA = {1} AND TIPO = '{2}' ) e ON e.CUENTA = CODIGO ", DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "ASIENTOS"), DB.SQLString(_CodigoEmpresa), Convert.ToInt32(eTipoMovimientoAsiento.Cierre));
1213  lcSql += String.Format("WHERE CUENTA NOT IN (SELECT CODIGO FROM {0})", DB.SQLDatabase("GESTION", "CUENTAS"));
1214  }
1215  DB.SQLExec(lcSql, ref loDt);
1216  }
1217 
1218  return loDt;
1219  }
1220 
1221  private bool _ValidarCuentasAplicacion()
1222  {
1223  if (_GenerarAsientoAplicacionPerdidasGanancias && (String.IsNullOrEmpty(_CuentaRemanenteAcreedor) || (String.IsNullOrEmpty(_CuentaRemanenteDeudor))))
1224  {
1225  String lcErrorMessage;
1226 
1227  if (String.IsNullOrEmpty(_CuentaRemanenteAcreedor) && (String.IsNullOrEmpty(_CuentaRemanenteDeudor)))
1228  {
1229  lcErrorMessage = " porque no existe la cuenta (120 - Remanente) ni la cuenta (121 - Resultados negativos de ejercicios anteriores).";
1230  }
1231  else
1232  {
1233  lcErrorMessage = String.Format(" porque no existe la cuenta {0}. ", String.IsNullOrEmpty(_CuentaRemanenteAcreedor) ? "(120 - Remanente)" : " (121 - Resultados negativos de ejercicios anteriores)");
1234  }
1235 
1236  if (_GenerAsientoApertura)
1237  {
1238  lcErrorMessage = String.Format("No se puede generar el asiento de aplicación de pérdidas o ganancias {0}{1}{1}¿Desea continuar y generar el asiento de apertura {2}? ", lcErrorMessage, Environment.NewLine, _IsProvisional ? "provisional" : "definitivo");
1239 
1240  if (DialogResult.Yes == FUNCTIONS._MessageBox(lcErrorMessage, "Validación cuentas", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2))
1241  {
1242  _GenerarAsientoAplicacionPerdidasGanancias = false;
1243  }
1244  else
1245  {
1246  return false;
1247  }
1248  }
1249  else
1250  {
1251  _cErrorMessage = lcErrorMessage;
1252  return false;
1253  }
1254  }
1255 
1256  return true;
1257  }
1258 
1259  private Boolean _ExistenAsientosAperturaAplicacion()
1260  {
1261  Int32 lnResultAper = 0, lnResultApli = 0;
1262  String lcErrorMessage, lcTitulo;
1263  Boolean lbApertura = false, lbAplicacion = false;
1264 
1265  lbApertura = _GenerAsientoApertura && (lnResultAper = _ExisteAsientoApertura()) > 0;
1266  lbAplicacion = _GenerarAsientoAplicacionPerdidasGanancias && (lnResultApli = _ExisteAsientoAplicacion()) > 0;
1267 
1268  if (lbApertura || lbAplicacion)
1269  {
1270  if (lbApertura && lbAplicacion)
1271  {
1272  lcTitulo = "No se pueden crear los asientos";
1273  lcErrorMessage = String.Format("Ya existen los asientos de apertura con número {0} y de aplicación de pérdidas o ganancias con número {1} en el ejercicio actual.{2}{2}Si continua con el proceso se eliminarán los asientos existentes y se crearán de nuevo.{1}{1}¿Desea continuar? ", lnResultAper, lnResultApli, Environment.NewLine);
1274  }
1275  else if (!lbApertura && lbAplicacion)
1276  {
1277  lcTitulo = "No se puede crear el asiento de aplicación de pérdidas o ganancias";
1278  lcErrorMessage = String.Format("Ya existe un asiento de aplicación de pérdidas o ganancias con número {0} en el ejercicio actual.{1}{1}Si continua con el proceso se eliminará el asiento de aplicación de pérdidas o ganancias existente y se creará de nuevo.{1}{1}¿Desea continuar? ", lnResultApli, Environment.NewLine);
1279  }
1280  else
1281  {
1282  lcTitulo = "No se puede crear el asiento de apertura";
1283  lcErrorMessage = String.Format("Ya existe un asiento de apertura con número {0} en el ejercicio actual.{1}{1}Si continua con el proceso se eliminará el asiento de apertura existente y se creará de nuevo.{1}{1}¿Desea continuar? ", lnResultAper, Environment.NewLine);
1284  }
1285 
1286  if (DialogResult.No == FUNCTIONS._MessageBox(lcErrorMessage, lcTitulo, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2))
1287  {
1288  return false;
1289  }
1290  }
1291  return true;
1292  }
1293 
1294  private Int32 _ExisteAsientoApertura()
1295  {
1296  return _ExisteAsiento("AND TIPO = 1");
1297  }
1298 
1299  private Int32 _ExisteAsientoAplicacion()
1300  {
1301  return _ExisteAsiento("AND TIPO = 4");
1302  }
1303 
1304  private Int32 _ExisteAsiento(String tcCond)
1305  {
1306  Int32 lnNum = 0;
1307  String lcSql;
1308  DataTable loDt = new DataTable();
1309 
1310  lcSql = String.Format("SELECT NUMERO FROM {0} WHERE EMPRESA = '{1}' {2} ", DB.SQLDatabase("GESTION", "ASIENTOS"), _CodigoEmpresa, tcCond);
1311  DB.SQLExec(lcSql, ref loDt);
1312 
1313  if (loDt.Rows.Count > 0) lnNum = Convert.ToInt32(loDt.Rows[0]["numero"]);
1314 
1315  return lnNum;
1316  }
1317 
1318  private Int32 _AsientosDescuadrados()
1319  {
1320  String lcSql, lcCon;
1321  DataTable loDt = new DataTable();
1322 
1323  if (_ConfigEjercicioAnterior.Rows.Count > 0)
1324  {
1325  lcCon = DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0]["CONEXION"]), "ASIENTOS");
1326 
1327  lcSql = String.Format("SELECT numero, SUM(debe - haber) as saldo FROM {0} WHERE EMPRESA = '{1}' {3} GROUP BY numero HAVING ROUND(SUM(debe - haber), {2}) != 0" , lcCon, _CodigoEmpresa, EW_GLOBAL._GetVariable("wn_Decimales"), _FiltroFecha());
1328 
1329  DB.SQLExec(lcSql, ref loDt);
1330  }
1331 
1332  return loDt.Rows.Count;
1333  }
1334 
1335  private bool _ExisteEjercicioAnterior()
1336  {
1337  return _ConfigEjercicioAnterior.Rows.Count > 0;
1338  }
1339 
1340  private bool _MesCerrado(DateTime? toFecha)
1341  {
1342  String lcSql;
1343  DataTable loDt = new DataTable();
1344 
1345  lcSql = String.Format("SELECT * FROM {0} WHERE EMPRESA = '{1}' AND CERRADO = {2} AND CODIGO = {3}", DB.SQLDatabase("GESTION", "MESES"), _CodigoEmpresa, DB.SQLTrue(), toFecha?.Month);
1346  DB.SQLExec(lcSql, ref loDt);
1347 
1348  return loDt.Rows.Count > 0;
1349  }
1350  }
1351 }
Clase para almacenar información del asiento generado
Classe empresa basada en sage.ew.ewmante
Definition: clsEmpresa.cs:48
eTipoMovimientoAsiento
Enumerado de los tipos de asientos Normal, Apertura, Regularización, Cierre o Liquidación ...
Clase de negocio para el proceso de renumeración de asientos
static void Cerrar(List< String > toMesesCerrados)
Cierra los meses pasados por parametros
decimal _Debe
Importe en la partida DEBE
static bool ContieneAsientoApertura(string ejercicio, string empresa="")
Método para determinar si el ejercicio recibido por parámetro contiene asiento de apertura ...
Definition: Asientos.cs:4413
decimal _Cambio
Coeficiente de cambio entre DEBE y DEBEDIV y HABER y HABERDIV
int _Numero
Número de asiento.
Definition: Asientos.cs:650
static bool DeleteAsientoApertura(string ejercicio, string empresa="")
Método para borrar el asiento de apertura del ejercicio recibido por parámetro
Definition: Asientos.cs:4424
string _Cuenta
Código de la cuenta
static void AbrirTodos()
Método para abrir todos los meses de forma incondicional
Clase utilizada para realizar asientos contables.
Definition: Asientos.cs:36
KeyDiccionarioLenCampos
Clave del diccionario LenCampos
Definition: Diccionarios.cs:11
Boolean _AsientoAperturaProvisional(ref Asientos toAsiento, bool tlRenumerar)
Task 167460 - Sobrecarga para renumerar asientos si venimos del nuevo ejercicio Función FOX Asiento_i...
Calse para controlar la barra de progreso
Definition: ProcessBar.cs:16
string _Definicion
Definición de la cuenta.
Formulario para la craeación del asiento de apertura
string _Divisa
Divisa del asiento.
Boolean _AsientoApertura(ref Asientos toAsiento)
Función FOX Asiento_Ini() del fichero FUNCIONS.PRG
decimal _Haber
Importe en la partida HABER
bool _Save()
Método publico para guardar asientos.
Definition: Asientos.cs:1791
bool _Valida()
Valida que se pueda generar
Divisa()
Constructor vacío
Definition: Divisa.cs:606
Clase para representar el resultado de una operación
bool _Execute_Process()
Ejecuta el listado (de tipo 2)
AsientoTipoMov
Enumerado para los diferentes valores que puede coger el cmapo TIPO_MOV de tabla Asientos IMPORTANTE:...
Clase para la generación de asientos de apertura
ResultadoOperacion CrearAsientoApertura(string ejercicio, List< AsientoCierreRegularizacion.SaldoCierre > lineasParaApertura)
Método para realizar una apertura multi ejercicio
decimal _DebeDiv
Importe de la partida DEBE en divisa
Boolean _AsientoAperturaProvisional(ref Asientos toAsiento)
Función FOX Asiento_ini_provisional del fichero APERTURA.PRG
void _Clonar(IAsientos toAsiento)
Clonamos el asiento pasado por parámetro
Definition: Asientos.cs:3060
decimal _HaberDiv
Importe de la partida HABER en divisa
Clase de negocio para la DIVISA (Moneda)
Definition: Divisa.cs:76
Clase para gestionar los meses cerrados
interficie asiento linia
void _Generar(ProcessBar _oProcess=null)
Gnera el asiento de apertura
static List< String > ObtenerMesesCerrados()
Obtiene los meses cerrados