Files
BeWoPlaner/Service/Plugins/TimeSheetService.cs
2023-05-10 13:30:08 +02:00

426 lines
14 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Threading;
using BeWo.Data;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.DCEntityMapper;
using BeWo.Service.Plugins;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;
using DevExpress.XtraReports.UI;
namespace BeWo.Service.Plugins
{
public class TimeSheetService : AbstractIDSpecificDefaultClass<TimeSheetService>
{
public String DebugDetails { get; set; }
public virtual List<TimeSheetStatusItemDC> GetTimesheetStatusList(DateTime monat)
{
var tsService = PluginLoader.FindClass<TimeSheetService>();
List<TimeSheetStatusItemDC> liste = new List<TimeSheetStatusItemDC>();
var employees = DAOFactory.GenericDAO.GetAllActive<Employee>();
var timesheets = DAOFactory.SearchDAO.FindTimeSheetsForMonth(monat);
Dictionary<long, Timesheet> empOid2TimeSheet = new Dictionary<long, Timesheet>();
foreach (var ts in timesheets)
{
if (ts.EmployeeOid.HasValue)
{
if (!empOid2TimeSheet.ContainsKey(ts.EmployeeOid.Value))
{
empOid2TimeSheet.Add(ts.EmployeeOid.Value, ts);
}
}
}
foreach (var employee in employees)
{
var customers = MapperFactory.CompactCustomerDC_Customer.MapToNewDCs(employee.Employee2CustomerList.Where(e2c => HasValidRelation(e2c))
.Select(e2c => e2c.Customer).Where(c => c.IsActive == ActivationTypeId.Active && HasValidSupportConcept(c, monat))
.OrderBy(c => c.Person.LastName));
if (customers.Count > 0)
{
TimeSheetStatusItemDC newitem = new TimeSheetStatusItemDC();
newitem.Monat = monat;
newitem.Customer = customers;
newitem.Employee = MapperFactory.CompactEmployeeDC_Employee.MapToNewDC(employee);
var contact = employee.Person.Contacts.FirstOrDefault(c => c.Type == ContactType.business_Mail);
if (contact != null)
{
newitem.MailAddress = contact.Value;
}
newitem.MailSubjectTemplate = tsService.GetMailSubjectTemplate();
newitem.MailMessageTemplate = tsService.GetMailMessageTemplate();
if (empOid2TimeSheet.ContainsKey(employee.Oid.Value))
{
var ts = empOid2TimeSheet[employee.Oid.Value];
newitem.Status = ts.Status;
var timesheetMails =
DAOFactory.SearchDAO.FindTimeSheetMails(ts.Oid.Value, employee.Oid.Value);
newitem.Mails = new List<MailDC>();
foreach (var t2m in timesheetMails)
{
newitem.Mails.Add(MapperFactory.MailDC_Mail.MapToNewDC(t2m.Mail));
}
}
String teamleader = "";
var teams = DAOFactory.SearchDAO.FindTeamsOfEmployee(employee.Oid.Value);
foreach (var team in teams)
{
var name = team.Leader.Person.FirstNameLastName;
if (!teamleader.Contains(name))
{
if (teamleader.Length > 0)
{
teamleader += ", ";
}
teamleader += name;
}
}
newitem.TeamLeader = teamleader;
liste.Add(newitem);
}
}
return liste;
}
protected virtual bool HasValidRelation(Employee2Customer e2C)
{
//für abgeleitete Klassen
return true;
}
protected virtual bool HasValidSupportConcept(Customer c, DateTime monat)
{
foreach (var sc in c.SupportConcepts)
{
if (sc.IsActive == ActivationTypeId.Active && sc.StartDate.HasValue && sc.StartDate < monat.AddMonths(1) && sc.EndDate.HasValue && sc.EndDate.Value >= monat)
{
return true;
}
}
return false;
}
public virtual string SendTimeSheetMail(TimeSheetStatusItemDC item, bool saveMailToDatabase, XtraReport report, Dictionary<String, XtraReport> additionalAttachments)
{
Dictionary<String, MemoryStream> additionalStreams = new Dictionary<String, MemoryStream>();
try
{
using (var ms = new MemoryStream())
{
report.ExportToPdf(ms);
var fileName = CreateFileName(report, item);
var subject = CreateSubject(item);
var mailBody = CreateMailMessage(item);
var replyAddress = GetReplyAddress(item);
if (additionalAttachments != null && additionalAttachments.Count > 0)
{
foreach (var key in additionalAttachments.Keys)
{
var addReport = additionalAttachments[key];
var newms = new MemoryStream();
addReport.ExportToPdf(newms);
additionalStreams.Add(key, newms);
}
}
SendMail(replyAddress, item.MailAddress, ms, fileName, subject, mailBody, additionalStreams);
if (saveMailToDatabase)
{
var mail = new Mail();
mail.Subject = subject;
mail.Message = mailBody;
mail.Sender = replyAddress;
mail.Receiver = item.MailAddress;
if (ms != null)
{
ms.Position = 0;
mail.AttachmentList.Add(new FileAttachment
{
IsLocked = false,
ObjectTid = TableID.Mail,
Data = BS.Shared.Core.Utils.ReadFully(ms)
});
}
DAOFactory.GenericDAO.Insert(mail);
Timesheet ts =
DAOFactory.SearchDAO.FindEmployeeTimeSheetForMonth(item.Employee.EmployeeOid, item.Monat.Value);
if (ts == null)
{
ts = new Timesheet();
ts.EmployeeOid = item.Employee.EmployeeOid;
ts.CreationDate = DateTime.Now;
ts.StartDate = new DateTime(item.Monat.Value.Year, item.Monat.Value.Month, 1);
ts.EndDate = ts.StartDate.Value.AddMonths(1).AddDays(-1);
DAOFactory.GenericDAO.Insert(ts);
}
Timesheet2Mail t2m = new Timesheet2Mail();
t2m.TimesheetOid = ts.Oid;
t2m.Mail = mail;
t2m.EmployeeOid = ts.EmployeeOid;
DAOFactory.GenericDAO.Insert(t2m);
}
}
}
catch (Exception e)
{
return e.Message;
}
finally
{
foreach (var ms in additionalStreams.Values)
{
ms.Close();
ms.Dispose();
}
}
return "";
}
public virtual string CreateMailMessage(TimeSheetStatusItemDC item)
{
String message = item.MailMessageTemplate;
return ReplacePlaceholder(message, item);
}
public virtual string GetMailSubjectTemplate()
{
String subject = "Stundenzettel {Monat} {Jahr}";
return subject;
}
public virtual string GetMailMessageTemplate()
{
String message = @"Lieber {Vorname},
hiermit senden wir dir deinen Stundenzettel für {Monat} {Jahr} zu.
Viele Grüße
{SenderVorname} {SenderNachname}
Telefon Durchwahl: {BenutzerTelefon}
";
return message;
}
protected virtual string ReplacePlaceholder(string message, TimeSheetStatusItemDC item)
{
if (message.Contains("{Benutzer"))
{
ApplicationUser loggedInUser = null;
if (LoggedInUserOperationContextExt.Current != null &&
LoggedInUserOperationContextExt.Current.User != null)
{
loggedInUser = LoggedInUserOperationContextExt.Current.User;
}
else
{
loggedInUser = SessionFacade.LoggedInUser;
}
if (loggedInUser != null && loggedInUser.Employee != null)
{
message = message.Replace("{BenutzerVorname}", loggedInUser.Employee.Person.FirstName);
message = message.Replace("{BenutzerNachname}", loggedInUser.Employee.Person.LastName);
if (message.Contains("{BenutzerTelefon}"))
{
String telefon = "";
var telContact = loggedInUser.Employee.Person.Contacts.FirstOrDefault(c => c.Type == ContactType.business_Phone);
if (telContact != null)
{
telefon = telContact.Value;
}
message = message.Replace("{BenutzerTelefon}", telefon);
}
}
}
if (message.Contains("{MitarbeiterAnrede}"))
{
String anrede = "Liebe Frau";
var emp = DAOFactory.GenericDAO.LoadByID<Employee>(item.Employee.EmployeeOid);
if (emp.Person.Sex.HasValue && emp.Person.Sex.Value == Sex.Male)
{
anrede = "Lieber Herr";
}
message = message.Replace("{MitarbeiterAnrede}", anrede);
}
//message = message.Replace("{KlientVorname}", customer.FirstName);
//message = message.Replace("{KlientNachname}", customer.LastName);
message = message.Replace("{Monat}", String.Format("{0:MMMM}", item.Monat));
message = message.Replace("{Jahr}", String.Format("{0:yyyy}", item.Monat));
message = message.Replace("{MitarbeiterVorname}", item.Employee.FirstName);
message = message.Replace("{MitarbeiterNachname}", item.Employee.LastName);
return message;
}
public virtual string CreateSubject(TimeSheetStatusItemDC item)
{
return ReplacePlaceholder(item.MailSubjectTemplate, item);
}
public virtual string CreateFileName(XtraReport report, TimeSheetStatusItemDC item)
{
return String.Format("Stundenzettel {0:MMMM yyyy}.pdf", item.Monat);
}
public void SendMail(String fromAddress, String receiverAddress, MemoryStream attachementStream, String fileName, String subject, String messageBody, Dictionary<String, MemoryStream> additionalStreams)
{
try
{
DebugDetails = String.Format("Send Mail from: {0} to {1}", fromAddress, receiverAddress);
//#if DEBUG
// messageBody = receiverAddress + "\n\n" + messageBody;
// receiverAddress = "cb@ownsoft.de";
//#endif
MailAddress fromMailAddress = new MailAddress(fromAddress);
MailAddress toMailAddress = new MailAddress(receiverAddress);
var message = new MailMessage(fromMailAddress, toMailAddress);
message.Subject = subject;
message.Body = messageBody;
if (attachementStream != null)
{
attachementStream.Position = 0;
//Attachment data = new Attachment(reportStream, fileName, MediaTypeNames.Application.Octet);
Attachment data = new Attachment(attachementStream, new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf));
data.Name = fileName;
message.Attachments.Add(data);
}
if (additionalStreams != null)
{
foreach (var key in additionalStreams.Keys)
{
var ms = additionalStreams[key];
ms.Position = 0;
Attachment data = new Attachment(ms, new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf));
data.Name = key;
message.Attachments.Add(data);
}
}
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = false;
SmtpClient mailClient = CreateSmtpClient();
//details = String.Format("{0}", mailClient.Credentials.)
mailClient.Send(message);
//var msg = new ErrorMessage();
//msg.Modul = "BeWo.Service.Plugins.TimeSheetService";
//msg.Message = "Debug Info: Erfolgreicher Mailversand";
//msg.MessageDetails = DebugDetails;
//DAOFactory.GenericDAO.Insert(msg);
//Thread.Sleep(2000);
}
catch (Exception e)
{
var msg = new ErrorMessage();
msg.Modul = "BeWo.Service.Plugins.TimeSheetService";
msg.Message = e.Message;
msg.MessageDetails = String.Format("{0} - Stacktrace: {1}", DebugDetails, e.StackTrace);
if (e.InnerException != null)
{
msg.MessageDetails += String.Format("\n\nInner Exception: {0}\n{1}", e.InnerException.Message, e.InnerException.StackTrace);
}
DAOFactory.GenericDAO.Insert(msg);
throw e;
}
}
public virtual String GetReplyAddress(TimeSheetStatusItemDC item)
{
return "noreply@bewoplaner.de";
}
public virtual SmtpClient CreateSmtpClient()
{
var mailClient = new SmtpClient("mail.ownsoft.de", 587) { Credentials = new NetworkCredential("bewoplaner.support@ownsoft.de", "JJVjJntw2yaRDAxInotF") };
mailClient.EnableSsl = true;
return mailClient;
}
}
}