Files
BeWoPlaner/ReportImp/Kette2/Export/DatevExporter.cs
2021-05-24 21:40:02 +02:00

425 lines
17 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.DCEntityMapper;
using BS.Shared;
using BS.Shared.DataContracts;
using BS.Shared.Extensions;
namespace KetteReports.Export
{
public class DatevExporter
{
public static QueryDC CreateQuery(QueryDC query)
{
DateTime dt = DateTime.Now;
DateTime.TryParse(query.Parameter[0].Value.ToString(), out dt);
query.FileName = String.Format("DatevListe{0:yyyyMM}.csv", dt);
query.QueryResult = GetAbrechnungenString(dt);
return query;
}
public static string CreateExportString(string[] pHeaderCaption, string[][] pContent)
{
if (pHeaderCaption != null && pHeaderCaption.Length > 1 && pHeaderCaption[0].Contains("DatevListe"))
{
DateTime dt = DateTime.Now;
DateTime.TryParse(pHeaderCaption[1], out dt);
return GetAbrechnungenString(dt);
}
return null;
}
public static String GetAbrechnungenString(DateTime date)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Debitoren Nr.;Kostenstelle;Name;Kostenträger;FLS;Forderung;Belegnr.;Stundensatz;Pauschaler Faktor in %;Gegenkonto");
//5 Fachleistungsstunde LVR
//7 Sozialdienst allgemein
//8 Sozialdienst Geronto
//9 Ergänzungskräfte(sonstige Kostenträger)
//10 Ergänzungskräfte LVR(Fachleistungsstunde)
//12 Fachleistungsstunde Jugendamt
//13 Gruppe LVR(Fachleistungsstunde)
//15 Indirekte Betreuungsleistung
//16 Fachleistungsstunde Selbstzahler
//17 Wohngruppe
//23 Tagesstätte
//24 Jugendberatung
//25 Fachleistungsstunde Jugend BeWo
//26 Ergänzungskräfte LVR(Assistenz)
//27 LT15
List<long> oidList = new List<long>();
oidList.Add(5); // Fachleistung
var s = GetMonatlicheAbrechnungStringForCats(date, oidList, null, "8000", null, true, true);
if (!String.IsNullOrWhiteSpace(s))
{
sb.Append(s);
}
oidList.Clear();
oidList.Add(16); // Fachleistungsstunde Selbstzahler
s = GetMonatlicheAbrechnungStringForCats(date, oidList, null, "8001", null, true, true);
if (!String.IsNullOrWhiteSpace(s))
{
if (sb.Length > 0)
sb.AppendLine();
sb.Append(s);
}
oidList.Clear();
oidList.Add(9); // Ergänzungskräfte(sonstige Kostenträger)
s = GetMonatlicheAbrechnungStringForCats(date, oidList, null, "8005", null, true, true);
if (!String.IsNullOrWhiteSpace(s))
{
if (sb.Length > 0)
sb.AppendLine();
sb.Append(s);
}
oidList.Clear();
oidList.Add(25); // Fachleistungsstunde Jugend BeWo
oidList.Add(12); // Fachleistungsstunde Jugendamt
s = GetMonatlicheAbrechnungStringForCats(date, oidList, null, "8010", null, true, true);
if (!String.IsNullOrWhiteSpace(s))
{
if (sb.Length > 0)
sb.AppendLine();
sb.Append(s);
}
//Alle anderen
oidList.Clear();
oidList.Add(5);
oidList.Add(16);
oidList.Add(9);
oidList.Add(25);
oidList.Add(12);
//var costDict = CreateHourlyRateDict(oidList, date);
s = GetMonatlicheAbrechnungStringForCats(date, null, oidList, "", null, true, true);
if (!String.IsNullOrWhiteSpace(s))
{
if (sb.Length > 0)
sb.AppendLine();
sb.Append(s);
}
return sb.ToString();
}
public static String GetMonatlicheAbrechnungStringForCats(DateTime date, IList<long> includeCatOids, IList<long> excludeCatOids, String sachkonto, Dictionary<long, decimal> costDict, bool holeEinzel, bool holeGruppen)
{
var sql = GetMonatlicheAbrechnungStringForCatsSql(date, includeCatOids, excludeCatOids, holeEinzel, holeGruppen);
var dt = ExecuteQuery(sql, date);
StringBuilder sb = new StringBuilder();
foreach (DataRow row in dt.Rows)
{
if (sb.Length > 0)
{
sb.AppendLine();
}
for (int i = 0; i < row.ItemArray.Length; i++)
{
if (i < 999)
{
if (i > 0)
{
sb.Append(";");
}
var item = row[i];
//if (i == 5 && row[5] != null)
//{
// decimal betrag = 0;
// Decimal.TryParse(row[5].ToString(), out betrag);
// //var betrag = (decimal) row[4];
// if (row[9] != null && row[10] != null && costDict != null)
// {
// var minuten = (decimal) row[9];
// var catOid = (long) row[10];
// if (costDict.ContainsKey(catOid))
// {
// var stundensatz = costDict[catOid];
// betrag =
// Math.Round(
// stundensatz * Math.Round(minuten / 60, 2, MidpointRounding.AwayFromZero), 2,
// MidpointRounding.AwayFromZero);
// }
// }
// sb.Append(betrag);
//}
//else
//{
sb.Append(item);
//}
//if (i == 4)
//{
// sb.Append(" Std");
//}
}
}
sb.Append(";");
sb.Append(sachkonto);
}
return sb.ToString();
}
private static Dictionary<long, decimal> CreateHourlyRateDict(List<long> catOids, DateTime date)
{
Dictionary<long, decimal> dict = new Dictionary<long, decimal>();
foreach (var oid in catOids)
{
var cat = DAOFactory.GenericDAO.LoadByID<ServiceCategory>(oid);
var crps = MapperFactory.CostRatePeriodDC_CostRatePeriod.MapToNewDCs(cat.CostRatePeriods);
var cp = crps.GetCostRatePeriodForDate(CostRatePeriodType.AmountOfMoney, date);
if (cp != null && cp.CostRateValue.HasValue)
{
dict.Add(oid, cp.CostRateValue.Value);
}
}
return dict;
}
private static String GetMonatlicheAbrechnungStringForCatsSql(DateTime date, IList<long> includeCatOids, IList<long> excludeOids, bool holeEinzel, bool holeGruppen)
{
String sql = @"
SELECT distinct
c.`DebitorNumber` AS 'Debitoren Nr.',
c.`CostCenter` AS 'Kostenstelle',
CONCAT(p.`LastName`, ', ', p.`FirstName`) as Name,
org.`Name` as 'Kostentraeger',
ROUND(sr.`GeleisteteFLM` / 60, 2) as 'FLS',
IF(crpRateFactor.`CostRateValue` is null, ROUND((sr.`GeleisteteFLM` / 60) * crpHourlyRate.`CostRateValue`, 2),ROUND(ROUND((sr.`GeleisteteFLM` / 60), 2) * crpHourlyRate.`CostRateValue` * ((100 + crpRateFactor.`CostRateValue`)/100), 2)) AS 'Forderung',
':Monat_MM' AS 'Belegnr.',
ROUND(crpHourlyRate.`CostRateValue`,2) as 'Stundensatz', ROUND(crpRateFactor.`CostRateValue`,2) as 'Pauschaler Faktor in %'
FROM `supportconcept` sc
INNER JOIN `costbearer2supportconcept` cb2sc ON sc.`Oid` = cb2sc.`SupportConceptOid`
INNER JOIN `costbearer` cb ON cb2sc.`CostBearerOid` = cb.`Oid`
INNER JOIN
(SELECT crp.`ObjectOid`, crp.costratetype, crp.`CostRateValue`, If(crp.Enddate is null, '9999-01-01', crp.enddate) as aenddatum, crptemp.enddatum FROM `costrateperiod` crp
inner join (SELECT crpi.`ObjectOid`, Min(If(crpi.Enddate is null, '9999-01-01', crpi.enddate)) as enddatum FROM `costrateperiod` crpi
WHERE crpi.`ObjectTid` = 22 AND crpi.`CostRateType` = 0 AND (crpi.`EndDate` is null or crpi.`EndDate` > ':Monat_Start')
group by crpi.objectoid) as crptemp on crptemp.objectoid = crp.objectoid
WHERE crp.`ObjectTid` = 22 and crp.costratetype = 0
having aenddatum = crptemp.enddatum)
AS crpHourlyRate ON crpHourlyRate.`ObjectOid` = cb.`Oid`
LEFT JOIN
(SELECT crp.`ObjectOid`, crp.costratetype, crp.`CostRateValue`, If(crp.Enddate is null, '9999-01-01', crp.enddate) as aenddatum, crptemp.enddatum FROM `costrateperiod` crp
inner join (SELECT crpi.`ObjectOid`, Min(If(crpi.Enddate is null, '9999-01-01', crpi.enddate)) as enddatum FROM `costrateperiod` crpi
WHERE crpi.`ObjectTid` = 22 AND crpi.`CostRateType` = 2 AND (crpi.`EndDate` is null or crpi.`EndDate` > ':Monat_Start')
group by crpi.objectoid) as crptemp on crptemp.objectoid = crp.objectoid
WHERE crp.`ObjectTid` = 22 and crp.costratetype = 2
having aenddatum = crptemp.enddatum)
AS crpRateFactor ON crpRateFactor.`ObjectOid` = cb.`Oid`
INNER JOIN `organisation` org ON org.`CostBearerOid` = cb.`Oid`
INNER JOIN `customer` c ON sc.`CustomerOid` = c.`Oid`
INNER JOIN `person` p on c.`PersonOid` = p.`Oid`
INNER JOIN
(SELECT
v2o.`ObjectOid`,
v2o.`ValueListEntryOid`
FROM `valuelistentry2object` v2o
WHERE v2o.`ValueListEntryOid` in (12,13,14) ) as vle2o ON vle2o.`ObjectOid` = c.`Oid`
INNER JOIN `valuelistentry` vle on vle.`Oid` = vle2o.`ValueListEntryOid`
INNER JOIN
(SELECT sr2.`CostBearer2SupportConceptOid`, SUM(sr2.`roundedduration` / IF(sr2.`GroupEmployeeCount` is null, 1, sr2.`GroupEmployeeCount`)) AS GeleisteteFLM FROM `servicerecord` sr2
INNER JOIN `servicedescription` sd ON sr2.`ServiceDescriptionOid` = sd.`Oid`
INNER JOIN `servicecategory` sc ON sd.`ServiceCategoryOid` = sc.`Oid`
WHERE sr2.`StartDate` >= ':Monat_Start' AND sr2.`StartDate` < ':Monat_End' AND sc.`Billable` = 1:IncludeCatOidList:ExcludeCatOidList GROUP BY sr2.`CostBearer2SupportConceptOid`)
AS sr ON sr.`CostBearer2SupportConceptOid` = cb2sc.`Oid`
WHERE c.`IsActive` <> 0 AND sc.`IsActive` <> 0 and
((If (cb2sc.`ApprovedStartDate` is null, cb2sc.`RequestedStartDate`, cb2sc.`ApprovedStartDate`) < ':Monat_End' and
If (cb2sc.`ApprovedEndDate` is null, cb2sc.`RequestedEndDate`, cb2sc.`ApprovedEndDate`) >= ':Monat_Start'
and GeleisteteFLM is null) or GeleisteteFLM is not null)
ORDER BY p.`LastName`
";
String sqlalt = @"
SELECT
CONCAT(p.Lastname, ', ', p.Firstname),
c.DebitorNumber as 'DebKonto',
DATE_FORMAT(DATE_ADD(':Monat_End',INTERVAL -1 DAY), '%d.%m.%Y') as 'Datum',
c.`CostCenter` AS 'Kst',
ROUND(sr.`GeleisteteFLM` / 60, 2) as 'Text',
IF(crpRateFactor.`CostRateValue` is null,
ROUND(ROUND(sr.`GeleisteteFLM` / 60, 2) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22 AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 ), 2),
ROUND(ROUND((sr.`GeleisteteFLM` / 60) * ((100 + crpRateFactor.`CostRateValue`)/100), 2) * (SELECT crp.`CostRateValue` FROM `costrateperiod` crp WHERE crp.`ObjectTid` = 22 AND crp.`CostRateType` = 0 AND crp.`ObjectOid` = cb2sc.`CostBearerOid` AND (crp.`EndDate` is null or crp.`EndDate` > ':Monat_Start') order by IF(crp.`EndDate` is null, MAKEDATE(9999,365),crp.`EndDate`) LIMIT 1 ), 2)) AS 'Betrag',
'',
'',
'',
sr.`GeleisteteFLM`,
sr.CatOid
FROM `supportconcept` sc
INNER JOIN `costbearer2supportconcept` cb2sc ON sc.`Oid` = cb2sc.`SupportConceptOid`
INNER JOIN `costbearer` cb ON cb2sc.`CostBearerOid` = cb.`Oid`
LEFT JOIN
(SELECT crp.`ObjectOid`, crp.`CostRateValue` FROM `costrateperiod` crp
WHERE crp.`ObjectTid` = 22 AND crp.`CostRateType` = 2 AND (crp.`EndDate` is null or crp.`EndDate` > NOW()))
AS crpRateFactor ON crpRateFactor.`ObjectOid` = cb.`Oid`
INNER JOIN `organisation` org ON org.`CostBearerOid` = cb.`Oid`
INNER JOIN `customer` c ON sc.`CustomerOid` = c.`Oid`
INNER JOIN `person` p on c.`PersonOid` = p.`Oid`
LEFT JOIN
(SELECT sr2.`CostBearer2SupportConceptOid`, SUM(sr2.`roundedduration` / IF(sr2.`GroupEmployeeCount` is null, 1, sr2.`GroupEmployeeCount`)) AS GeleisteteFLM, sc.Oid as CatOid FROM `servicerecord` sr2
INNER JOIN `servicedescription` sd ON sr2.`ServiceDescriptionOid` = sd.`Oid`
INNER JOIN `servicecategory` sc ON sd.`ServiceCategoryOid` = sc.`Oid`
WHERE sr2.`StartDate` >= ':Monat_Start' AND sr2.`StartDate` < ':Monat_End' AND sc.`Billable` = 1 AND sc.oid in (CATOIDLIST) :Gruppenfilter GROUP BY sr2.`CostBearer2SupportConceptOid`)
AS sr ON sr.`CostBearer2SupportConceptOid` = cb2sc.`Oid`
WHERE c.`IsActive` <> 0 AND sc.`IsActive` <> 0
and (sr.`GeleisteteFLM` is not null)
ORDER BY p.`LastName`, p.`FirstName`, cb2sc.`ApprovedStartDate`
";
String includeString = "";
String excludeString = "";
if (includeCatOids != null && includeCatOids.Count > 0)
{
StringBuilder oidList = new StringBuilder();
foreach (var catOid in includeCatOids)
{
if (oidList.Length > 0)
oidList.Append(",");
oidList.Append(catOid);
}
includeString = String.Format(" AND sc.oid in ({0})", oidList.ToString());
}
if (excludeOids != null && excludeOids.Count > 0)
{
StringBuilder notoidList = new StringBuilder();
foreach (var catOid in excludeOids)
{
if (notoidList.Length > 0)
notoidList.Append(",");
notoidList.Append(catOid);
}
excludeString = String.Format(" AND sc.oid not in ({0})", notoidList.ToString());
}
String gruppenfilter = "";
if (!holeEinzel || !holeGruppen)
{
if (holeGruppen)
{
gruppenfilter = "AND sr2.GroupOid is not null";
}
else
{
gruppenfilter = "AND sr2.GroupOid is null";
}
}
sql = sql.Replace(":Gruppenfilter", gruppenfilter);
sql = sql.Replace(":IncludeCatOidList", includeString);
sql = sql.Replace(":ExcludeCatOidList", excludeString);
return sql;
}
private static String GetAbschlagszahlungenSql(DateTime date)
{
String sql = @"
SELECT
date_format(at.BookingDate, '%d.%m.%Y') as 'Belegdatum',
':Belegnr',
'S13690' as 'Konto Soll',
'' as 'Kostenstelle Soll',
c.DebitorNumber as 'Konto Haben',
'' as 'Kostenstelle Haben',
Round(at.Amount, 2) as 'Betrag',
CONCAT('Abschlagszahlung,', p.FirstName, ' ', p.LastName) as 'Buchungstext'
from accountingtransaction at
join costbearer2supportconcept c2s on c2s.oid = at.costbearer2supportconceptoid
join supportconcept sc on sc.oid = c2s.supportconceptoid
join customer c on sc.customeroid = c.oid
join person p on c.personoid = p.oid
WHERE at.`BookingDate` >= ':Monat_Start' AND at.`BookingDate` < ':Monat_End' and c.`IsActive` <> 0 AND sc.`IsActive` <> 0
ORDER BY p.`LastName`, p.`FirstName`
";
return sql;
}
private static String GetSelbstzahlerSql(DateTime date)
{
String sql = @"
SELECT
date_format(ib.InvoiceDate, '%d.%m.%Y') as 'Belegdatum',
ib.InvoiceNumber as 'Belegnummer',
c.DebitorNumber as 'Konto Soll',
'' as 'Kostenstelle Soll',
'S86400' as 'Konto Haben',
c.CostCenter as 'Kostenstelle Haben',
Round(ii.AmountTotal, 2) as 'Betrag',
CONCAT('Eigenanteil, ', p.`FirstName`, ' ', p.`LastName`) as 'Buchungstext'
from invoicebase ib
join invoiceitem ii on ii.invoicebaseoid = ib.oid
join customer c on c.oid = ib.recipientcustomeroid
join `person` p on c.`PersonOid` = p.`Oid`
where ib.`InvoiceDate` >= ':Monat_Start' AND ib.`InvoiceDate` < ':Monat_End'
and ib.type = 0 and ib.isactive = 1 and c.isactive <> 0
";
return sql;
}
public static DataTable ExecuteQuery(String sql, DateTime dt)
{
var newsql = sql;
newsql = newsql.Replace(":Abrechnungsmonat", String.Format("{0:dd.MM.yyyy}", dt));
newsql = newsql.Replace(":Belegnr", String.Format("{0:yyMM}", dt));
newsql = newsql.Replace(":Monat_MM", String.Format("{0:MM}", dt));
newsql = newsql.Replace(":Monat_Start", String.Format("{0:yyyy-MM}-01", dt));
dt = dt.AddMonths(1);
newsql = newsql.Replace(":Monat_End", String.Format("{0:yyyy-MM}-01", dt));
return DAOFactory.AdoDAO.ExecuteQuery(newsql).Tables[0];
}
}
}