14 using System.Collections.Generic;
18 using System.Windows.Forms;
27 private String _cErrorMessage;
28 private String _cInfoMessage;
29 private Boolean _bGenerarAsientoAplicacionPerdidasGanancias =
true;
30 private Boolean _bGenerAsientoApertura =
true;
32 private DateTime? _oDateIni = null;
33 private DataTable _oDatosCierre = null;
34 private DataTable _oDatosEjercicioAnterior = null;
38 private string _cCuentaResultados =
"";
39 private string _cCuentaRemanenteAcreedor =
"";
40 private string _cCuentaRemanenteDeudor =
"";
42 private string _cNombreCuentaResultados =
"";
43 private string _cNombreCuentaRemanenteAcreedor =
"";
44 private string _cNombreCuentaRemanenteDeudor =
"";
46 private String _cMonedaEmpresa = EW_GLOBAL._Moneda._Codigo;
49 private enum TipoAsiento
55 private String _CuentaResultados
59 if (String.IsNullOrEmpty(_cCuentaResultados)) _cCuentaResultados = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_perdi"));
61 return _cCuentaResultados;
65 private String _NombreCuentaResultados
69 if(String.IsNullOrEmpty(_cNombreCuentaResultados)) _ObtenerCuentasRemanentes();
71 return _cNombreCuentaResultados;
78 private String _CuentaRemanenteAcreedor
82 if (String.IsNullOrEmpty(_cCuentaRemanenteAcreedor)) _ObtenerCuentasRemanentes();
84 return _cCuentaRemanenteAcreedor;
88 private String _NombreCuentaRemanenteAcreedor
92 if (String.IsNullOrEmpty(_cNombreCuentaRemanenteAcreedor)) _ObtenerCuentasRemanentes();
94 return _cNombreCuentaRemanenteAcreedor;
101 private String _CuentaRemanenteDeudor
105 if (String.IsNullOrEmpty(_cCuentaRemanenteDeudor)) _ObtenerCuentasRemanentes();
107 return _cCuentaRemanenteDeudor;
111 private String _NombreCuentaRemanenteDeudor
115 if (String.IsNullOrEmpty(_cNombreCuentaRemanenteDeudor)) _ObtenerCuentasRemanentes();
117 return _cNombreCuentaRemanenteDeudor;
124 public Boolean _GenerAsientoApertura
128 return _bGenerAsientoApertura;
132 _bGenerAsientoApertura = value;
139 public Boolean _GenerarAsientoAplicacionPerdidasGanancias
143 return _bGenerarAsientoAplicacionPerdidasGanancias;
147 _bGenerarAsientoAplicacionPerdidasGanancias = value;
158 if (_oProcess == null) _oProcess =
new ProcessBar(
false,
"");
167 private Asientos _AsientoAntiguo
171 if (_oAsientoAntiguo == null) _oAsientoAntiguo =
new Asientos();
172 return _oAsientoAntiguo;
176 private String _CodigoEmpresa
180 return EW_GLOBAL._Empresa._Codigo;
187 public String _ErrorMessage
191 return _cErrorMessage;
198 public String _InfoMessage
202 return _cInfoMessage;
209 public DateTime _Fecha
213 if(_oDateIni == null)
215 _oDateIni =((DateTime)ew.global.EW_GLOBAL._GetVariable(
"wd_periodoini", DateTime.Today));
217 return Convert.ToDateTime(_oDateIni);
224 public Boolean _IsProvisional
228 return _DatosCierre.Rows.Count == 0;
232 private DataTable _DatosCierre
236 if (_oDatosCierre == null)
240 _oDatosCierre =
new DataTable();
242 if (_ConfigEjercicioAnterior.Rows.Count > 0)
244 lcCon = DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0][
"CONEXION"]),
"ASIENTOS");
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);
251 return _oDatosCierre;
258 private DataTable _ConfigEjercicioAnterior
262 if(_oDatosEjercicioAnterior == null)
266 _oDatosEjercicioAnterior =
new DataTable();
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);
273 return _oDatosEjercicioAnterior;
277 private void _ObtenerCuentasRemanentes()
280 DataTable loDt =
new DataTable();
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);
285 if (loDt.Rows.Count > 0)
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();
292 if (loRows.Count > 0)
294 _cCuentaRemanenteAcreedor = Convert.ToString(loRows.First()[
"CODIGO"]);
295 _cNombreCuentaRemanenteAcreedor = Convert.ToString(loRows.First()[
"NOMBRE"]);
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();
303 if (loRows.Count > 0)
305 _cCuentaRemanenteDeudor = Convert.ToString(loRows.First()[
"CODIGO"]);
306 _cNombreCuentaRemanenteDeudor = Convert.ToString(loRows.First()[
"NOMBRE"]);
309 loRows = (from loRow in loDt.AsEnumerable()
310 where Convert.ToString(loRow[
"CODIGO"]) == _CuentaResultados
311 select loRow).ToList();
312 if (loRows.Count > 0)
314 _cNombreCuentaResultados = Convert.ToString(loRows.First()[
"NOMBRE"]);
319 private String _FiltroFecha(String lcAlias =
"")
322 DateTime loPerIniAnt, loPerFinAnt;
324 lcAlias = lcAlias.Trim();
325 if (!
String.IsNullOrEmpty(lcAlias) && !lcAlias.EndsWith(
".")) lcAlias =
String.Format(
"{0}.", lcAlias.Trim());
327 if (_ConfigEjercicioAnterior.Rows.Count > 0)
329 loPerIniAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0][
"PERIODOINI"]);
330 loPerFinAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0][
"PERIODOFIN"]);
332 lcSql =
String.Format(
"AND {0}fecha >= {1} AND {0}fecha <= {2} ", lcAlias, DB.SQLString(loPerIniAnt), DB.SQLString(loPerFinAnt));
345 return _AsientoAperturaProvisional(ref toAsiento,
false);
361 _ProcessBar.InitGauge(1, 100, String.Format(
"Obteniendo datos del ejercicio anterior"));
363 loDt = _ObtenerSaldos();
365 bool llOk = _CreaAsientoApertura(ref toAsiento, loDt);
367 if (llOk && tlRenumerar)
368 RenumerarAsientos(2, 0, out
string _cErrorMessage);
374 private Boolean _ObtenerAsiento(ref
Asientos toAsiento, TipoAsiento totipo)
376 Int32 lnNumTipo, lnNum = 0;
378 toAsiento._Empresa = _CodigoEmpresa;
379 toAsiento._Fecha = _Fecha;
383 if (totipo == TipoAsiento.Apertura)
385 lnNum = _ExisteAsientoApertura();
387 toAsiento._Tipo =
"1";
391 toAsiento._Tipo =
"4";
392 lnNum = _ExisteAsientoAplicacion();
396 toAsiento._Numero = lnNum == 0 && !_ExisteNumAsiento(lnNumTipo) ? lnNumTipo : lnNum;
400 Asientos loAsientoAper =
new Asientos();
401 loAsientoAper._Empresa = _CodigoEmpresa;
402 loAsientoAper._Numero = lnNum;
403 loAsientoAper._Load();
404 _oAsientoAntiguo.
_Clonar(loAsientoAper);
406 if (!loAsientoAper._Delete())
408 _cErrorMessage = String.Format(
"No se ha podido eliminar el asiento {0}", lnNum);
416 private Boolean _AsientoAplicacionPerdidasGanancias(ref Asientos toAsiento)
420 _ProcessBar.InitGauge(1, 10,
String.Format(
"Creando asiento de aplicación de pérdidas o ganancias "));
422 lnNum = _ExisteAsientoApertura();
425 loAsientoApertura._Empresa = _CodigoEmpresa;
426 loAsientoApertura._Numero = lnNum;
427 loAsientoApertura._Load();
429 List<IAsientosLinea> loLinResultados = (from loLin in loAsientoApertura._Lineas
430 where loLin._Cuenta == _CuentaResultados
431 select loLin).ToList();
433 if(loLinResultados.Count > 0)
435 if (_ObtenerAsiento(ref toAsiento, TipoAsiento.Aplicacion))
437 if (loLinResultados.First()._Haber != 0 || loLinResultados.First()._Debe != 0)
443 lineaResultados.
_Cuenta = _CuentaResultados;
444 lineaResultados.
_Definicion = _NombreCuentaResultados;
448 if (loLinResultados.First()._Haber > 0)
450 lineaResultados.
_Debe = loLinResultados.First()._Haber;
452 lineaRemanente.
_Cuenta = _CuentaRemanenteAcreedor;
453 lineaRemanente.
_Definicion = _NombreCuentaRemanenteAcreedor;
456 else if (loLinResultados.First()._Haber < 0)
458 lineaResultados.
_Debe = loLinResultados.First()._Haber;
460 lineaRemanente.
_Cuenta = _CuentaRemanenteDeudor;
461 lineaRemanente.
_Definicion = _NombreCuentaRemanenteDeudor;
464 else if (loLinResultados.First()._Debe > 0)
466 lineaResultados.
_Debe = loLinResultados.First()._Debe * -1;
468 lineaRemanente.
_Cuenta = _CuentaRemanenteDeudor;
469 lineaRemanente.
_Definicion = _NombreCuentaRemanenteDeudor;
472 else if (loLinResultados.First()._Debe < 0)
474 lineaResultados.
_Debe = loLinResultados.First()._Debe;
476 lineaRemanente.
_Cuenta = _CuentaRemanenteDeudor;
477 lineaRemanente.
_Definicion = _NombreCuentaRemanenteDeudor;
481 if (!toAsiento._Save())
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);
489 _cInfoMessage =
"No se ha podido crear el asiento de aplicación ya que el resultado del ejercicio es cero.";
492 _ProcessBar.InitGauge(10, 10,
string.Format(
"Creando asiento de aplicación de pérdidas o ganancias "));
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);
500 return string.IsNullOrEmpty(_cErrorMessage) &&
string.IsNullOrEmpty(_cInfoMessage);
503 private Boolean _ExisteNumAsiento(Int32 tnNum)
506 DataTable loDt =
new DataTable();
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);
511 return loDt.Rows.Count > 0;
514 private DataTable _ObtenerSaldos()
516 DataTable loDtDebe =
new DataTable();
517 DataTable loDtHaber =
new DataTable();
518 DataTable loDt =
new DataTable();
519 String lcCompra, lcVenta, lcSql, lcCon;
521 DateTime loPerIniAnt, loPerFinAnt;
523 lcCompra = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_compra")).Substring(0, 1);
524 lcVenta = Convert.ToString(EW_GLOBAL._GetVariable(
"wc_venta")).Substring(0, 1);
526 lcCon = Convert.ToString(_ConfigEjercicioAnterior.Rows[0][
"CONEXION"]);
529 llNoDivisa = Convert.ToBoolean(EW_GLOBAL._GetVariable(
"wl_asicierrediv"));
531 loPerIniAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0][
"PERIODOINI"]);
532 loPerFinAnt = Convert.ToDateTime(_ConfigEjercicioAnterior.Rows[0][
"PERIODOFIN"]);
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");
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");
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);
549 if (llNoDivisa) lcSql +=
String.Format(
"GROUP BY asi.cuenta, cue.nombre {0} ", llNoDivisa ?
"" :
", asi.divisa");
550 lcSql +=
"ORDER BY asi.CUENTA ";
552 if(!DB.SQLExec(lcSql, ref loDtDebe))
554 throw new Exception(
"No se ha podido obtener los saldos de las cuentas. Imposible realizar els asiento de apertura provisional.");
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");
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");
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 ";
574 if (!DB.SQLExec(lcSql, ref loDtHaber))
576 throw new Exception(
"No se ha podido obtener los saldos de las cuentas. Imposible realizar els asiento de apertura provisional.");
579 loDt = loDtDebe.Clone();
581 _AddRows(ref loDt, loDtDebe);
582 _AddRows(ref loDt, loDtHaber);
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
593 Rows = g.ToList().Where(f => Convert.ToString(f[
"divisa"]) != _cMonedaEmpresa).ToList()
597 loGroups.Where(f => f.Rows.Count > 0).ToList().ForEach(f =>
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();
605 f.Rows.ForEach(loRow =>
607 loRow[
"divisa"] = loDiv.Divisa;
608 loRow[
"tipo_mov"] = 0;
609 loRow[
"haberdiv"] = 0;
610 loRow[
"debediv"] = 0;
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
623 Cuenta = g.Key.Cuenta,
624 Nombre = g.Key.Nombre,
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"])),
632 }).__CopyToDataTable();
635 _TratarMonedaEmpresa(loDt);
637 for (Int32 lnI = 0; lnI < loDt.Rows.Count; lnI++)
639 DataRow loRowTmp = loDt.Rows[lnI];
641 _TrataLinea(ref loRowTmp);
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"]));
654 _TrataLinea(ref loRowPerdidadGanancias);
655 loDt.Rows.Add(loRowPerdidadGanancias);
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();
665 private void _AddRows(ref DataTable loDtTo, DataTable loDtFrom)
667 foreach (DataRow loRow
in loDtFrom.Rows)
669 loDtTo.ImportRow(loRow);
673 private bool _EsDiferenciaCambio(
int tnTipoMov,
string tcCuenta)
677 if (Enum.IsDefined(typeof(AsientoTipoMov), tnTipoMov))
685 return CONTABILIDAD._EsCliente(tcCuenta);
688 return CONTABILIDAD._EsProveedor(tcCuenta);
691 return _EsBanco(tcCuenta);
698 private void _TratarMonedaEmpresa(DataTable dtDatos)
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)
707 Rows = g.ToList().Where(f => Convert.ToString(f[
"divisa"]) != _cMonedaEmpresa).ToList()
710 loGroups.Where(f => f.Rows.Count > 0).ToList().ForEach(f => f.Rows.ForEach(loRow =>
712 loRow[
"divisa"] = _cMonedaEmpresa;
713 loRow[
"debediv"] = loRow[
"debe"];
714 loRow[
"haberdiv"] = loRow[
"haber"];
718 private bool _EsBanco(
string tcCuenta)
720 return tcCuenta.Length > 2 ? CONTABILIDAD._EsBancoCajaDivisa(tcCuenta.Substring(0, 3)) :
false;
723 private void _TrataLinea(ref DataRow loRow)
725 Decimal lnDebe, lnHaber, lnDebeDiv, lnHaverDiv, lnCambio;
727 lnDebe = Convert.ToDecimal(loRow[
"DEBE"]);
728 lnHaber = Convert.ToDecimal(loRow[
"HABER"]);
729 lnDebeDiv = Convert.ToDecimal(loRow[
"DEBEDIV"]);
730 lnHaverDiv = Convert.ToDecimal(loRow[
"HABERDIV"]);
733 if (lnDebe > lnHaber)
735 loRow[
"DEBE"] = loRow[
"DEBEDIV"] = 0;
736 loRow[
"HABER"] = lnDebe - lnHaber;
738 if (Convert.ToString(loRow[
"DIVISA"]) == _cMonedaEmpresa)
740 loRow[
"HABERDIV"] = loRow[
"HABER"];
744 loRow[
"HABERDIV"] = lnDebeDiv - lnHaverDiv;
745 lnCambio = Convert.ToDecimal(loRow[
"HABERDIV"]) == 0 ? 1 : Convert.ToDecimal(loRow[
"HABER"]) / Convert.ToDecimal(loRow[
"HABERDIV"]);
748 loRow[
"CAMBIO"] = lnCambio;
750 else if (lnHaber > lnDebe)
752 loRow[
"DEBE"] = lnHaber - lnDebe;
753 loRow[
"HABERDIV"] = loRow[
"HABER"] = 0;
755 if (Convert.ToString(loRow[
"DIVISA"]) ==_cMonedaEmpresa)
757 loRow[
"DEBEDIV"] = loRow[
"DEBE"];
761 loRow[
"DEBEDIV"] = lnHaverDiv - lnDebeDiv;
762 lnCambio = Convert.ToDecimal(loRow[
"DEBEDIV"]) == 0 ? 1 : Convert.ToDecimal(loRow[
"DEBE"]) / Convert.ToDecimal(loRow[
"DEBEDIV"]);
771 loRow[
"CAMBIO"] = lnCambio;
780 return _CreaAsientoApertura(ref toAsiento, _DatosCierre);
792 List<String> loMesesCerrados =
new List<String>();
797 if (
string.IsNullOrWhiteSpace(ejercicio))
800 if (lineasParaApertura == null || lineasParaApertura.Count() == 0)
801 return new ResultadoOperacion(
false,
"No se han especificado lineas para el asiento de apertura.");
807 bool aperturaCorrecta =
true;
808 bool aplicacionCorrecta =
true;
810 string mensajeEjecucion =
"Proceso realizado con éxito";
820 List<AsientoCierreGenerado> asientosGenerados =
new List<AsientoCierreGenerado>();
822 Int32 lnNumApertura = _ExisteAsientoApertura();
823 Int32 lnNumAplicacion = _ExisteAsientoAplicacion();
825 Boolean lRenumerar = (lnNumApertura == 0 || lnNumAplicacion == 0);
827 if (_ObtenerAsiento(ref asientoApertura, TipoAsiento.Apertura))
829 foreach (var lineaSaldo
in lineasParaApertura)
832 lineaSaldo.InvertirDebeHaber().ToAsientosLinea(loLin);
836 if (hayAperturaPrevia)
840 return new ResultadoOperacion(
false,
"No se ha podido borrar el asiento de apertura previo.");
844 if (aperturaCorrecta = asientoApertura._Save())
846 if (aplicacionCorrecta = _AsientoAplicacionPerdidasGanancias(ref asientoAplicacion))
850 if (RenumerarAsientos(asientoApertura._Numero, asientoAplicacion._Numero, out
string errorRenumeracion))
852 asientoApertura._Numero = 1;
853 asientoAplicacion._Numero = 2;
858 mensajeEjecucion = errorRenumeracion;
864 mensajeEjecucion = asientoAplicacion._Mensaje_Error;
869 mensajeEjecucion = asientoApertura._Mensaje_Error;
873 if (aperturaCorrecta)
878 Categoria =
"Asiento de apertura",
879 Descripcion =
"Asiento de apertura" 881 asientosGenerados.Add(asientoGenerado);
884 if(aplicacionCorrecta)
889 Categoria =
"Asiento de apertura",
890 Descripcion =
"Asiento de aplicación de pérdidas o ganancias" 892 asientosGenerados.Add(asientoGenerado);
898 Datos = asientosGenerados
909 private bool _CreaAsientoApertura(ref
Asientos toAsiento, DataTable toDatos)
911 if (toDatos is DataTable && toDatos.Rows.Count > 0)
915 _ProcessBar.InitGauge(1, 100, String.Format(
"Creación automática del asiento de apertura"));
917 if (_ObtenerAsiento(ref toAsiento, TipoAsiento.Apertura))
919 _ProcessBar.InitGauge(1, toDatos.Rows.Count + 1, String.Format(
"Creando lineas del asiento apertura "));
921 foreach (DataRow loRow
in toDatos.Rows)
925 loLin.
_Cuenta = Convert.ToString(loRow[
"CUENTA"]);
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"]);
934 _ProcessBar.Step(String.Format(
"Apertura de la cuenta {0} ", loLin.
_Cuenta));
937 _ProcessBar.Step(String.Format(
"Guardando asiento apertura ", toAsiento._Numero));
939 if (!toAsiento._Save())
942 _cErrorMessage = String.Format(
"No se ha podido crear el asiento de apertura: {0}", toAsiento._Mensaje_Error);
948 _cErrorMessage =
"No hay datos para generar el asiento de apertura";
951 return String.IsNullOrEmpty(_cErrorMessage);
962 Boolean lRenumerar =
true;
965 List<Asientos> loList =
new List<Asientos>();
966 List<String> loMesesCerrados =
new List<String>();
967 Int32 lnNumApertura, lnNumAplicacion;
974 _ProcessBar = _oProcess;
978 lnNumApertura = _ExisteAsientoApertura();
979 lnNumAplicacion = _ExisteAsientoAplicacion();
981 lRenumerar = (lnNumApertura == 0 || lnNumAplicacion == 0);
983 if (_GenerAsientoApertura)
987 lOk = _AsientoAperturaProvisional(ref loAsientosApertura);
991 lOk = _AsientoApertura(ref loAsientosApertura);
994 if (lOk) loList.Add(loAsientosApertura);
997 if (_GenerarAsientoAplicacionPerdidasGanancias && lOk)
999 lOk = _AsientoAplicacionPerdidasGanancias(ref loAsientosAplicacion);
1000 if (lOk) loList.Add(loAsientosAplicacion);
1003 if (loList.Count > 0)
1005 _ProcessBar._Result = loList;
1008 if (lRenumerar && (loAsientosApertura.
_Numero > 1 || loAsientosAplicacion.
_Numero > 2))
1010 _ProcessBar.InitGauge(1, 3, String.Format(
"Ejecutado proceso de renumeración"));
1012 if (RenumerarAsientos(loAsientosApertura.
_Numero, loAsientosAplicacion.
_Numero, out
string mensaje))
1014 loAsientosApertura.
_Numero = 1;
1015 loAsientosAplicacion.
_Numero = 2;
1021 _cInfoMessage = mensaje;
1041 private bool RenumerarAsientos(
int numeroAsientoApertura,
int numeroAsientoAplicacion, out
string mensaje)
1043 mensaje =
string.Empty;
1044 if (numeroAsientoApertura > 1 || numeroAsientoAplicacion > 2)
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}";
1058 mensaje = _GenerAsientoApertura ? (_GenerarAsientoAplicacionPerdidasGanancias ? ambosAsientos : soloApertura) : soloAplicacion;
1060 mensaje = $
"{mensaje}, ya que no se ha podido ejecutar el proceso de renumeración.{Environment.NewLine}({loProcess._Error_Message}) ";
1076 loForm._ShowDialog();
1087 DataTable loDtCuentas;
1089 _cErrorMessage =
"";
1091 if (((
Empresa)EW_GLOBAL._Empresa)._EsConsolidada)
1093 _cErrorMessage =
" en empresas consolidadas.";
1099 else if (!_ExisteEjercicioAnterior())
1101 _cErrorMessage =
". No existe ningún ejercicio anterior del que recuperar los datos.";
1103 else if (_GenerAsientoApertura && _IsProvisional && (lnResult = _AsientosDescuadrados()) > 0)
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);
1108 else if (!_GenerAsientoApertura && _GenerarAsientoAplicacionPerdidasGanancias && _ExisteAsientoApertura() == 0)
1110 _cErrorMessage =
" porque no existe asiento de apertura";
1113 if (String.IsNullOrEmpty(_cErrorMessage))
1115 loDtCuentas = _ValidarCuentasPorEjercicio();
1117 if (_GenerAsientoApertura && loDtCuentas.Rows.Count > 0)
1119 List<String> loCuentas = (from loRow in loDtCuentas.AsEnumerable()
1120 select Convert.ToString(loRow[
"CODIGO"]).Trim()).Distinct().ToList();
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);
1126 if (String.IsNullOrEmpty(_cErrorMessage))
1128 loDtCuentas = _ValidarLongitudCuentas();
1130 if (_GenerAsientoApertura && loDtCuentas.Rows.Count > 0)
1132 List<String> loCuentas = (from loRow in loDtCuentas.AsEnumerable()
1133 select Convert.ToString(loRow[
"CODIGO"]).Trim()).Distinct().ToList();
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);
1139 if (String.IsNullOrEmpty(_cErrorMessage))
1141 lOk = _ValidarCuentasAplicacion();
1142 lOk = lOk && _ExistenAsientosAperturaAplicacion();
1146 if (!String.IsNullOrEmpty(_cErrorMessage))
1148 String lcCadenaAsientos;
1150 if(_GenerarAsientoAplicacionPerdidasGanancias && _GenerAsientoApertura)
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");
1154 else if (_GenerAsientoApertura)
1156 lcCadenaAsientos = String.Format(
"No se puede crear el asiento de apertura {0}", _IsProvisional ?
"provisional" :
"definitivo");
1160 lcCadenaAsientos =
"No se puede crear el asiento de aplicación de pérdidas o ganancias";
1162 _cErrorMessage = String.Format(
"{0}{1}", lcCadenaAsientos, _cErrorMessage);
1165 lOk &= String.IsNullOrEmpty(_cErrorMessage);
1170 private DataTable _ValidarLongitudCuentas()
1174 DataTable loDt =
new DataTable();
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);
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);
1189 DB.SQLExec(lcSql, ref loDt);
1196 private DataTable _ValidarCuentasPorEjercicio()
1199 DataTable loDt =
new DataTable();
1201 if (_ConfigEjercicioAnterior.Rows.Count > 0)
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"));
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"));
1215 DB.SQLExec(lcSql, ref loDt);
1221 private bool _ValidarCuentasAplicacion()
1223 if (_GenerarAsientoAplicacionPerdidasGanancias && (
String.IsNullOrEmpty(_CuentaRemanenteAcreedor) || (
String.IsNullOrEmpty(_CuentaRemanenteDeudor))))
1227 if (
String.IsNullOrEmpty(_CuentaRemanenteAcreedor) && (
String.IsNullOrEmpty(_CuentaRemanenteDeudor)))
1229 lcErrorMessage =
" porque no existe la cuenta (120 - Remanente) ni la cuenta (121 - Resultados negativos de ejercicios anteriores).";
1233 lcErrorMessage =
String.Format(
" porque no existe la cuenta {0}. ",
String.IsNullOrEmpty(_CuentaRemanenteAcreedor) ?
"(120 - Remanente)" :
" (121 - Resultados negativos de ejercicios anteriores)");
1236 if (_GenerAsientoApertura)
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");
1240 if (DialogResult.Yes == FUNCTIONS._MessageBox(lcErrorMessage,
"Validación cuentas", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2))
1242 _GenerarAsientoAplicacionPerdidasGanancias =
false;
1251 _cErrorMessage = lcErrorMessage;
1259 private Boolean _ExistenAsientosAperturaAplicacion()
1261 Int32 lnResultAper = 0, lnResultApli = 0;
1262 String lcErrorMessage, lcTitulo;
1263 Boolean lbApertura =
false, lbAplicacion =
false;
1265 lbApertura = _GenerAsientoApertura && (lnResultAper = _ExisteAsientoApertura()) > 0;
1266 lbAplicacion = _GenerarAsientoAplicacionPerdidasGanancias && (lnResultApli = _ExisteAsientoAplicacion()) > 0;
1268 if (lbApertura || lbAplicacion)
1270 if (lbApertura && lbAplicacion)
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);
1275 else if (!lbApertura && lbAplicacion)
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);
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);
1286 if (DialogResult.No == FUNCTIONS._MessageBox(lcErrorMessage, lcTitulo, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2))
1294 private Int32 _ExisteAsientoApertura()
1296 return _ExisteAsiento(
"AND TIPO = 1");
1299 private Int32 _ExisteAsientoAplicacion()
1301 return _ExisteAsiento(
"AND TIPO = 4");
1304 private Int32 _ExisteAsiento(String tcCond)
1308 DataTable loDt =
new DataTable();
1310 lcSql =
String.Format(
"SELECT NUMERO FROM {0} WHERE EMPRESA = '{1}' {2} ", DB.SQLDatabase(
"GESTION",
"ASIENTOS"), _CodigoEmpresa, tcCond);
1311 DB.SQLExec(lcSql, ref loDt);
1313 if (loDt.Rows.Count > 0) lnNum = Convert.ToInt32(loDt.Rows[0][
"numero"]);
1318 private Int32 _AsientosDescuadrados()
1321 DataTable loDt =
new DataTable();
1323 if (_ConfigEjercicioAnterior.Rows.Count > 0)
1325 lcCon = DB.SQLDatabaseReal(Convert.ToString(_ConfigEjercicioAnterior.Rows[0][
"CONEXION"]),
"ASIENTOS");
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());
1329 DB.SQLExec(lcSql, ref loDt);
1332 return loDt.Rows.Count;
1335 private bool _ExisteEjercicioAnterior()
1337 return _ConfigEjercicioAnterior.Rows.Count > 0;
1340 private bool _MesCerrado(DateTime? toFecha)
1343 DataTable loDt =
new DataTable();
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);
1348 return loDt.Rows.Count > 0;
Clase para almacenar información del asiento generado
Classe empresa basada en sage.ew.ewmante
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 ...
decimal _Cambio
Coeficiente de cambio entre DEBE y DEBEDIV y HABER y HABERDIV
int _Numero
Número de asiento.
static bool DeleteAsientoApertura(string ejercicio, string empresa="")
Método para borrar el asiento de apertura del ejercicio recibido por parámetro
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.
KeyDiccionarioLenCampos
Clave del diccionario LenCampos
Boolean _AsientoAperturaProvisional(ref Asientos toAsiento, bool tlRenumerar)
Task 167460 - Sobrecarga para renumerar asientos si venimos del nuevo ejercicio Función FOX Asiento_i...
void _Show()
Muestra el formulario
string _Definicion
Definición de la cuenta.
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.
bool _Valida()
Valida que se pueda generar
Divisa()
Constructor vacío
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
decimal _HaberDiv
Importe de la partida HABER en divisa
Clase de negocio para la DIVISA (Moneda)
Clase para gestionar los meses cerrados
void _Generar(ProcessBar _oProcess=null)
Gnera el asiento de apertura
static List< String > ObtenerMesesCerrados()
Obtiene los meses cerrados