diff --git a/Data/Access/SearchDAO.cs b/Data/Access/SearchDAO.cs index d67332426..22698f6ae 100644 --- a/Data/Access/SearchDAO.cs +++ b/Data/Access/SearchDAO.cs @@ -30,3488 +30,3500 @@ using Resource = BeWo.Data.Entities.Resource; namespace BeWo.Data.Access { - public class SearchDAO : AbstractBaseDAO - { - private static readonly Regex RecurrenceIdRegex = new Regex("(Id=\\\"[a-z0-9-]+\\\")"); - - public IEnumerable FindValueListEntry(ValueListEntryType pType) - { - return CreateCriteria().Add(Restrictions.Eq(ValueListEntry.PropertyName_Type, pType)).AddOrder(Order.Asc(ValueListEntry.PropertyName_Value)).List(); - } - - public IEnumerable FindValueListEntries(List pTypes) - { - return CreateCriteria().Add(Restrictions.In(ValueListEntry.PropertyName_Type, pTypes)).AddOrder(Order.Asc(ValueListEntry.PropertyName_Value)).List(); - } - - public virtual IEnumerable FindEmployee(string pFirstName, string pLastName, string pPersonnelNumber) - { - return CreateCriteria() - .Add(Restrictions.Like(Employee.PropertyName_PersonnelNumber, pPersonnelNumber, MatchMode.Anywhere)) - .CreateCriteria(Employee.PropertyName_Person, JoinType.InnerJoin) - .Add(Restrictions.Like(Person.PropertyName_FirstName, pFirstName, MatchMode.Anywhere)) - .Add(Restrictions.Like(Person.PropertyName_LastName, pLastName, MatchMode.Anywhere)) - .List(); - } - - public virtual Employee FindEmployeeByFullname(string pFullname) - { - var q = Session.CreateSQLQuery(Format("SELECT e.oid FROM employee e join Person p on e.personoid = p.oid WHERE CONCAT_WS(' ', FirstName, LastName) LIKE '%{0}%' AND Type = 1", pFullname)); - var x = q.List(); - - return x.Count > 0 ? DAOFactory.GenericDAO.GetByID(x.Last()) : null; - } - - public virtual IEnumerable FindWohnheim(string pwohnheimName, string pWohnheimStrasse, string pWohnheimPlz) - { - return CreateCriteria() - .Add(Restrictions.Like(Wohnheim.PropertyName_WohnheimName, pwohnheimName, MatchMode.Anywhere)) - .CreateCriteria(Wohnheim.PropertyName_Wohnheim, JoinType.InnerJoin) - .Add(Restrictions.Like(Wohnheim.PropertyName_Strasse, pWohnheimStrasse, MatchMode.Anywhere)) - .Add(Restrictions.Like(Wohnheim.PropertyName_PlZ, pWohnheimPlz, MatchMode.Anywhere)) - .List(); - } - - public virtual Wohnheim FindWohnheimByFullname(string pWohnheimName) - { - var q = Session.CreateSQLQuery(Format("SELECT Oid FROM Wohnheim WHERE CONCAT_WS(' ', WohnheimName) LIKE '%{0}%'", pWohnheimName)); - var x = q.List(); - - return x.Count > 0 ? DAOFactory.GenericDAO.GetByID(x.First()) : null; - } - - public virtual IEnumerable FindCustomer(string pFirstName, string pLastName, string pReferenceNumber) - { - return CreateCriteria() - .Add(Restrictions.Like(Customer.PropertyName_ReferenceNumber, pReferenceNumber, MatchMode.Anywhere)) - .CreateCriteria(Customer.PropertyName_Person, JoinType.InnerJoin) - .Add(Restrictions.Like(Person.PropertyName_FirstName, pFirstName, MatchMode.Anywhere)) - .Add(Restrictions.Like(Person.PropertyName_LastName, pLastName, MatchMode.Anywhere)) - .List(); - } - - public virtual IList FindCustomer(string pFirstName, string pLastName, DateTime pBirthDate) - { - return CreateCriteriaIsActiveOrArchived() - .CreateCriteria(Customer.PropertyName_Person, JoinType.InnerJoin) - .Add(Restrictions.Eq(Person.PropertyName_FirstName, pFirstName)) - .Add(Restrictions.Eq(Person.PropertyName_LastName, pLastName)) - .Add(Restrictions.Eq(Person.PropertyName_DateOfBirth, pBirthDate)) - .List(); - } - - public virtual IList GetAllDienstEintraege(long wOid, DateTime start, DateTime end) - { - var c = CreateCriteria() - .Add(Restrictions.Eq("WohnheimOid", wOid)) - .Add(Restrictions.Between("Datum", start, end)) - .Add(Restrictions.Eq("IsActive", ActivationTypeId.Active)); - - return c.List(); - } - public virtual IList GetEmployeeForWohnheim(long wOid) - { - var c = CreateCriteria() - .Add(Restrictions.Eq("WohnheimOid", wOid)); - - return c.List(); - } - - public virtual IEnumerable FindPerson(string pFirstName, string pLastName, DateTime? pDateOfBirth, PersonType? pPersonType) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Like(Person.PropertyName_FirstName, pFirstName, MatchMode.Anywhere)) - .Add(Restrictions.Like(Person.PropertyName_LastName, pLastName, MatchMode.Anywhere)); - if (pDateOfBirth != null) - lCriteria.Add(Restrictions.Eq(Person.PropertyName_DateOfBirth, pDateOfBirth)); - if (pPersonType != null) - lCriteria.Add(Restrictions.Eq(Person.PropertyName_Type, pPersonType)); - - return lCriteria.List(); - } - - public virtual IEnumerable FindOrganisation(string pName, bool pOnlyCostBearer) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Like(Organisation.PropertyName_Name, pName, MatchMode.Anywhere)); - - if (pOnlyCostBearer) - lCriteria.Add(Restrictions.IsNotNull(Organisation.PropertyName_CostBearer)); - - return lCriteria.List(); - } - - public virtual IEnumerable FindTeams(string pTeamName, string pLeaderFirstName, string pLeaderLastName) - { - return CreateCriteria() - .Add(Restrictions.Like(Team.PropertyName_Name, pTeamName, MatchMode.Anywhere)) - .CreateCriteria(Team.PropertyName_Leader, JoinType.InnerJoin) - .CreateCriteria(Employee.PropertyName_Person) - .Add(Restrictions.Like(Person.PropertyName_FirstName, pLeaderFirstName, MatchMode.Anywhere)) - .Add(Restrictions.Like(Person.PropertyName_LastName, pLeaderLastName, MatchMode.Anywhere)) - .List(); - } - - public virtual IList FindTeamsOfEmployee(long employeeOid) - { - return CreateCriteriaIsActiveOrArchived() - .CreateCriteria(Team.PropertyName_MemberList, JoinType.InnerJoin) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeOid)) - .List(); - } - - public virtual IEnumerable FindLeadingTeams(long employeeOid) - { - return CreateCriteriaIsActiveOrArchived() - .CreateCriteria(Team.PropertyName_Leader, JoinType.InnerJoin) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeOid)) - .List(); - } - - public virtual IList FindAllActiveTeamsOfEmployee(long employeeOid) - { - return CreateCriteriaIsActive() - .CreateAlias(Team.PropertyName_MemberList, "m", JoinType.InnerJoin) - .CreateAlias(Team.PropertyName_Leader, "l", JoinType.InnerJoin) - .Add(Restrictions.Disjunction() - .Add(Restrictions.Eq("m." + BeWoEntityBase.PropertyName_Oid, employeeOid)) - .Add(Restrictions.Eq("l." + BeWoEntityBase.PropertyName_Oid, employeeOid))) - .List().Distinct().ToList(); - - } - - public virtual IList FindCustomerOfTeam(long teamOid) - { - return CreateCriteriaIsActiveOrArchived() - .CreateCriteria(Customer.PropertyName_Team2CustomerList, JoinType.InnerJoin) - .Add(Restrictions.Eq(Team2Customer.PropertyName_TeamOid, teamOid)) - .List(); - } - - public IEnumerable FindBookings(long pResourceOid, DateTime pSpanStart, DateTime pSpanEnd) - { - var lResult = CreateCriteria() - .CreateAlias(ResourceBookingSequence.PropertyName_Resource, "r") - .CreateAlias(ResourceBookingSequence.PropertyName_Details, "d") - .Add(Restrictions.Eq("r." + BeWoEntityBase.PropertyName_Oid, pResourceOid)) - .Add(Restrictions.Eq("d." + ResourceBooking.PropertyName_SequencePosition, 0)) - .Add(Restrictions.Disjunction() - .Add(Restrictions.Between("d." + ResourceBooking.PropertyName_Start, pSpanStart, pSpanEnd)) - .Add(Restrictions.Between(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanStart, pSpanEnd)) - .Add(Restrictions.Conjunction() - .Add(Restrictions.Le("d." + ResourceBooking.PropertyName_Start, pSpanStart)) - .Add(Restrictions.Ge(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanEnd)) - ) - ) - .List(); - - return lResult; - } - - public IEnumerable FindBookings(DateTime pSpanStart, DateTime pSpanEnd) - { - var lResult = CreateCriteria() - .CreateAlias(ResourceBookingSequence.PropertyName_Details, "d") - .Add(Restrictions.Eq("d." + ResourceBooking.PropertyName_SequencePosition, 0)) - .Add(Restrictions.Disjunction() - .Add(Restrictions.Between("d." + ResourceBooking.PropertyName_Start, pSpanStart, pSpanEnd)) - .Add(Restrictions.Between(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanStart, pSpanEnd)) - .Add(Restrictions.Conjunction() - .Add(Restrictions.Le("d." + ResourceBooking.PropertyName_Start, pSpanStart)) - .Add(Restrictions.Ge(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanEnd)) - ) - ) - .List(); - - return lResult; - } - - public void RemoveServiceRecordsFromAppointments(IEnumerable enumerable) - { - throw new NotImplementedException(); - } - - public List FindServiceRecords(long? pEmployeeOid, long? pCostBearer2SupportConceptOid) - { - var c = CreateCriteria() - .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin); - - if (pCostBearer2SupportConceptOid.HasValue) - { - c = c.CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin) - .CreateAlias("sc." + SupportConcept.PropertyName_CostBearer2SupportConceptList, "c2s", JoinType.InnerJoin); - } - - if (pEmployeeOid.HasValue) - c = c.Add(Restrictions.Eq("e." + BeWoEntityBase.PropertyName_Oid, pEmployeeOid)); - if (pCostBearer2SupportConceptOid.HasValue) - c = c.Add(Restrictions.Eq("c2s." + BeWoEntityBase.PropertyName_Oid, pCostBearer2SupportConceptOid)); - - return c.List().ToList(); - } - - public List FindServiceRecordsForSupportConcept(long pSupportConceptOid) - { - var c = CreateCriteria() - .CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin); - - c = c.Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_Oid, pSupportConceptOid)); - return c.List().ToList(); - } - - public List FindServiceRecords(long? supportConceptOid, long? costBearer2SupportConceptOid, long? serviceCategoryOid, DateTime? start, DateTime? end) - { - var c = CreateCriteria() - .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin); - - if (supportConceptOid.HasValue) - { - c = c.CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin); - } - - if (serviceCategoryOid.HasValue) - { - c = c.CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "cat", JoinType.InnerJoin); - } - - if (supportConceptOid.HasValue) - { - c = c.Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_Oid, supportConceptOid)); - } - - if (costBearer2SupportConceptOid.HasValue) - { - c = c.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); - } - - if (serviceCategoryOid.HasValue) - { - c = c.Add(Restrictions.Eq("cat." + BeWoEntityBase.PropertyName_Oid, serviceCategoryOid)); - } - - if (start.HasValue && end.HasValue) - { - c.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, start, end)); - } - //{ - // c = c.CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin) - // .CreateAlias("sc." + SupportConcept.PropertyName_CostBearer2SupportConceptList, "c2s", JoinType.InnerJoin); - //} - - //if (pEmployeeOid.HasValue) - // c = c.Add(Restrictions.Eq("e." + BeWoEntityBase.PropertyName_Oid, pEmployeeOid)); - - - return c.List().ToList(); - } - - public IList FindSupportConceptApprovalPeriod2Employees(Employee emp) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(SupportConceptApprovalPeriod2Employee.PropertyName_Employee, emp)); - return c.List().ToList(); - } - - public IList FindSupportConceptApprovalPeriod2Employees(SupportConceptApprovalPeriod scap) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(SupportConceptApprovalPeriod2Employee.PropertyName_SupportConceptApprovalPeriod, scap)); - return c.List().ToList(); - } - - public IEnumerable FindServiceRecordsInSpan(long pCostBearer2SupportConceptOid, DateTimeSpan period) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, pCostBearer2SupportConceptOid)); - - if (period != null) - criteria = - criteria.Add( - Restrictions.Or( - Restrictions.Between(ServiceRecord.PropertyName_Start, period.StartDateTime, period.EndDateTime), - Restrictions.Between(ServiceRecord.PropertyName_End, period.StartDateTime, period.EndDateTime))); - - return criteria.List().ToList(); - } - - public IEnumerable FindServiceRecordHistory(long serviceRecordOid) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecordHistory.PropertyName_ServiceRecordOid, serviceRecordOid)); - - - return criteria.List().ToList(); - } - - public IEnumerable FindEmployeeServiceRecordsWithoutCustomer(long pEmployeeOid, long? days) - { - - var c = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - - if (days.HasValue) - { - var minDate = DateTime.Now.Date.AddDays(-1 * days.Value); - c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); - } - - return c.List().ToList(); - } - - public IEnumerable FindEmployeeServiceRecordsWithoutCustomerInSpan(long pEmployeeOid, DateTimeSpan period) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - - if (period != null) - { - criteria = - criteria.Add( - Restrictions.Or( - Restrictions.Between(ServiceRecord.PropertyName_Start, period.StartDateTime, period.EndDateTime), - Restrictions.Between(ServiceRecord.PropertyName_End, period.StartDateTime, period.EndDateTime))); - } - - return criteria.List().ToList(); - } - - public IEnumerable FindEmployeeServiceRecordsWithoutCustomerWithStartEndDate(long pEmployeeOid, DateTime start, DateTime ende) - { - - var c = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - - var max = ende.Date.AddDays(1); - - c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) - .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); - - - return c.List().ToList(); - } - - public IList FindEmployeeServiceRecords(long pEmployeeOid, DateTimeSpan pSpan, long? customerOid, ServiceRecordTypeId? srTypeFilter) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)); - - if (pSpan != null) - lCriteria.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)); - if (customerOid != null) - lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_CustomerOid, customerOid.Value)); - if (srTypeFilter.HasValue) - { - lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_ServiceRecordType, srTypeFilter.Value)); - } - - var result = lCriteria.List().ToList(); - - return result; - } - - public IList FindCustomerServiceRecords(long customerOid) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CustomerOid, customerOid)); - - return lCriteria.List(); - } - - public IList FindCustomerServiceRecords(long customerOid, DateTimeSpan pSpan, long? employeeOid, ServiceRecordTypeId? srTypeFilter, bool includeEndDateInSearch) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CustomerOid, customerOid)); - - - if (includeEndDateInSearch) - { - var orCriteria = Restrictions.Or( - Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime), - Restrictions.Between(ServiceRecord.PropertyName_End, pSpan.StartDateTime, pSpan.EndDateTime)); - - orCriteria = Restrictions.Or(orCriteria, - Restrictions.And( - Restrictions.Le(ServiceRecord.PropertyName_Start, pSpan.EndDateTime), - Restrictions.Ge(ServiceRecord.PropertyName_End, pSpan.StartDateTime))); - - - lCriteria.Add(orCriteria); - } - else - { - lCriteria.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)); - } - - - - if (employeeOid != null) - lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid.Value)); - if (srTypeFilter.HasValue) - { - lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_ServiceRecordType, srTypeFilter.Value)); - } - - return lCriteria.List(); - } - - public IEnumerable FindServiceRecordsInSpan(DateTimeSpan pSpan, ServiceRecordTypeId? srTypeFilter) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)); - if (srTypeFilter.HasValue) - { - lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_ServiceRecordType, srTypeFilter.Value)); - } - - return lCriteria.List().ToList(); - } - - public IEnumerable FindUnassignedAccountingTransactions() - { - return CreateCriteria() - .Add(Restrictions.IsNull(AccountingTransaction.PropertyName_CostBearer2SupportConcept)) - .List().ToList(); - } - - public IEnumerable FindSupportConcept( - string pCustomerFirstName, - string pCustomerLastName, - string pCustomerReferenceNumber, - DateTime? pFrom, - DateTime? pTill) - { - var lCriteria = CreateCriteria(); - - //if (pFrom != null) - // lCriteria.Add(Expression.Ge(SupportConcept.PropertyName_Start, pFrom)); - //if (pTill != null) - // lCriteria.Add(Expression.Le(SupportConcept.PropertyName_End, pTill)); - - lCriteria = lCriteria.CreateCriteria(SupportConcept.PropertyName_Customer, JoinType.InnerJoin); - - if (!IsNullOrEmpty(pCustomerReferenceNumber)) - lCriteria.Add(Restrictions.Eq(Customer.PropertyName_ReferenceNumber, pCustomerReferenceNumber)); - - if (!BS.Shared.Core.Utils.AreAllNullOrEmpty(pCustomerFirstName, pCustomerLastName)) - lCriteria.CreateCriteria(Customer.PropertyName_Person) - .Add(Restrictions.Like(Person.PropertyName_FirstName, pCustomerFirstName, MatchMode.Anywhere)) - .Add(Restrictions.Like(Person.PropertyName_LastName, pCustomerLastName, MatchMode.Anywhere)); - - return lCriteria.List(); - } - - public TwoFactorCode GetLastTwoFactorCode(string loginName, string bCryptPassword) - { - return CreateCriteriaIsActive() - .Add(Expression.Eq("LoginName", loginName)) - .Add(Expression.Eq("Password", bCryptPassword)) - .AddOrder(new Order("Oid", false)).List().FirstOrDefault(); - } - - public IEnumerable FindCurrentSupportConcepts() - { - return CreateCriteriaIsActive() - //.Add(Expression.Ge(SupportConcept.PropertyName_End, DateTime.Now)) - .List(); - } - - public IEnumerable FindSupportConceptsInSpan(DateTimeSpan pSpan) - { - return CreateCriteriaIsActive() - //.Add(Expression.Disjunction() - // .Add(Expression.Between(SupportConcept.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)) - // .Add(Expression.Between(SupportConcept.PropertyName_End, pSpan.StartDateTime, pSpan.EndDateTime)) - // .Add(Expression.Conjunction() - // .Add(Expression.Le(SupportConcept.PropertyName_Start, pSpan.StartDateTime)) - // .Add(Expression.Ge(SupportConcept.PropertyName_End, pSpan.EndDateTime)) - // ) - // ) - .List(); - } - - public IEnumerable FindExpiringSupportConcepts(long? employeeOid, DateTime minDate, DateTime expiredUntil) - { - var c = CreateCriteriaIsActive(); - if (employeeOid == null) - { - return c - .CreateCriteria(SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) - .Add(Restrictions.Between(CostBearer2SupportConcept.PropertyName_ApprovedEndDate, minDate, expiredUntil)) - .List(); - } - - return c - .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) - .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .CreateAlias("c.Employee2CustomerList", "e2c", JoinType.InnerJoin) - .Add(Restrictions.Eq("e2c." + Employee2Customer.PropertyName_EmployeeOid, employeeOid.Value)) - .Add(Restrictions.Or(Restrictions.Or( - Restrictions.Between("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate, minDate, expiredUntil), - Restrictions.Between("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate, minDate, expiredUntil)), - Restrictions.And(Restrictions.IsNotNull("c.TerminationDate"), Restrictions.Between("c.TerminationDate", minDate, expiredUntil)))) - .List().Distinct().ToList(); - } - - public IEnumerable FindSupportConceptsWithConferenceDate(long? employeeOid, DateTime conferenceDateUntil) - { - var c = CreateCriteriaIsActive(); - if (employeeOid == null) - { - return c - .Add(Restrictions.Between(SupportConcept.PropertyName_ConferenceDate, DateTime.Now, conferenceDateUntil)) - .List(); - } - - return c - .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .CreateAlias("c.Employee2CustomerList", "e2c", JoinType.InnerJoin) - .Add(Restrictions.Between(SupportConcept.PropertyName_ConferenceDate, DateTime.Now.Date, conferenceDateUntil)) - .Add(Restrictions.Eq("e2c." + Employee2Customer.PropertyName_EmployeeOid, employeeOid.Value)) - .List().Distinct().ToList(); - } - - public ApplicationUser FindUserForEmployee(Employee employee) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(ApplicationUser.PropertyName_Employee, employee)) - .List().FirstOrDefault(); - } - - public IEnumerable FindPersonsHavingBirthday(DateTime birthdayUntil) - { - var ts = birthdayUntil.Subtract(DateTime.Now); - var days = ts.Days + 1; - - return CreateCriteriaIsActive() - .Add(Expression.Sql(new SqlString("dayofyear(CAST(CONCAT(Year(CURDATE()), '-', Month(" + Person.PropertyName_DateOfBirth + "), '-', Day(" + Person.PropertyName_DateOfBirth + ")) AS DATE )) between dayofyear(CURDATE()) -4 and dayofyear(CURDATE()) + " + days))) - .List(); - } - - public IEnumerable FindLastLogins(string loginName, int maxResults) - { - return CreateCriteria() - .Add(Restrictions.Eq(Login.PropertyName_LoginName, loginName)) - .AddOrder(Order.Desc("Oid")) - .SetMaxResults(maxResults) - .List(); - } - - public IEnumerable FindQuery(QueryType pType) - { - return CreateCriteria().Add(Restrictions.Eq(Query.PropertyName_Type, pType)) - .List().ToList(); - } - - public IList FindAccoutingTransactions(DateTimeSpan pSpan) - { - var lCriteria = CreateCriteriaIsActive(); - - if (pSpan != null) - lCriteria.Add(Restrictions.Between(AccountingTransaction.PropertyName_BookingDate, pSpan.StartDateTime, pSpan.EndDateTime)); - - var test = lCriteria.List(); - - return test; - } - - public IEnumerable FindAccoutingTransactions(DateTimeSpan pSpan, long? pSupportConceptOid, long? pSupportConceptCostBearerRelOid) - { - var lCriteria = CreateCriteriaIsActive() - .CreateAlias(AccountingTransaction.PropertyName_CostBearer2SupportConcept, "cb2sc", JoinType.LeftOuterJoin); - - if (pSpan != null) - lCriteria.Add(Restrictions.Between(AccountingTransaction.PropertyName_BookingDate, pSpan.StartDateTime, pSpan.EndDateTime)); - - if (pSupportConceptCostBearerRelOid != null) - lCriteria.Add(Restrictions.Eq("cb2sc." + BeWoEntityBase.PropertyName_Oid, pSupportConceptCostBearerRelOid)); - - if (pSupportConceptOid != null) - { - lCriteria.CreateCriteria("cb2sc." + CostBearer2SupportConcept.PropertyName_SupportConcept) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pSupportConceptOid)); - } - - var test = lCriteria.List(); - - return test; - } - - public IList FindSettingsByValuePart(SettingsType pType, string pValuePart) - { - return CreateCriteria() - .Add(Restrictions.Eq(Settings.PropertyName_Type, pType)) - .Add(Restrictions.Like(Settings.PropertyName_Value, pValuePart, MatchMode.Anywhere)) - .List(); - } - - public IList FindFileAttachments(TableID pObjTid, long pObjOid) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(FileAttachment.PropertyName_ObjectOid, pObjOid)) - .Add(Restrictions.Eq(FileAttachment.PropertyName_ObjectTid, pObjTid)) - .List(); - } - - public IEnumerable FindFileAttachmentInfos(TableID pObjTid, long pObjOid) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(FileAttachmentInfo.PropertyName_ObjectOid, pObjOid)) - .Add(Restrictions.Eq(FileAttachmentInfo.PropertyName_ObjectTid, pObjTid)) - .List(); - } - - public IList FindBeWoFolders(TableID pObjTid, long pObjOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(BeWoFolder.PropertyName_ObjectTid, pObjTid)); - - if (pObjOid > 0) - { - c.Add(Restrictions.Eq(BeWoFolder.PropertyName_ObjectOid, pObjOid)); - } - - return c.List(); - } - - //public IList FindAllActiveApprovedLVRSupportConcepts() - //{ - // return CreateCriteriaIsActive() - // .CreateCriteria(SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) - // .Add(Expression.Eq(CostBearer2SupportConcept.PropertyName_Status, CostBearer2SupportConceptStatus.Approved)) - // .CreateCriteria(CostBearer2SupportConcept.PropertyName_CostBearer, JoinType.InnerJoin) - // .Add(Expression.Eq(CostBearer.PropertyName_SystemEntryID, SystemEntryID.CostBearerLVR)) - // .List(); - //} - - public IList FindAllActiveApprovedSupportConcepts() - { - return CreateCriteriaIsActive() - .CreateCriteria(SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) - .Add(Restrictions.Eq(CostBearer2SupportConcept.PropertyName_Status, CostBearer2SupportConceptStatus.Approved)) - - .List().Distinct().ToList(); - } - - public Employee FindEmployeeWithPersonOid(long pPersonOid) - { - var person = DAOFactory.GenericDAO.LoadByID(pPersonOid); - if (person != null) - { - return CreateCriteria() - .Add(Restrictions.Eq(Employee.PropertyName_Person, person)).UniqueResult(); - } - - return null; - } - - public Customer FindCustomerWithPersonOid(long pPersonOid) - { - var person = DAOFactory.GenericDAO.LoadByID(pPersonOid); - if (person != null) - { - return CreateCriteria() - .Add(Restrictions.Eq(Customer.PropertyName_Person, person)).UniqueResult(); - } - - return null; - } - - public IList FindCustomersWithPersonOids(IEnumerable pPersonOid) - { - - return CreateCriteriaIsActive() - .CreateAlias(Customer.PropertyName_Person, "p", JoinType.InnerJoin) - .Add(Restrictions.In("p." + BeWoEntityBase.PropertyName_Oid, pPersonOid.ToArray())) - .List(); - } - - public IList GetActivePersonsWithType(PersonType type) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(Person.PropertyName_Type, type)) - .List(); - } - - public IEnumerable GetAllActiveCustomersWithSupportConceptData() - { - return CreateCriteriaIsActiveOrArchived() - .CreateAlias(Customer.PropertyName_SupportConcepts, "sc", JoinType.LeftOuterJoin) - .CreateCriteria("sc." + SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.LeftOuterJoin) - .Add(Restrictions.Eq("sc." + SupportConcept.PropertyName_IsActive, ActivationTypeId.Active)) - .List(); - } - - public IEnumerable GetAllActiveCustomersWithAddress() - { - return CreateCriteriaIsActive() - .CreateCriteria(Customer.PropertyName_Person, JoinType.LeftOuterJoin) - .CreateCriteria(Person.PropertyName_Address, JoinType.LeftOuterJoin) - .List(); - } - - public IEnumerable GetAllCustomersWithRelatedEmployee() - { - return CreateCriteria() - .CreateAlias("Person", "cp", JoinType.InnerJoin) - .CreateAlias("cp." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) - .CreateAlias("Employee2CustomerList", "e2c", JoinType.LeftOuterJoin) - .CreateAlias("e2c." + Employee2Customer.PropertyName_Employee, "e", JoinType.LeftOuterJoin) - .CreateCriteria("e2c." + Employee2Customer.PropertyName_ValueList, JoinType.LeftOuterJoin) - .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.LeftOuterJoin) - .List(); - } - - public IList FindServiceRecordsDetailsForLastDays(long costbearer2SupportConcept, long? days) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); - - if (days.HasValue) - { - - var minDate = DateTime.Now.Date.AddDays(-1 * days.Value); - c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); - } - - return c.CreateAlias(ServiceRecord.PropertyName_ValueList, "vl", JoinType.LeftOuterJoin) - .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin) - .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.InnerJoin) - .List().Distinct().ToList(); - } - - public IList FindServiceRecordsDetailsForLastDaysWithStartEndDate(long costbearer2SupportConcept, DateTime start, DateTime ende) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); - - - var max = ende.Date.AddDays(1); - - c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) - .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); - - var result = c.CreateAlias(ServiceRecord.PropertyName_ValueList, "vl", JoinType.LeftOuterJoin) - .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin) - .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.InnerJoin) - .List(); - - return result; - } - - public IList FindServiceRecordsDetailWithServiceInfo(long costbearer2SupportConcept) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); - - - return c.CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .List(); - } - - public Customer FindCustomerWithServiceRecordsWithDetail(long pCustomerOid) - { - return CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pCustomerOid)) - .CreateAlias(Customer.PropertyName_ServiceRecordList, "sr", JoinType.InnerJoin) - .CreateCriteria("sr." + ServiceRecord.PropertyName_ValueList, JoinType.LeftOuterJoin) - .CreateAlias("sr." + ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateCriteria("sd." + ServiceDescription.PropertyName_ServiceCategory, JoinType.InnerJoin) - .CreateAlias("sr." + ServiceRecord.PropertyName_CostBearer2SupportConcept, "c2s", JoinType.InnerJoin) - .CreateCriteria("c2s." + CostBearer2SupportConcept.PropertyName_SupportConcept, JoinType.InnerJoin) - .CreateAlias("c2s." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb", JoinType.InnerJoin) - .CreateAlias("cb." + CostBearer.PropertyName_Organisation, "org", JoinType.InnerJoin) - .UniqueResult(); - } - - public ServiceRecordGroup FindServiceRecordGroup(long pGroupOid) - { - return CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pGroupOid)) - .CreateCriteria(ServiceRecordGroup.PropertyName_ServiceRecordList, JoinType.InnerJoin) - .UniqueResult(); - } - - public IEnumerable GetAllActiveAndArchivedSupportConceptsCompact() - { - return CreateCriteria() - .Add(Restrictions.Or(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Archived))) - .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.LeftOuterJoin) - .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .CreateAlias("c." + Customer.PropertyName_Person, "p", JoinType.InnerJoin) - .CreateAlias("p." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) - .CreateAlias("c." + Customer.PropertyName_Employee2CustomerList, "e2c", JoinType.LeftOuterJoin) - .List(); - } - - public IEnumerable GetAllSupportConceptsCompact() - { - return CreateCriteria() - .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.LeftOuterJoin) - .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .CreateAlias("c." + Customer.PropertyName_Person, "p", JoinType.InnerJoin) - .CreateAlias("p." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) - .CreateAlias("c." + Customer.PropertyName_Employee2CustomerList, "e2c", JoinType.LeftOuterJoin) - .List(); - } - - public IList GetAllActiveAndArchivedListedSupportConceptsCompact() - { - return Session.CreateCriteria() - .List(); - } - - public IList GetAllActiveAndArchivedListedSupportConceptsCompact(List oids) - { - return Session.CreateCriteria() - .Add(Restrictions.In("SupportConceptOid", oids)) - .List(); - } - - public IList GetAllCustomerWithServiceRecordsInSpan(DateTimeSpan pSpan) - { - return CreateCriteria() - .CreateCriteria(Customer.PropertyName_ServiceRecordList, JoinType.InnerJoin) - .Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)) - .List(); - } - - public IEnumerable GetAllAccountingTransactionsWithDetails() - { - return CreateCriteria() - .AddOrder(Order.Desc(AccountingTransaction.PropertyName_BookingDate)) - .CreateAlias(AccountingTransaction.PropertyName_CostBearer2SupportConcept, "cb2sc", JoinType.LeftOuterJoin) - .CreateCriteria("cb2sc." + CostBearer2SupportConcept.PropertyName_CostBearer, JoinType.LeftOuterJoin) - .CreateCriteria(CostBearer.PropertyName_Organisation, JoinType.LeftOuterJoin) - .CreateCriteria("cb2sc." + CostBearer2SupportConcept.PropertyName_SupportConcept, JoinType.LeftOuterJoin) - .CreateCriteria(SupportConcept.PropertyName_Customer, JoinType.LeftOuterJoin) - .CreateCriteria(Customer.PropertyName_Person, JoinType.LeftOuterJoin) - .List(); - } - - public IEnumerable FindAccountingTransactionsWithImportNotice(String notice) - { - return CreateCriteria() - .Add(Restrictions.Eq(AccountingTransaction.PropertyName_ImportNotice, notice)).List(); - } - - public IEnumerable GetAllActiveAndArchivedSupportConcepts() - { - return CreateCriteria() - .Add(Restrictions.Or(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Archived))) - .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) - .CreateAlias("cb2sc." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb", JoinType.InnerJoin) - .CreateAlias("cb." + CostBearer.PropertyName_Organisation, "org", JoinType.InnerJoin) - .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .CreateAlias("c." + Customer.PropertyName_Person, "p", JoinType.InnerJoin) - .List(); - } - - public IEnumerable GetAllActiveAndArchivedCustomersWithRelatedEmployee() - { - return CreateCriteria() - .Add(Restrictions.Or(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Archived))) - .CreateAlias(Customer.PropertyName_Person, "cp", JoinType.InnerJoin) - .CreateAlias("cp." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) - .CreateAlias(Customer.PropertyName_Employee2CustomerList, "e2c", JoinType.LeftOuterJoin) - .CreateAlias("e2c." + Employee2Customer.PropertyName_Employee, "e", JoinType.LeftOuterJoin) - .CreateCriteria("e2c." + Employee2Customer.PropertyName_ValueList, JoinType.LeftOuterJoin) - .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.LeftOuterJoin) - .List(); - } - - public IEnumerable GetSettlementInvoiceBySupportConceptOid(long supportConceptOid) - { - return CreateCriteriaIsActive() - .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_SupportConceptOid, supportConceptOid)) - .List(); - } - - public IList GetSettlementInvoiceByCostBearer2SupportConceptOid(long costBearer2SupportConceptOid) - { - return CreateCriteriaIsActive() - .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)) - .List(); - } - - public IEnumerable GetSettlementInvoicesForCostBearerAndPeriod(long costBearerOid, DateTime periodStart, DateTime periodEnd) - { - return CreateCriteriaIsActive() - .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .CreateAlias("ib." + InvoiceBase.PropertyName_CostBearer2SupportConcept, "cb2sc", JoinType.InnerJoin) - .CreateAlias("cb2sc." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb", JoinType.InnerJoin) - .Add(Restrictions.Eq("cb." + BeWoEntityBase.PropertyName_Oid, costBearerOid)) - .Add(Restrictions.Or( - Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, periodStart, periodEnd), - Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, periodStart, periodEnd))) - .List(); - } - - public IList GetInvoiceBaseByTypeAndSupportConceptOid(InvoiceType type, long supportConceptOid) - { - return SearchInvoiceBase(type, InvoiceBase.PropertyName_SupportConceptOid, supportConceptOid); - } - - public IEnumerable GetInvoiceBaseByOrganisationOid(InvoiceType type, long organisationOid) - { - return SearchInvoiceBase(type, InvoiceBase.PropertyName_RecipientOrganisationOid, organisationOid); - } - - public IEnumerable GetInvoiceBaseByCustomerOid(InvoiceType type, long customerOid) - { - return SearchInvoiceBase(type, InvoiceBase.PropertyName_RecipientCustomerOid, customerOid); - } - - public IEnumerable GetInvoiceBaseByPersonOid(InvoiceType type, long personOid) - { - return SearchInvoiceBase(type, InvoiceBase.PropertyName_RecipientPersonOid, personOid); - } - - private IList SearchInvoiceBase(InvoiceType type, string propertyname, long fkOid) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(InvoiceBase.PropertyName_Type, type)) - .Add(Restrictions.Eq(propertyname, fkOid)) - .List(); - } - - public SettlementInvoice GetSettlementInvoiceByInvoiceBaseOid(long invoiceBaseOid) - { - return CreateCriteria() - .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_Oid, invoiceBaseOid)) - .UniqueResult(); - } - - public ServiceInvoice GetServiceInvoiceByInvoiceBaseOid(long invoiceBaseOid) - { - var res = CreateCriteriaIsActive() - .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_Oid, invoiceBaseOid)) - .UniqueResult(); - - return res; - } - - public IEnumerable GetAssessmentSheetEntriesForCustomer(long customerOid, DateTime startDt, DateTime endDt) - { - - - return CreateCriteriaIsActive() - .CreateAlias(AssessmentSheetEntry.PropertyName_Customer, "c", JoinType.InnerJoin) - .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_Oid, customerOid)) - .Add(Restrictions.Ge(AssessmentSheetEntry.PropertyName_Day, startDt)) - .Add(Restrictions.Lt(AssessmentSheetEntry.PropertyName_Day, endDt)) - .List(); - } - - public IList GetVarFieldDefs(TableID tid) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(VarFieldDef.PropertyName_ObjectTid, tid)) - .List(); - } - - public IEnumerable FindTasksForEmployee(long employeeoid) - { - return CreateCriteriaIsActive() - .CreateAlias(Task.PropertyName_SupportConcept, "sc", JoinType.InnerJoin) - .CreateAlias("sc." + SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .CreateCriteria(Task.PropertyName_EmployeeList, JoinType.InnerJoin) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeoid)) - .Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .List(); - } - - public List GetServiceInvoices(long costBearerOid, long? supportConceptOid, DateTimeSpan period) - { - var criteria = CreateCriteriaIsActive() - .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_RecipientCostBearerOid, costBearerOid)) - .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); - - if (supportConceptOid.HasValue) - criteria = criteria - .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_SupportConceptOid, supportConceptOid.Value)); - - if (period != null) - criteria = criteria - .Add(Restrictions.Or( - Restrictions.Or( - Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime, period.EndDateTime), - Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.StartDateTime, period.EndDateTime)), - Restrictions.And( - Restrictions.Le("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime), - Restrictions.Ge("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.EndDateTime)))); - - return criteria.List().ToList(); - } - - public List GetServiceInvoices(long? costbearer2SupportConceptOid, DateTimeSpan period) - { - var criteria = CreateCriteriaIsActive() - .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); - - if (costbearer2SupportConceptOid.HasValue) - criteria = criteria - .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConceptOid.Value)); - - - - if (period != null) - criteria = criteria - .Add(Restrictions.Or( - Restrictions.Or( - Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime, period.EndDateTime), - Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.StartDateTime, period.EndDateTime)), - Restrictions.And( - Restrictions.Le("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime), - Restrictions.Ge("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.EndDateTime)))); - - return criteria.List().ToList(); - } - - public IEnumerable GetAssessmentSheetCategoryListForCustomer(long customerOid) - { - - return CreateCriteriaIsActive() - .CreateAlias(AssessmentSheetCategory.PropertyName_Customers, "c", JoinType.InnerJoin) - .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_Oid, customerOid)) - .List(); - - } - - public IEnumerable FindAbsenceTimes(bool fetchEmployees, bool fetchCustomers) - { - var criteria = CreateCriteriaIsActive(); - - if (!fetchEmployees) - criteria = criteria - .Add(Restrictions.IsNull(AbsenceTime.PropertyName_EmployeeOid)); - else if (!fetchCustomers) - criteria = criteria - .Add(Restrictions.IsNull(AbsenceTime.PropertyName_CustomerOid)); - - return criteria.List().ToList(); - - - } - - public List FindAbsenceTimes(DateTime startDate, DateTime endDate) - { - var criteria = CreateCriteriaIsActive() - .Add( - Restrictions.Or( - Restrictions.And( - Restrictions.Ge(AbsenceTime.PropertyName_End, startDate), - Restrictions.Lt(AbsenceTime.PropertyName_Start, endDate.Date.AddDays(1)) - ), - Restrictions.And( - Restrictions.Lt(AbsenceTime.PropertyName_Start, endDate.Date.AddDays(1)), - Restrictions.IsNull(AbsenceTime.PropertyName_End) - ) - ) - ); - - return criteria.List().ToList(); - } - - public IEnumerable FindAbsenceTimesForEmployee - (DateTime startDate, DateTime endDate, long empOid) - { - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.Eq("EmployeeOid", empOid)) - .Add(Restrictions.Gt(AbsenceTime.PropertyName_Start, startDate)) - .Add(Restrictions.Lt(AbsenceTime.PropertyName_End, endDate)); - - return criteria.List().ToList(); - } - - public IEnumerable FindAbsenceTimesForMonth(DateTime startDate, DateTime endDate) - { - var criteria = CreateCriteriaIsActive(); - criteria.Add(Restrictions.Gt("Start", startDate)); - criteria.Add(Restrictions.Lt("End", endDate)); - - return criteria.List().ToList(); - } - - public IEnumerable FindVertretungen(DateTime startDate, DateTime endDate) - { - var criteria = CreateCriteriaIsActive() - .Add( - Restrictions.Or( - Restrictions.And( - Restrictions.Ge(Vertretung.PropertyName_VertretungsZeitraumBis, startDate), - Restrictions.Le(Vertretung.PropertyName_VertretungsZeitraumVon, endDate) - ), - Restrictions.And( - Restrictions.Le(Vertretung.PropertyName_VertretungsZeitraumVon, endDate), - Restrictions.IsNull(Vertretung.PropertyName_VertretungsZeitraumBis) - ) - ) - ); - - return criteria.List().ToList(); - - - } - - public IEnumerable FindLastVertretungen(long customerOid) - { - var c = CreateCriteriaIsActive(); - c.Add(Restrictions.Eq("CustomerOid", customerOid)); - - return c.List().ToList(); - - - } - - public IEnumerable FindAppointments(long? customerOid, long? employeeOid) - { - var criteria = CreateCriteriaIsActive(); - - if (employeeOid.HasValue) - { - criteria = criteria.Add(Restrictions.Eq(AbsenceTime.PropertyName_EmployeeOid, employeeOid)); - } - - if (customerOid.HasValue) - { - criteria = criteria.Add(Restrictions.Eq(AbsenceTime.PropertyName_CustomerOid, customerOid)); - } - - return criteria.List().ToList(); - } - - public ServiceCategory FindDefaultIndividualServiceCategory() - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(ServiceCategory.PropertyName_ScopeType, ScopeTypeId.Individual)) - .List().FirstOrDefault(); - } - - public ServiceCategory FindServiceCategoryByName(String name) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(ServiceCategory.PropertyName_Name, name)) - .List().FirstOrDefault(); - } - - public IEnumerable FindFileAttachmentInfoByType(FileAttachmentType type) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq("Type", type)); - - return criteria.List().ToList(); - } - - public IEnumerable GetAdditionalAssessmentSheetEntries(DateTime dateTime) - { - return CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_SystemEntryID, SystemEntryID.AdditionalServiceAssessmentSheet)) - .Add(Restrictions.Eq(AssessmentSheetEntry.PropertyName_Day, dateTime.Date)) - .List(); - } - - public IEnumerable GetResourceAppointmentExceptionsWithIndexAndId(string info) - { - return CreateCriteria() - .Add(Restrictions.Like(ResourceAppointment.PropertyName_RecurrenceInfo, info)) - .List(); - - } - - public IEnumerable GetAdditionalServiceBookings(long? regionOid, DateTime start, DateTime end) - { - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.Between("Datum", start, end)); - - if (regionOid.HasValue) - criteria = criteria.CreateAlias(AdditionalServiceBooking.PropertyName_AdditionalServiceRegion, "asr", JoinType.InnerJoin) - .Add(Restrictions.Eq("asr." + BeWoEntityBase.PropertyName_Oid, regionOid)); - - return criteria.List(); - } - - public IEnumerable GetAdditionalServiceNoticeList(long? regionOid, DateTime start, DateTime end) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Between("Monat", start, end)); - - if (regionOid.HasValue) - { - c.Add(Restrictions.Eq("RegionOid", regionOid)); - } - - return c.List(); - } - - public IEnumerable GetAdditionalServiceBookingsForCustomer(long customerOid, DateTime start, DateTime end) - { - return CreateCriteriaIsActive() - .CreateAlias(AdditionalServiceBooking.PropertyName_Customer2AddServiceBookings, "c2s", JoinType.InnerJoin) - .Add(Restrictions.Between("Datum", start, end)) - .Add(Restrictions.Eq("c2s.CustomerOid", customerOid)) - .List(); - } - - public AssessmentSheetCategory GetAddServiceAssessmentSheetCategoryWithName(string name) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Eq(AssessmentSheetCategory.PropertyName_Description, name)) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_SystemEntryID, SystemEntryID.AdditionalServiceAssessmentSheet)) - .List().FirstOrDefault(); - } - - public IList GetBillableServiceRecords() - { - var c = CreateCriteria() - .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .Add(Restrictions.Eq("sc." + ServiceCategory.PropertyName_IsBillable, true)); - - return c.List(); - } - - public IList GetBillableServiceRecords(DateTime start, DateTime end) - { - var c = CreateCriteria() - .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .Add(Restrictions.Eq("sc." + ServiceCategory.PropertyName_IsBillable, true)) - .Add(Restrictions.Between(ServiceRecord.PropertyName_Start, start, end)); - - - return c.List(); - } - - public IList GetBillableServiceRecordsSqlArray(DateTime start, DateTime end) - { - var q = Session.CreateSQLQuery(String.Format(@" + public class SearchDAO : AbstractBaseDAO + { + private static readonly Regex RecurrenceIdRegex = new Regex("(Id=\\\"[a-z0-9-]+\\\")"); + + public IEnumerable FindValueListEntry(ValueListEntryType pType) + { + return CreateCriteria().Add(Restrictions.Eq(ValueListEntry.PropertyName_Type, pType)).AddOrder(Order.Asc(ValueListEntry.PropertyName_Value)).List(); + } + + public IEnumerable FindValueListEntries(List pTypes) + { + return CreateCriteria().Add(Restrictions.In(ValueListEntry.PropertyName_Type, pTypes)).AddOrder(Order.Asc(ValueListEntry.PropertyName_Value)).List(); + } + + public virtual IEnumerable FindEmployee(string pFirstName, string pLastName, string pPersonnelNumber) + { + return CreateCriteria() + .Add(Restrictions.Like(Employee.PropertyName_PersonnelNumber, pPersonnelNumber, MatchMode.Anywhere)) + .CreateCriteria(Employee.PropertyName_Person, JoinType.InnerJoin) + .Add(Restrictions.Like(Person.PropertyName_FirstName, pFirstName, MatchMode.Anywhere)) + .Add(Restrictions.Like(Person.PropertyName_LastName, pLastName, MatchMode.Anywhere)) + .List(); + } + + public virtual Employee FindEmployeeByFullname(string pFullname) + { + var q = Session.CreateSQLQuery(Format("SELECT e.oid FROM employee e join Person p on e.personoid = p.oid WHERE CONCAT_WS(' ', FirstName, LastName) LIKE '%{0}%' AND Type = 1", pFullname)); + var x = q.List(); + + return x.Count > 0 ? DAOFactory.GenericDAO.GetByID(x.Last()) : null; + } + + public virtual IEnumerable FindWohnheim(string pwohnheimName, string pWohnheimStrasse, string pWohnheimPlz) + { + return CreateCriteria() + .Add(Restrictions.Like(Wohnheim.PropertyName_WohnheimName, pwohnheimName, MatchMode.Anywhere)) + .CreateCriteria(Wohnheim.PropertyName_Wohnheim, JoinType.InnerJoin) + .Add(Restrictions.Like(Wohnheim.PropertyName_Strasse, pWohnheimStrasse, MatchMode.Anywhere)) + .Add(Restrictions.Like(Wohnheim.PropertyName_PlZ, pWohnheimPlz, MatchMode.Anywhere)) + .List(); + } + + public virtual Wohnheim FindWohnheimByFullname(string pWohnheimName) + { + var q = Session.CreateSQLQuery(Format("SELECT Oid FROM Wohnheim WHERE CONCAT_WS(' ', WohnheimName) LIKE '%{0}%'", pWohnheimName)); + var x = q.List(); + + return x.Count > 0 ? DAOFactory.GenericDAO.GetByID(x.First()) : null; + } + + public virtual IEnumerable FindCustomer(string pFirstName, string pLastName, string pReferenceNumber) + { + return CreateCriteria() + .Add(Restrictions.Like(Customer.PropertyName_ReferenceNumber, pReferenceNumber, MatchMode.Anywhere)) + .CreateCriteria(Customer.PropertyName_Person, JoinType.InnerJoin) + .Add(Restrictions.Like(Person.PropertyName_FirstName, pFirstName, MatchMode.Anywhere)) + .Add(Restrictions.Like(Person.PropertyName_LastName, pLastName, MatchMode.Anywhere)) + .List(); + } + + public virtual IList FindCustomer(string pFirstName, string pLastName, DateTime pBirthDate) + { + return CreateCriteriaIsActiveOrArchived() + .CreateCriteria(Customer.PropertyName_Person, JoinType.InnerJoin) + .Add(Restrictions.Eq(Person.PropertyName_FirstName, pFirstName)) + .Add(Restrictions.Eq(Person.PropertyName_LastName, pLastName)) + .Add(Restrictions.Eq(Person.PropertyName_DateOfBirth, pBirthDate)) + .List(); + } + + public virtual IList GetAllDienstEintraege(long wOid, DateTime start, DateTime end) + { + var c = CreateCriteria() + .Add(Restrictions.Eq("WohnheimOid", wOid)) + .Add(Restrictions.Between("Datum", start, end)) + .Add(Restrictions.Eq("IsActive", ActivationTypeId.Active)); + + return c.List(); + } + public virtual IList GetEmployeeForWohnheim(long wOid) + { + var c = CreateCriteria() + .Add(Restrictions.Eq("WohnheimOid", wOid)); + + return c.List(); + } + + public virtual IEnumerable FindPerson(string pFirstName, string pLastName, DateTime? pDateOfBirth, PersonType? pPersonType) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Like(Person.PropertyName_FirstName, pFirstName, MatchMode.Anywhere)) + .Add(Restrictions.Like(Person.PropertyName_LastName, pLastName, MatchMode.Anywhere)); + if (pDateOfBirth != null) + lCriteria.Add(Restrictions.Eq(Person.PropertyName_DateOfBirth, pDateOfBirth)); + if (pPersonType != null) + lCriteria.Add(Restrictions.Eq(Person.PropertyName_Type, pPersonType)); + + return lCriteria.List(); + } + + public virtual IEnumerable FindOrganisation(string pName, bool pOnlyCostBearer) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Like(Organisation.PropertyName_Name, pName, MatchMode.Anywhere)); + + if (pOnlyCostBearer) + lCriteria.Add(Restrictions.IsNotNull(Organisation.PropertyName_CostBearer)); + + return lCriteria.List(); + } + + public virtual IEnumerable FindTeams(string pTeamName, string pLeaderFirstName, string pLeaderLastName) + { + return CreateCriteria() + .Add(Restrictions.Like(Team.PropertyName_Name, pTeamName, MatchMode.Anywhere)) + .CreateCriteria(Team.PropertyName_Leader, JoinType.InnerJoin) + .CreateCriteria(Employee.PropertyName_Person) + .Add(Restrictions.Like(Person.PropertyName_FirstName, pLeaderFirstName, MatchMode.Anywhere)) + .Add(Restrictions.Like(Person.PropertyName_LastName, pLeaderLastName, MatchMode.Anywhere)) + .List(); + } + + public virtual IList FindTeamsOfEmployee(long employeeOid) + { + return CreateCriteriaIsActiveOrArchived() + .CreateCriteria(Team.PropertyName_MemberList, JoinType.InnerJoin) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeOid)) + .List(); + } + + public virtual IEnumerable FindLeadingTeams(long employeeOid) + { + return CreateCriteriaIsActiveOrArchived() + .CreateCriteria(Team.PropertyName_Leader, JoinType.InnerJoin) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeOid)) + .List(); + } + + public virtual IList FindAllActiveTeamsOfEmployee(long employeeOid) + { + return CreateCriteriaIsActive() + .CreateAlias(Team.PropertyName_MemberList, "m", JoinType.InnerJoin) + .CreateAlias(Team.PropertyName_Leader, "l", JoinType.InnerJoin) + .Add(Restrictions.Disjunction() + .Add(Restrictions.Eq("m." + BeWoEntityBase.PropertyName_Oid, employeeOid)) + .Add(Restrictions.Eq("l." + BeWoEntityBase.PropertyName_Oid, employeeOid))) + .List().Distinct().ToList(); + + } + + public virtual IList FindCustomerOfTeam(long teamOid) + { + return CreateCriteriaIsActiveOrArchived() + .CreateCriteria(Customer.PropertyName_Team2CustomerList, JoinType.InnerJoin) + .Add(Restrictions.Eq(Team2Customer.PropertyName_TeamOid, teamOid)) + .List(); + } + + public IEnumerable FindBookings(long pResourceOid, DateTime pSpanStart, DateTime pSpanEnd) + { + var lResult = CreateCriteria() + .CreateAlias(ResourceBookingSequence.PropertyName_Resource, "r") + .CreateAlias(ResourceBookingSequence.PropertyName_Details, "d") + .Add(Restrictions.Eq("r." + BeWoEntityBase.PropertyName_Oid, pResourceOid)) + .Add(Restrictions.Eq("d." + ResourceBooking.PropertyName_SequencePosition, 0)) + .Add(Restrictions.Disjunction() + .Add(Restrictions.Between("d." + ResourceBooking.PropertyName_Start, pSpanStart, pSpanEnd)) + .Add(Restrictions.Between(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanStart, pSpanEnd)) + .Add(Restrictions.Conjunction() + .Add(Restrictions.Le("d." + ResourceBooking.PropertyName_Start, pSpanStart)) + .Add(Restrictions.Ge(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanEnd)) + ) + ) + .List(); + + return lResult; + } + + public IEnumerable FindBookings(DateTime pSpanStart, DateTime pSpanEnd) + { + var lResult = CreateCriteria() + .CreateAlias(ResourceBookingSequence.PropertyName_Details, "d") + .Add(Restrictions.Eq("d." + ResourceBooking.PropertyName_SequencePosition, 0)) + .Add(Restrictions.Disjunction() + .Add(Restrictions.Between("d." + ResourceBooking.PropertyName_Start, pSpanStart, pSpanEnd)) + .Add(Restrictions.Between(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanStart, pSpanEnd)) + .Add(Restrictions.Conjunction() + .Add(Restrictions.Le("d." + ResourceBooking.PropertyName_Start, pSpanStart)) + .Add(Restrictions.Ge(ResourceBookingSequence.PropertyName_SequenceEnd, pSpanEnd)) + ) + ) + .List(); + + return lResult; + } + + public void RemoveServiceRecordsFromAppointments(IEnumerable enumerable) + { + throw new NotImplementedException(); + } + + public List FindServiceRecords(long? pEmployeeOid, long? pCostBearer2SupportConceptOid) + { + var c = CreateCriteria() + .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin); + + if (pCostBearer2SupportConceptOid.HasValue) + { + c = c.CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin) + .CreateAlias("sc." + SupportConcept.PropertyName_CostBearer2SupportConceptList, "c2s", JoinType.InnerJoin); + } + + if (pEmployeeOid.HasValue) + c = c.Add(Restrictions.Eq("e." + BeWoEntityBase.PropertyName_Oid, pEmployeeOid)); + if (pCostBearer2SupportConceptOid.HasValue) + c = c.Add(Restrictions.Eq("c2s." + BeWoEntityBase.PropertyName_Oid, pCostBearer2SupportConceptOid)); + + return c.List().ToList(); + } + + public List FindServiceRecordsForSupportConcept(long pSupportConceptOid) + { + var c = CreateCriteria() + .CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin); + + c = c.Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_Oid, pSupportConceptOid)); + return c.List().ToList(); + } + + public List FindServiceRecords(long? supportConceptOid, long? costBearer2SupportConceptOid, long? serviceCategoryOid, DateTime? start, DateTime? end) + { + var c = CreateCriteria() + .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin); + + if (supportConceptOid.HasValue) + { + c = c.CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin); + } + + if (serviceCategoryOid.HasValue) + { + c = c.CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "cat", JoinType.InnerJoin); + } + + if (supportConceptOid.HasValue) + { + c = c.Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_Oid, supportConceptOid)); + } + + if (costBearer2SupportConceptOid.HasValue) + { + c = c.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); + } + + if (serviceCategoryOid.HasValue) + { + c = c.Add(Restrictions.Eq("cat." + BeWoEntityBase.PropertyName_Oid, serviceCategoryOid)); + } + + if (start.HasValue && end.HasValue) + { + c.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, start, end)); + } + //{ + // c = c.CreateAlias(ServiceRecord.PropertyName_SupportConcept, "sc", JoinType.InnerJoin) + // .CreateAlias("sc." + SupportConcept.PropertyName_CostBearer2SupportConceptList, "c2s", JoinType.InnerJoin); + //} + + //if (pEmployeeOid.HasValue) + // c = c.Add(Restrictions.Eq("e." + BeWoEntityBase.PropertyName_Oid, pEmployeeOid)); + + + return c.List().ToList(); + } + + public IList FindSupportConceptApprovalPeriod2Employees(Employee emp) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(SupportConceptApprovalPeriod2Employee.PropertyName_Employee, emp)); + return c.List().ToList(); + } + + public IList FindSupportConceptApprovalPeriod2Employees(SupportConceptApprovalPeriod scap) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(SupportConceptApprovalPeriod2Employee.PropertyName_SupportConceptApprovalPeriod, scap)); + return c.List().ToList(); + } + + public IEnumerable FindServiceRecordsInSpan(long pCostBearer2SupportConceptOid, DateTimeSpan period) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, pCostBearer2SupportConceptOid)); + + if (period != null) + criteria = + criteria.Add( + Restrictions.Or( + Restrictions.Between(ServiceRecord.PropertyName_Start, period.StartDateTime, period.EndDateTime), + Restrictions.Between(ServiceRecord.PropertyName_End, period.StartDateTime, period.EndDateTime))); + + return criteria.List().ToList(); + } + + public IEnumerable FindServiceRecordHistory(long serviceRecordOid) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecordHistory.PropertyName_ServiceRecordOid, serviceRecordOid)); + + + return criteria.List().ToList(); + } + + public IEnumerable FindEmployeeServiceRecordsWithoutCustomer(long pEmployeeOid, long? days) + { + + var c = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + + if (days.HasValue) + { + var minDate = DateTime.Now.Date.AddDays(-1 * days.Value); + c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); + } + + return c.List().ToList(); + } + + public IEnumerable FindEmployeeServiceRecordsWithoutCustomerInSpan(long pEmployeeOid, DateTimeSpan period) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + + if (period != null) + { + criteria = + criteria.Add( + Restrictions.Or( + Restrictions.Between(ServiceRecord.PropertyName_Start, period.StartDateTime, period.EndDateTime), + Restrictions.Between(ServiceRecord.PropertyName_End, period.StartDateTime, period.EndDateTime))); + } + + return criteria.List().ToList(); + } + + public IEnumerable FindEmployeeServiceRecordsWithoutCustomerWithStartEndDate(long pEmployeeOid, DateTime start, DateTime ende) + { + + var c = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + + var max = ende.Date.AddDays(1); + + c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) + .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); + + + return c.List().ToList(); + } + + public IList FindEmployeeServiceRecords(long pEmployeeOid, DateTimeSpan pSpan, long? customerOid, ServiceRecordTypeId? srTypeFilter) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)); + + if (pSpan != null) + lCriteria.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)); + if (customerOid != null) + lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_CustomerOid, customerOid.Value)); + if (srTypeFilter.HasValue) + { + lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_ServiceRecordType, srTypeFilter.Value)); + } + + var result = lCriteria.List().ToList(); + + return result; + } + + public IList FindCustomerServiceRecords(long customerOid) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CustomerOid, customerOid)); + + return lCriteria.List(); + } + + public IList FindCustomerServiceRecords(long customerOid, DateTimeSpan pSpan, long? employeeOid, ServiceRecordTypeId? srTypeFilter, bool includeEndDateInSearch) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CustomerOid, customerOid)); + + + if (includeEndDateInSearch) + { + var orCriteria = Restrictions.Or( + Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime), + Restrictions.Between(ServiceRecord.PropertyName_End, pSpan.StartDateTime, pSpan.EndDateTime)); + + orCriteria = Restrictions.Or(orCriteria, + Restrictions.And( + Restrictions.Le(ServiceRecord.PropertyName_Start, pSpan.EndDateTime), + Restrictions.Ge(ServiceRecord.PropertyName_End, pSpan.StartDateTime))); + + + lCriteria.Add(orCriteria); + } + else + { + lCriteria.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)); + } + + + + if (employeeOid != null) + lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid.Value)); + if (srTypeFilter.HasValue) + { + lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_ServiceRecordType, srTypeFilter.Value)); + } + + return lCriteria.List(); + } + + public IEnumerable FindServiceRecordsInSpan(DateTimeSpan pSpan, ServiceRecordTypeId? srTypeFilter) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)); + if (srTypeFilter.HasValue) + { + lCriteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_ServiceRecordType, srTypeFilter.Value)); + } + + return lCriteria.List().ToList(); + } + + public IEnumerable FindUnassignedAccountingTransactions() + { + return CreateCriteria() + .Add(Restrictions.IsNull(AccountingTransaction.PropertyName_CostBearer2SupportConcept)) + .List().ToList(); + } + + public IEnumerable FindSupportConcept( + string pCustomerFirstName, + string pCustomerLastName, + string pCustomerReferenceNumber, + DateTime? pFrom, + DateTime? pTill) + { + var lCriteria = CreateCriteria(); + + //if (pFrom != null) + // lCriteria.Add(Expression.Ge(SupportConcept.PropertyName_Start, pFrom)); + //if (pTill != null) + // lCriteria.Add(Expression.Le(SupportConcept.PropertyName_End, pTill)); + + lCriteria = lCriteria.CreateCriteria(SupportConcept.PropertyName_Customer, JoinType.InnerJoin); + + if (!IsNullOrEmpty(pCustomerReferenceNumber)) + lCriteria.Add(Restrictions.Eq(Customer.PropertyName_ReferenceNumber, pCustomerReferenceNumber)); + + if (!BS.Shared.Core.Utils.AreAllNullOrEmpty(pCustomerFirstName, pCustomerLastName)) + lCriteria.CreateCriteria(Customer.PropertyName_Person) + .Add(Restrictions.Like(Person.PropertyName_FirstName, pCustomerFirstName, MatchMode.Anywhere)) + .Add(Restrictions.Like(Person.PropertyName_LastName, pCustomerLastName, MatchMode.Anywhere)); + + return lCriteria.List(); + } + + public TwoFactorCode GetLastTwoFactorCode(string loginName, string bCryptPassword) + { + return CreateCriteriaIsActive() + .Add(Expression.Eq("LoginName", loginName)) + .Add(Expression.Eq("Password", bCryptPassword)) + .AddOrder(new Order("Oid", false)).List().FirstOrDefault(); + } + + public IEnumerable FindCurrentSupportConcepts() + { + return CreateCriteriaIsActive() + //.Add(Expression.Ge(SupportConcept.PropertyName_End, DateTime.Now)) + .List(); + } + + public IEnumerable FindSupportConceptsInSpan(DateTimeSpan pSpan) + { + return CreateCriteriaIsActive() + //.Add(Expression.Disjunction() + // .Add(Expression.Between(SupportConcept.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)) + // .Add(Expression.Between(SupportConcept.PropertyName_End, pSpan.StartDateTime, pSpan.EndDateTime)) + // .Add(Expression.Conjunction() + // .Add(Expression.Le(SupportConcept.PropertyName_Start, pSpan.StartDateTime)) + // .Add(Expression.Ge(SupportConcept.PropertyName_End, pSpan.EndDateTime)) + // ) + // ) + .List(); + } + + public IEnumerable FindExpiringSupportConcepts(long? employeeOid, DateTime minDate, DateTime expiredUntil) + { + var c = CreateCriteriaIsActive(); + if (employeeOid == null) + { + return c + .CreateCriteria(SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) + .Add(Restrictions.Between(CostBearer2SupportConcept.PropertyName_ApprovedEndDate, minDate, expiredUntil)) + .List(); + } + + return c + .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) + .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .CreateAlias("c.Employee2CustomerList", "e2c", JoinType.InnerJoin) + .Add(Restrictions.Eq("e2c." + Employee2Customer.PropertyName_EmployeeOid, employeeOid.Value)) + .Add(Restrictions.Or(Restrictions.Or( + Restrictions.Between("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate, minDate, expiredUntil), + Restrictions.Between("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate, minDate, expiredUntil)), + Restrictions.And(Restrictions.IsNotNull("c.TerminationDate"), Restrictions.Between("c.TerminationDate", minDate, expiredUntil)))) + .List().Distinct().ToList(); + } + + public IEnumerable FindSupportConceptsWithConferenceDate(long? employeeOid, DateTime conferenceDateUntil) + { + var c = CreateCriteriaIsActive(); + if (employeeOid == null) + { + return c + .Add(Restrictions.Between(SupportConcept.PropertyName_ConferenceDate, DateTime.Now, conferenceDateUntil)) + .List(); + } + + return c + .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .CreateAlias("c.Employee2CustomerList", "e2c", JoinType.InnerJoin) + .Add(Restrictions.Between(SupportConcept.PropertyName_ConferenceDate, DateTime.Now.Date, conferenceDateUntil)) + .Add(Restrictions.Eq("e2c." + Employee2Customer.PropertyName_EmployeeOid, employeeOid.Value)) + .List().Distinct().ToList(); + } + + public ApplicationUser FindUserForEmployee(Employee employee) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(ApplicationUser.PropertyName_Employee, employee)) + .List().FirstOrDefault(); + } + + public IEnumerable FindPersonsHavingBirthday(DateTime birthdayUntil) + { + var ts = birthdayUntil.Subtract(DateTime.Now); + var days = ts.Days + 1; + + return CreateCriteriaIsActive() + .Add(Expression.Sql(new SqlString("dayofyear(CAST(CONCAT(Year(CURDATE()), '-', Month(" + Person.PropertyName_DateOfBirth + "), '-', Day(" + Person.PropertyName_DateOfBirth + ")) AS DATE )) between dayofyear(CURDATE()) -4 and dayofyear(CURDATE()) + " + days))) + .List(); + } + + public IEnumerable FindLastLogins(string loginName, int maxResults) + { + return CreateCriteria() + .Add(Restrictions.Eq(Login.PropertyName_LoginName, loginName)) + .AddOrder(Order.Desc("Oid")) + .SetMaxResults(maxResults) + .List(); + } + + public IEnumerable FindQuery(QueryType pType) + { + return CreateCriteria().Add(Restrictions.Eq(Query.PropertyName_Type, pType)) + .List().ToList(); + } + + public IList FindAccoutingTransactions(DateTimeSpan pSpan) + { + var lCriteria = CreateCriteriaIsActive(); + + if (pSpan != null) + lCriteria.Add(Restrictions.Between(AccountingTransaction.PropertyName_BookingDate, pSpan.StartDateTime, pSpan.EndDateTime)); + + var test = lCriteria.List(); + + return test; + } + + public IEnumerable FindAccoutingTransactions(DateTimeSpan pSpan, long? pSupportConceptOid, long? pSupportConceptCostBearerRelOid) + { + var lCriteria = CreateCriteriaIsActive() + .CreateAlias(AccountingTransaction.PropertyName_CostBearer2SupportConcept, "cb2sc", JoinType.LeftOuterJoin); + + if (pSpan != null) + lCriteria.Add(Restrictions.Between(AccountingTransaction.PropertyName_BookingDate, pSpan.StartDateTime, pSpan.EndDateTime)); + + if (pSupportConceptCostBearerRelOid != null) + lCriteria.Add(Restrictions.Eq("cb2sc." + BeWoEntityBase.PropertyName_Oid, pSupportConceptCostBearerRelOid)); + + if (pSupportConceptOid != null) + { + lCriteria.CreateCriteria("cb2sc." + CostBearer2SupportConcept.PropertyName_SupportConcept) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pSupportConceptOid)); + } + + var test = lCriteria.List(); + + return test; + } + + public IList FindSettingsByValuePart(SettingsType pType, string pValuePart) + { + return CreateCriteria() + .Add(Restrictions.Eq(Settings.PropertyName_Type, pType)) + .Add(Restrictions.Like(Settings.PropertyName_Value, pValuePart, MatchMode.Anywhere)) + .List(); + } + + public IList FindFileAttachments(TableID pObjTid, long pObjOid) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(FileAttachment.PropertyName_ObjectOid, pObjOid)) + .Add(Restrictions.Eq(FileAttachment.PropertyName_ObjectTid, pObjTid)) + .List(); + } + + public IEnumerable FindFileAttachmentInfos(TableID pObjTid, long pObjOid) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(FileAttachmentInfo.PropertyName_ObjectOid, pObjOid)) + .Add(Restrictions.Eq(FileAttachmentInfo.PropertyName_ObjectTid, pObjTid)) + .List(); + } + + public IList FindBeWoFolders(TableID pObjTid, long pObjOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(BeWoFolder.PropertyName_ObjectTid, pObjTid)); + + if (pObjOid > 0) + { + c.Add(Restrictions.Eq(BeWoFolder.PropertyName_ObjectOid, pObjOid)); + } + + return c.List(); + } + + //public IList FindAllActiveApprovedLVRSupportConcepts() + //{ + // return CreateCriteriaIsActive() + // .CreateCriteria(SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) + // .Add(Expression.Eq(CostBearer2SupportConcept.PropertyName_Status, CostBearer2SupportConceptStatus.Approved)) + // .CreateCriteria(CostBearer2SupportConcept.PropertyName_CostBearer, JoinType.InnerJoin) + // .Add(Expression.Eq(CostBearer.PropertyName_SystemEntryID, SystemEntryID.CostBearerLVR)) + // .List(); + //} + + public IList FindAllActiveApprovedSupportConcepts() + { + return CreateCriteriaIsActive() + .CreateCriteria(SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) + .Add(Restrictions.Eq(CostBearer2SupportConcept.PropertyName_Status, CostBearer2SupportConceptStatus.Approved)) + + .List().Distinct().ToList(); + } + + public Employee FindEmployeeWithPersonOid(long pPersonOid) + { + var person = DAOFactory.GenericDAO.LoadByID(pPersonOid); + if (person != null) + { + return CreateCriteria() + .Add(Restrictions.Eq(Employee.PropertyName_Person, person)).UniqueResult(); + } + + return null; + } + + public Customer FindCustomerWithPersonOid(long pPersonOid) + { + var person = DAOFactory.GenericDAO.LoadByID(pPersonOid); + if (person != null) + { + return CreateCriteria() + .Add(Restrictions.Eq(Customer.PropertyName_Person, person)).UniqueResult(); + } + + return null; + } + + public IList FindCustomersWithPersonOids(IEnumerable pPersonOid) + { + + return CreateCriteriaIsActive() + .CreateAlias(Customer.PropertyName_Person, "p", JoinType.InnerJoin) + .Add(Restrictions.In("p." + BeWoEntityBase.PropertyName_Oid, pPersonOid.ToArray())) + .List(); + } + + public IList GetActivePersonsWithType(PersonType type) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(Person.PropertyName_Type, type)) + .List(); + } + + public IEnumerable GetAllActiveCustomersWithSupportConceptData() + { + return CreateCriteriaIsActiveOrArchived() + .CreateAlias(Customer.PropertyName_SupportConcepts, "sc", JoinType.LeftOuterJoin) + .CreateCriteria("sc." + SupportConcept.PropertyName_CostBearer2SupportConceptList, JoinType.LeftOuterJoin) + .Add(Restrictions.Eq("sc." + SupportConcept.PropertyName_IsActive, ActivationTypeId.Active)) + .List(); + } + + public IEnumerable GetAllActiveCustomersWithAddress() + { + return CreateCriteriaIsActive() + .CreateCriteria(Customer.PropertyName_Person, JoinType.LeftOuterJoin) + .CreateCriteria(Person.PropertyName_Address, JoinType.LeftOuterJoin) + .List(); + } + + public IEnumerable GetAllCustomersWithRelatedEmployee() + { + return CreateCriteria() + .CreateAlias("Person", "cp", JoinType.InnerJoin) + .CreateAlias("cp." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) + .CreateAlias("Employee2CustomerList", "e2c", JoinType.LeftOuterJoin) + .CreateAlias("e2c." + Employee2Customer.PropertyName_Employee, "e", JoinType.LeftOuterJoin) + .CreateCriteria("e2c." + Employee2Customer.PropertyName_ValueList, JoinType.LeftOuterJoin) + .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.LeftOuterJoin) + .List(); + } + + public IList FindServiceRecordsDetailsForLastDays(long costbearer2SupportConcept, long? days) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); + + if (days.HasValue) + { + + var minDate = DateTime.Now.Date.AddDays(-1 * days.Value); + c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); + } + + return c.CreateAlias(ServiceRecord.PropertyName_ValueList, "vl", JoinType.LeftOuterJoin) + .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin) + .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.InnerJoin) + .List().Distinct().ToList(); + } + + public IList FindServiceRecordsDetailsForLastDaysWithStartEndDate(long costbearer2SupportConcept, DateTime start, DateTime ende) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); + + + var max = ende.Date.AddDays(1); + + c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) + .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); + + var result = c.CreateAlias(ServiceRecord.PropertyName_ValueList, "vl", JoinType.LeftOuterJoin) + .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin) + .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.InnerJoin) + .List(); + + return result; + } + + public IList FindServiceRecordsDetailWithServiceInfo(long costbearer2SupportConcept) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); + + + return c.CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .List(); + } + + public Customer FindCustomerWithServiceRecordsWithDetail(long pCustomerOid) + { + return CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pCustomerOid)) + .CreateAlias(Customer.PropertyName_ServiceRecordList, "sr", JoinType.InnerJoin) + .CreateCriteria("sr." + ServiceRecord.PropertyName_ValueList, JoinType.LeftOuterJoin) + .CreateAlias("sr." + ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateCriteria("sd." + ServiceDescription.PropertyName_ServiceCategory, JoinType.InnerJoin) + .CreateAlias("sr." + ServiceRecord.PropertyName_CostBearer2SupportConcept, "c2s", JoinType.InnerJoin) + .CreateCriteria("c2s." + CostBearer2SupportConcept.PropertyName_SupportConcept, JoinType.InnerJoin) + .CreateAlias("c2s." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb", JoinType.InnerJoin) + .CreateAlias("cb." + CostBearer.PropertyName_Organisation, "org", JoinType.InnerJoin) + .UniqueResult(); + } + + public ServiceRecordGroup FindServiceRecordGroup(long pGroupOid) + { + return CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pGroupOid)) + .CreateCriteria(ServiceRecordGroup.PropertyName_ServiceRecordList, JoinType.InnerJoin) + .UniqueResult(); + } + + public IEnumerable GetAllActiveAndArchivedSupportConceptsCompact() + { + return CreateCriteria() + .Add(Restrictions.Or(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Archived))) + .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.LeftOuterJoin) + .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .CreateAlias("c." + Customer.PropertyName_Person, "p", JoinType.InnerJoin) + .CreateAlias("p." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) + .CreateAlias("c." + Customer.PropertyName_Employee2CustomerList, "e2c", JoinType.LeftOuterJoin) + .List(); + } + + public IEnumerable GetAllSupportConceptsCompact() + { + return CreateCriteria() + .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.LeftOuterJoin) + .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .CreateAlias("c." + Customer.PropertyName_Person, "p", JoinType.InnerJoin) + .CreateAlias("p." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) + .CreateAlias("c." + Customer.PropertyName_Employee2CustomerList, "e2c", JoinType.LeftOuterJoin) + .List(); + } + + public IList GetAllActiveAndArchivedListedSupportConceptsCompact() + { + return Session.CreateCriteria() + .List(); + } + + public IList GetAllActiveAndArchivedListedSupportConceptsCompact(List oids) + { + return Session.CreateCriteria() + .Add(Restrictions.In("SupportConceptOid", oids)) + .List(); + } + + public IList GetAllCustomerWithServiceRecordsInSpan(DateTimeSpan pSpan) + { + return CreateCriteria() + .CreateCriteria(Customer.PropertyName_ServiceRecordList, JoinType.InnerJoin) + .Add(Restrictions.Between(ServiceRecord.PropertyName_Start, pSpan.StartDateTime, pSpan.EndDateTime)) + .List(); + } + + public IEnumerable GetAllAccountingTransactionsWithDetails() + { + return CreateCriteria() + .AddOrder(Order.Desc(AccountingTransaction.PropertyName_BookingDate)) + .CreateAlias(AccountingTransaction.PropertyName_CostBearer2SupportConcept, "cb2sc", JoinType.LeftOuterJoin) + .CreateCriteria("cb2sc." + CostBearer2SupportConcept.PropertyName_CostBearer, JoinType.LeftOuterJoin) + .CreateCriteria(CostBearer.PropertyName_Organisation, JoinType.LeftOuterJoin) + .CreateCriteria("cb2sc." + CostBearer2SupportConcept.PropertyName_SupportConcept, JoinType.LeftOuterJoin) + .CreateCriteria(SupportConcept.PropertyName_Customer, JoinType.LeftOuterJoin) + .CreateCriteria(Customer.PropertyName_Person, JoinType.LeftOuterJoin) + .List(); + } + + public IEnumerable FindAccountingTransactionsWithImportNotice(String notice) + { + return CreateCriteria() + .Add(Restrictions.Eq(AccountingTransaction.PropertyName_ImportNotice, notice)).List(); + } + + public IEnumerable GetAllActiveAndArchivedSupportConcepts() + { + return CreateCriteria() + .Add(Restrictions.Or(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Archived))) + .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) + .CreateAlias("cb2sc." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb", JoinType.InnerJoin) + .CreateAlias("cb." + CostBearer.PropertyName_Organisation, "org", JoinType.InnerJoin) + .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .CreateAlias("c." + Customer.PropertyName_Person, "p", JoinType.InnerJoin) + .List(); + } + + public IEnumerable GetAllActiveAndArchivedCustomersWithRelatedEmployee() + { + return CreateCriteria() + .Add(Restrictions.Or(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Archived))) + .CreateAlias(Customer.PropertyName_Person, "cp", JoinType.InnerJoin) + .CreateAlias("cp." + Person.PropertyName_Address, "a", JoinType.LeftOuterJoin) + .CreateAlias(Customer.PropertyName_Employee2CustomerList, "e2c", JoinType.LeftOuterJoin) + .CreateAlias("e2c." + Employee2Customer.PropertyName_Employee, "e", JoinType.LeftOuterJoin) + .CreateCriteria("e2c." + Employee2Customer.PropertyName_ValueList, JoinType.LeftOuterJoin) + .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.LeftOuterJoin) + .List(); + } + + public IEnumerable GetSettlementInvoiceBySupportConceptOid(long supportConceptOid) + { + return CreateCriteriaIsActive() + .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_SupportConceptOid, supportConceptOid)) + .List(); + } + + public IList GetSettlementInvoiceByCostBearer2SupportConceptOid(long costBearer2SupportConceptOid) + { + return CreateCriteriaIsActive() + .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)) + .List(); + } + + public IEnumerable GetSettlementInvoicesForCostBearerAndPeriod(long costBearerOid, DateTime periodStart, DateTime periodEnd) + { + return CreateCriteriaIsActive() + .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .CreateAlias("ib." + InvoiceBase.PropertyName_CostBearer2SupportConcept, "cb2sc", JoinType.InnerJoin) + .CreateAlias("cb2sc." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb", JoinType.InnerJoin) + .Add(Restrictions.Eq("cb." + BeWoEntityBase.PropertyName_Oid, costBearerOid)) + .Add(Restrictions.Or( + Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, periodStart, periodEnd), + Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, periodStart, periodEnd))) + .List(); + } + + public IList GetInvoiceBaseByTypeAndSupportConceptOid(InvoiceType type, long supportConceptOid) + { + return SearchInvoiceBase(type, InvoiceBase.PropertyName_SupportConceptOid, supportConceptOid); + } + + public IEnumerable GetInvoiceBaseByOrganisationOid(InvoiceType type, long organisationOid) + { + return SearchInvoiceBase(type, InvoiceBase.PropertyName_RecipientOrganisationOid, organisationOid); + } + + public IEnumerable GetInvoiceBaseByCustomerOid(InvoiceType type, long customerOid) + { + return SearchInvoiceBase(type, InvoiceBase.PropertyName_RecipientCustomerOid, customerOid); + } + + public IEnumerable GetInvoiceBaseByPersonOid(InvoiceType type, long personOid) + { + return SearchInvoiceBase(type, InvoiceBase.PropertyName_RecipientPersonOid, personOid); + } + + private IList SearchInvoiceBase(InvoiceType type, string propertyname, long fkOid) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(InvoiceBase.PropertyName_Type, type)) + .Add(Restrictions.Eq(propertyname, fkOid)) + .List(); + } + + public SettlementInvoice GetSettlementInvoiceByInvoiceBaseOid(long invoiceBaseOid) + { + return CreateCriteria() + .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_Oid, invoiceBaseOid)) + .UniqueResult(); + } + + public ServiceInvoice GetServiceInvoiceByInvoiceBaseOid(long invoiceBaseOid) + { + var res = CreateCriteriaIsActive() + .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_Oid, invoiceBaseOid)) + .UniqueResult(); + + return res; + } + + public IEnumerable GetAssessmentSheetEntriesForCustomer(long customerOid, DateTime startDt, DateTime endDt) + { + + + return CreateCriteriaIsActive() + .CreateAlias(AssessmentSheetEntry.PropertyName_Customer, "c", JoinType.InnerJoin) + .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_Oid, customerOid)) + .Add(Restrictions.Ge(AssessmentSheetEntry.PropertyName_Day, startDt)) + .Add(Restrictions.Lt(AssessmentSheetEntry.PropertyName_Day, endDt)) + .List(); + } + + public IList GetVarFieldDefs(TableID tid) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(VarFieldDef.PropertyName_ObjectTid, tid)) + .List(); + } + + public IEnumerable FindTasksForEmployee(long employeeoid) + { + return CreateCriteriaIsActive() + .CreateAlias(Task.PropertyName_SupportConcept, "sc", JoinType.InnerJoin) + .CreateAlias("sc." + SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .CreateCriteria(Task.PropertyName_EmployeeList, JoinType.InnerJoin) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeoid)) + .Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .List(); + } + + public List GetServiceInvoices(long costBearerOid, long? supportConceptOid, DateTimeSpan period) + { + var criteria = CreateCriteriaIsActive() + .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_RecipientCostBearerOid, costBearerOid)) + .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); + + if (supportConceptOid.HasValue) + criteria = criteria + .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_SupportConceptOid, supportConceptOid.Value)); + + if (period != null) + criteria = criteria + .Add(Restrictions.Or( + Restrictions.Or( + Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime, period.EndDateTime), + Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.StartDateTime, period.EndDateTime)), + Restrictions.And( + Restrictions.Le("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime), + Restrictions.Ge("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.EndDateTime)))); + + return criteria.List().ToList(); + } + + public List GetServiceInvoices(long? costbearer2SupportConceptOid, DateTimeSpan period) + { + var criteria = CreateCriteriaIsActive() + .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.Eq("ib." + BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); + + if (costbearer2SupportConceptOid.HasValue) + criteria = criteria + .Add(Restrictions.Eq("ib." + InvoiceBase.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConceptOid.Value)); + + + + if (period != null) + criteria = criteria + .Add(Restrictions.Or( + Restrictions.Or( + Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime, period.EndDateTime), + Restrictions.Between("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.StartDateTime, period.EndDateTime)), + Restrictions.And( + Restrictions.Le("ib." + InvoiceBase.PropertyName_AccountingPeriodStart, period.StartDateTime), + Restrictions.Ge("ib." + InvoiceBase.PropertyName_AccountingPeriodEnd, period.EndDateTime)))); + + return criteria.List().ToList(); + } + + public IEnumerable GetAssessmentSheetCategoryListForCustomer(long customerOid) + { + + return CreateCriteriaIsActive() + .CreateAlias(AssessmentSheetCategory.PropertyName_Customers, "c", JoinType.InnerJoin) + .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_Oid, customerOid)) + .List(); + + } + + public IEnumerable FindAbsenceTimes(bool fetchEmployees, bool fetchCustomers) + { + var criteria = CreateCriteriaIsActive(); + + if (!fetchEmployees) + criteria = criteria + .Add(Restrictions.IsNull(AbsenceTime.PropertyName_EmployeeOid)); + else if (!fetchCustomers) + criteria = criteria + .Add(Restrictions.IsNull(AbsenceTime.PropertyName_CustomerOid)); + + return criteria.List().ToList(); + + + } + + public List FindAbsenceTimes(DateTime startDate, DateTime endDate) + { + var criteria = CreateCriteriaIsActive() + .Add( + Restrictions.Or( + Restrictions.And( + Restrictions.Ge(AbsenceTime.PropertyName_End, startDate), + Restrictions.Lt(AbsenceTime.PropertyName_Start, endDate.Date.AddDays(1)) + ), + Restrictions.And( + Restrictions.Lt(AbsenceTime.PropertyName_Start, endDate.Date.AddDays(1)), + Restrictions.IsNull(AbsenceTime.PropertyName_End) + ) + ) + ); + + return criteria.List().ToList(); + } + + public IEnumerable FindAbsenceTimesForEmployee + (DateTime startDate, DateTime endDate, long empOid) + { + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.Eq("EmployeeOid", empOid)) + .Add(Restrictions.Gt(AbsenceTime.PropertyName_Start, startDate)) + .Add(Restrictions.Lt(AbsenceTime.PropertyName_End, endDate)); + + return criteria.List().ToList(); + } + + public IEnumerable FindAbsenceTimesForMonth(DateTime startDate, DateTime endDate) + { + var criteria = CreateCriteriaIsActive(); + criteria.Add(Restrictions.Gt("Start", startDate)); + criteria.Add(Restrictions.Lt("End", endDate)); + + return criteria.List().ToList(); + } + + public IEnumerable FindVertretungen(DateTime startDate, DateTime endDate) + { + var criteria = CreateCriteriaIsActive() + .Add( + Restrictions.Or( + Restrictions.And( + Restrictions.Ge(Vertretung.PropertyName_VertretungsZeitraumBis, startDate), + Restrictions.Le(Vertretung.PropertyName_VertretungsZeitraumVon, endDate) + ), + Restrictions.And( + Restrictions.Le(Vertretung.PropertyName_VertretungsZeitraumVon, endDate), + Restrictions.IsNull(Vertretung.PropertyName_VertretungsZeitraumBis) + ) + ) + ); + + return criteria.List().ToList(); + + + } + + public IEnumerable FindLastVertretungen(long customerOid) + { + var c = CreateCriteriaIsActive(); + c.Add(Restrictions.Eq("CustomerOid", customerOid)); + + return c.List().ToList(); + + + } + + public IEnumerable FindAppointments(long? customerOid, long? employeeOid) + { + var criteria = CreateCriteriaIsActive(); + + if (employeeOid.HasValue) + { + criteria = criteria.Add(Restrictions.Eq(AbsenceTime.PropertyName_EmployeeOid, employeeOid)); + } + + if (customerOid.HasValue) + { + criteria = criteria.Add(Restrictions.Eq(AbsenceTime.PropertyName_CustomerOid, customerOid)); + } + + return criteria.List().ToList(); + } + + public ServiceCategory FindDefaultIndividualServiceCategory() + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(ServiceCategory.PropertyName_ScopeType, ScopeTypeId.Individual)) + .List().FirstOrDefault(); + } + + public ServiceCategory FindServiceCategoryByName(String name) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(ServiceCategory.PropertyName_Name, name)) + .List().FirstOrDefault(); + } + + public IEnumerable FindFileAttachmentInfoByType(FileAttachmentType type) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq("Type", type)); + + return criteria.List().ToList(); + } + + public IEnumerable GetAdditionalAssessmentSheetEntries(DateTime dateTime) + { + return CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_SystemEntryID, SystemEntryID.AdditionalServiceAssessmentSheet)) + .Add(Restrictions.Eq(AssessmentSheetEntry.PropertyName_Day, dateTime.Date)) + .List(); + } + + public IEnumerable GetResourceAppointmentExceptionsWithIndexAndId(string info) + { + return CreateCriteria() + .Add(Restrictions.Like(ResourceAppointment.PropertyName_RecurrenceInfo, info)) + .List(); + + } + + public IEnumerable GetAdditionalServiceBookings(long? regionOid, DateTime start, DateTime end) + { + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.Between("Datum", start, end)); + + if (regionOid.HasValue) + criteria = criteria.CreateAlias(AdditionalServiceBooking.PropertyName_AdditionalServiceRegion, "asr", JoinType.InnerJoin) + .Add(Restrictions.Eq("asr." + BeWoEntityBase.PropertyName_Oid, regionOid)); + + return criteria.List(); + } + + public IEnumerable GetAdditionalServiceNoticeList(long? regionOid, DateTime start, DateTime end) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Between("Monat", start, end)); + + if (regionOid.HasValue) + { + c.Add(Restrictions.Eq("RegionOid", regionOid)); + } + + return c.List(); + } + + public IEnumerable GetAdditionalServiceBookingsForCustomer(long customerOid, DateTime start, DateTime end) + { + return CreateCriteriaIsActive() + .CreateAlias(AdditionalServiceBooking.PropertyName_Customer2AddServiceBookings, "c2s", JoinType.InnerJoin) + .Add(Restrictions.Between("Datum", start, end)) + .Add(Restrictions.Eq("c2s.CustomerOid", customerOid)) + .List(); + } + + public AssessmentSheetCategory GetAddServiceAssessmentSheetCategoryWithName(string name) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Eq(AssessmentSheetCategory.PropertyName_Description, name)) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_SystemEntryID, SystemEntryID.AdditionalServiceAssessmentSheet)) + .List().FirstOrDefault(); + } + + public IList GetBillableServiceRecords() + { + var c = CreateCriteria() + .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .Add(Restrictions.Eq("sc." + ServiceCategory.PropertyName_IsBillable, true)); + + return c.List(); + } + + public IList GetBillableServiceRecords(DateTime start, DateTime end) + { + var c = CreateCriteria() + .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .Add(Restrictions.Eq("sc." + ServiceCategory.PropertyName_IsBillable, true)) + .Add(Restrictions.Between(ServiceRecord.PropertyName_Start, start, end)); + + + return c.List(); + } + + public IList GetBillableServiceRecordsSqlArray(DateTime start, DateTime end) + { + var q = Session.CreateSQLQuery(String.Format(@" SELECT sr.Oid, sr.StartDate, sr.EndDate, sr.EmployeeOid, sr.CustomerOid, sr.GroupOid, sr.costbearer2supportconceptoid, sd.Name, sc.Name FROM ServiceRecord sr inner join ServiceDescription sd on sr.ServiceDescriptionOid = sd.Oid inner join ServiceCategory sc on sd.ServiceCategoryOid = sc.Oid WHERE sc.Billable = 1 and sr.StartDate >= '{0:yyyy-MM-dd}' and sr.StartDate < '{1:yyyy-MM-dd}'", start, end)); - return q.List(); - - } - - public IEnumerable FindServiceDescriptionForCategory(long categoryOid) - { - var c = CreateCriteriaIsActive() - .CreateAlias(ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_Oid, categoryOid)); - - return c.List(); - } - - public IEnumerable FindServiceAccountingsForServiceDescriptions(IList descriptionOids) - { - var c = CreateCriteriaIsActive() - .CreateAlias("ServiceDescription", "sd", JoinType.InnerJoin) - .Add(Restrictions.In("sd." + BeWoEntityBase.PropertyName_Oid, descriptionOids.ToArray())); - - return c.List(); - } - - public IList GetAllMedikamentenverordnungslistenButNewestByCustomerOid(long customerOid, long newestOid, bool isBedarfsListe) - { - var c = CreateCriteria() - .CreateAlias(Medikamentenverordnungsliste.PropertyName_Customer, "c") - .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_Oid, customerOid)) - .Add(Restrictions.Not(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, newestOid))) - .Add(Restrictions.Eq(Medikamentenverordnungsliste.PropertyName_MedListType, isBedarfsListe)); - - return c.List(); - } - - public IList GetAllOpenAppointmentsForEmployee(long employeeOid) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .Add(Restrictions.Not(Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", employeeOid))) - .Add(Restrictions.Or(Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, DateTime.Now.AddDays(-7)), Restrictions.IsNull(SchedulerAppointment.PropertyName_EndDate))) - .CreateCriteria(SchedulerAppointment.PropertyName_EmployeeList) - .Add(Restrictions.And(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", employeeOid), - Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Offen))); - - return c.List(); - } - - public IEnumerable GetAllParticipationNotificationsForEmployee(long employeeOid) - { - var c = CreateCriteria() - .Add(Restrictions.And(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", employeeOid))) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .Add(Restrictions.Or(Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, DateTime.Now.AddDays(-7)), Restrictions.IsNull(SchedulerAppointment.PropertyName_EndDate))) - .CreateCriteria(SchedulerAppointment.PropertyName_EmployeeList) - .Add(Restrictions.And(Restrictions.And(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_IsPChanged, true), Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", employeeOid))), Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Offen)))) - .Add(Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Verstrichen))) - .Add(Restrictions.IsNull(Employee2SchedulerAppointment.PropertyName_IsPC_CheckedTs)); - - var result = c.List(); - - return result; - } - - public IEnumerable GetRemovedEmp2AppObjectsBySchAppOid(long schAppOid) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment, schAppOid)); - - return c.List(); - } - - public IEnumerable GetAllActiveAndNotDeclinedForEmployeeAppointments(long employeeOid) - { - var detachedCriteria = DetachedCriteria.For() - .Add(Restrictions.And(Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", employeeOid)), - Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Absage))); - detachedCriteria.SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); - - var crit = CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .Add(Restrictions.Or(Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", employeeOid), Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria))); - - return crit.List(); - } - - public bool ResetPasswordCodeExists(string code, long userOid) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, userOid)) - .CreateCriteria(ApplicationUser.PropertyName_ResetPasswordInfos) - .Add(Restrictions.Eq(ResetPasswordInfo.PropertyName_Code, code)); - - return c.List().Count > 0; - } - - public bool OverlappingAppointmentsExist(DateTime start, DateTime end, IEnumerable employees, IEnumerable customers, IEnumerable resources, long originator, long? appointmentOid, string recurrenceId = "", int occurrenceIndex = 0) - { - if (employees is null) - { - employees = new List(); - } - - if (customers is null) - { - customers = new List(); - } - - if (resources is null) - { - resources = new List(); - } - - var isRecurrenceException = appointmentOid is null; - var isBeingUpdatedToNormalAppointment = false; - Guid? recurrenceIdToIgnore = null; - - if (appointmentOid != null) - { - // Das Pattern wird geladen, bzw. mit der Ausnahme mit Index 0 verglichen - // Wird die Serie in einen Einzeltermin geändert und es existiert eine Ausnahme mit Index 0, sollte die Ausnahme behalten werden und nicht der Root-Termin - var original = DAOFactory.GenericDAO.LoadByID(appointmentOid.Value); - var ri = original?.GetRecurrenceId(); - if (ri != null && IsNullOrWhiteSpace(recurrenceId)) - { - isBeingUpdatedToNormalAppointment = true; - recurrenceIdToIgnore = ri; - } - } - - Guid? recurrenceGuid = null; - - if (Guid.TryParse(recurrenceId, out var parsedGuid)) - { - recurrenceGuid = parsedGuid; - } - - var betweenDateTimesCriterion = CreateBetweenDateTimesCriterion(start, end, nameof(SchedulerAppointment.StartDate), nameof(SchedulerAppointment.EndDate)); - - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) - .Add(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), false)) - .Add(betweenDateTimesCriterion); - - if (isRecurrenceException == false) - { - criteria.Add(Restrictions.Not(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, appointmentOid))); - } - - var appTmp = criteria.List(); - - var appointments = appTmp.Where(a => - { - if (a.RecurrenceInfo is null) - { - return true; - } - - var recId2 = a.GetRecurrenceIdAndIndex(out var index); - - return !(Guid.TryParse(recurrenceId, out var guid) && guid.Equals(recId2) && occurrenceIndex == index); - }); - - var schedulerAppointments = appointments as IList ?? appointments.ToList(); - - // Serientermine anhand der RecurrenceInfo erzeugen und den schedulerAppointments hinzufügen ------------------------------------------------------------ - var deletedOccurences = schedulerAppointments.Where(app => app.Type == 4).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); - var changedOccurences = schedulerAppointments.Where(app => app.Type == 3).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); - - var recurringAppointmentsCriteria = CreateRecurrenceCriteria(start, end).Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 1)); - - var recurringAppointments = recurringAppointmentsCriteria.List().ToList(); - - if (isBeingUpdatedToNormalAppointment) - { - recurringAppointments = recurringAppointments.Where(root => - { - var recId = root.GetRecurrenceId(); - - if (recId is null || recurrenceIdToIgnore is null) - { - return true; - } - - return !recId.Equals(recurrenceIdToIgnore); - }).ToList(); - - schedulerAppointments = schedulerAppointments.Where(root => - { - var recId = root.GetRecurrenceId(); - - if (recId is null || recurrenceIdToIgnore is null) - { - return true; - } - - return !recId.Equals(recurrenceIdToIgnore); - }).ToList(); - } - - foreach (var appointment in recurringAppointments) - { - var recurrenceInfo = new RecurrenceInfo(); - recurrenceInfo.FromXml(appointment.RecurrenceInfo); - - var occurenceCalculator = OccurrenceCalculator.CreateInstance(recurrenceInfo); - - // Das Muster für die Terminserie wird berechnet - var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); - - if (pattern is null) - { - continue; - } - - pattern.RecurrenceInfo.FromXml(appointment.RecurrenceInfo); - pattern.Start = pattern.RecurrenceInfo.Start; - pattern.End = appointment.EndDate.Value; //pattern.RecurrenceInfo.End; - - var patternId = pattern.RecurrenceInfo.Id.ToString(); - - // In diesem Fall die Start- und Enddaten des zu überprüfenden, neuen Termins - var interval = new TimeInterval(start, end); - - // Die Serientermine werden berechnet (ausnahmslos, d.h. es werden auch bearbeitete und gelöschte Termine erstellt, die herausgefiltert werden müssen). - var occurrences = occurenceCalculator.CalcOccurrences(interval, pattern); - - foreach (var occurrence in occurrences.GetAppointments(interval)) - { - if (appointment.EndDate is null || appointment.StartDate is null) - { - continue; - } - - // Terminindex in der Serie - var index = occurrence.RecurrenceIndex; - - // Das Ende ist offen, da die Terminserie kein Ende hat. Deshalb wird das Ende berechnet. - var duration = (appointment.EndDate.Value - appointment.StartDate.Value).TotalMinutes; - - var guidParsingSuccessful = Guid.TryParse(occurrence.RecurrenceInfo?.Id?.ToString(), out var occurrenceGuid); - - // Der generierte Serientermin muss sich zeitlich mit dem neuen Termin überschneiden - // und darf nicht in der Liste der geänderten Serientermine oder der Liste der gelöschten Serientermine sein. - - var isInIntervalTest = start.IsInInterval(end, occurrence.Start, occurrence.Start.AddMinutes(duration)); - - if (!isInIntervalTest || - changedOccurences != null && changedOccurences.Any(changedOccurence => changedOccurence.PatternId.Equals(patternId) && changedOccurence.Index == index) || - deletedOccurences != null && deletedOccurences.Any(deletedOccurence => deletedOccurence.PatternId.Equals(patternId) && deletedOccurence.Index == index) || - index == occurrenceIndex && guidParsingSuccessful && recurrenceGuid != null && recurrenceGuid.Equals(occurrenceGuid)) - { - continue; - } - - // Prüfen, ob es eine Ausnahme an dem Tag gibt, die zu dem Pattern gehört, um das Pattern auszuschließen - var relatedAppointments = FindAppointmentsByRecurrenceId(new List { recurrenceInfo.Id.ToString() }, true); - var relatedAppointmentsInInterval = relatedAppointments.Where(a => - { - if (a.StartDate == null || a.EndDate == null) - { - return false; - } - - var myStart = a.StartDate.Value.Date; - var myEnd = a.EndDate.Value.Date; - - var isInInterval = start.Date.InBetween(myStart.GetShortDateTime(), myEnd, true); - - return isInInterval && a.Type != 4; - }).ToList(); - - var hasToStop = false; - - // Prüfen, ob es sich bei dem Termin für den Überschneidungen gesucht werden, um zu unterscheiden, ob ein Serientermin in einen normalen geändert wird. - var root = FindRootAppointmentByRecurrenceId(recurrenceInfo.Id.ToString()); - if (root.Oid != null && appointmentOid != null && root.Oid == appointmentOid && root.RecurrenceInfo != null && IsNullOrWhiteSpace(recurrenceId)) - { - hasToStop = true; - } - - // Indices und Ids der RecurrenceInfo vergleichen. Stimmen sie überein, dann wird das generiert Serienelement ignoriert. - if (occurrence.RecurrenceInfo?.Id != null && !hasToStop) - { - if (Guid.TryParse(occurrence.RecurrenceInfo.Id.ToString(), out var guid)) - { - foreach (var relatedAppointment in relatedAppointmentsInInterval) - { - var relatedAppointmentRecurrenceId = relatedAppointment.GetRecurrenceIdAndIndex(out var relatedAppointmentRecurrenceIndex); - - if (relatedAppointmentRecurrenceId != null) - { - if (guid.Equals(relatedAppointmentRecurrenceId) && relatedAppointmentRecurrenceIndex.Equals(occurrence.RecurrenceIndex)) - { - hasToStop = true; - break; - } - } - } - } - } - - if (hasToStop) - { - continue; - } - - var recurringAppointment = new SchedulerAppointment - { - AllDay = occurrence.AllDay, - CustomerList = appointment.CustomerList, - Notice = appointment.Notice, - EmployeeList = appointment.EmployeeList, - EndDate = occurrence.Start.AddMinutes(duration), - FormerBookingSequenceOid = appointment.FormerBookingSequenceOid, - IsPrivate = appointment.IsPrivate, - Location = appointment.Location, - Originator = appointment.Originator, - RecurrenceInfo = occurrence.RecurrenceInfo.ToXml(), - ReminderInfo = appointment.ReminderInfo, - ResourceList = appointment.ResourceList, - StartDate = occurrence.Start, - Subject = appointment.Subject ?? "", - Type = appointment.Type - }; - - schedulerAppointments.AddIfNotIn(recurringAppointment); - } - } - // -------------------------------------------------------------------------------------------------------------------------------------- - - // Falls es sich um eine Ausnahme einer Serie handelt, muss die Serie ignoriert werden - var shouldIgnoreAppointment = false; - if (isRecurrenceException && recurrenceId != null) - { - if (recurrenceGuid.HasValue) - { - shouldIgnoreAppointment = true; - } - } - - var employeeOidList = new List(); - - schedulerAppointments = schedulerAppointments.Where(appointment => appointment.Type != 4).ToList(); - - foreach (var appointment in schedulerAppointments) - { - if (shouldIgnoreAppointment) - { - if (!ShouldDoAppointmentOverlappingCheck(appointment, recurrenceGuid.Value)) - { - continue; - } - } - - employeeOidList.AddRange(appointment.EmployeeList.Select(rel => rel.ParticipationAnswer != ParticipationAnswer.Absage && rel.Employee.Oid != null ? rel.Employee.Oid.Value : 0)); - } - - var hasOverlappingEmployeeAppointments = employeeOidList.Intersect(employees).Any(); - var hasOverlappingCustomerAppointments = schedulerAppointments.Any(app => { return ShouldDoAppointmentOverlappingCheck(app, recurrenceGuid) && app.CustomerList.Select(c => c.Oid ?? 0).Intersect(customers).Any(); }); - - var hasOverlappingResourceAppointments = schedulerAppointments.Any(app => { return ShouldDoAppointmentOverlappingCheck(app, recurrenceGuid) && app.ResourceList.Select(r => r.Oid ?? 0).Intersect(resources).Any(); }); - - var hasOverlappingOriginatorAppointments = schedulerAppointments.Any(appointment => - { - if (!ShouldDoAppointmentOverlappingCheck(appointment, recurrenceGuid)) - { - return false; - } - - return appointment.Originator.Oid.HasValue && - appointment.Originator.Oid.Value == originator && - (appointment.EmployeeList.Count == 0 || appointment.EmployeeList.Any(a => a.Employee.Oid.HasValue && a.Employee.Oid.Value == originator)); - }); - - return hasOverlappingEmployeeAppointments || hasOverlappingCustomerAppointments || hasOverlappingResourceAppointments || hasOverlappingOriginatorAppointments; - } - - private static bool ShouldDoAppointmentOverlappingCheck(SchedulerAppointment appointment, Guid? recurrenceId) - { - if (!appointment.Oid.HasValue || !recurrenceId.HasValue) - { - return true; - } - - var recId = appointment.GetRecurrenceIdAndIndex(out var recIndex); - - if (appointment.RecurrenceInfo is null || recId is null) - { - return true; - } - - return !recId.Equals(recurrenceId); - } - - public IEnumerable GetAllActiveAppointmentsForEmployeeInInterval(DateTime start, DateTime end, long pEmployeeOid) - { - var hasResources = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp)"; - - var criteria = CreateRecurrenceCriteria(start, end) - .Add(Restrictions.Or( - Expression.Sql(new SqlString(hasResources)), - CreateOwnAppointmentsCriteria(pEmployeeOid))); - - return criteria.List(); - } - - public IEnumerable GetAllActiveAppointmentsInInterval(DateTime start, DateTime end) - { - return CreateRecurrenceCriteria(start, end).List(); - } - - public ResourceBooking GetFirstResourceBookingFromSequence(long sequenceOid) - { - return CreateCriteria() - .Add(Restrictions.Eq(ResourceBooking.PropertyName_SequencePosition, 0)) - .CreateAlias(ResourceBooking.PropertyName_Sequence, "s") - .Add(Restrictions.Eq("s." + BeWoEntityBase.PropertyName_Oid, sequenceOid)).UniqueResult(); - } - - public List GetExcludedBookingSequencePositions(long sequenceOid) - { - var c = CreateCriteria() - .Add(Restrictions.Gt(ResourceBooking.PropertyName_SequencePosition, 0)) - .CreateAlias(ResourceBooking.PropertyName_Sequence, "s") - .Add(Restrictions.Eq("s." + BeWoEntityBase.PropertyName_Oid, sequenceOid)).List(); - - return c.Select(s => s.SequencePosition).ToList(); - } - - public IEnumerable GetInvoiceBases(DateTime? startDate, DateTime? endDate, bool useInvoiceDate = true) - { - var lCriteria = CreateCriteriaIsActive(); - if (useInvoiceDate) - { - if (startDate.HasValue) - lCriteria.Add(Restrictions.Ge(InvoiceBase.PropertyName_InvoiceDate, startDate)); - if (endDate.HasValue) - lCriteria.Add(Restrictions.Le(InvoiceBase.PropertyName_InvoiceDate, endDate)); - } - else - { - if (startDate.HasValue) - lCriteria.Add(Restrictions.Ge(InvoiceBase.PropertyName_AccountingPeriodEnd, startDate)); - if (endDate.HasValue) - lCriteria.Add(Restrictions.Le(InvoiceBase.PropertyName_AccountingPeriodStart, endDate)); - } - - return lCriteria.List(); - } - - public IEnumerable GetGkvAbrechnungen(DateTime? startDate, DateTime? endDate, bool useInvoiceDate = true) - { - if (endDate.HasValue) - endDate = endDate.Value.Date.AddDays(1).AddMilliseconds(-1); - - var lCriteria = CreateCriteriaIsActive(); - if (useInvoiceDate) - { - if (startDate.HasValue) - lCriteria.Add(Restrictions.Ge(nameof(GkvAbrechnung.ErstelltAm), startDate)); - if (endDate.HasValue) - lCriteria.Add(Restrictions.Le(nameof(GkvAbrechnung.ErstelltAm), endDate)); - } - else - { - if (startDate.HasValue) - lCriteria.Add(Restrictions.Ge(nameof(GkvAbrechnung.AbrechnungsZeitraumEnde), startDate)); - if (endDate.HasValue) - lCriteria.Add(Restrictions.Le(nameof(GkvAbrechnung.AbrechnungsZeitraumStart), endDate)); - } - - return lCriteria.List(); - } - - public IEnumerable GetInvoiceBases(DateTime? startDate, DateTime? endDate, long costBearerOid, String invoiceId) - { - var lCriteria = CreateCriteriaIsActive(); - - if (startDate.HasValue) - lCriteria.Add(Restrictions.Ge(InvoiceBase.PropertyName_InvoiceDate, startDate)); - - if (endDate.HasValue) - lCriteria.Add(Restrictions.Le(InvoiceBase.PropertyName_InvoiceDate, endDate)); - - lCriteria.Add(Restrictions.Eq(InvoiceBase.PropertyName_InvoiceId, invoiceId)); - - lCriteria.CreateAlias(InvoiceBase.PropertyName_CostBearer2SupportConcept, "c2s"); - lCriteria.CreateAlias("c2s." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb"); - lCriteria.Add(Restrictions.Eq("cb.Oid", costBearerOid)); - lCriteria.Add(Restrictions.Eq("c2s.CostBearer.Oid", costBearerOid)); - - return lCriteria.List(); - } - - public IEnumerable GetAllActiveSupportConceptsByCustomers(List customerOids, bool expiredOnesToo = false) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .CreateAlias(SupportConcept.PropertyName_Customer, "c") - .Add(Restrictions.In("c." + BeWoEntityBase.PropertyName_Oid, customerOids)); - - if (expiredOnesToo) - { - - } - - return c.List(); - } - - public IEnumerable FindServiceRecordsForDays(long? costBearer2SupportConceptOid, int dayCount, long? employeeOid) - { - var minStart = DateTime.Now.GetShortDateTime().AddDays(-dayCount); - var c = CreateCriteriaIsActive(); - - if (costBearer2SupportConceptOid.HasValue) - { - c.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); - } - else - { - c.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - } - - if (dayCount > 0) - { - c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minStart)); - } - - return c.List(); - } - - public IEnumerable GetActiveTextModuleByServiceCategory(long pServiceCategoryOid) - { - var c = CreateCriteria(); - - c.Add(Restrictions.Or(Restrictions.Eq(TextModule.PropertyName_ServiceCategory + ".Oid", pServiceCategoryOid), Restrictions.IsNull(TextModule.PropertyName_ServiceCategory))); - - return c.List(); - } - - public IEnumerable GetAllActiveAppointmentsForEmployeeInInterval2(DateTime start, DateTime end, List pEmployeeOids) - { - var mainCriteria = CreateRecurrenceCriteria(start, end); - - var detachedCriteria1 = DetachedCriteria.For() - .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pEmployeeOids)) - .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); - var employee2SchedCrit = Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria1); - - var originatorCrit = Restrictions.In(SchedulerAppointment.PropertyName_Originator, pEmployeeOids); - - var detachedCriteria2 = DetachedCriteria.For("e2s2") - .SetProjection(Projections.Property(BeWoEntityBase.PropertyName_Oid)) - .Add(Restrictions.EqProperty("e2s2." + Employee2SchedulerAppointment.PropertyName_SchedulerAppointment, "sa.Oid")); - - var employee2SchedCrit2 = Subqueries.NotExists(detachedCriteria2); - - var and = Restrictions.And(originatorCrit, employee2SchedCrit2); - - ICriterion employeeCriterion = Restrictions.Or(employee2SchedCrit, and); - - mainCriteria.Add(employeeCriterion); - - var appointments = mainCriteria.List(); - - var exceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null && w.Type == 3).ToList(); - - var exceptionIds = new List(); - var regex = new Regex("(Id=\\\"[a-z0-9-]+\\\")"); - - foreach (var appointment in exceptionalRecurrenceInfos) - { - var match = regex.Match(appointment.RecurrenceInfo); - if (match.Success) - { - var value = match.Value; - var actualId = value.Split("\""); - if (actualId.Count > 1) - { - var id = actualId[1]; - - if (!appointments.Any(w => w.RecurrenceInfo != null && w.RecurrenceInfo.Contains(id) && w.Type == 1)) - { - exceptionIds.Add(appointment.Oid.Value); - } - } - } - } - - var exceptionsToModify = appointments.Where(w => w.Oid.HasValue && exceptionIds.Contains(w.Oid.Value)).ToList(); - - foreach (var exception in exceptionsToModify) - { - var replacingAppointment = new SchedulerAppointment - { - Oid = exception.Oid.Value * -1, - Version = 1, - Type = 4, - RecurrenceInfo = exception.RecurrenceInfo, - Originator = exception.Originator, - EmployeeList = exception.EmployeeList, - CustomerList = exception.CustomerList, - ResourceList = exception.ResourceList - }; - - exception.RecurrenceInfo = null; - exception.Type = 0; - - appointments.Add(replacingAppointment); - } - - var recurrenceIds = new List(); - - var allExceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null); - foreach (var appointment in allExceptionalRecurrenceInfos) - { - var match = regex.Match(appointment.RecurrenceInfo); - if (match.Success) - { - var value = match.Value; - var actualId = value.Split("\""); - if (actualId.Count > 1) - { - recurrenceIds.AddIfNotIn(actualId[1]); - } - } - } - - var changedOrDeletedOccurences = FindAppointmentsByRecurrenceId(recurrenceIds, true); - - appointments.AddRangeIfElementsNotIn(changedOrDeletedOccurences); - - return appointments; - } - - public IEnumerable FilterEmployeesWithAppointments(List pEmployeeOids, DateTime pStartTime, DateTime pEndTime) - { - if (pEmployeeOids == null) - { - pEmployeeOids = new List(); - } - - var result = new List(); - var appointments = GetAllActiveAppointmentsForEmployeeInInterval2(pStartTime, pEndTime, pEmployeeOids) ?? new List(); - var gefilterteTermine = - appointments.Where(w => w.EmployeeList != null && w.EmployeeList - .Select(s => s.Employee.Oid.Value) - .Intersect(pEmployeeOids).Any() || !w.EmployeeList.Select(s => s.Employee.Oid.Value) - .Intersect(pEmployeeOids).Any() && pEmployeeOids.Contains(w.Originator.Oid.Value)).ToList(); - - var employee2SchedulerAppointmentsList = gefilterteTermine.Select(s => s.EmployeeList).ToList(); - foreach (var employee2SchedulerAppointments in employee2SchedulerAppointmentsList) - { - foreach (var employee2SchedulerAppointment in employee2SchedulerAppointments) - { - if (employee2SchedulerAppointment.Employee.Oid.HasValue && !result.Contains(employee2SchedulerAppointment.Employee.Oid.Value)) - { - result.Add(employee2SchedulerAppointment.Employee.Oid.Value); - } - } - } - - foreach (var originator in gefilterteTermine.Select(s => s.Originator)) - { - if (originator.Oid.HasValue && !result.Contains(originator.Oid.Value)) - { - result.Add(originator.Oid.Value); - } - } - - var c = CreateCriteria() - .Add(Restrictions.In(AbsenceTime.PropertyName_EmployeeOid, pEmployeeOids)) - .Add(Restrictions.Or( - Restrictions.Or( - Restrictions.Or( - Restrictions.And( - Restrictions.Eq(AbsenceTime.PropertyName_Start, pStartTime), - Restrictions.Eq(AbsenceTime.PropertyName_End, pEndTime)), - Restrictions.And( - Restrictions.And( - Restrictions.Lt(AbsenceTime.PropertyName_Start, pStartTime), - Restrictions.Lt(AbsenceTime.PropertyName_End, pStartTime)), - Restrictions.Gt(AbsenceTime.PropertyName_End, pEndTime))), - Restrictions.And( - Restrictions.Lt(AbsenceTime.PropertyName_Start, pStartTime), - Restrictions.Gt(AbsenceTime.PropertyName_End, pStartTime))), - Restrictions.And( - Restrictions.Gt(AbsenceTime.PropertyName_Start, pStartTime), - Restrictions.Lt(AbsenceTime.PropertyName_End, pEndTime)))); - - var abwesenheiten = c.List(); - - foreach (var abwesenheit in abwesenheiten) - { - result.AddIfNotIn(abwesenheit.EmployeeOid.Value); - } - - return result; - } - - public IEnumerable GetTasksForEmployeeByDate(long employeeOid, DateTime date) - { - var c = CreateCriteria().Add(Restrictions.Between(Task.PropertyName_DueDate, date, date.AddDays(1))).CreateCriteria(Task.PropertyName_EmployeeList, JoinType.InnerJoin) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeOid)).List(); - - return c; - } - - public Wohnheimbuchung GetWohnheimbuchungByWohnheimAndBuchungsdatum(long pWohnheimOid, DateTime pBuchungsdatum) - { - var c = CreateCriteriaIsActive(); - - c.Add(Restrictions.Eq(Wohnheimbuchung.PropertyName_Buchungsdatum, pBuchungsdatum)) - .Add(Restrictions.Eq(Format("{0}.Oid", Wohnheimbuchung.PropertyName_Wohnheim), pWohnheimOid)); - - return c.UniqueResult(); - } - - public List FindWohnheimbuchungsServiceRecords(long pWohnheimbuchungsOid) - { - var c = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_WohnheimbuchungsOid, pWohnheimbuchungsOid)); - - return c.List().ToList(); - } - - public bool CheckIfUserGroupIsLastWithUserGroupEditingRights(List pUserGroupOids) - { - var dc = DetachedCriteria.For() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .SetProjection(Projections.Property(BeWoEntityBase.PropertyName_Oid)); - - var c = CreateCriteriaIsActive() - .Add(Restrictions.Not(Restrictions.In(RightRelation.PropertyName_UserGroupOid, pUserGroupOids))) - .Add(Restrictions.In(RightRelation.PropertyName_RightType, new[] { UserRightType.UserGroupView_View, UserRightType.UserGroupView_Edit, UserRightType.ViewAll, UserRightType.EditAll })) - .Add(Subqueries.PropertyIn(RightRelation.PropertyName_UserGroupOid, dc)); - - var result = c.List(); - var nachUserGroupOidSortiert = new Dictionary>(); - - foreach (var relation in result) - { - nachUserGroupOidSortiert.AddOrUpdateValueInDictionary(relation.UserGroupOid.Value, relation.RightType); - } - - var minRights2 = nachUserGroupOidSortiert.Any(intersection => - intersection.Value.Contains(UserRightType.UserGroupView_Edit) && intersection.Value.Contains(UserRightType.ViewAll) || - intersection.Value.Contains(UserRightType.UserGroupView_Edit) && intersection.Value.Contains(UserRightType.UserGroupView_View) || - intersection.Value.Contains(UserRightType.EditAll) && intersection.Value.Contains(UserRightType.ViewAll) || - intersection.Value.Contains(UserRightType.EditAll) && intersection.Value.Contains(UserRightType.UserGroupView_View)); - - return minRights2 == false; - } - - public ServiceDescription FindServiceDescriptionForWohnheimbuchungsServiceRecord(long pWohnheimbuchungsOid) - { - var dc = DetachedCriteria.For() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_WohnheimbuchungsOid, pWohnheimbuchungsOid)) - .SetProjection(Projections.Property(ServiceRecord.PropertyName_ServiceDescription + ".Oid")); - - var c = CreateCriteriaIsActive() - .Add(Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, dc)).SetMaxResults(1); - - return c.List().FirstOrDefault(); - } - - public IEnumerable FindBargeldkasse(TableID objectTid, long objectOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(Bargeldkasse.PropertyName_ObjectTid, objectTid)) - .Add(Restrictions.Eq(Bargeldkasse.PropertyName_ObjectOid, objectOid)); - - return c.List().ToList(); - } - - public IEnumerable FindArbeitszeiten(TableID objectTid, long objectOid) - { - var c = CreateCriteriaIsActive(); - - if (objectTid == TableID.Employee) - { - c.Add(Restrictions.Eq(Arbeitszeit.PropertyName_EmployeeOid, objectOid)); - } - else - { - c.Add(Restrictions.Eq("Customer", DAOFactory.GenericDAO.GetByID(objectOid))); - } - - - return c.List().ToList(); - } - - public IList FindNotizenKategorien(TableID objectTid, long objectOid) - { - var c = CreateCriteriaIsActiveOrArchived() - .Add(Restrictions.Eq(NotizenKategorie.PropertyName_ObjectTid, objectTid)) - .Add(Restrictions.Eq(NotizenKategorie.PropertyName_ObjectOid, objectOid)); - - return c.List().ToList(); - } - - public IEnumerable FindMedRecordsForCustomer(long pCustomerOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(MedRecord.PropertyName_Customer + ".Oid", pCustomerOid)); - - return c.List().ToList(); - } - - public IEnumerable FindAllChatActiveCustomers() - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_IsChatAktiv, 1)); - - var codes = c.List().Select(s => s.CustomerOid.Value).ToArray(); - - var c2 = CreateCriteriaIsActive() - .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)); - - return c2.List(); - } - - public IEnumerable FindAllChatpartnerEmployee2Customer(long pRecipientOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(Employee2Customer.PropertyName_EmployeeOid, pRecipientOid)) - .Add(Restrictions.Eq(Employee2Customer.PropertyName_Chatpartner, true)); - - return c.List(); - } - - public IEnumerable FindAllChatMessages(long senderOid, long empfaengerOid, int maxNachrichten) - { - var c = CreateCriteriaIsActive() - .Add( - Restrictions.Or( - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid)), - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, empfaengerOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, senderOid)))) - .Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)) - .AddOrder(Order.Desc(ChatMessage.PropertyName_Uhrzeit)) - .SetMaxResults(maxNachrichten); - - return c.List(); - } - - public IEnumerable FindNextChatMessages(long senderOid, long empfaengerOid, int messlateZahl, List list, bool isteam) - { - var c = CreateCriteriaIsActive(); - if (!isteam) - { - c.Add( - Restrictions.Or( - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid)), - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, empfaengerOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, senderOid)))).Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)); - } - else - { - - c.Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, empfaengerOid)); - } - - c.Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, list))); - - c.AddOrder(Order.Desc(ChatMessage.PropertyName_Uhrzeit)); - c.SetMaxResults(messlateZahl); - - return c.List(); - } - - public int CountChatMessages(int aktuelleZahl, long senderOid, long empfaengerOid, bool isTeam) - { - //Zähle hier alle ChatMessages - int xc; - if (!isTeam) - { - xc = - Session.QueryOver() - .Where( - message => - message.SenderPersonOid == senderOid && message.EmpfaengerPersonOid == empfaengerOid || - message.SenderPersonOid == empfaengerOid && message.EmpfaengerPersonOid == senderOid) - .RowCount(); - - } - else - { - xc = - Session.QueryOver() - .Where( - message => - message.TeamOid == empfaengerOid) - .RowCount(); - } - - int ergebnis = xc - aktuelleZahl; - - if (ergebnis < 0) - ergebnis = 0; - - return ergebnis; - } - - public IEnumerable FindAllChatMessagesFromTeam(long senderOid, long teamOid, int messlateZahl) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, teamOid)); - - c.AddOrder(Order.Desc(ChatMessage.PropertyName_Uhrzeit)); - c.SetMaxResults(messlateZahl); - - return c.List(); - } - - public IEnumerable FindAllEmpfängerChatMessages(long senderOid, long empfaengerOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid))); - - return c.List(); - } - - public IEnumerable FindEmpfängerChatMessages(long senderOid, long empfaengerOid, string messageOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid))); - - c.Add(Restrictions.Eq(ChatMessage.PropertyName_MessageId, messageOid)); - - return c.List(); - } - - public IEnumerable FindAllChatActiveEmployees() - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_IsChatAktiv, 1)); - - var codes = c.List().Select(s => s.EmployeeOid.Value).ToArray(); - - var c2 = CreateCriteriaIsActive() - .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)); - - return c2.List(); - } - - public bool CheckIfEmployeeIsAllowedToChat(long pPersonOid) - { - var employee = FindEmployeeWithPersonOid(pPersonOid); - - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_IsChatAktiv, 1)) - .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_EmployeeOid, employee.Oid)); - - var codes = c.List().ToArray(); - - return codes.Length > 0; - } - - public IEnumerable FindAllEmployeeAppCodes(long employeeoid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_EmployeeOid, employeeoid)); - - return c.List(); - } - - public IEnumerable FindAllCustomerAppCodes(long customeroid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_CustomerOid, customeroid)); - - - return c.List(); - } - - public IEnumerable FindAllCustomerAppCodeBenutzer(string benutzername) - { - var c = - CreateCriteriaIsActive() - .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_Benutzername, benutzername)); - - return c.List(); - } + return q.List(); + + } + + public IEnumerable FindServiceDescriptionForCategory(long categoryOid) + { + var c = CreateCriteriaIsActive() + .CreateAlias(ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .Add(Restrictions.Eq("sc." + BeWoEntityBase.PropertyName_Oid, categoryOid)); + + return c.List(); + } + + public IEnumerable FindServiceAccountingsForServiceDescriptions(IList descriptionOids) + { + var c = CreateCriteriaIsActive() + .CreateAlias("ServiceDescription", "sd", JoinType.InnerJoin) + .Add(Restrictions.In("sd." + BeWoEntityBase.PropertyName_Oid, descriptionOids.ToArray())); + + return c.List(); + } + + public IList GetAllMedikamentenverordnungslistenButNewestByCustomerOid(long customerOid, long newestOid, bool isBedarfsListe) + { + var c = CreateCriteria() + .CreateAlias(Medikamentenverordnungsliste.PropertyName_Customer, "c") + .Add(Restrictions.Eq("c." + BeWoEntityBase.PropertyName_Oid, customerOid)) + .Add(Restrictions.Not(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, newestOid))) + .Add(Restrictions.Eq(Medikamentenverordnungsliste.PropertyName_MedListType, isBedarfsListe)); + + return c.List(); + } + + public IList GetAllOpenAppointmentsForEmployee(long employeeOid) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .Add(Restrictions.Not(Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", employeeOid))) + .Add(Restrictions.Or(Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, DateTime.Now.AddDays(-7)), Restrictions.IsNull(SchedulerAppointment.PropertyName_EndDate))) + .CreateCriteria(SchedulerAppointment.PropertyName_EmployeeList) + .Add(Restrictions.And(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", employeeOid), + Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Offen))); + + return c.List(); + } + + public IEnumerable GetAllParticipationNotificationsForEmployee(long employeeOid) + { + var c = CreateCriteria() + .Add(Restrictions.And(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active), Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", employeeOid))) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .Add(Restrictions.Or(Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, DateTime.Now.AddDays(-7)), Restrictions.IsNull(SchedulerAppointment.PropertyName_EndDate))) + .CreateCriteria(SchedulerAppointment.PropertyName_EmployeeList) + .Add(Restrictions.And(Restrictions.And(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_IsPChanged, true), Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", employeeOid))), Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Offen)))) + .Add(Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Verstrichen))) + .Add(Restrictions.IsNull(Employee2SchedulerAppointment.PropertyName_IsPC_CheckedTs)); + + var result = c.List(); + + return result; + } + + public IEnumerable GetRemovedEmp2AppObjectsBySchAppOid(long schAppOid) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment, schAppOid)); + + return c.List(); + } + + public IEnumerable GetAllActiveAndNotDeclinedForEmployeeAppointments(long employeeOid) + { + var detachedCriteria = DetachedCriteria.For() + .Add(Restrictions.And(Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", employeeOid)), + Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, ParticipationAnswer.Absage))); + detachedCriteria.SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); + + var crit = CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .Add(Restrictions.Or(Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", employeeOid), Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria))); + + return crit.List(); + } + + public bool ResetPasswordCodeExists(string code, long userOid) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, userOid)) + .CreateCriteria(ApplicationUser.PropertyName_ResetPasswordInfos) + .Add(Restrictions.Eq(ResetPasswordInfo.PropertyName_Code, code)); + + return c.List().Count > 0; + } + + public bool OverlappingAppointmentsExist(DateTime start, DateTime end, IEnumerable employees, IEnumerable customers, IEnumerable resources, long originator, long? appointmentOid, string recurrenceId = "", int occurrenceIndex = 0) + { + if (employees is null) + { + employees = new List(); + } + + if (customers is null) + { + customers = new List(); + } + + if (resources is null) + { + resources = new List(); + } + + var isRecurrenceException = appointmentOid is null; + var isBeingUpdatedToNormalAppointment = false; + Guid? recurrenceIdToIgnore = null; + + if (appointmentOid != null) + { + // Das Pattern wird geladen, bzw. mit der Ausnahme mit Index 0 verglichen + // Wird die Serie in einen Einzeltermin geändert und es existiert eine Ausnahme mit Index 0, sollte die Ausnahme behalten werden und nicht der Root-Termin + var original = DAOFactory.GenericDAO.LoadByID(appointmentOid.Value); + var ri = original?.GetRecurrenceId(); + if (ri != null && IsNullOrWhiteSpace(recurrenceId)) + { + isBeingUpdatedToNormalAppointment = true; + recurrenceIdToIgnore = ri; + } + } + + Guid? recurrenceGuid = null; + + if (Guid.TryParse(recurrenceId, out var parsedGuid)) + { + recurrenceGuid = parsedGuid; + } + + var betweenDateTimesCriterion = CreateBetweenDateTimesCriterion(start, end, nameof(SchedulerAppointment.StartDate), nameof(SchedulerAppointment.EndDate)); + + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) + .Add(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), false)) + .Add(betweenDateTimesCriterion); + + if (isRecurrenceException == false) + { + criteria.Add(Restrictions.Not(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, appointmentOid))); + } + + var appTmp = criteria.List(); + + var appointments = appTmp.Where(a => + { + if (a.RecurrenceInfo is null) + { + return true; + } + + var recId2 = a.GetRecurrenceIdAndIndex(out var index); + + return !(Guid.TryParse(recurrenceId, out var guid) && guid.Equals(recId2) && occurrenceIndex == index); + }); + + var schedulerAppointments = appointments as IList ?? appointments.ToList(); + + // Serientermine anhand der RecurrenceInfo erzeugen und den schedulerAppointments hinzufügen ------------------------------------------------------------ + var deletedOccurences = schedulerAppointments.Where(app => app.Type == 4).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); + var changedOccurences = schedulerAppointments.Where(app => app.Type == 3).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); + + var recurringAppointmentsCriteria = CreateRecurrenceCriteria(start, end).Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 1)); + + var recurringAppointments = recurringAppointmentsCriteria.List().ToList(); + + if (isBeingUpdatedToNormalAppointment) + { + recurringAppointments = recurringAppointments.Where(root => + { + var recId = root.GetRecurrenceId(); + + if (recId is null || recurrenceIdToIgnore is null) + { + return true; + } + + return !recId.Equals(recurrenceIdToIgnore); + }).ToList(); + + schedulerAppointments = schedulerAppointments.Where(root => + { + var recId = root.GetRecurrenceId(); + + if (recId is null || recurrenceIdToIgnore is null) + { + return true; + } + + return !recId.Equals(recurrenceIdToIgnore); + }).ToList(); + } + + foreach (var appointment in recurringAppointments) + { + var recurrenceInfo = new RecurrenceInfo(); + recurrenceInfo.FromXml(appointment.RecurrenceInfo); + + var occurenceCalculator = OccurrenceCalculator.CreateInstance(recurrenceInfo); + + // Das Muster für die Terminserie wird berechnet + var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); + + if (pattern is null) + { + continue; + } + + pattern.RecurrenceInfo.FromXml(appointment.RecurrenceInfo); + pattern.Start = pattern.RecurrenceInfo.Start; + pattern.End = appointment.EndDate.Value; //pattern.RecurrenceInfo.End; + + var patternId = pattern.RecurrenceInfo.Id.ToString(); + + // In diesem Fall die Start- und Enddaten des zu überprüfenden, neuen Termins + var interval = new TimeInterval(start, end); + + // Die Serientermine werden berechnet (ausnahmslos, d.h. es werden auch bearbeitete und gelöschte Termine erstellt, die herausgefiltert werden müssen). + var occurrences = occurenceCalculator.CalcOccurrences(interval, pattern); + + foreach (var occurrence in occurrences.GetAppointments(interval)) + { + if (appointment.EndDate is null || appointment.StartDate is null) + { + continue; + } + + // Terminindex in der Serie + var index = occurrence.RecurrenceIndex; + + // Das Ende ist offen, da die Terminserie kein Ende hat. Deshalb wird das Ende berechnet. + var duration = (appointment.EndDate.Value - appointment.StartDate.Value).TotalMinutes; + + var guidParsingSuccessful = Guid.TryParse(occurrence.RecurrenceInfo?.Id?.ToString(), out var occurrenceGuid); + + // Der generierte Serientermin muss sich zeitlich mit dem neuen Termin überschneiden + // und darf nicht in der Liste der geänderten Serientermine oder der Liste der gelöschten Serientermine sein. + + var isInIntervalTest = start.IsInInterval(end, occurrence.Start, occurrence.Start.AddMinutes(duration)); + + if (!isInIntervalTest || + changedOccurences != null && changedOccurences.Any(changedOccurence => changedOccurence.PatternId.Equals(patternId) && changedOccurence.Index == index) || + deletedOccurences != null && deletedOccurences.Any(deletedOccurence => deletedOccurence.PatternId.Equals(patternId) && deletedOccurence.Index == index) || + index == occurrenceIndex && guidParsingSuccessful && recurrenceGuid != null && recurrenceGuid.Equals(occurrenceGuid)) + { + continue; + } + + // Prüfen, ob es eine Ausnahme an dem Tag gibt, die zu dem Pattern gehört, um das Pattern auszuschließen + var relatedAppointments = FindAppointmentsByRecurrenceId(new List { recurrenceInfo.Id.ToString() }, true); + var relatedAppointmentsInInterval = relatedAppointments.Where(a => + { + if (a.StartDate == null || a.EndDate == null) + { + return false; + } + + var myStart = a.StartDate.Value.Date; + var myEnd = a.EndDate.Value.Date; + + var isInInterval = start.Date.InBetween(myStart.GetShortDateTime(), myEnd, true); + + return isInInterval && a.Type != 4; + }).ToList(); + + var hasToStop = false; + + // Prüfen, ob es sich bei dem Termin für den Überschneidungen gesucht werden, um zu unterscheiden, ob ein Serientermin in einen normalen geändert wird. + var root = FindRootAppointmentByRecurrenceId(recurrenceInfo.Id.ToString()); + if (root.Oid != null && appointmentOid != null && root.Oid == appointmentOid && root.RecurrenceInfo != null && IsNullOrWhiteSpace(recurrenceId)) + { + hasToStop = true; + } + + // Indices und Ids der RecurrenceInfo vergleichen. Stimmen sie überein, dann wird das generiert Serienelement ignoriert. + if (occurrence.RecurrenceInfo?.Id != null && !hasToStop) + { + if (Guid.TryParse(occurrence.RecurrenceInfo.Id.ToString(), out var guid)) + { + foreach (var relatedAppointment in relatedAppointmentsInInterval) + { + var relatedAppointmentRecurrenceId = relatedAppointment.GetRecurrenceIdAndIndex(out var relatedAppointmentRecurrenceIndex); + + if (relatedAppointmentRecurrenceId != null) + { + if (guid.Equals(relatedAppointmentRecurrenceId) && relatedAppointmentRecurrenceIndex.Equals(occurrence.RecurrenceIndex)) + { + hasToStop = true; + break; + } + } + } + } + } + + if (hasToStop) + { + continue; + } + + var recurringAppointment = new SchedulerAppointment + { + AllDay = occurrence.AllDay, + CustomerList = appointment.CustomerList, + Notice = appointment.Notice, + EmployeeList = appointment.EmployeeList, + EndDate = occurrence.Start.AddMinutes(duration), + FormerBookingSequenceOid = appointment.FormerBookingSequenceOid, + IsPrivate = appointment.IsPrivate, + Location = appointment.Location, + Originator = appointment.Originator, + RecurrenceInfo = occurrence.RecurrenceInfo.ToXml(), + ReminderInfo = appointment.ReminderInfo, + ResourceList = appointment.ResourceList, + StartDate = occurrence.Start, + Subject = appointment.Subject ?? "", + Type = appointment.Type + }; + + schedulerAppointments.AddIfNotIn(recurringAppointment); + } + } + // -------------------------------------------------------------------------------------------------------------------------------------- + + // Falls es sich um eine Ausnahme einer Serie handelt, muss die Serie ignoriert werden + var shouldIgnoreAppointment = false; + if (isRecurrenceException && recurrenceId != null) + { + if (recurrenceGuid.HasValue) + { + shouldIgnoreAppointment = true; + } + } + + var employeeOidList = new List(); + + schedulerAppointments = schedulerAppointments.Where(appointment => appointment.Type != 4).ToList(); + + foreach (var appointment in schedulerAppointments) + { + if (shouldIgnoreAppointment) + { + if (!ShouldDoAppointmentOverlappingCheck(appointment, recurrenceGuid.Value)) + { + continue; + } + } + + employeeOidList.AddRange(appointment.EmployeeList.Select(rel => rel.ParticipationAnswer != ParticipationAnswer.Absage && rel.Employee.Oid != null ? rel.Employee.Oid.Value : 0)); + } + + var hasOverlappingEmployeeAppointments = employeeOidList.Intersect(employees).Any(); + var hasOverlappingCustomerAppointments = schedulerAppointments.Any(app => { return ShouldDoAppointmentOverlappingCheck(app, recurrenceGuid) && app.CustomerList.Select(c => c.Oid ?? 0).Intersect(customers).Any(); }); + + var hasOverlappingResourceAppointments = schedulerAppointments.Any(app => { return ShouldDoAppointmentOverlappingCheck(app, recurrenceGuid) && app.ResourceList.Select(r => r.Oid ?? 0).Intersect(resources).Any(); }); + + var hasOverlappingOriginatorAppointments = schedulerAppointments.Any(appointment => + { + if (!ShouldDoAppointmentOverlappingCheck(appointment, recurrenceGuid)) + { + return false; + } + + return appointment.Originator.Oid.HasValue && + appointment.Originator.Oid.Value == originator && + (appointment.EmployeeList.Count == 0 || appointment.EmployeeList.Any(a => a.Employee.Oid.HasValue && a.Employee.Oid.Value == originator)); + }); + + return hasOverlappingEmployeeAppointments || hasOverlappingCustomerAppointments || hasOverlappingResourceAppointments || hasOverlappingOriginatorAppointments; + } + + private static bool ShouldDoAppointmentOverlappingCheck(SchedulerAppointment appointment, Guid? recurrenceId) + { + if (!appointment.Oid.HasValue || !recurrenceId.HasValue) + { + return true; + } + + var recId = appointment.GetRecurrenceIdAndIndex(out var recIndex); + + if (appointment.RecurrenceInfo is null || recId is null) + { + return true; + } + + return !recId.Equals(recurrenceId); + } + + public IEnumerable GetAllActiveAppointmentsForEmployeeInInterval(DateTime start, DateTime end, long pEmployeeOid) + { + var hasResources = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp)"; + + var criteria = CreateRecurrenceCriteria(start, end) + .Add(Restrictions.Or( + Expression.Sql(new SqlString(hasResources)), + CreateOwnAppointmentsCriteria(pEmployeeOid))); + + return criteria.List(); + } + + public IEnumerable GetAllActiveAppointmentsInInterval(DateTime start, DateTime end) + { + return CreateRecurrenceCriteria(start, end).List(); + } + + public ResourceBooking GetFirstResourceBookingFromSequence(long sequenceOid) + { + return CreateCriteria() + .Add(Restrictions.Eq(ResourceBooking.PropertyName_SequencePosition, 0)) + .CreateAlias(ResourceBooking.PropertyName_Sequence, "s") + .Add(Restrictions.Eq("s." + BeWoEntityBase.PropertyName_Oid, sequenceOid)).UniqueResult(); + } + + public List GetExcludedBookingSequencePositions(long sequenceOid) + { + var c = CreateCriteria() + .Add(Restrictions.Gt(ResourceBooking.PropertyName_SequencePosition, 0)) + .CreateAlias(ResourceBooking.PropertyName_Sequence, "s") + .Add(Restrictions.Eq("s." + BeWoEntityBase.PropertyName_Oid, sequenceOid)).List(); + + return c.Select(s => s.SequencePosition).ToList(); + } + + public IEnumerable GetInvoiceBases(DateTime? startDate, DateTime? endDate, bool useInvoiceDate = true) + { + var lCriteria = CreateCriteriaIsActive(); + if (useInvoiceDate) + { + if (startDate.HasValue) + lCriteria.Add(Restrictions.Ge(InvoiceBase.PropertyName_InvoiceDate, startDate)); + if (endDate.HasValue) + lCriteria.Add(Restrictions.Le(InvoiceBase.PropertyName_InvoiceDate, endDate)); + } + else + { + if (startDate.HasValue) + lCriteria.Add(Restrictions.Ge(InvoiceBase.PropertyName_AccountingPeriodEnd, startDate)); + if (endDate.HasValue) + lCriteria.Add(Restrictions.Le(InvoiceBase.PropertyName_AccountingPeriodStart, endDate)); + } + + return lCriteria.List(); + } + + public IEnumerable GetGkvAbrechnungen(DateTime? startDate, DateTime? endDate, bool useInvoiceDate = true) + { + if (endDate.HasValue) + endDate = endDate.Value.Date.AddDays(1).AddMilliseconds(-1); + + var lCriteria = CreateCriteriaIsActive(); + if (useInvoiceDate) + { + if (startDate.HasValue) + lCriteria.Add(Restrictions.Ge(nameof(GkvAbrechnung.ErstelltAm), startDate)); + if (endDate.HasValue) + lCriteria.Add(Restrictions.Le(nameof(GkvAbrechnung.ErstelltAm), endDate)); + } + else + { + if (startDate.HasValue) + lCriteria.Add(Restrictions.Ge(nameof(GkvAbrechnung.AbrechnungsZeitraumEnde), startDate)); + if (endDate.HasValue) + lCriteria.Add(Restrictions.Le(nameof(GkvAbrechnung.AbrechnungsZeitraumStart), endDate)); + } + + return lCriteria.List(); + } + + public IEnumerable GetGkvTransferProtokollByDateRange(DateTime? start, DateTime? end) + { + var lCriteria = CreateCriteria(); + + if (start.HasValue) + lCriteria.Add(Restrictions.Ge(nameof(GkvTransferProtokoll.ErstelltAm), start)); + if (end.HasValue) + lCriteria.Add(Restrictions.Le(nameof(GkvTransferProtokoll.ErstelltAm), end)); + + return lCriteria.List(); + } + + public IEnumerable GetInvoiceBases(DateTime? startDate, DateTime? endDate, long costBearerOid, String invoiceId) + { + var lCriteria = CreateCriteriaIsActive(); + + if (startDate.HasValue) + lCriteria.Add(Restrictions.Ge(InvoiceBase.PropertyName_InvoiceDate, startDate)); + + if (endDate.HasValue) + lCriteria.Add(Restrictions.Le(InvoiceBase.PropertyName_InvoiceDate, endDate)); + + lCriteria.Add(Restrictions.Eq(InvoiceBase.PropertyName_InvoiceId, invoiceId)); + + lCriteria.CreateAlias(InvoiceBase.PropertyName_CostBearer2SupportConcept, "c2s"); + lCriteria.CreateAlias("c2s." + CostBearer2SupportConcept.PropertyName_CostBearer, "cb"); + lCriteria.Add(Restrictions.Eq("cb.Oid", costBearerOid)); + lCriteria.Add(Restrictions.Eq("c2s.CostBearer.Oid", costBearerOid)); + + return lCriteria.List(); + } + + public IEnumerable GetAllActiveSupportConceptsByCustomers(List customerOids, bool expiredOnesToo = false) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .CreateAlias(SupportConcept.PropertyName_Customer, "c") + .Add(Restrictions.In("c." + BeWoEntityBase.PropertyName_Oid, customerOids)); + + if (expiredOnesToo) + { + + } + + return c.List(); + } + + public IEnumerable FindServiceRecordsForDays(long? costBearer2SupportConceptOid, int dayCount, long? employeeOid) + { + var minStart = DateTime.Now.GetShortDateTime().AddDays(-dayCount); + var c = CreateCriteriaIsActive(); + + if (costBearer2SupportConceptOid.HasValue) + { + c.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); + } + else + { + c.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + } + + if (dayCount > 0) + { + c.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minStart)); + } + + return c.List(); + } + + public IEnumerable GetActiveTextModuleByServiceCategory(long pServiceCategoryOid) + { + var c = CreateCriteria(); + + c.Add(Restrictions.Or(Restrictions.Eq(TextModule.PropertyName_ServiceCategory + ".Oid", pServiceCategoryOid), Restrictions.IsNull(TextModule.PropertyName_ServiceCategory))); + + return c.List(); + } + + public IEnumerable GetAllActiveAppointmentsForEmployeeInInterval2(DateTime start, DateTime end, List pEmployeeOids) + { + var mainCriteria = CreateRecurrenceCriteria(start, end); + + var detachedCriteria1 = DetachedCriteria.For() + .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pEmployeeOids)) + .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); + var employee2SchedCrit = Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria1); + + var originatorCrit = Restrictions.In(SchedulerAppointment.PropertyName_Originator, pEmployeeOids); + + var detachedCriteria2 = DetachedCriteria.For("e2s2") + .SetProjection(Projections.Property(BeWoEntityBase.PropertyName_Oid)) + .Add(Restrictions.EqProperty("e2s2." + Employee2SchedulerAppointment.PropertyName_SchedulerAppointment, "sa.Oid")); + + var employee2SchedCrit2 = Subqueries.NotExists(detachedCriteria2); + + var and = Restrictions.And(originatorCrit, employee2SchedCrit2); + + ICriterion employeeCriterion = Restrictions.Or(employee2SchedCrit, and); + + mainCriteria.Add(employeeCriterion); + + var appointments = mainCriteria.List(); + + var exceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null && w.Type == 3).ToList(); + + var exceptionIds = new List(); + var regex = new Regex("(Id=\\\"[a-z0-9-]+\\\")"); + + foreach (var appointment in exceptionalRecurrenceInfos) + { + var match = regex.Match(appointment.RecurrenceInfo); + if (match.Success) + { + var value = match.Value; + var actualId = value.Split("\""); + if (actualId.Count > 1) + { + var id = actualId[1]; + + if (!appointments.Any(w => w.RecurrenceInfo != null && w.RecurrenceInfo.Contains(id) && w.Type == 1)) + { + exceptionIds.Add(appointment.Oid.Value); + } + } + } + } + + var exceptionsToModify = appointments.Where(w => w.Oid.HasValue && exceptionIds.Contains(w.Oid.Value)).ToList(); + + foreach (var exception in exceptionsToModify) + { + var replacingAppointment = new SchedulerAppointment + { + Oid = exception.Oid.Value * -1, + Version = 1, + Type = 4, + RecurrenceInfo = exception.RecurrenceInfo, + Originator = exception.Originator, + EmployeeList = exception.EmployeeList, + CustomerList = exception.CustomerList, + ResourceList = exception.ResourceList + }; + + exception.RecurrenceInfo = null; + exception.Type = 0; + + appointments.Add(replacingAppointment); + } + + var recurrenceIds = new List(); + + var allExceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null); + foreach (var appointment in allExceptionalRecurrenceInfos) + { + var match = regex.Match(appointment.RecurrenceInfo); + if (match.Success) + { + var value = match.Value; + var actualId = value.Split("\""); + if (actualId.Count > 1) + { + recurrenceIds.AddIfNotIn(actualId[1]); + } + } + } + + var changedOrDeletedOccurences = FindAppointmentsByRecurrenceId(recurrenceIds, true); + + appointments.AddRangeIfElementsNotIn(changedOrDeletedOccurences); + + return appointments; + } + + public IEnumerable FilterEmployeesWithAppointments(List pEmployeeOids, DateTime pStartTime, DateTime pEndTime) + { + if (pEmployeeOids == null) + { + pEmployeeOids = new List(); + } + + var result = new List(); + var appointments = GetAllActiveAppointmentsForEmployeeInInterval2(pStartTime, pEndTime, pEmployeeOids) ?? new List(); + var gefilterteTermine = + appointments.Where(w => w.EmployeeList != null && w.EmployeeList + .Select(s => s.Employee.Oid.Value) + .Intersect(pEmployeeOids).Any() || !w.EmployeeList.Select(s => s.Employee.Oid.Value) + .Intersect(pEmployeeOids).Any() && pEmployeeOids.Contains(w.Originator.Oid.Value)).ToList(); + + var employee2SchedulerAppointmentsList = gefilterteTermine.Select(s => s.EmployeeList).ToList(); + foreach (var employee2SchedulerAppointments in employee2SchedulerAppointmentsList) + { + foreach (var employee2SchedulerAppointment in employee2SchedulerAppointments) + { + if (employee2SchedulerAppointment.Employee.Oid.HasValue && !result.Contains(employee2SchedulerAppointment.Employee.Oid.Value)) + { + result.Add(employee2SchedulerAppointment.Employee.Oid.Value); + } + } + } + + foreach (var originator in gefilterteTermine.Select(s => s.Originator)) + { + if (originator.Oid.HasValue && !result.Contains(originator.Oid.Value)) + { + result.Add(originator.Oid.Value); + } + } + + var c = CreateCriteria() + .Add(Restrictions.In(AbsenceTime.PropertyName_EmployeeOid, pEmployeeOids)) + .Add(Restrictions.Or( + Restrictions.Or( + Restrictions.Or( + Restrictions.And( + Restrictions.Eq(AbsenceTime.PropertyName_Start, pStartTime), + Restrictions.Eq(AbsenceTime.PropertyName_End, pEndTime)), + Restrictions.And( + Restrictions.And( + Restrictions.Lt(AbsenceTime.PropertyName_Start, pStartTime), + Restrictions.Lt(AbsenceTime.PropertyName_End, pStartTime)), + Restrictions.Gt(AbsenceTime.PropertyName_End, pEndTime))), + Restrictions.And( + Restrictions.Lt(AbsenceTime.PropertyName_Start, pStartTime), + Restrictions.Gt(AbsenceTime.PropertyName_End, pStartTime))), + Restrictions.And( + Restrictions.Gt(AbsenceTime.PropertyName_Start, pStartTime), + Restrictions.Lt(AbsenceTime.PropertyName_End, pEndTime)))); + + var abwesenheiten = c.List(); + + foreach (var abwesenheit in abwesenheiten) + { + result.AddIfNotIn(abwesenheit.EmployeeOid.Value); + } + + return result; + } + + public IEnumerable GetTasksForEmployeeByDate(long employeeOid, DateTime date) + { + var c = CreateCriteria().Add(Restrictions.Between(Task.PropertyName_DueDate, date, date.AddDays(1))).CreateCriteria(Task.PropertyName_EmployeeList, JoinType.InnerJoin) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, employeeOid)).List(); + + return c; + } + + public Wohnheimbuchung GetWohnheimbuchungByWohnheimAndBuchungsdatum(long pWohnheimOid, DateTime pBuchungsdatum) + { + var c = CreateCriteriaIsActive(); + + c.Add(Restrictions.Eq(Wohnheimbuchung.PropertyName_Buchungsdatum, pBuchungsdatum)) + .Add(Restrictions.Eq(Format("{0}.Oid", Wohnheimbuchung.PropertyName_Wohnheim), pWohnheimOid)); + + return c.UniqueResult(); + } + + public List FindWohnheimbuchungsServiceRecords(long pWohnheimbuchungsOid) + { + var c = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_WohnheimbuchungsOid, pWohnheimbuchungsOid)); + + return c.List().ToList(); + } + + public bool CheckIfUserGroupIsLastWithUserGroupEditingRights(List pUserGroupOids) + { + var dc = DetachedCriteria.For() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .SetProjection(Projections.Property(BeWoEntityBase.PropertyName_Oid)); + + var c = CreateCriteriaIsActive() + .Add(Restrictions.Not(Restrictions.In(RightRelation.PropertyName_UserGroupOid, pUserGroupOids))) + .Add(Restrictions.In(RightRelation.PropertyName_RightType, new[] { UserRightType.UserGroupView_View, UserRightType.UserGroupView_Edit, UserRightType.ViewAll, UserRightType.EditAll })) + .Add(Subqueries.PropertyIn(RightRelation.PropertyName_UserGroupOid, dc)); + + var result = c.List(); + var nachUserGroupOidSortiert = new Dictionary>(); + + foreach (var relation in result) + { + nachUserGroupOidSortiert.AddOrUpdateValueInDictionary(relation.UserGroupOid.Value, relation.RightType); + } + + var minRights2 = nachUserGroupOidSortiert.Any(intersection => + intersection.Value.Contains(UserRightType.UserGroupView_Edit) && intersection.Value.Contains(UserRightType.ViewAll) || + intersection.Value.Contains(UserRightType.UserGroupView_Edit) && intersection.Value.Contains(UserRightType.UserGroupView_View) || + intersection.Value.Contains(UserRightType.EditAll) && intersection.Value.Contains(UserRightType.ViewAll) || + intersection.Value.Contains(UserRightType.EditAll) && intersection.Value.Contains(UserRightType.UserGroupView_View)); + + return minRights2 == false; + } + + public ServiceDescription FindServiceDescriptionForWohnheimbuchungsServiceRecord(long pWohnheimbuchungsOid) + { + var dc = DetachedCriteria.For() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_WohnheimbuchungsOid, pWohnheimbuchungsOid)) + .SetProjection(Projections.Property(ServiceRecord.PropertyName_ServiceDescription + ".Oid")); + + var c = CreateCriteriaIsActive() + .Add(Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, dc)).SetMaxResults(1); + + return c.List().FirstOrDefault(); + } + + public IEnumerable FindBargeldkasse(TableID objectTid, long objectOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(Bargeldkasse.PropertyName_ObjectTid, objectTid)) + .Add(Restrictions.Eq(Bargeldkasse.PropertyName_ObjectOid, objectOid)); + + return c.List().ToList(); + } + + public IEnumerable FindArbeitszeiten(TableID objectTid, long objectOid) + { + var c = CreateCriteriaIsActive(); + + if (objectTid == TableID.Employee) + { + c.Add(Restrictions.Eq(Arbeitszeit.PropertyName_EmployeeOid, objectOid)); + } + else + { + c.Add(Restrictions.Eq("Customer", DAOFactory.GenericDAO.GetByID(objectOid))); + } + + + return c.List().ToList(); + } + + public IList FindNotizenKategorien(TableID objectTid, long objectOid) + { + var c = CreateCriteriaIsActiveOrArchived() + .Add(Restrictions.Eq(NotizenKategorie.PropertyName_ObjectTid, objectTid)) + .Add(Restrictions.Eq(NotizenKategorie.PropertyName_ObjectOid, objectOid)); + + return c.List().ToList(); + } + + public IEnumerable FindMedRecordsForCustomer(long pCustomerOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(MedRecord.PropertyName_Customer + ".Oid", pCustomerOid)); + + return c.List().ToList(); + } + + public IEnumerable FindAllChatActiveCustomers() + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_IsChatAktiv, 1)); + + var codes = c.List().Select(s => s.CustomerOid.Value).ToArray(); + + var c2 = CreateCriteriaIsActive() + .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)); + + return c2.List(); + } + + public IEnumerable FindAllChatpartnerEmployee2Customer(long pRecipientOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(Employee2Customer.PropertyName_EmployeeOid, pRecipientOid)) + .Add(Restrictions.Eq(Employee2Customer.PropertyName_Chatpartner, true)); + + return c.List(); + } + + public IEnumerable FindAllChatMessages(long senderOid, long empfaengerOid, int maxNachrichten) + { + var c = CreateCriteriaIsActive() + .Add( + Restrictions.Or( + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid)), + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, empfaengerOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, senderOid)))) + .Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)) + .AddOrder(Order.Desc(ChatMessage.PropertyName_Uhrzeit)) + .SetMaxResults(maxNachrichten); + + return c.List(); + } + + public IEnumerable FindNextChatMessages(long senderOid, long empfaengerOid, int messlateZahl, List list, bool isteam) + { + var c = CreateCriteriaIsActive(); + if (!isteam) + { + c.Add( + Restrictions.Or( + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid)), + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, empfaengerOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, senderOid)))).Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)); + } + else + { + + c.Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, empfaengerOid)); + } + + c.Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, list))); + + c.AddOrder(Order.Desc(ChatMessage.PropertyName_Uhrzeit)); + c.SetMaxResults(messlateZahl); + + return c.List(); + } + + public int CountChatMessages(int aktuelleZahl, long senderOid, long empfaengerOid, bool isTeam) + { + //Zähle hier alle ChatMessages + int xc; + if (!isTeam) + { + xc = + Session.QueryOver() + .Where( + message => + message.SenderPersonOid == senderOid && message.EmpfaengerPersonOid == empfaengerOid || + message.SenderPersonOid == empfaengerOid && message.EmpfaengerPersonOid == senderOid) + .RowCount(); + + } + else + { + xc = + Session.QueryOver() + .Where( + message => + message.TeamOid == empfaengerOid) + .RowCount(); + } + + int ergebnis = xc - aktuelleZahl; + + if (ergebnis < 0) + ergebnis = 0; + + return ergebnis; + } + + public IEnumerable FindAllChatMessagesFromTeam(long senderOid, long teamOid, int messlateZahl) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, teamOid)); + + c.AddOrder(Order.Desc(ChatMessage.PropertyName_Uhrzeit)); + c.SetMaxResults(messlateZahl); + + return c.List(); + } + + public IEnumerable FindAllEmpfängerChatMessages(long senderOid, long empfaengerOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid))); + + return c.List(); + } + + public IEnumerable FindEmpfängerChatMessages(long senderOid, long empfaengerOid, string messageOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, senderOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, empfaengerOid))); + + c.Add(Restrictions.Eq(ChatMessage.PropertyName_MessageId, messageOid)); + + return c.List(); + } + + public IEnumerable FindAllChatActiveEmployees() + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_IsChatAktiv, 1)); + + var codes = c.List().Select(s => s.EmployeeOid.Value).ToArray(); + + var c2 = CreateCriteriaIsActive() + .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)); + + return c2.List(); + } + + public bool CheckIfEmployeeIsAllowedToChat(long pPersonOid) + { + var employee = FindEmployeeWithPersonOid(pPersonOid); + + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_IsChatAktiv, 1)) + .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_EmployeeOid, employee.Oid)); + + var codes = c.List().ToArray(); + + return codes.Length > 0; + } + + public IEnumerable FindAllEmployeeAppCodes(long employeeoid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(EmployeeAPPCode.PropertyName_EmployeeOid, employeeoid)); + + return c.List(); + } + + public IEnumerable FindAllCustomerAppCodes(long customeroid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_CustomerOid, customeroid)); + + + return c.List(); + } + + public IEnumerable FindAllCustomerAppCodeBenutzer(string benutzername) + { + var c = + CreateCriteriaIsActive() + .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_Benutzername, benutzername)); + + return c.List(); + } - public IEnumerable FindAllChatMessagesForAndroid(long pSenderOid, long pRecipientOid, List pExceptions, bool pForTeam) - { - var c = CreateCriteriaIsActive() - .Add( - Restrictions.Or( - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pSenderOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pRecipientOid)), - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pRecipientOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pSenderOid)))) - .Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))) - .Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)); - - if (pForTeam) - { - c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, pRecipientOid)) - .Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))); - } + public IEnumerable FindAllChatMessagesForAndroid(long pSenderOid, long pRecipientOid, List pExceptions, bool pForTeam) + { + var c = CreateCriteriaIsActive() + .Add( + Restrictions.Or( + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pSenderOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pRecipientOid)), + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pRecipientOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pSenderOid)))) + .Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))) + .Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)); + + if (pForTeam) + { + c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, pRecipientOid)) + .Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))); + } - return c.List(); - } - - //public IEnumerable FindAllUnreadChatMessages(List pExceptions) - //{ - // var c = CreateCriteriaIsActive() - // .Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))); - - // return c.List(); - //} - - public Dictionary FindAllChatAuthorizedPersonsForEmployee(long pEmployeeOid) - { - var result = new Dictionary(); + return c.List(); + } + + //public IEnumerable FindAllUnreadChatMessages(List pExceptions) + //{ + // var c = CreateCriteriaIsActive() + // .Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))); + + // return c.List(); + //} + + public Dictionary FindAllChatAuthorizedPersonsForEmployee(long pEmployeeOid) + { + var result = new Dictionary(); - var employee = CreateCriteriaIsActive().Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pEmployeeOid)).UniqueResult(); + var employee = CreateCriteriaIsActive().Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pEmployeeOid)).UniqueResult(); - var relatedCustomerOids = employee.Employee2CustomerList.Select(s => s.CustomerOid.Value); + var relatedCustomerOids = employee.Employee2CustomerList.Select(s => s.CustomerOid.Value); - var c1 = CreateCriteriaIsActive() - .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_IsChatAktiv, 1)); - var codes = c1.List().Select(s => s.CustomerOid.Value).ToArray(); - var c2 = CreateCriteriaIsActive() - .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)) - .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, relatedCustomerOids.ToList())); + var c1 = CreateCriteriaIsActive() + .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_IsChatAktiv, 1)); + var codes = c1.List().Select(s => s.CustomerOid.Value).ToArray(); + var c2 = CreateCriteriaIsActive() + .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)) + .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, relatedCustomerOids.ToList())); - var customers = c2.List(); - var employees = FindAllChatActiveEmployees(); + var customers = c2.List(); + var employees = FindAllChatActiveEmployees(); - employees.DoForEach(d => result.Add(d.Person, true)); - customers.DoForEach(d => result.Add(d.Person, false)); + employees.DoForEach(d => result.Add(d.Person, true)); + customers.DoForEach(d => result.Add(d.Person, false)); - return result; - } - - public Dictionary FindImagesForChatAuthorizedPersonsForEmployee(long pEmployeeOid) - { - var result = new Dictionary(); - - var employee = CreateCriteriaIsActive().Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pEmployeeOid)).UniqueResult(); - - var relatedCustomerOids = employee.Employee2CustomerList.Select(s => s.CustomerOid.Value); - - var c1 = CreateCriteriaIsActive() - .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_IsChatAktiv, 1)); - var codes = c1.List().Select(s => s.CustomerOid.Value).ToArray(); - var c2 = CreateCriteriaIsActive() - .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)) - .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, relatedCustomerOids.ToList())); - - var customers = c2.List(); - var employees = FindAllChatActiveEmployees(); - - //foreach (var customer in customers.Where(w => w.CustomerImage != null)) - //{ - // result.Add(customer.Person.Oid.Value, customer.CustomerImage); - //} - - //foreach (var emp in employees.Where(w => w.EmployeeImage != null)) - //{ - // result.Add(emp.Person.Oid.Value, emp.EmployeeImage); - //} - - return result; - } - - public IEnumerable FindUnreadChatMessagesForRecipient(long pRecipientOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pRecipientOid)) - .Add(Restrictions.Eq(ChatMessage.PropertyName_IstGelesen, 0)); - - return c.List(); - } - - public IEnumerable FindNewestChatMessages(long pRecipientPersonOid) - { - var blubb = FindTeamsOfEmployee(pRecipientPersonOid); - - var c = CreateCriteria(); - c.Add(Subqueries.PropertyIn("Oid", - DetachedCriteria.For() - - .Add( - Restrictions.Or( - Restrictions.And( - Restrictions.Or( - Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pRecipientPersonOid), - Restrictions.Eq(NewestChatMessage.PropertyName_SenderPersonOid, pRecipientPersonOid)), - Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, false)), - Restrictions.And(Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, true), Restrictions.In(NewestChatMessage.PropertyName_RecipientPersonOid, blubb.Select(s => s.Oid.Value).ToArray()))) - ) - - .SetProjection(Projections.Property("ChatMessageOid")))); - - var query = ToSql(c); - - return c.List(); - } + return result; + } + + public Dictionary FindImagesForChatAuthorizedPersonsForEmployee(long pEmployeeOid) + { + var result = new Dictionary(); + + var employee = CreateCriteriaIsActive().Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pEmployeeOid)).UniqueResult(); + + var relatedCustomerOids = employee.Employee2CustomerList.Select(s => s.CustomerOid.Value); + + var c1 = CreateCriteriaIsActive() + .Add(Restrictions.Eq(CustomerAPPCode.PropertyName_IsChatAktiv, 1)); + var codes = c1.List().Select(s => s.CustomerOid.Value).ToArray(); + var c2 = CreateCriteriaIsActive() + .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, codes)) + .Add(Restrictions.In(BeWoEntityBase.PropertyName_Oid, relatedCustomerOids.ToList())); + + var customers = c2.List(); + var employees = FindAllChatActiveEmployees(); + + //foreach (var customer in customers.Where(w => w.CustomerImage != null)) + //{ + // result.Add(customer.Person.Oid.Value, customer.CustomerImage); + //} + + //foreach (var emp in employees.Where(w => w.EmployeeImage != null)) + //{ + // result.Add(emp.Person.Oid.Value, emp.EmployeeImage); + //} + + return result; + } + + public IEnumerable FindUnreadChatMessagesForRecipient(long pRecipientOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pRecipientOid)) + .Add(Restrictions.Eq(ChatMessage.PropertyName_IstGelesen, 0)); + + return c.List(); + } + + public IEnumerable FindNewestChatMessages(long pRecipientPersonOid) + { + var blubb = FindTeamsOfEmployee(pRecipientPersonOid); + + var c = CreateCriteria(); + c.Add(Subqueries.PropertyIn("Oid", + DetachedCriteria.For() + + .Add( + Restrictions.Or( + Restrictions.And( + Restrictions.Or( + Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pRecipientPersonOid), + Restrictions.Eq(NewestChatMessage.PropertyName_SenderPersonOid, pRecipientPersonOid)), + Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, false)), + Restrictions.And(Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, true), Restrictions.In(NewestChatMessage.PropertyName_RecipientPersonOid, blubb.Select(s => s.Oid.Value).ToArray()))) + ) + + .SetProjection(Projections.Property("ChatMessageOid")))); + + var query = ToSql(c); + + return c.List(); + } - public static string ToSql(ICriteria criteria) - { - var criteriaImpl = (CriteriaImpl)criteria; - var sessionImpl = (SessionImpl)criteriaImpl.Session; - var factory = (ISessionFactoryImplementor)sessionImpl.SessionFactory; - var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName); - - if (implementors.Length == 0) - { - return "No entity or class name found!"; - } - - var loader = new CriteriaLoader((IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters); - - return loader.SqlString.ToString(); - } - - public IEnumerable FindChatMessageIds(List messageIds) - { - var c = CreateCriteria() - .Add(Restrictions.In(ChatMessage.PropertyName_MessageId, messageIds)); - - var liste = c.List(); - - return liste.Select(s => s.MessageId); - } - - public IEnumerable LoadChatMessagesChunkwise(string pMessageId, long pRecipientOid, long pSenderOid, bool pForTeam, List pExceptions, bool pIsInitialCall) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Or( - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pSenderOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pRecipientOid)), - Restrictions.And( - Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pRecipientOid), - Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pSenderOid)))); - - c.Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)); - - if (pForTeam) - { - c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, pRecipientOid)); - } - - if (!IsNullOrEmpty(pMessageId)) - { - var c1 = CreateCriteriaIsActive() - .Add(Restrictions.Eq(ChatMessage.PropertyName_MessageId, pMessageId)) - .AddOrder(Order.Desc(BeWoEntityBase.PropertyName_InsTs)); - - var list = c1.List(); - if (list.Count > 0) - { - var lastLoadedChatMessage = c1.List().First(); - - c.Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))); - - if (pIsInitialCall) - { - c.Add(Restrictions.Gt(BeWoEntityBase.PropertyName_InsTs, lastLoadedChatMessage.InsTs)); - } - } - } - - c.AddOrder(Order.Desc(BeWoEntityBase.PropertyName_InsTs)); - c.SetMaxResults(50); - - var sqlQeury = ToSql(c); + public static string ToSql(ICriteria criteria) + { + var criteriaImpl = (CriteriaImpl)criteria; + var sessionImpl = (SessionImpl)criteriaImpl.Session; + var factory = (ISessionFactoryImplementor)sessionImpl.SessionFactory; + var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName); + + if (implementors.Length == 0) + { + return "No entity or class name found!"; + } + + var loader = new CriteriaLoader((IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters); + + return loader.SqlString.ToString(); + } + + public IEnumerable FindChatMessageIds(List messageIds) + { + var c = CreateCriteria() + .Add(Restrictions.In(ChatMessage.PropertyName_MessageId, messageIds)); + + var liste = c.List(); + + return liste.Select(s => s.MessageId); + } + + public IEnumerable LoadChatMessagesChunkwise(string pMessageId, long pRecipientOid, long pSenderOid, bool pForTeam, List pExceptions, bool pIsInitialCall) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Or( + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pSenderOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pRecipientOid)), + Restrictions.And( + Restrictions.Eq(ChatMessage.PropertyName_SenderPersonOid, pRecipientOid), + Restrictions.Eq(ChatMessage.PropertyName_EmpfaengerPersonOid, pSenderOid)))); + + c.Add(Restrictions.IsNull(ChatMessage.PropertyName_TeamOid)); + + if (pForTeam) + { + c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(ChatMessage.PropertyName_TeamOid, pRecipientOid)); + } + + if (!IsNullOrEmpty(pMessageId)) + { + var c1 = CreateCriteriaIsActive() + .Add(Restrictions.Eq(ChatMessage.PropertyName_MessageId, pMessageId)) + .AddOrder(Order.Desc(BeWoEntityBase.PropertyName_InsTs)); + + var list = c1.List(); + if (list.Count > 0) + { + var lastLoadedChatMessage = c1.List().First(); + + c.Add(Restrictions.Not(Restrictions.In(ChatMessage.PropertyName_MessageId, pExceptions))); + + if (pIsInitialCall) + { + c.Add(Restrictions.Gt(BeWoEntityBase.PropertyName_InsTs, lastLoadedChatMessage.InsTs)); + } + } + } + + c.AddOrder(Order.Desc(BeWoEntityBase.PropertyName_InsTs)); + c.SetMaxResults(50); + + var sqlQeury = ToSql(c); - var result = c.List(); + var result = c.List(); - return result; - } + return result; + } - public IList GetChatMediaMessagesForChatMessage(long chatMessageOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(ChatMediaMessage.PropertyName_ChatMessageOid, chatMessageOid)); + public IList GetChatMediaMessagesForChatMessage(long chatMessageOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(ChatMediaMessage.PropertyName_ChatMessageOid, chatMessageOid)); - return c.List(); - } - - public NewestChatMessage GetNewestChatMessageForConversation(long pRecipientPersonOid, long pSenderPersonOid, bool pIsTeam) - { - var teams = new List(); - - if (pIsTeam) - { - var employee = FindEmployeeWithPersonOid(pSenderPersonOid); - if (employee != null) - { - teams.AddRange(FindTeamsOfEmployee(employee.Oid.Value).Select(s => s.Oid.Value)); - } - } - - var c = CreateCriteria(); - - if (pIsTeam) - { - c.Add(Restrictions.And(Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, true), - Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pRecipientPersonOid))); - } - else - { - c.Add( - Restrictions.And( - Restrictions.Or( - Restrictions.And( - Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pRecipientPersonOid), - Restrictions.Eq(NewestChatMessage.PropertyName_SenderPersonOid, pSenderPersonOid)), - Restrictions.And( - Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pSenderPersonOid), - Restrictions.Eq(NewestChatMessage.PropertyName_SenderPersonOid, pRecipientPersonOid))), - - Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, false))); - } - - return c.UniqueResult(); - } - - public IList GetAllOrganisation2PersonRelations(long personOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, personOid)).UniqueResult().Organisation2Persons.Select(s => s.Organisation).ToList(); - - - return c; - } - - public IList GetAllPerson2OrganisationRelations(long organisationOid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, organisationOid)).UniqueResult().Organisation2PersonList.Select(s => s.Person).ToList(); - - return c; - } - - public ServiceRecord FindServiceRecordforHistory(long? pServiceRecordOid) - { - var c = CreateCriteria().Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pServiceRecordOid)); - - return c.UniqueResult(); - } - - public ArbeitszeitListe FindEmployeeArbeitszeitListe(long employeeOid) - { - var c = CreateCriteria().Add(Restrictions.Eq(Arbeitszeit.PropertyName_EmployeeOid, employeeOid)); - - List nAr = new List(); - - - foreach (var item in c.List()) - { - nAr.Add(item.Oid.Value); - } - - ArbeitszeitListe a = new ArbeitszeitListe(); - a.Arbeitszeit = c.List().ToList(); - - if (nAr.Count != 0) - { - var cEintrag = - CreateCriteria() - .Add(Restrictions.In(ArbeitszeitEintrag.PropertyName_ArbeitszeitOid, nAr)); - - - - a.ArbeitszeitEintrag = cEintrag.List().ToList(); - - } - - return a; - } - - public IList FindCostBearer2SupportConceptForDate(DateTime datum) - { - var c = CreateCriteriaIsActive(); - - return c - .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) - .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .Add(Restrictions.Or( - Restrictions.And(Restrictions.Le("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedStartDate, datum), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate, datum)), - Restrictions.And(Restrictions.Le("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedStartDate, datum), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate, datum)))) - .List().Distinct().ToList(); - } - - public IList FindSupportConceptsInDateRange(bool auchArchivierteHolen, DateTime start, DateTime end) - { - ICriteria c = null; - if (auchArchivierteHolen) - { - c = CreateCriteriaIsActiveOrArchived(); - } - else - { - c = CreateCriteriaIsActive(); - } - - - return c - .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) - .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) - .Add( - Restrictions.Or(Restrictions.And( - Restrictions.And(Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedStartDate), Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate)), - Restrictions.And(Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedStartDate), Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate))), - Restrictions.Or( - Restrictions.And(Restrictions.Lt("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedStartDate, end), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate, start)), - Restrictions.And(Restrictions.Lt("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedStartDate, end), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate, start))))) - .List().Distinct().ToList(); - } - - public IList FindQuittierungsCheckWithCustomerOids(List oids) - { - var c = CreateCriteria() - .Add(Restrictions.In(QuittierungsCheck.PropertyName_CustomerOid, oids)) - .List(); - - return c; - } - - public IList FindQuittierungsCheckWithCustomerOid(long oid) - { - - var c = CreateCriteria() - .Add(Restrictions.Eq(QuittierungsCheck.PropertyName_CustomerOid, oid)); - //.UniqueResult(); - - - return c.List(); - } - - public IList FindTimeSheetsForMonth(DateTime monat) - { - DateTime start = new DateTime(monat.Year, monat.Month, 1); - DateTime end = start.AddMonths(1); - - return CreateCriteria() - .Add(Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, end), Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, start))) - .List(); - } - - public Timesheet FindEmployeeTimeSheetForMonth(long employeeOid, DateTime monat) - { - DateTime start = new DateTime(monat.Year, monat.Month, 1); - DateTime end = start.AddMonths(1); - - return CreateCriteria() - .Add(Restrictions.Eq("EmployeeOid", employeeOid)) - .Add(Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, end), - Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, start))) - .List().FirstOrDefault(); - } - - public IList FindTimeSheetMails(long timesheetOid, long employeeOid) - { - - return CreateCriteria() - .Add(Restrictions.Eq("TimesheetOid", timesheetOid)) - .Add(Restrictions.Eq("EmployeeOid", employeeOid)) - .List(); - } - - public IEnumerable GetAllAbsenceTimesInIntervalByEmployee(DateTime start, DateTime end, long pEmployeeOid, bool pHasRightToSeeAllEmployeeAppointments) - { - // Wenn das Enddatum null ist, wird das Ende des Intervalls als Enddatum gesetzt (Ist ja eh read-only). - - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.IsNotNull(AbsenceTime.PropertyName_EmployeeOid)) - .Add(Restrictions.Or - (Restrictions.Or(Restrictions.Or( - Restrictions.And(Restrictions.Ge(AbsenceTime.PropertyName_Start, start), Restrictions.Le(AbsenceTime.PropertyName_Start, end)), - Restrictions.Eq(AbsenceTime.PropertyName_Start, start) - ), Restrictions.And(Restrictions.Le(AbsenceTime.PropertyName_Start, start), Restrictions.IsNull(AbsenceTime.PropertyName_End)) - ), Restrictions.And(Restrictions.Lt(AbsenceTime.PropertyName_Start, start), Restrictions.Gt(AbsenceTime.PropertyName_End, start))) - ); - - if (!pHasRightToSeeAllEmployeeAppointments) - { - criteria.Add(Restrictions.Eq(AbsenceTime.PropertyName_EmployeeOid, pEmployeeOid)); - } - - return criteria.List(); - } - - public IEnumerable GetActiveTextModules(bool pShouldOnlyLoadOwnTextModules, bool pHasRightToSeeAll, bool pIsInAdministrationView, long pEmployeeOid) - { - var criteria = CreateCriteriaIsActive(); - - if (pIsInAdministrationView) - { - criteria.Add(Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), false)); - } - else if (!pHasRightToSeeAll) - { - criteria.Add(Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), true)) - .Add(Restrictions.Eq(nameof(TextModule.Employee) + "." + nameof(BeWoEntityBase.Oid), pEmployeeOid)); - } - else - { - criteria.Add( - Restrictions.Or( - Restrictions.And( - Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), true), - Restrictions.Eq(nameof(TextModule.Employee) + "." + nameof(BeWoEntityBase.Oid), pEmployeeOid)), - Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), false))); - } - - return criteria.List(); - } - - public IEnumerable GetChildTextModules(TextModule textModule) - { - var criteria = CreateCriteria(); - - criteria.Add(Restrictions.Eq(nameof(TextModule.Parent), textModule)); - - return criteria.List(); - } - - public IEnumerable FindEmployeeChatBewoMessageSync(long oid) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(ChatBewoMessageSync.PropertyName_EmployeeOid, oid)); - - return c.List(); - } - - public IList FindCustomerPersonRelationsForPerson(long personOid) - { - var c = CreateCriteriaIsActive() - .CreateCriteria(Customer2Person.PropertyName_Person, JoinType.InnerJoin) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, personOid)); - - return c.List(); - } - - // KALENDER - public IList LoadFilteredAppointments(bool pHasRightToSeeAllEmployeeAppointments, long pEmployeeOid, DateTime pIntervalStart, DateTime pIntervalEnd, List pSelectedEmployees, List pSelectedCustomers, List pSelectedResources, bool pEmployeesOnly, bool pCustomersOnly, bool pResourcesOnly, bool pPrivateAppointmentsOnly, bool pOnlyMyAppointments, bool pIncludeInactiveOnes, bool includeTasks) - { - var recurrenceBetween = Format("'{0:yyyy-MM-dd} 00:00:00' BETWEEN STR_TO_DATE(SUBSTRING({1}, 24, 19), '%m/%d/%Y %H:%i:%s') AND STR_TO_DATE(SUBSTRING({1}, 50, 19), '%m/%d/%Y %H:%i:%s')", pIntervalStart, SchedulerAppointment.PropertyName_RecurrenceInfo); - - var criteria = CreateCriteria(); - - if (!pIncludeInactiveOnes) - { - criteria.Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); - } - if (!includeTasks) - { - criteria.Add(Restrictions.Or( - Restrictions.Eq(SchedulerAppointment.PropertyName_IsTask, false), - Restrictions.IsNull(SchedulerAppointment.PropertyName_IsTask))); - } - - criteria.Add(Restrictions.Or( - Restrictions.And(Restrictions.Not(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "Range", MatchMode.Anywhere)), - Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "OccurrenceCount=\"10\"", MatchMode.Anywhere)), - Restrictions.Or( - Restrictions.Or( - Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, pIntervalEnd), Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, pIntervalStart)), - Restrictions.And(Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo), Expression.Sql(new SqlString(recurrenceBetween)))), - Restrictions.And(Restrictions.Eq(SchedulerAppointment.PropertyName_Type, 3), Expression.Sql(new SqlString(recurrenceBetween)))))); - - if (pPrivateAppointmentsOnly) - { - criteria.Add(Restrictions.Eq(SchedulerAppointment.PropertyName_IsPrivate, true)); - } - else - { - if (pEmployeesOnly) - { - var hasEmployees = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM employee2newschapp)"; - criteria.Add(Expression.Sql(hasEmployees)); - } - - if (pCustomersOnly) - { - var hasCustomers = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp)"; - criteria.Add(Expression.Sql(hasCustomers)); - } - - if (pResourcesOnly) - { - var hasResources = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp)"; - criteria.Add(Expression.Sql(hasResources)); - } - - if (pSelectedEmployees.Any()) - { - var detachedCriteria1 = DetachedCriteria.For() - .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pSelectedEmployees)) - .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); - criteria.Add(Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria1)); - } - - if (pSelectedCustomers.Any()) - { - var list = ""; - for (var i = 0; i < pSelectedCustomers.Count; i++) - { - if (i != pSelectedCustomers.Count - 1) - { - list += "" + pSelectedCustomers[i] + ","; - } - else - { - list += "" + pSelectedCustomers[i]; - } - } - - - var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({list}))"; - criteria.Add(Expression.Sql(blah)); - } - - if (pSelectedResources.Any()) - { - var list = ""; - for (var i = 0; i < pSelectedResources.Count; i++) - { - if (i != pSelectedResources.Count - 1) - { - list += "" + pSelectedResources[i] + ","; - } - else - { - list += "" + pSelectedResources[i]; - } - } - - - var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp WHERE resourceoid IN ({list}))"; - criteria.Add(Expression.Sql(blah)); - } - } - - var test = criteria.List().ToList(); - - return criteria.List(); - } - - // ToDo: zu anonymisierende Termine nicht herausfiltern! Also sämtliche, aktive Termine mit den ausgewählten Ressourcen laden! - // KALENDER - public IEnumerable LoadFilteredAppointmentsForEmployee(bool pHasRightToSeeAllEmployeeAppointments, long? pEmployeeOid, DateTime pIntervalStart, DateTime pIntervalEnd, List pSelectedEmployees, List pSelectedCustomers, List pSelectedResources, bool pEmployeesOnly, bool pCustomersOnly, bool pResourcesOnly, bool pPrivateAppointmentsOnly, bool pOnlyMyAppointments, bool pIncludeInactiveOnes) - { - var mainCriteria = CreateRecurrenceCriteria(pIntervalStart, pIntervalEnd, pIncludeInactiveOnes); - - ICriterion ownAppointmentCriterion = null; - ICriterion employeeCriterion = null; - ICriterion customerCriterion = null; - ICriterion resourceCriterion = null; - - if (pEmployeeOid.HasValue) - { - ownAppointmentCriterion = CreateOwnAppointmentsCriteria(pEmployeeOid.Value); - } - - if (pPrivateAppointmentsOnly) - { - mainCriteria.Add(Restrictions.Eq(SchedulerAppointment.PropertyName_IsPrivate, true)); - } - - if (pEmployeesOnly) - { - var hasEmployees = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM employee2newschapp)"; - mainCriteria.Add(Expression.Sql(hasEmployees)); - } - - if (pCustomersOnly) - { - var hasCustomers = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp)"; - mainCriteria.Add(Expression.Sql(hasCustomers)); - } - - if (pResourcesOnly) - { - var hasResources = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp)"; - mainCriteria.Add(Expression.Sql(hasResources)); - } - - if (pSelectedEmployees.Any()) - { - var detachedCriteria1 = DetachedCriteria.For() - .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pSelectedEmployees)) - .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); - var employee2SchedCrit = Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria1); - - var originatorCrit = Restrictions.In(SchedulerAppointment.PropertyName_Originator, pSelectedEmployees); - - var detachedCriteria2 = DetachedCriteria.For("e2s2") - .SetProjection(Projections.Property(BeWoEntityBase.PropertyName_Oid)) - .Add(Restrictions.EqProperty("e2s2." + Employee2SchedulerAppointment.PropertyName_SchedulerAppointment, "sa.Oid")); - - var employee2SchedCrit2 = Subqueries.NotExists(detachedCriteria2); - - var and = Restrictions.And(originatorCrit, employee2SchedCrit2); - - employeeCriterion = Restrictions.Or(employee2SchedCrit, and); - } - - if (pSelectedCustomers.Any()) - { - var list = ""; - for (var i = 0; i < pSelectedCustomers.Count; i++) - { - if (i != pSelectedCustomers.Count - 1) - { - list += "" + pSelectedCustomers[i] + ","; - } - else - { - list += "" + pSelectedCustomers[i]; - } - } - - var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({list}))"; - customerCriterion = Expression.Sql(blah); - } - - if (pSelectedResources.Any()) - { - var list = ""; - for (var i = 0; i < pSelectedResources.Count; i++) - { - if (i != pSelectedResources.Count - 1) - { - list += "" + pSelectedResources[i] + ","; - } - else - { - list += "" + pSelectedResources[i]; - } - } - - var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp WHERE resourceoid IN ({list}))"; - resourceCriterion = Expression.Sql(blah); - } - - var listOfCriterias = new List - { - employeeCriterion, - customerCriterion, - resourceCriterion - }; - - if (pSelectedResources.Count == 0) - { - if (!pHasRightToSeeAllEmployeeAppointments && pSelectedEmployees.Count == 0) - { - mainCriteria.Add(ownAppointmentCriterion); - } - else - { - listOfCriterias.Add(ownAppointmentCriterion); - } - } - - var orCriteria = CreateOrCriteria(listOfCriterias); - - if (orCriteria != null) - { - mainCriteria.Add(orCriteria); - } - - var appointments = mainCriteria.List(); - - #region Serientermine - - var exceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null && w.Type == 3).ToList(); - - var exceptionIds = new List(); - - foreach (var appointment in exceptionalRecurrenceInfos) - { - var match = RecurrenceIdRegex.Match(appointment.RecurrenceInfo); - if (match.Success) - { - var value = match.Value; - var actualId = value.Split("\""); - if (actualId.Count > 1) - { - var id = actualId[1]; - - if (!appointments.Any(w => w.RecurrenceInfo != null && w.RecurrenceInfo.Contains(id) && w.Type == 1)) - { - exceptionIds.Add(appointment.Oid.Value); - } - } - } - } - - // Serienausnahmen werden als gelöscht markiert und es wird die RecurrenceInfo entfernt. - // Der Type wird auf "normal" gesetzt, damit nicht die ganze Serie angezeigt werden muss, die unter Umständen nichts mit den Filterkriterien zu tun hat. - var exceptionsToModify = appointments.Where(w => w.Oid.HasValue && exceptionIds.Contains(w.Oid.Value)).ToList(); - - foreach (var exception in exceptionsToModify) - { - var replacingAppointment = new SchedulerAppointment - { - Oid = exception.Oid.Value * -1, - Version = 1, - Type = 4, - RecurrenceInfo = exception.RecurrenceInfo, - Originator = exception.Originator, - EmployeeList = exception.EmployeeList, - CustomerList = exception.CustomerList, - ResourceList = exception.ResourceList - }; - - exception.RecurrenceInfo = null; - exception.Type = 0; - - appointments.Add(replacingAppointment); - } - - // Wenn ein Serientermin bearbeitet wird, sodass er außerhalb des Fetch-Zeitraumes liegt, wird er nicht mehr korrekt angezeigt. - // Deshalb werden hier alle Ausnahmen von den in der appointments-Collection enthaltenen Terminen mitgeladen. - var allExceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null); - - var changedOrDeletedOccurences = FindAppointmentsByRecurrenceId(ExtractRecurrenceIdFromRecurrenceInfo(allExceptionalRecurrenceInfos.Select(s => s.RecurrenceInfo).ToList()), true); - - appointments.AddRangeIfElementsNotIn(changedOrDeletedOccurences); - - #endregion - - var deletedAppointments = appointments.Where(a => a.IsActive != ActivationTypeId.Active).ToList(); - - return appointments; - } - - private static ICriterion CreateOrCriteria(IReadOnlyCollection criterionList) - { - ICriterion orCriterion = null; - - if (criterionList != null && criterionList.Count > 0) - { - foreach (var c in criterionList) - { - if (c != null) - { - orCriterion = orCriterion == null ? c : Restrictions.Or(orCriterion, c); - } - } - } - - return orCriterion; - } - - private static ICriterion CreateOwnAppointmentsCriteria(long pEmployeeOid) - { - var detachedCriteria = DetachedCriteria.For() - .Add(Restrictions.And( - Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pEmployeeOid), - Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, - ParticipationAnswer.Absage)))); - detachedCriteria.SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); - - var detachedCriteria2 = DetachedCriteria.For() - .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); - - ICriterion ownAppointmentCriterion = Restrictions.Or( - //Restrictions.And(Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", pEmployeeOid), Subqueries.PropertyNotIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria2)), - Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", pEmployeeOid), - Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria)); - - - return ownAppointmentCriterion; - } - - private ICriteria CreateRecurrenceCriteria(DateTime start, DateTime end, bool pIncludeInactiveOnes = false, bool excludeTasks = false) - { - var recurrenceBetween = Format("'{0:yyyy-MM-dd} 00:00:00' BETWEEN STR_TO_DATE(SUBSTRING({1}, 24, 19), '%m/%d/%Y %H:%i:%s') AND STR_TO_DATE(SUBSTRING({1}, 50, 19), '%m/%d/%Y %H:%i:%s')", start, SchedulerAppointment.PropertyName_RecurrenceInfo); - var recurrenceAfter = $"'{start:yyyy-MM-dd} 00:00:00' > STR_TO_DATE(SUBSTRING({SchedulerAppointment.PropertyName_RecurrenceInfo}, 24, 19), '%m/%d/%Y %H:%i:%s')"; - - var criteria = CreateCriteria("sa"); - - if (!excludeTasks) - { - criteria.Add(Restrictions.Not(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), true))); - } - - if (!pIncludeInactiveOnes) - { - criteria.Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); - } - - criteria.Add(Restrictions.Or( - Restrictions.And( - Restrictions.Not(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "Range", MatchMode.Anywhere)), - Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "OccurrenceCount=\"10\"", MatchMode.Anywhere)), - Restrictions.Or( - Restrictions.Or( - Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, end), Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, start)), - Restrictions.Or(Restrictions.And( - Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "End", MatchMode.Anywhere), - Restrictions.And(Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo), Expression.Sql(new SqlString(recurrenceBetween))) - ), Restrictions.And( - Restrictions.And( - Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo), - Restrictions.Not(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "End", MatchMode.Anywhere))), - Expression.Sql(recurrenceAfter))) - ), - Restrictions.And(Restrictions.Eq(SchedulerAppointment.PropertyName_Type, 3), Expression.Sql(new SqlString(recurrenceBetween)))))); - - return criteria; - } - - public IList FindDeletedRecurrencesByRecurrenceId(string pRecurrenceId) - { - var c = CreateCriteria() - .Add(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, pRecurrenceId, MatchMode.Anywhere)) - .Add(Restrictions.Eq(SchedulerAppointment.PropertyName_Type, 4)); - - return c.List(); - } - - public IList FindAppointmentsByRecurrenecInfo(List pRecurrenceInfos, bool pExcludeRootAppointments = false) - { - if (pRecurrenceInfos == null || pRecurrenceInfos.Count == 0) - { - return new List(); - } - - return FindAppointmentsByRecurrenceId(ExtractRecurrenceIdFromRecurrenceInfo(pRecurrenceInfos), pExcludeRootAppointments); - } - - public IList FindAppointmentsByRecurrenceId(List pRecurrenceIds, bool pExcludeRootAppointments = false) - { - if (pRecurrenceIds == null || pRecurrenceIds.Count == 0) - { - return new List(); - } - - var criterionList = new List(); - - pRecurrenceIds.DoForEach(id => { criterionList.AddIfNotIn(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, id, MatchMode.Anywhere)); }); - - var recurrenceIdOr = CreateOrCriteria(criterionList); - if (recurrenceIdOr == null) - { - return new List(); - ; - } - - var c = CreateCriteria() - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) - .Add(Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo)) - .Add(recurrenceIdOr); - - if (pExcludeRootAppointments) - { - c.Add(Restrictions.In(nameof(Appointment.Type), new[] { 2, 3, 4 })); - } - - return c.List(); - } - - public SchedulerAppointment FindRootAppointmentByRecurrenceId(string recurrenceId) - { - if (Guid.TryParse(recurrenceId, out var guid)) - { - var criteria = CreateCriteria() - .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), recurrenceId, MatchMode.Anywhere)) - .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); - - return criteria.List().FirstOrDefault(); - } - - return null; - } - - public IList FindAppointmentsForCustomer(long pCustomerOid) - { - var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({pCustomerOid}))"; - var customerCriterion = Expression.Sql(blah); - - var c = CreateCriteria().Add(customerCriterion); - - return c.List(); - } - - public IList FindAppointmentsForEmployee(long employeeOid) - { - var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM employee2newschapp WHERE employeeOid IN ({employeeOid}))"; - var ec = Expression.Sql(blah); - - var c = CreateCriteria().Add(ec); - - return c.List(); - } - - public IList GroupOfPeopleForSupportConcept(long pCostBearer2SupportConceptOid) - { - var c = CreateCriteria(); - - c.CreateCriteria(GroupOfPeople.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) - .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pCostBearer2SupportConceptOid)); - - return c.List(); - } - - public IList FindDefaultHourlyRateCostRatePeriods() - { - var c = CreateCriteria(); - - c.Add(Restrictions.Eq(CostRatePeriod.PropertyName_CostRateType, CostRatePeriodType.HourlyRate)) - .Add(Restrictions.IsNull(CostRatePeriod.PropertyName_ObjectOid)); - - return c.List(); - } - - public virtual IList GetSqlResult(string sql) - { - var q = Session.CreateSQLQuery(sql); - return q.List(); - - } - - public SchedulerAppointment FindRootAppointmentForException(SchedulerAppointmentDC pAppointment) - { - if (pAppointment?.RecurrenceInfo == null) - { - return null; - } - - var match = RecurrenceIdRegex.Match(pAppointment.RecurrenceInfo); - if (match.Success) - { - var value = match.Value; - var actualId = value.Split("\""); - if (actualId.Count > 1) - { - var id = actualId[1]; - - var criteria = CreateCriteria() - .Add(Restrictions.IsNotNull(nameof(SchedulerAppointment.RecurrenceInfo))) - .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), id, MatchMode.Anywhere)) - .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); - - var resultList = criteria.List(); - - if (resultList == null || resultList.Count == 0) - { - return null; - } - - return resultList.First(); - } - } - - return null; - } - - public SchedulerAppointment FindRootAppointmentForException(SchedulerAppointment pAppointment) - { - if (pAppointment?.RecurrenceInfo == null) - { - return null; - } - - var match = RecurrenceIdRegex.Match(pAppointment.RecurrenceInfo); - if (match.Success) - { - var value = match.Value; - var actualId = value.Split("\""); - if (actualId.Count > 1) - { - var id = actualId[1]; + return c.List(); + } + + public NewestChatMessage GetNewestChatMessageForConversation(long pRecipientPersonOid, long pSenderPersonOid, bool pIsTeam) + { + var teams = new List(); + + if (pIsTeam) + { + var employee = FindEmployeeWithPersonOid(pSenderPersonOid); + if (employee != null) + { + teams.AddRange(FindTeamsOfEmployee(employee.Oid.Value).Select(s => s.Oid.Value)); + } + } + + var c = CreateCriteria(); + + if (pIsTeam) + { + c.Add(Restrictions.And(Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, true), + Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pRecipientPersonOid))); + } + else + { + c.Add( + Restrictions.And( + Restrictions.Or( + Restrictions.And( + Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pRecipientPersonOid), + Restrictions.Eq(NewestChatMessage.PropertyName_SenderPersonOid, pSenderPersonOid)), + Restrictions.And( + Restrictions.Eq(NewestChatMessage.PropertyName_RecipientPersonOid, pSenderPersonOid), + Restrictions.Eq(NewestChatMessage.PropertyName_SenderPersonOid, pRecipientPersonOid))), + + Restrictions.Eq(NewestChatMessage.PropertyName_IsTeam, false))); + } + + return c.UniqueResult(); + } + + public IList GetAllOrganisation2PersonRelations(long personOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, personOid)).UniqueResult().Organisation2Persons.Select(s => s.Organisation).ToList(); + + + return c; + } + + public IList GetAllPerson2OrganisationRelations(long organisationOid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, organisationOid)).UniqueResult().Organisation2PersonList.Select(s => s.Person).ToList(); + + return c; + } + + public ServiceRecord FindServiceRecordforHistory(long? pServiceRecordOid) + { + var c = CreateCriteria().Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pServiceRecordOid)); + + return c.UniqueResult(); + } + + public ArbeitszeitListe FindEmployeeArbeitszeitListe(long employeeOid) + { + var c = CreateCriteria().Add(Restrictions.Eq(Arbeitszeit.PropertyName_EmployeeOid, employeeOid)); + + List nAr = new List(); + + + foreach (var item in c.List()) + { + nAr.Add(item.Oid.Value); + } + + ArbeitszeitListe a = new ArbeitszeitListe(); + a.Arbeitszeit = c.List().ToList(); + + if (nAr.Count != 0) + { + var cEintrag = + CreateCriteria() + .Add(Restrictions.In(ArbeitszeitEintrag.PropertyName_ArbeitszeitOid, nAr)); + + + + a.ArbeitszeitEintrag = cEintrag.List().ToList(); + + } + + return a; + } + + public IList FindCostBearer2SupportConceptForDate(DateTime datum) + { + var c = CreateCriteriaIsActive(); + + return c + .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) + .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .Add(Restrictions.Or( + Restrictions.And(Restrictions.Le("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedStartDate, datum), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate, datum)), + Restrictions.And(Restrictions.Le("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedStartDate, datum), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate, datum)))) + .List().Distinct().ToList(); + } + + public IList FindSupportConceptsInDateRange(bool auchArchivierteHolen, DateTime start, DateTime end) + { + ICriteria c = null; + if (auchArchivierteHolen) + { + c = CreateCriteriaIsActiveOrArchived(); + } + else + { + c = CreateCriteriaIsActive(); + } + + + return c + .CreateAlias(SupportConcept.PropertyName_CostBearer2SupportConceptList, "cb2sc", JoinType.InnerJoin) + .CreateAlias(SupportConcept.PropertyName_Customer, "c", JoinType.InnerJoin) + .Add( + Restrictions.Or(Restrictions.And( + Restrictions.And(Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedStartDate), Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate)), + Restrictions.And(Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedStartDate), Restrictions.IsNull("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate))), + Restrictions.Or( + Restrictions.And(Restrictions.Lt("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedStartDate, end), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_RequestedEndDate, start)), + Restrictions.And(Restrictions.Lt("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedStartDate, end), Restrictions.Ge("cb2sc." + CostBearer2SupportConcept.PropertyName_ApprovedEndDate, start))))) + .List().Distinct().ToList(); + } + + public IList FindQuittierungsCheckWithCustomerOids(List oids) + { + var c = CreateCriteria() + .Add(Restrictions.In(QuittierungsCheck.PropertyName_CustomerOid, oids)) + .List(); + + return c; + } + + public IList FindQuittierungsCheckWithCustomerOid(long oid) + { + + var c = CreateCriteria() + .Add(Restrictions.Eq(QuittierungsCheck.PropertyName_CustomerOid, oid)); + //.UniqueResult(); + + + return c.List(); + } + + public IList FindTimeSheetsForMonth(DateTime monat) + { + DateTime start = new DateTime(monat.Year, monat.Month, 1); + DateTime end = start.AddMonths(1); + + return CreateCriteria() + .Add(Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, end), Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, start))) + .List(); + } + + public Timesheet FindEmployeeTimeSheetForMonth(long employeeOid, DateTime monat) + { + DateTime start = new DateTime(monat.Year, monat.Month, 1); + DateTime end = start.AddMonths(1); + + return CreateCriteria() + .Add(Restrictions.Eq("EmployeeOid", employeeOid)) + .Add(Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, end), + Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, start))) + .List().FirstOrDefault(); + } + + public IList FindTimeSheetMails(long timesheetOid, long employeeOid) + { + + return CreateCriteria() + .Add(Restrictions.Eq("TimesheetOid", timesheetOid)) + .Add(Restrictions.Eq("EmployeeOid", employeeOid)) + .List(); + } + + public IEnumerable GetAllAbsenceTimesInIntervalByEmployee(DateTime start, DateTime end, long pEmployeeOid, bool pHasRightToSeeAllEmployeeAppointments) + { + // Wenn das Enddatum null ist, wird das Ende des Intervalls als Enddatum gesetzt (Ist ja eh read-only). + + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.IsNotNull(AbsenceTime.PropertyName_EmployeeOid)) + .Add(Restrictions.Or + (Restrictions.Or(Restrictions.Or( + Restrictions.And(Restrictions.Ge(AbsenceTime.PropertyName_Start, start), Restrictions.Le(AbsenceTime.PropertyName_Start, end)), + Restrictions.Eq(AbsenceTime.PropertyName_Start, start) + ), Restrictions.And(Restrictions.Le(AbsenceTime.PropertyName_Start, start), Restrictions.IsNull(AbsenceTime.PropertyName_End)) + ), Restrictions.And(Restrictions.Lt(AbsenceTime.PropertyName_Start, start), Restrictions.Gt(AbsenceTime.PropertyName_End, start))) + ); + + if (!pHasRightToSeeAllEmployeeAppointments) + { + criteria.Add(Restrictions.Eq(AbsenceTime.PropertyName_EmployeeOid, pEmployeeOid)); + } + + return criteria.List(); + } + + public IEnumerable GetActiveTextModules(bool pShouldOnlyLoadOwnTextModules, bool pHasRightToSeeAll, bool pIsInAdministrationView, long pEmployeeOid) + { + var criteria = CreateCriteriaIsActive(); + + if (pIsInAdministrationView) + { + criteria.Add(Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), false)); + } + else if (!pHasRightToSeeAll) + { + criteria.Add(Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), true)) + .Add(Restrictions.Eq(nameof(TextModule.Employee) + "." + nameof(BeWoEntityBase.Oid), pEmployeeOid)); + } + else + { + criteria.Add( + Restrictions.Or( + Restrictions.And( + Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), true), + Restrictions.Eq(nameof(TextModule.Employee) + "." + nameof(BeWoEntityBase.Oid), pEmployeeOid)), + Restrictions.Eq(nameof(TextModule.IsOnlyForEmployee), false))); + } + + return criteria.List(); + } + + public IEnumerable GetChildTextModules(TextModule textModule) + { + var criteria = CreateCriteria(); + + criteria.Add(Restrictions.Eq(nameof(TextModule.Parent), textModule)); + + return criteria.List(); + } + + public IEnumerable FindEmployeeChatBewoMessageSync(long oid) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(ChatBewoMessageSync.PropertyName_EmployeeOid, oid)); + + return c.List(); + } + + public IList FindCustomerPersonRelationsForPerson(long personOid) + { + var c = CreateCriteriaIsActive() + .CreateCriteria(Customer2Person.PropertyName_Person, JoinType.InnerJoin) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, personOid)); + + return c.List(); + } + + // KALENDER + public IList LoadFilteredAppointments(bool pHasRightToSeeAllEmployeeAppointments, long pEmployeeOid, DateTime pIntervalStart, DateTime pIntervalEnd, List pSelectedEmployees, List pSelectedCustomers, List pSelectedResources, bool pEmployeesOnly, bool pCustomersOnly, bool pResourcesOnly, bool pPrivateAppointmentsOnly, bool pOnlyMyAppointments, bool pIncludeInactiveOnes, bool includeTasks) + { + var recurrenceBetween = Format("'{0:yyyy-MM-dd} 00:00:00' BETWEEN STR_TO_DATE(SUBSTRING({1}, 24, 19), '%m/%d/%Y %H:%i:%s') AND STR_TO_DATE(SUBSTRING({1}, 50, 19), '%m/%d/%Y %H:%i:%s')", pIntervalStart, SchedulerAppointment.PropertyName_RecurrenceInfo); + + var criteria = CreateCriteria(); + + if (!pIncludeInactiveOnes) + { + criteria.Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); + } + if (!includeTasks) + { + criteria.Add(Restrictions.Or( + Restrictions.Eq(SchedulerAppointment.PropertyName_IsTask, false), + Restrictions.IsNull(SchedulerAppointment.PropertyName_IsTask))); + } + + criteria.Add(Restrictions.Or( + Restrictions.And(Restrictions.Not(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "Range", MatchMode.Anywhere)), + Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "OccurrenceCount=\"10\"", MatchMode.Anywhere)), + Restrictions.Or( + Restrictions.Or( + Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, pIntervalEnd), Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, pIntervalStart)), + Restrictions.And(Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo), Expression.Sql(new SqlString(recurrenceBetween)))), + Restrictions.And(Restrictions.Eq(SchedulerAppointment.PropertyName_Type, 3), Expression.Sql(new SqlString(recurrenceBetween)))))); + + if (pPrivateAppointmentsOnly) + { + criteria.Add(Restrictions.Eq(SchedulerAppointment.PropertyName_IsPrivate, true)); + } + else + { + if (pEmployeesOnly) + { + var hasEmployees = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM employee2newschapp)"; + criteria.Add(Expression.Sql(hasEmployees)); + } + + if (pCustomersOnly) + { + var hasCustomers = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp)"; + criteria.Add(Expression.Sql(hasCustomers)); + } + + if (pResourcesOnly) + { + var hasResources = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp)"; + criteria.Add(Expression.Sql(hasResources)); + } + + if (pSelectedEmployees.Any()) + { + var detachedCriteria1 = DetachedCriteria.For() + .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pSelectedEmployees)) + .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); + criteria.Add(Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria1)); + } + + if (pSelectedCustomers.Any()) + { + var list = ""; + for (var i = 0; i < pSelectedCustomers.Count; i++) + { + if (i != pSelectedCustomers.Count - 1) + { + list += "" + pSelectedCustomers[i] + ","; + } + else + { + list += "" + pSelectedCustomers[i]; + } + } + + + var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({list}))"; + criteria.Add(Expression.Sql(blah)); + } + + if (pSelectedResources.Any()) + { + var list = ""; + for (var i = 0; i < pSelectedResources.Count; i++) + { + if (i != pSelectedResources.Count - 1) + { + list += "" + pSelectedResources[i] + ","; + } + else + { + list += "" + pSelectedResources[i]; + } + } + + + var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp WHERE resourceoid IN ({list}))"; + criteria.Add(Expression.Sql(blah)); + } + } + + var test = criteria.List().ToList(); + + return criteria.List(); + } + + // ToDo: zu anonymisierende Termine nicht herausfiltern! Also sämtliche, aktive Termine mit den ausgewählten Ressourcen laden! + // KALENDER + public IEnumerable LoadFilteredAppointmentsForEmployee(bool pHasRightToSeeAllEmployeeAppointments, long? pEmployeeOid, DateTime pIntervalStart, DateTime pIntervalEnd, List pSelectedEmployees, List pSelectedCustomers, List pSelectedResources, bool pEmployeesOnly, bool pCustomersOnly, bool pResourcesOnly, bool pPrivateAppointmentsOnly, bool pOnlyMyAppointments, bool pIncludeInactiveOnes) + { + var mainCriteria = CreateRecurrenceCriteria(pIntervalStart, pIntervalEnd, pIncludeInactiveOnes); + + ICriterion ownAppointmentCriterion = null; + ICriterion employeeCriterion = null; + ICriterion customerCriterion = null; + ICriterion resourceCriterion = null; + + if (pEmployeeOid.HasValue) + { + ownAppointmentCriterion = CreateOwnAppointmentsCriteria(pEmployeeOid.Value); + } + + if (pPrivateAppointmentsOnly) + { + mainCriteria.Add(Restrictions.Eq(SchedulerAppointment.PropertyName_IsPrivate, true)); + } + + if (pEmployeesOnly) + { + var hasEmployees = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM employee2newschapp)"; + mainCriteria.Add(Expression.Sql(hasEmployees)); + } + + if (pCustomersOnly) + { + var hasCustomers = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp)"; + mainCriteria.Add(Expression.Sql(hasCustomers)); + } + + if (pResourcesOnly) + { + var hasResources = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp)"; + mainCriteria.Add(Expression.Sql(hasResources)); + } + + if (pSelectedEmployees.Any()) + { + var detachedCriteria1 = DetachedCriteria.For() + .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pSelectedEmployees)) + .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); + var employee2SchedCrit = Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria1); + + var originatorCrit = Restrictions.In(SchedulerAppointment.PropertyName_Originator, pSelectedEmployees); + + var detachedCriteria2 = DetachedCriteria.For("e2s2") + .SetProjection(Projections.Property(BeWoEntityBase.PropertyName_Oid)) + .Add(Restrictions.EqProperty("e2s2." + Employee2SchedulerAppointment.PropertyName_SchedulerAppointment, "sa.Oid")); + + var employee2SchedCrit2 = Subqueries.NotExists(detachedCriteria2); + + var and = Restrictions.And(originatorCrit, employee2SchedCrit2); + + employeeCriterion = Restrictions.Or(employee2SchedCrit, and); + } + + if (pSelectedCustomers.Any()) + { + var list = ""; + for (var i = 0; i < pSelectedCustomers.Count; i++) + { + if (i != pSelectedCustomers.Count - 1) + { + list += "" + pSelectedCustomers[i] + ","; + } + else + { + list += "" + pSelectedCustomers[i]; + } + } + + var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({list}))"; + customerCriterion = Expression.Sql(blah); + } + + if (pSelectedResources.Any()) + { + var list = ""; + for (var i = 0; i < pSelectedResources.Count; i++) + { + if (i != pSelectedResources.Count - 1) + { + list += "" + pSelectedResources[i] + ","; + } + else + { + list += "" + pSelectedResources[i]; + } + } + + var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp WHERE resourceoid IN ({list}))"; + resourceCriterion = Expression.Sql(blah); + } + + var listOfCriterias = new List + { + employeeCriterion, + customerCriterion, + resourceCriterion + }; + + if (pSelectedResources.Count == 0) + { + if (!pHasRightToSeeAllEmployeeAppointments && pSelectedEmployees.Count == 0) + { + mainCriteria.Add(ownAppointmentCriterion); + } + else + { + listOfCriterias.Add(ownAppointmentCriterion); + } + } + + var orCriteria = CreateOrCriteria(listOfCriterias); + + if (orCriteria != null) + { + mainCriteria.Add(orCriteria); + } + + var appointments = mainCriteria.List(); + + #region Serientermine + + var exceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null && w.Type == 3).ToList(); + + var exceptionIds = new List(); + + foreach (var appointment in exceptionalRecurrenceInfos) + { + var match = RecurrenceIdRegex.Match(appointment.RecurrenceInfo); + if (match.Success) + { + var value = match.Value; + var actualId = value.Split("\""); + if (actualId.Count > 1) + { + var id = actualId[1]; + + if (!appointments.Any(w => w.RecurrenceInfo != null && w.RecurrenceInfo.Contains(id) && w.Type == 1)) + { + exceptionIds.Add(appointment.Oid.Value); + } + } + } + } + + // Serienausnahmen werden als gelöscht markiert und es wird die RecurrenceInfo entfernt. + // Der Type wird auf "normal" gesetzt, damit nicht die ganze Serie angezeigt werden muss, die unter Umständen nichts mit den Filterkriterien zu tun hat. + var exceptionsToModify = appointments.Where(w => w.Oid.HasValue && exceptionIds.Contains(w.Oid.Value)).ToList(); + + foreach (var exception in exceptionsToModify) + { + var replacingAppointment = new SchedulerAppointment + { + Oid = exception.Oid.Value * -1, + Version = 1, + Type = 4, + RecurrenceInfo = exception.RecurrenceInfo, + Originator = exception.Originator, + EmployeeList = exception.EmployeeList, + CustomerList = exception.CustomerList, + ResourceList = exception.ResourceList + }; + + exception.RecurrenceInfo = null; + exception.Type = 0; + + appointments.Add(replacingAppointment); + } + + // Wenn ein Serientermin bearbeitet wird, sodass er außerhalb des Fetch-Zeitraumes liegt, wird er nicht mehr korrekt angezeigt. + // Deshalb werden hier alle Ausnahmen von den in der appointments-Collection enthaltenen Terminen mitgeladen. + var allExceptionalRecurrenceInfos = appointments.Where(w => w.RecurrenceInfo != null); + + var changedOrDeletedOccurences = FindAppointmentsByRecurrenceId(ExtractRecurrenceIdFromRecurrenceInfo(allExceptionalRecurrenceInfos.Select(s => s.RecurrenceInfo).ToList()), true); + + appointments.AddRangeIfElementsNotIn(changedOrDeletedOccurences); + + #endregion + + var deletedAppointments = appointments.Where(a => a.IsActive != ActivationTypeId.Active).ToList(); + + return appointments; + } + + private static ICriterion CreateOrCriteria(IReadOnlyCollection criterionList) + { + ICriterion orCriterion = null; + + if (criterionList != null && criterionList.Count > 0) + { + foreach (var c in criterionList) + { + if (c != null) + { + orCriterion = orCriterion == null ? c : Restrictions.Or(orCriterion, c); + } + } + } + + return orCriterion; + } + + private static ICriterion CreateOwnAppointmentsCriteria(long pEmployeeOid) + { + var detachedCriteria = DetachedCriteria.For() + .Add(Restrictions.And( + Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", pEmployeeOid), + Restrictions.Not(Restrictions.Eq(Employee2SchedulerAppointment.PropertyName_ParticipationAnswer, + ParticipationAnswer.Absage)))); + detachedCriteria.SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); + + var detachedCriteria2 = DetachedCriteria.For() + .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); + + ICriterion ownAppointmentCriterion = Restrictions.Or( + //Restrictions.And(Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", pEmployeeOid), Subqueries.PropertyNotIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria2)), + Restrictions.Eq(SchedulerAppointment.PropertyName_Originator + ".Oid", pEmployeeOid), + Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, detachedCriteria)); + + + return ownAppointmentCriterion; + } + + private ICriteria CreateRecurrenceCriteria(DateTime start, DateTime end, bool pIncludeInactiveOnes = false, bool excludeTasks = false) + { + var recurrenceBetween = Format("'{0:yyyy-MM-dd} 00:00:00' BETWEEN STR_TO_DATE(SUBSTRING({1}, 24, 19), '%m/%d/%Y %H:%i:%s') AND STR_TO_DATE(SUBSTRING({1}, 50, 19), '%m/%d/%Y %H:%i:%s')", start, SchedulerAppointment.PropertyName_RecurrenceInfo); + var recurrenceAfter = $"'{start:yyyy-MM-dd} 00:00:00' > STR_TO_DATE(SUBSTRING({SchedulerAppointment.PropertyName_RecurrenceInfo}, 24, 19), '%m/%d/%Y %H:%i:%s')"; + + var criteria = CreateCriteria("sa"); + + if (!excludeTasks) + { + criteria.Add(Restrictions.Not(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), true))); + } + + if (!pIncludeInactiveOnes) + { + criteria.Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)); + } + + criteria.Add(Restrictions.Or( + Restrictions.And( + Restrictions.Not(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "Range", MatchMode.Anywhere)), + Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "OccurrenceCount=\"10\"", MatchMode.Anywhere)), + Restrictions.Or( + Restrictions.Or( + Restrictions.And(Restrictions.Lt(SchedulerAppointment.PropertyName_StartDate, end), Restrictions.Ge(SchedulerAppointment.PropertyName_EndDate, start)), + Restrictions.Or(Restrictions.And( + Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "End", MatchMode.Anywhere), + Restrictions.And(Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo), Expression.Sql(new SqlString(recurrenceBetween))) + ), Restrictions.And( + Restrictions.And( + Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo), + Restrictions.Not(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, "End", MatchMode.Anywhere))), + Expression.Sql(recurrenceAfter))) + ), + Restrictions.And(Restrictions.Eq(SchedulerAppointment.PropertyName_Type, 3), Expression.Sql(new SqlString(recurrenceBetween)))))); + + return criteria; + } + + public IList FindDeletedRecurrencesByRecurrenceId(string pRecurrenceId) + { + var c = CreateCriteria() + .Add(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, pRecurrenceId, MatchMode.Anywhere)) + .Add(Restrictions.Eq(SchedulerAppointment.PropertyName_Type, 4)); + + return c.List(); + } + + public IList FindAppointmentsByRecurrenecInfo(List pRecurrenceInfos, bool pExcludeRootAppointments = false) + { + if (pRecurrenceInfos == null || pRecurrenceInfos.Count == 0) + { + return new List(); + } + + return FindAppointmentsByRecurrenceId(ExtractRecurrenceIdFromRecurrenceInfo(pRecurrenceInfos), pExcludeRootAppointments); + } + + public IList FindAppointmentsByRecurrenceId(List pRecurrenceIds, bool pExcludeRootAppointments = false) + { + if (pRecurrenceIds == null || pRecurrenceIds.Count == 0) + { + return new List(); + } + + var criterionList = new List(); + + pRecurrenceIds.DoForEach(id => { criterionList.AddIfNotIn(Restrictions.Like(SchedulerAppointment.PropertyName_RecurrenceInfo, id, MatchMode.Anywhere)); }); + + var recurrenceIdOr = CreateOrCriteria(criterionList); + if (recurrenceIdOr == null) + { + return new List(); + ; + } + + var c = CreateCriteria() + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_IsActive, ActivationTypeId.Active)) + .Add(Restrictions.IsNotNull(SchedulerAppointment.PropertyName_RecurrenceInfo)) + .Add(recurrenceIdOr); + + if (pExcludeRootAppointments) + { + c.Add(Restrictions.In(nameof(Appointment.Type), new[] { 2, 3, 4 })); + } + + return c.List(); + } + + public SchedulerAppointment FindRootAppointmentByRecurrenceId(string recurrenceId) + { + if (Guid.TryParse(recurrenceId, out var guid)) + { + var criteria = CreateCriteria() + .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), recurrenceId, MatchMode.Anywhere)) + .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); + + return criteria.List().FirstOrDefault(); + } + + return null; + } + + public IList FindAppointmentsForCustomer(long pCustomerOid) + { + var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({pCustomerOid}))"; + var customerCriterion = Expression.Sql(blah); + + var c = CreateCriteria().Add(customerCriterion); + + return c.List(); + } + + public IList FindAppointmentsForEmployee(long employeeOid) + { + var blah = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM employee2newschapp WHERE employeeOid IN ({employeeOid}))"; + var ec = Expression.Sql(blah); + + var c = CreateCriteria().Add(ec); + + return c.List(); + } + + public IList GroupOfPeopleForSupportConcept(long pCostBearer2SupportConceptOid) + { + var c = CreateCriteria(); + + c.CreateCriteria(GroupOfPeople.PropertyName_CostBearer2SupportConceptList, JoinType.InnerJoin) + .Add(Restrictions.Eq(BeWoEntityBase.PropertyName_Oid, pCostBearer2SupportConceptOid)); + + return c.List(); + } + + public IList FindDefaultHourlyRateCostRatePeriods() + { + var c = CreateCriteria(); + + c.Add(Restrictions.Eq(CostRatePeriod.PropertyName_CostRateType, CostRatePeriodType.HourlyRate)) + .Add(Restrictions.IsNull(CostRatePeriod.PropertyName_ObjectOid)); + + return c.List(); + } + + public virtual IList GetSqlResult(string sql) + { + var q = Session.CreateSQLQuery(sql); + return q.List(); + + } + + public SchedulerAppointment FindRootAppointmentForException(SchedulerAppointmentDC pAppointment) + { + if (pAppointment?.RecurrenceInfo == null) + { + return null; + } + + var match = RecurrenceIdRegex.Match(pAppointment.RecurrenceInfo); + if (match.Success) + { + var value = match.Value; + var actualId = value.Split("\""); + if (actualId.Count > 1) + { + var id = actualId[1]; + + var criteria = CreateCriteria() + .Add(Restrictions.IsNotNull(nameof(SchedulerAppointment.RecurrenceInfo))) + .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), id, MatchMode.Anywhere)) + .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); + + var resultList = criteria.List(); + + if (resultList == null || resultList.Count == 0) + { + return null; + } + + return resultList.First(); + } + } + + return null; + } + + public SchedulerAppointment FindRootAppointmentForException(SchedulerAppointment pAppointment) + { + if (pAppointment?.RecurrenceInfo == null) + { + return null; + } + + var match = RecurrenceIdRegex.Match(pAppointment.RecurrenceInfo); + if (match.Success) + { + var value = match.Value; + var actualId = value.Split("\""); + if (actualId.Count > 1) + { + var id = actualId[1]; - var criteria = CreateCriteria() - .Add(Restrictions.IsNotNull(nameof(SchedulerAppointment.RecurrenceInfo))) - .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), id, MatchMode.Anywhere)) - .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); + var criteria = CreateCriteria() + .Add(Restrictions.IsNotNull(nameof(SchedulerAppointment.RecurrenceInfo))) + .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), id, MatchMode.Anywhere)) + .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); - var resultList = criteria.List(); + var resultList = criteria.List(); - if (resultList == null || resultList.Count == 0) - { - return null; - } + if (resultList == null || resultList.Count == 0) + { + return null; + } - return resultList.First(); - } - } + return resultList.First(); + } + } - return null; - } - - private static List ExtractRecurrenceIdFromRecurrenceInfo(List pRecurrenceInfos) - { - var recurrenceIds = new List(); - - foreach (var info in pRecurrenceInfos) - { - var match = RecurrenceIdRegex.Match(info); - if (match.Success) - { - var value = match.Value; - var actualId = value.Split("\""); - if (actualId.Count > 1) - { - recurrenceIds.AddIfNotIn(actualId[1]); - } - } - } - - return recurrenceIds; - } - - public IList LoadTasksForConversion(long pEmployeeOid) - { - var c = CreateCriteriaIsActive(); - - c.Add(Expression.Sql($"this_.{nameof(BeWoEntityBase.Oid)} NOT IN (SELECT {nameof(SchedulerAppointment.FormerTaskOid)} FROM newschedulerappointment WHERE {nameof(SchedulerAppointment.FormerTaskOid)} IS NOT NULL)")); - - var result = c.CreateAlias(nameof(Task.SupportConcept), "sc", JoinType.InnerJoin) - .CreateAlias("sc." + nameof(SupportConcept.Customer), "c", JoinType.InnerJoin) - .CreateCriteria(nameof(Task.EmployeeList), JoinType.InnerJoin) - .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), pEmployeeOid)) - .Add(Restrictions.Eq("sc." + nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) - .Add(Restrictions.Eq("c." + nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) - .List(); - - return result; - } - - public IList LoadTaskAppointmentsForEmployee(long pEmployee, bool hideCompletedTasks) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), true)); - - if (hideCompletedTasks) - { - c.Add(Restrictions.IsNull(nameof(SchedulerAppointment.CompletedDate))); - } - - var employeeListRelationCriteria = DetachedCriteria.For() - .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", new List { pEmployee })) - .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); - - var employee2SchedCrit = Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, employeeListRelationCriteria); - - c.Add(employee2SchedCrit); - - var result = c.List(); - - return result; - } - - public IList GetTasksForEmployeeBySupportConcept(long pEmployeeOid, long pSupportConceptOid) - { - var c = CreateCriteriaIsActive(); - - var employeeListRelationCriteria = DetachedCriteria.For() - .Add(Restrictions.In(nameof(Employee2SchedulerAppointment.Employee) + ".Oid", new List { pEmployeeOid })) - .SetProjection(Projections.Property(nameof(Employee2SchedulerAppointment.SchedulerAppointmentOid))); - - var employee2SchedCrit = Subqueries.PropertyIn(nameof(BeWoEntityBase.Oid), employeeListRelationCriteria); - - c.Add(employee2SchedCrit); - - var sql = Expression.Sql($"{nameof(BeWoEntityBase.Oid)} IN (SELECT newschappoid FROM supportconcept2newschapp WHERE supportconceptoid = {pSupportConceptOid})"); + return null; + } + + private static List ExtractRecurrenceIdFromRecurrenceInfo(List pRecurrenceInfos) + { + var recurrenceIds = new List(); + + foreach (var info in pRecurrenceInfos) + { + var match = RecurrenceIdRegex.Match(info); + if (match.Success) + { + var value = match.Value; + var actualId = value.Split("\""); + if (actualId.Count > 1) + { + recurrenceIds.AddIfNotIn(actualId[1]); + } + } + } + + return recurrenceIds; + } + + public IList LoadTasksForConversion(long pEmployeeOid) + { + var c = CreateCriteriaIsActive(); + + c.Add(Expression.Sql($"this_.{nameof(BeWoEntityBase.Oid)} NOT IN (SELECT {nameof(SchedulerAppointment.FormerTaskOid)} FROM newschedulerappointment WHERE {nameof(SchedulerAppointment.FormerTaskOid)} IS NOT NULL)")); + + var result = c.CreateAlias(nameof(Task.SupportConcept), "sc", JoinType.InnerJoin) + .CreateAlias("sc." + nameof(SupportConcept.Customer), "c", JoinType.InnerJoin) + .CreateCriteria(nameof(Task.EmployeeList), JoinType.InnerJoin) + .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), pEmployeeOid)) + .Add(Restrictions.Eq("sc." + nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) + .Add(Restrictions.Eq("c." + nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) + .List(); + + return result; + } + + public IList LoadTaskAppointmentsForEmployee(long pEmployee, bool hideCompletedTasks) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), true)); + + if (hideCompletedTasks) + { + c.Add(Restrictions.IsNull(nameof(SchedulerAppointment.CompletedDate))); + } + + var employeeListRelationCriteria = DetachedCriteria.For() + .Add(Restrictions.In(Employee2SchedulerAppointment.PropertyName_Employee + ".Oid", new List { pEmployee })) + .SetProjection(Projections.Property(Employee2SchedulerAppointment.PropertyName_SchedulerAppointment)); + + var employee2SchedCrit = Subqueries.PropertyIn(BeWoEntityBase.PropertyName_Oid, employeeListRelationCriteria); + + c.Add(employee2SchedCrit); + + var result = c.List(); + + return result; + } + + public IList GetTasksForEmployeeBySupportConcept(long pEmployeeOid, long pSupportConceptOid) + { + var c = CreateCriteriaIsActive(); + + var employeeListRelationCriteria = DetachedCriteria.For() + .Add(Restrictions.In(nameof(Employee2SchedulerAppointment.Employee) + ".Oid", new List { pEmployeeOid })) + .SetProjection(Projections.Property(nameof(Employee2SchedulerAppointment.SchedulerAppointmentOid))); + + var employee2SchedCrit = Subqueries.PropertyIn(nameof(BeWoEntityBase.Oid), employeeListRelationCriteria); + + c.Add(employee2SchedCrit); + + var sql = Expression.Sql($"{nameof(BeWoEntityBase.Oid)} IN (SELECT newschappoid FROM supportconcept2newschapp WHERE supportconceptoid = {pSupportConceptOid})"); - c.Add(sql); + c.Add(sql); - return c.List(); - } + return c.List(); + } - public IList GetInvoiceBasesBySupportConceptOids(List pSupprortConceptOids) - { - var c = CreateCriteria(); + public IList GetInvoiceBasesBySupportConceptOids(List pSupprortConceptOids) + { + var c = CreateCriteria(); - c.Add(Restrictions.In(nameof(InvoiceBase.SupportConceptOid), pSupprortConceptOids)); + c.Add(Restrictions.In(nameof(InvoiceBase.SupportConceptOid), pSupprortConceptOids)); - return c.List(); - } + return c.List(); + } - public IEnumerable GetSettlementInvoiceBySupportConceptOids(List pSupportConceptOids) - { - return CreateCriteria() - .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.In("ib." + InvoiceBase.PropertyName_SupportConceptOid, pSupportConceptOids)) - .List(); - } + public IEnumerable GetSettlementInvoiceBySupportConceptOids(List pSupportConceptOids) + { + return CreateCriteria() + .CreateAlias(SettlementInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.In("ib." + InvoiceBase.PropertyName_SupportConceptOid, pSupportConceptOids)) + .List(); + } - public IList GetServiceInvoicesByInvoiceBaseOids(List pIinvoiceBaseOids) - { - var res = CreateCriteria() - .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) - .Add(Restrictions.In("ib." + BeWoEntityBase.PropertyName_Oid, pIinvoiceBaseOids)) - .List(); + public IList GetServiceInvoicesByInvoiceBaseOids(List pIinvoiceBaseOids) + { + var res = CreateCriteria() + .CreateAlias(ServiceInvoice.PropertyName_InvoiceBase, "ib", JoinType.InnerJoin) + .Add(Restrictions.In("ib." + BeWoEntityBase.PropertyName_Oid, pIinvoiceBaseOids)) + .List(); - return res; - } + return res; + } - public IList GetAllAdditionalServiceBookingsForCustomer(long pCustomerOid) - { - return CreateCriteria() - .CreateAlias(AdditionalServiceBooking.PropertyName_Customer2AddServiceBookings, "c2s", JoinType.InnerJoin) - .Add(Restrictions.Eq("c2s.CustomerOid", pCustomerOid)) - .List(); - } + public IList GetAllAdditionalServiceBookingsForCustomer(long pCustomerOid) + { + return CreateCriteria() + .CreateAlias(AdditionalServiceBooking.PropertyName_Customer2AddServiceBookings, "c2s", JoinType.InnerJoin) + .Add(Restrictions.Eq("c2s.CustomerOid", pCustomerOid)) + .List(); + } - public IList GetAdditionalServiceGroupOfPeopleForCustomer(long pCustomerOid) - { - var c = CreateCriteria(); + public IList GetAdditionalServiceGroupOfPeopleForCustomer(long pCustomerOid) + { + var c = CreateCriteria(); - c.CreateCriteria(nameof(AdditionalServiceGroupOfPeople.CustomerList), JoinType.InnerJoin) - .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), pCustomerOid)); + c.CreateCriteria(nameof(AdditionalServiceGroupOfPeople.CustomerList), JoinType.InnerJoin) + .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), pCustomerOid)); - return c.List(); - } + return c.List(); + } - public IList GetTasksAndAppointmentsBySupportConceptOids(List pSupportConceptOids) - { - var c = CreateCriteria(); + public IList GetTasksAndAppointmentsBySupportConceptOids(List pSupportConceptOids) + { + var c = CreateCriteria(); - var list = ""; - for (var i = 0; i < pSupportConceptOids.Count; i++) - { - if (i != pSupportConceptOids.Count - 1) - { - list += "" + pSupportConceptOids[i] + ","; - } - else - { - list += "" + pSupportConceptOids[i]; - } - } + var list = ""; + for (var i = 0; i < pSupportConceptOids.Count; i++) + { + if (i != pSupportConceptOids.Count - 1) + { + list += "" + pSupportConceptOids[i] + ","; + } + else + { + list += "" + pSupportConceptOids[i]; + } + } - var blah = $"{nameof(BeWoEntityBase.Oid)} IN (SELECT newschappoid FROM supportconcept2newschapp WHERE supportconceptoid IN ({list}))"; - var supportConceptCriterion = Expression.Sql(blah); + var blah = $"{nameof(BeWoEntityBase.Oid)} IN (SELECT newschappoid FROM supportconcept2newschapp WHERE supportconceptoid IN ({list}))"; + var supportConceptCriterion = Expression.Sql(blah); - c.Add(supportConceptCriterion); + c.Add(supportConceptCriterion); - return c.List(); - } + return c.List(); + } - public IList GetCustomer2TokensByCustomerOid(long pCustomerOid) - { - var c = CreateCriteria(); + public IList GetCustomer2TokensByCustomerOid(long pCustomerOid) + { + var c = CreateCriteria(); - c.Add(Restrictions.Eq(nameof(Customer2Token.Customer) + "." + nameof(BeWoEntityBase.Oid), pCustomerOid)); + c.Add(Restrictions.Eq(nameof(Customer2Token.Customer) + "." + nameof(BeWoEntityBase.Oid), pCustomerOid)); - return c.List(); - } + return c.List(); + } - public IList GeEmployee2TokensByEmployeeOid(long employeeOid) - { - var c = CreateCriteria(); + public IList GeEmployee2TokensByEmployeeOid(long employeeOid) + { + var c = CreateCriteria(); - c.Add(Restrictions.Eq(nameof(Employee2Token.Employee) + "." + nameof(BeWoEntityBase.Oid), employeeOid)); + c.Add(Restrictions.Eq(nameof(Employee2Token.Employee) + "." + nameof(BeWoEntityBase.Oid), employeeOid)); - return c.List(); - } + return c.List(); + } - public IList GetTestAppointments() - { - var c = CreateCriteria(); + public IList GetTestAppointments() + { + var c = CreateCriteria(); - c.Add(Restrictions.Eq(nameof(BeWoEntityBase.Notice), BS.Shared.Core.Utils.TestAppointmentNotice)); + c.Add(Restrictions.Eq(nameof(BeWoEntityBase.Notice), BS.Shared.Core.Utils.TestAppointmentNotice)); - return c.List(); - } + return c.List(); + } - public bool CheckForOverlappingSubstitutions(long? employeeOid, long? customerOid, DateTime startDate, DateTime endDate, long? substitutionOid) - { - var c = CreateCriteria(); + public bool CheckForOverlappingSubstitutions(long? employeeOid, long? customerOid, DateTime startDate, DateTime endDate, long? substitutionOid) + { + var c = CreateCriteria(); - var employeeRestriction = Restrictions.Eq(nameof(Vertretung.EmployeeOid), employeeOid); - var customerRestriction = Restrictions.Eq(nameof(Vertretung.CustomerOid), customerOid); + var employeeRestriction = Restrictions.Eq(nameof(Vertretung.EmployeeOid), employeeOid); + var customerRestriction = Restrictions.Eq(nameof(Vertretung.CustomerOid), customerOid); - var notCurrentSubstitution = Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), substitutionOid)); + var notCurrentSubstitution = Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), substitutionOid)); - var peopleRestriction = Restrictions.Or(employeeRestriction, customerRestriction); - var timeRestriction = CreateBetweenDateTimesCriterion(startDate, endDate, nameof(Vertretung.VertretungsZeitraumVon), nameof(Vertretung.VertretungsZeitraumBis)); + var peopleRestriction = Restrictions.Or(employeeRestriction, customerRestriction); + var timeRestriction = CreateBetweenDateTimesCriterion(startDate, endDate, nameof(Vertretung.VertretungsZeitraumVon), nameof(Vertretung.VertretungsZeitraumBis)); - c.Add(peopleRestriction).Add(timeRestriction).Add(notCurrentSubstitution); + c.Add(peopleRestriction).Add(timeRestriction).Add(notCurrentSubstitution); - return c.List().Any(); - } + return c.List().Any(); + } - private static AbstractCriterion CreateBetweenDateTimesCriterion(DateTime start, DateTime end, string propertyNameStart, string propertyNameEnd) - { - /* -- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET -- + private static AbstractCriterion CreateBetweenDateTimesCriterion(DateTime start, DateTime end, string propertyNameStart, string propertyNameEnd) + { + /* -- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET -- * Sql für Spalten namens 'StartDate' und 'EndDate': * WHERE * ((start >= StartDate AND end <= StartDate) OR (start <= StartDate AND end >= EndDate)) @@ -3519,16 +3531,16 @@ WHERE sc.Billable = 1 and sr.StartDate >= '{0:yyyy-MM-dd}' and sr.StartDate < '{ * ((start <= StartDate AND start >= EndDate) OR (start >= StartDate AND end <= EndDate)) */ - //var inBetween1 = Restrictions.And(Restrictions.Ge(propertyNameStart, start), Restrictions.Le(propertyNameStart, end)); - //var inBetween2 = Restrictions.And(Restrictions.Le(propertyNameStart, start), Restrictions.Ge(propertyNameEnd, end)); - //var inBetween3 = Restrictions.And(Restrictions.Le(propertyNameStart, start), Restrictions.Ge(propertyNameEnd, start)); - //var inBetween4 = Restrictions.And(Restrictions.Ge(propertyNameStart, start), Restrictions.Le(propertyNameEnd, end)); + //var inBetween1 = Restrictions.And(Restrictions.Ge(propertyNameStart, start), Restrictions.Le(propertyNameStart, end)); + //var inBetween2 = Restrictions.And(Restrictions.Le(propertyNameStart, start), Restrictions.Ge(propertyNameEnd, end)); + //var inBetween3 = Restrictions.And(Restrictions.Le(propertyNameStart, start), Restrictions.Ge(propertyNameEnd, start)); + //var inBetween4 = Restrictions.And(Restrictions.Ge(propertyNameStart, start), Restrictions.Le(propertyNameEnd, end)); - //return Restrictions.Or(Restrictions.Or(inBetween1, inBetween2), Restrictions.Or(inBetween3, inBetween4)); - // -- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET -- + //return Restrictions.Or(Restrictions.Or(inBetween1, inBetween2), Restrictions.Or(inBetween3, inBetween4)); + // -- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET ----- VERALTET -- - // NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU - /* Sql für Spalten namens 'StartDate' und 'EndDate': + // NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU + /* Sql für Spalten namens 'StartDate' und 'EndDate': * (StartDate < '2020-11-19 10:00:00' AND EndDate <= '2020-11-19 12:00:00' AND EndDate > '2020-11-19 10:00:00') OR (StartDate < '2020-11-19 10:00:00' AND EndDate > '2020-11-19 12:00:00') @@ -3539,1371 +3551,1371 @@ WHERE sc.Billable = 1 and sr.StartDate >= '{0:yyyy-MM-dd}' and sr.StartDate < '{ OR (StartDate = '2020-11-19 10:00:00' AND EndDate >= '2020-11-19 12:00:00') */ - // NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU + // NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU -- NEU - var inBetween1 = Restrictions.And(Restrictions.Lt(propertyNameStart, start), Restrictions.And(Restrictions.Le(propertyNameEnd, end), Restrictions.Gt(propertyNameEnd, start))); - var inBetween2 = Restrictions.And(Restrictions.Lt(propertyNameStart, start), Restrictions.Gt(propertyNameEnd, end)); - var inBetween3 = Restrictions.And(Restrictions.Gt(propertyNameStart, start), Restrictions.Lt(propertyNameStart, end)); - var inBetween4 = Restrictions.And(Restrictions.Eq(propertyNameStart, start), Restrictions.Eq(propertyNameEnd, end)); - var inBetween5 = Restrictions.And(Restrictions.Eq(propertyNameStart, start), Restrictions.Le(propertyNameEnd, end)); + var inBetween1 = Restrictions.And(Restrictions.Lt(propertyNameStart, start), Restrictions.And(Restrictions.Le(propertyNameEnd, end), Restrictions.Gt(propertyNameEnd, start))); + var inBetween2 = Restrictions.And(Restrictions.Lt(propertyNameStart, start), Restrictions.Gt(propertyNameEnd, end)); + var inBetween3 = Restrictions.And(Restrictions.Gt(propertyNameStart, start), Restrictions.Lt(propertyNameStart, end)); + var inBetween4 = Restrictions.And(Restrictions.Eq(propertyNameStart, start), Restrictions.Eq(propertyNameEnd, end)); + var inBetween5 = Restrictions.And(Restrictions.Eq(propertyNameStart, start), Restrictions.Le(propertyNameEnd, end)); - return Restrictions.Or(inBetween1, Restrictions.Or(Restrictions.Or(inBetween2, inBetween3), Restrictions.Or(inBetween4, inBetween5))); - } + return Restrictions.Or(inBetween1, Restrictions.Or(Restrictions.Or(inBetween2, inBetween3), Restrictions.Or(inBetween4, inBetween5))); + } - public bool CheckForOverlappingAbsenceTimes(DateTime startDate, DateTime endDate, long? employeeOid, long? customerOid) - { - var c = CreateCriteria(); + public bool CheckForOverlappingAbsenceTimes(DateTime startDate, DateTime endDate, long? employeeOid, long? customerOid) + { + var c = CreateCriteria(); - var peopleRestriction = employeeOid != null ? Restrictions.Eq(nameof(AbsenceTime.EmployeeOid), employeeOid) : Restrictions.Eq(nameof(AbsenceTime.CustomerOid), customerOid); + var peopleRestriction = employeeOid != null ? Restrictions.Eq(nameof(AbsenceTime.EmployeeOid), employeeOid) : Restrictions.Eq(nameof(AbsenceTime.CustomerOid), customerOid); - var timeRestriction = CreateBetweenDateTimesCriterion(startDate, endDate, nameof(AbsenceTime.Start), nameof(AbsenceTime.End)); + var timeRestriction = CreateBetweenDateTimesCriterion(startDate, endDate, nameof(AbsenceTime.Start), nameof(AbsenceTime.End)); - c.Add(peopleRestriction).Add(timeRestriction); + c.Add(peopleRestriction).Add(timeRestriction); - return c.List().Any(); - } + return c.List().Any(); + } - public IList GetLastSubstitutionItems(long employeeOid, int count) - { - var criteria = CreateCriteria(); + public IList GetLastSubstitutionItems(long employeeOid, int count) + { + var criteria = CreateCriteria(); - criteria.Add(Restrictions.Eq(nameof(Vertretung.EmployeeOid), employeeOid)); + criteria.Add(Restrictions.Eq(nameof(Vertretung.EmployeeOid), employeeOid)); - criteria.AddOrder(Order.Desc(nameof(Vertretung.VertretungsZeitraumBis))); + criteria.AddOrder(Order.Desc(nameof(Vertretung.VertretungsZeitraumBis))); - criteria.SetMaxResults(count); + criteria.SetMaxResults(count); - return criteria.List().Where(w => w.VertretungsZeitraumVon > DateTime.MinValue && w.VertretungsZeitraumBis > DateTime.MinValue).ToList(); - } + return criteria.List().Where(w => w.VertretungsZeitraumVon > DateTime.MinValue && w.VertretungsZeitraumBis > DateTime.MinValue).ToList(); + } - public Dictionary> GetAssistanceTimesForEmployee(long employeeOid, DateTime start, DateTime end) - { - // Arbeitszeit -> keine EmployeeOid, nur in den Arbeitszeiteinträgen + public Dictionary> GetAssistanceTimesForEmployee(long employeeOid, DateTime start, DateTime end) + { + // Arbeitszeit -> keine EmployeeOid, nur in den Arbeitszeiteinträgen - var criteria = CreateCriteria(); + var criteria = CreateCriteria(); - var detachedCriteria = DetachedCriteria.For().Add(Restrictions.Eq(nameof(ArbeitszeitEintrag.Employee) + ".Oid", employeeOid)).SetProjection(Projections.Property(nameof(ArbeitszeitEintrag.ArbeitszeitOid))); + var detachedCriteria = DetachedCriteria.For().Add(Restrictions.Eq(nameof(ArbeitszeitEintrag.Employee) + ".Oid", employeeOid)).SetProjection(Projections.Property(nameof(ArbeitszeitEintrag.ArbeitszeitOid))); - var subquery = Subqueries.PropertyIn(nameof(BeWoEntityBase.Oid), detachedCriteria); + var subquery = Subqueries.PropertyIn(nameof(BeWoEntityBase.Oid), detachedCriteria); - criteria.Add(subquery); + criteria.Add(subquery); - criteria.Add(CreateArbeitszeitenTimeRestictions(start, end)); + criteria.Add(CreateArbeitszeitenTimeRestictions(start, end)); - var assistanceTimes = criteria.List(); + var assistanceTimes = criteria.List(); - var result = new Dictionary>(); + var result = new Dictionary>(); - foreach (var assistanceTimeEntry in assistanceTimes) - { - if (assistanceTimeEntry.Customer != null) - { - result.AddOrUpdateValueInDictionary(assistanceTimeEntry.Customer, assistanceTimeEntry.ArbeitszeitEintraege.ToList()); - } - } + foreach (var assistanceTimeEntry in assistanceTimes) + { + if (assistanceTimeEntry.Customer != null) + { + result.AddOrUpdateValueInDictionary(assistanceTimeEntry.Customer, assistanceTimeEntry.ArbeitszeitEintraege.ToList()); + } + } - return result; - } + return result; + } - private ICriterion CreateArbeitszeitenTimeRestictions(DateTime start, DateTime end) - { - // GueltigVon und GueltigBis sind null - var gueltigVonAndGueltigBisAreNull = Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.IsNull(nameof(Arbeitszeit.GueltigBis))); + private ICriterion CreateArbeitszeitenTimeRestictions(DateTime start, DateTime end) + { + // GueltigVon und GueltigBis sind null + var gueltigVonAndGueltigBisAreNull = Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.IsNull(nameof(Arbeitszeit.GueltigBis))); - // GueltigVon ist null, GueltigBis ist nicht null - var gueltigVonIsNullAndGueltigBisIsGtStart = Restrictions.And(Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.Gt(nameof(Arbeitszeit.GueltigBis), start)), Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.Ge(nameof(Arbeitszeit.GueltigBis), start))); + // GueltigVon ist null, GueltigBis ist nicht null + var gueltigVonIsNullAndGueltigBisIsGtStart = Restrictions.And(Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.Gt(nameof(Arbeitszeit.GueltigBis), start)), Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.Ge(nameof(Arbeitszeit.GueltigBis), start))); - // GueltigVon ist nicht null, GueltigBis ist null - var gueltigBisIsNullAndGueltigVonIsLtEnd = Restrictions.And(Restrictions.IsNotNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigBis)), Restrictions.Gt(nameof(Arbeitszeit.GueltigVon), end))); + // GueltigVon ist nicht null, GueltigBis ist null + var gueltigBisIsNullAndGueltigVonIsLtEnd = Restrictions.And(Restrictions.IsNotNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.And(Restrictions.IsNull(nameof(Arbeitszeit.GueltigBis)), Restrictions.Gt(nameof(Arbeitszeit.GueltigVon), end))); - var and1 = Restrictions.And(Restrictions.IsNotNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.IsNotNull(nameof(Arbeitszeit.GueltigBis))); - var and3 = Restrictions.And(Restrictions.Le(nameof(Arbeitszeit.GueltigVon), start), Restrictions.Ge(nameof(Arbeitszeit.GueltigBis), start)); - var and4 = Restrictions.And(Restrictions.Le(nameof(Arbeitszeit.GueltigVon), end), Restrictions.Gt(nameof(Arbeitszeit.GueltigBis), end)); - var and5 = Restrictions.And(Restrictions.Ge(nameof(Arbeitszeit.GueltigVon), start), Restrictions.Le(nameof(Arbeitszeit.GueltigBis), end)); + var and1 = Restrictions.And(Restrictions.IsNotNull(nameof(Arbeitszeit.GueltigVon)), Restrictions.IsNotNull(nameof(Arbeitszeit.GueltigBis))); + var and3 = Restrictions.And(Restrictions.Le(nameof(Arbeitszeit.GueltigVon), start), Restrictions.Ge(nameof(Arbeitszeit.GueltigBis), start)); + var and4 = Restrictions.And(Restrictions.Le(nameof(Arbeitszeit.GueltigVon), end), Restrictions.Gt(nameof(Arbeitszeit.GueltigBis), end)); + var and5 = Restrictions.And(Restrictions.Ge(nameof(Arbeitszeit.GueltigVon), start), Restrictions.Le(nameof(Arbeitszeit.GueltigBis), end)); - var or1 = Restrictions.Or(and4, and5); - var or2 = Restrictions.Or(and3, or1); + var or1 = Restrictions.Or(and4, and5); + var or2 = Restrictions.Or(and3, or1); - // GueltigVon und GueltigBis sind nicht null - var gueltigVonAndGueltigBisAreNotNull = Restrictions.And(and1, or2); + // GueltigVon und GueltigBis sind nicht null + var gueltigVonAndGueltigBisAreNotNull = Restrictions.And(and1, or2); - return Restrictions.Or(gueltigVonAndGueltigBisAreNull, Restrictions.Or(Restrictions.Or(gueltigVonIsNullAndGueltigBisIsGtStart, gueltigBisIsNullAndGueltigVonIsLtEnd), gueltigVonAndGueltigBisAreNotNull)); - } + return Restrictions.Or(gueltigVonAndGueltigBisAreNull, Restrictions.Or(Restrictions.Or(gueltigVonIsNullAndGueltigBisIsGtStart, gueltigBisIsNullAndGueltigVonIsLtEnd), gueltigVonAndGueltigBisAreNotNull)); + } - public IList GetCustomersWithSubstitutionNeedUnset() - { - var c = CreateCriteria(); + public IList GetCustomersWithSubstitutionNeedUnset() + { + var c = CreateCriteria(); - c.Add(Restrictions.IsNull(nameof(Customer.SubstitutionNeed))); + c.Add(Restrictions.IsNull(nameof(Customer.SubstitutionNeed))); - return c.List(); - } + return c.List(); + } - public List FindTeamRelatedCustomerOids(long employeeOid) - { - var result = new List(); + public List FindTeamRelatedCustomerOids(long employeeOid) + { + var result = new List(); - var teams = CreateCriteriaIsActive() - .Add(Restrictions.IsNotNull(nameof(BeWoEntityBase.Oid))) - .CreateCriteria(nameof(Team.MemberList), JoinType.InnerJoin) - .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) - .List(); + var teams = CreateCriteriaIsActive() + .Add(Restrictions.IsNotNull(nameof(BeWoEntityBase.Oid))) + .CreateCriteria(nameof(Team.MemberList), JoinType.InnerJoin) + .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) + .List(); - var members = new List(); + var members = new List(); - foreach (var team in teams) - { - members.AddRangeIfElementsNotIn(team.MemberList); - } + foreach (var team in teams) + { + members.AddRangeIfElementsNotIn(team.MemberList); + } - foreach (var member in members) - { - foreach (var employee2customer in member.Employee2CustomerList) - { - if (employee2customer.CustomerOid.HasValue) - { - result.AddIfNotIn(employee2customer.CustomerOid.Value); - } - } - } + foreach (var member in members) + { + foreach (var employee2customer in member.Employee2CustomerList) + { + if (employee2customer.CustomerOid.HasValue) + { + result.AddIfNotIn(employee2customer.CustomerOid.Value); + } + } + } - return result; - } + return result; + } - public List FindCustomersForAbsenceTimesByStartAndEnd(DateTime intervalStart, DateTime intervalEnd) - { - var criteria = CreateCriteriaIsActive(); - // Arbeitszeiten im gewählten Intervall holen und dann die einträge nach customeroid durchsuchen - // TODO: implementieren + public List FindCustomersForAbsenceTimesByStartAndEnd(DateTime intervalStart, DateTime intervalEnd) + { + var criteria = CreateCriteriaIsActive(); + // Arbeitszeiten im gewählten Intervall holen und dann die einträge nach customeroid durchsuchen + // TODO: implementieren - return criteria.List().ToList(); - } + return criteria.List().ToList(); + } - public List FindCostBearer2SupportConceptsByOids(List costbearer2SupportConceptOids) - { - var c = CreateCriteriaIsActive(); + public List FindCostBearer2SupportConceptsByOids(List costbearer2SupportConceptOids) + { + var c = CreateCriteriaIsActive(); - c.Add(Restrictions.In(nameof(CostBearer2SupportConcept.Oid), costbearer2SupportConceptOids)); + c.Add(Restrictions.In(nameof(CostBearer2SupportConcept.Oid), costbearer2SupportConceptOids)); - return c.List().ToList(); - } + return c.List().ToList(); + } - public bool IsResourceAvailable(DateTime start, DateTime end, long resourceOid) - { - var c = CreateCriteriaIsActive(); + public bool IsResourceAvailable(DateTime start, DateTime end, long resourceOid) + { + var c = CreateCriteriaIsActive(); - var sql = $"SELECT COUNT(*) FROM resource WHERE oid = {resourceOid} AND isactive = 1 AND oid NOT IN (SELECT resourceoid FROM resource2newschapp r WHERE r.newschappoid NOT IN (SELECT oid FROM newschedulerappointment WHERE startdate > '{start:yyyy-MM-dd HH:mm:ss}' OR enddate < '{end:yyyy-MM-dd HH:mm:ss}'));"; + var sql = $"SELECT COUNT(*) FROM resource WHERE oid = {resourceOid} AND isactive = 1 AND oid NOT IN (SELECT resourceoid FROM resource2newschapp r WHERE r.newschappoid NOT IN (SELECT oid FROM newschedulerappointment WHERE startdate > '{start:yyyy-MM-dd HH:mm:ss}' OR enddate < '{end:yyyy-MM-dd HH:mm:ss}'));"; - var criterion = Expression.Sql(sql); + var criterion = Expression.Sql(sql); - c.Add(criterion); + c.Add(criterion); - return c.List().Count > 0; - } + return c.List().Count > 0; + } - public List GetAvailableResources(DateTime start, DateTime end) - { - var c = CreateCriteria("r").Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)); + public List GetAvailableResources(DateTime start, DateTime end) + { + var c = CreateCriteria("r").Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)); - var sql = $"Oid NOT IN (SELECT Oid FROM resource WHERE isactive = 1 AND Oid NOT IN (SELECT resourceoid FROM resource2newschapp r2n WHERE r2n.newschappoid NOT IN (SELECT oid FROM newschedulerappointment WHERE startdate > '{start:yyyy-MM-dd HH:mm:ss}' OR enddate < '{end:yyyy-MM-dd HH:mm:ss}')))"; + var sql = $"Oid NOT IN (SELECT Oid FROM resource WHERE isactive = 1 AND Oid NOT IN (SELECT resourceoid FROM resource2newschapp r2n WHERE r2n.newschappoid NOT IN (SELECT oid FROM newschedulerappointment WHERE startdate > '{start:yyyy-MM-dd HH:mm:ss}' OR enddate < '{end:yyyy-MM-dd HH:mm:ss}')))"; - var criterion = Expression.Sql(sql); + var criterion = Expression.Sql(sql); - c.Add(criterion); + c.Add(criterion); - return c.List().ToList(); - } + return c.List().ToList(); + } - /// - /// Prüft anhand der Oids von Ressourcen deren Verfügbarkeit in einem Zeitraum. - /// Gibt die nicht verfügbaren Ressourcen zurück für eine detaillierte Fehlermeldung. - /// - /// Die Oids der zu überprüfenden Ressourcen - /// Anfang des zu prüfenden Intervalls - /// Ende des zu prüfenden Intervalls - /// Die Oid des Termins - /// Recurrence Id, falls es sich um einen Serientermin handelt, der keine eigene Oid hat. - /// Occurrence-Index des Serientermins ohne eigene Oid - /// Die im angegebenen Zeitraum belegten Ressourcen - public List CheckAvailabilityOfResources(List resourceOids, DateTime start, DateTime end, long? selectedAppointmentOid, Guid? recurrenceId = null, int? occurrenceIndex = null) - { - var c = CreateCriteria("r").Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)).Add(Restrictions.In(nameof(BeWoEntityBase.Oid), resourceOids)); + /// + /// Prüft anhand der Oids von Ressourcen deren Verfügbarkeit in einem Zeitraum. + /// Gibt die nicht verfügbaren Ressourcen zurück für eine detaillierte Fehlermeldung. + /// + /// Die Oids der zu überprüfenden Ressourcen + /// Anfang des zu prüfenden Intervalls + /// Ende des zu prüfenden Intervalls + /// Die Oid des Termins + /// Recurrence Id, falls es sich um einen Serientermin handelt, der keine eigene Oid hat. + /// Occurrence-Index des Serientermins ohne eigene Oid + /// Die im angegebenen Zeitraum belegten Ressourcen + public List CheckAvailabilityOfResources(List resourceOids, DateTime start, DateTime end, long? selectedAppointmentOid, Guid? recurrenceId = null, int? occurrenceIndex = null) + { + var c = CreateCriteria("r").Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)).Add(Restrictions.In(nameof(BeWoEntityBase.Oid), resourceOids)); - var excludingSelectedAppointment = selectedAppointmentOid.HasValue ? $"Oid <> {selectedAppointmentOid} AND " : ""; + var excludingSelectedAppointment = selectedAppointmentOid.HasValue ? $"Oid <> {selectedAppointmentOid} AND " : ""; - var sql = "Oid IN " + - "(SELECT ResourceOid FROM resource2newschapp r2n WHERE r2n.NewSchAppOid IN " + - $"(SELECT Oid FROM newschedulerappointment WHERE IsActive = 1 AND Type <> 4 AND {excludingSelectedAppointment}('{start:yyyy-MM-dd HH:mm:ss}' > StartDate OR '{end:yyyy-MM-dd HH:mm:ss}' > StartDate) AND ('{start:yyyy-MM-dd HH:mm:ss}' < EndDate OR '{end:yyyy-MM-dd HH:mm:ss}' < EndDate)))"; + var sql = "Oid IN " + + "(SELECT ResourceOid FROM resource2newschapp r2n WHERE r2n.NewSchAppOid IN " + + $"(SELECT Oid FROM newschedulerappointment WHERE IsActive = 1 AND Type <> 4 AND {excludingSelectedAppointment}('{start:yyyy-MM-dd HH:mm:ss}' > StartDate OR '{end:yyyy-MM-dd HH:mm:ss}' > StartDate) AND ('{start:yyyy-MM-dd HH:mm:ss}' < EndDate OR '{end:yyyy-MM-dd HH:mm:ss}' < EndDate)))"; - var criterion = Expression.Sql(sql); + var criterion = Expression.Sql(sql); - c.Add(criterion); + c.Add(criterion); - var resources = c.List().ToList(); + var resources = c.List().ToList(); - var recurringAppointmentsCriteria = CreateRecurrenceCriteria(start, end).Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 1)); + var recurringAppointmentsCriteria = CreateRecurrenceCriteria(start, end).Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 1)); - var recurringAppointments = recurringAppointmentsCriteria.List().ToList(); + var recurringAppointments = recurringAppointmentsCriteria.List().ToList(); - recurringAppointments = recurringAppointments.Where(s => s.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); + recurringAppointments = recurringAppointments.Where(s => s.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); - if (recurringAppointments.Count == 0) - { - return resources; - } + if (recurringAppointments.Count == 0) + { + return resources; + } - var changedOccurrencesCriteria = CreateCriteriaIsActive().Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 3)); - var deletedOccurrencesCriteria = CreateCriteria().Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 4)); + var changedOccurrencesCriteria = CreateCriteriaIsActive().Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 3)); + var deletedOccurrencesCriteria = CreateCriteria().Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 4)); - var inBetween = CreateBetweenDateTimesCriterion(start, end, nameof(SchedulerAppointment.StartDate), nameof(SchedulerAppointment.EndDate)); + var inBetween = CreateBetweenDateTimesCriterion(start, end, nameof(SchedulerAppointment.StartDate), nameof(SchedulerAppointment.EndDate)); - changedOccurrencesCriteria.Add(inBetween); - deletedOccurrencesCriteria.Add(inBetween); + changedOccurrencesCriteria.Add(inBetween); + deletedOccurrencesCriteria.Add(inBetween); - var appointments = new List(); + var appointments = new List(); - if (selectedAppointmentOid.HasValue) - { - changedOccurrencesCriteria.Add(Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), selectedAppointmentOid.Value))); - deletedOccurrencesCriteria.Add(Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), selectedAppointmentOid.Value))); - } + if (selectedAppointmentOid.HasValue) + { + changedOccurrencesCriteria.Add(Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), selectedAppointmentOid.Value))); + deletedOccurrencesCriteria.Add(Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), selectedAppointmentOid.Value))); + } - var changedOccurrences = new List(); + var changedOccurrences = new List(); - var recurrenceIds = string.Empty; - recurringAppointments.DoForEach(appointment => recurrenceIds += $"'{appointment.GetRecurrenceId()}',"); - recurrenceIds = recurrenceIds.Trim(','); + var recurrenceIds = string.Empty; + recurringAppointments.DoForEach(appointment => recurrenceIds += $"'{appointment.GetRecurrenceId()}',"); + recurrenceIds = recurrenceIds.Trim(','); - if (recurrenceIds.Any()) - { - var changedCriteria = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 3)) - .Add(Expression.Sql($"RecurrenceInfo IS NOT NULL AND RecurrenceInfo LIKE '%Id%' AND SUBSTRING(RecurrenceInfo, LOCATE('Id', RecurrenceInfo) + 4, 36) IN ({recurrenceIds})")); + if (recurrenceIds.Any()) + { + var changedCriteria = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 3)) + .Add(Expression.Sql($"RecurrenceInfo IS NOT NULL AND RecurrenceInfo LIKE '%Id%' AND SUBSTRING(RecurrenceInfo, LOCATE('Id', RecurrenceInfo) + 4, 36) IN ({recurrenceIds})")); - changedOccurrences = changedCriteria.List().ToList(); - } + changedOccurrences = changedCriteria.List().ToList(); + } - //var changedOccurrences = changedOccurrencesCriteria.List().Where(a => a.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); - var deletedOccurrences = deletedOccurrencesCriteria.List().Where(a => a.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); + //var changedOccurrences = changedOccurrencesCriteria.List().Where(a => a.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); + var deletedOccurrences = deletedOccurrencesCriteria.List().Where(a => a.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); - // Sich wiederholende Termine erzeugen und dabei die Ausnahmen und gelöschten Ausnahmen ignorieren - var interval = new TimeInterval(start, end); - foreach (var recurringAppointment in recurringAppointments) - { - var recurrenceInfo = new RecurrenceInfo(); - recurrenceInfo.FromXml(recurringAppointment.RecurrenceInfo); - - var occurenceCalculator = OccurrenceCalculator.CreateInstance(recurrenceInfo); - - // Das Muster für die Terminserie wird berechnet - var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); - pattern.RecurrenceInfo.FromXml(recurringAppointment.RecurrenceInfo); - pattern.Start = pattern.RecurrenceInfo.Start; - pattern.End = pattern.RecurrenceInfo.End; - - if (!Guid.TryParse(pattern.RecurrenceInfo.Id.ToString(), out var patternId)) - { - continue; - } - - // Die Serientermine werden berechnet (ausnahmslos, d.h. es werden auch bearbeitete und gelöschte Termine erstellt, die herausgefiltert werden müssen). - var occurrences = occurenceCalculator.CalcOccurrences(interval, pattern); - - var occurrenceAppointments = occurrences.GetAppointments(interval); - - foreach (var occurrence in occurrenceAppointments) - { - if (recurringAppointment.EndDate is null || recurringAppointment.StartDate is null) - { - continue; - } - - // Sicher machen - var index = occurrence.RecurrenceIndex; - - var isDeletedOrChanged = changedOccurrences.Any(a => - { - var guid = a.GetRecurrenceIdAndIndex(out var i); - - if (guid is null) - { - return false; - } - - if (guid.Value.Equals(patternId) && index == i) - { - return true; - } - - return false; - }) || deletedOccurrences.Any(a => - { - var guid = a.GetRecurrenceIdAndIndex(out var i); - - if (guid is null) - { - return false; - } - - if (guid.Value.Equals(patternId) && index == i) - { - return true; - } - - return false; - }); - - if (isDeletedOrChanged) - { - continue; - } - - var duration = (recurringAppointment.EndDate.Value - recurringAppointment.StartDate.Value).TotalMinutes; - var isInIntervalTest = start.IsInInterval(end, occurrence.Start, occurrence.Start.AddMinutes(duration)); - - if (!isInIntervalTest) - { - continue; - } - - var occurrenceAppointment = new SchedulerAppointment - { - AllDay = occurrence.AllDay, - CustomerList = recurringAppointment.CustomerList, - Notice = recurringAppointment.Notice, - EmployeeList = recurringAppointment.EmployeeList, - EndDate = occurrence.Start.AddMinutes(duration), - FormerBookingSequenceOid = recurringAppointment.FormerBookingSequenceOid, - IsPrivate = recurringAppointment.IsPrivate, - Location = recurringAppointment.Location, - Originator = recurringAppointment.Originator, - RecurrenceInfo = occurrence.RecurrenceInfo.ToXml(), - ReminderInfo = recurringAppointment.ReminderInfo, - ResourceList = recurringAppointment.ResourceList, - StartDate = occurrence.Start, - Subject = recurringAppointment.Subject ?? Empty, - Type = recurringAppointment.Type - }; - - if (!(recurrenceId is null) && occurrenceIndex.HasValue) - { - var recId = occurrenceAppointment.GetRecurrenceId(); - - if ((recId?.Equals(recurrenceId.Value) ?? false) && index.Equals(occurrenceIndex.Value)) - { - continue; - } - } - - appointments.AddIfNotIn(occurrenceAppointment); - } - } - - appointments.DoForEach(a => a.ResourceList.DoForEach(resources.AddIfNotIn)); - - return resources; - } - - public IList FindCustomerServiceRecordsForKilometerauswertung(long customerOid, DateTimeSpan pSpan) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(ServiceRecord.CustomerOid), customerOid)) - .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) - .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); - - var orCriteria = Restrictions.Or( - Restrictions.Between(nameof(ServiceRecord.Start), pSpan.StartDateTime, pSpan.EndDateTime), - Restrictions.Between(nameof(ServiceRecord.End), pSpan.StartDateTime, pSpan.EndDateTime)); - - orCriteria = Restrictions.Or(orCriteria, - Restrictions.And( - Restrictions.Le(nameof(ServiceRecord.Start), pSpan.EndDateTime), - Restrictions.Ge(nameof(ServiceRecord.End), pSpan.StartDateTime))); - - lCriteria.Add(orCriteria); - - return lCriteria.List(); - } - - public Dictionary> FindListOfCustomerServiceRecordsForKilometerauswertung(List customerOids, List serviceDescriptionOids, DateTimeSpan span) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.In(nameof(ServiceRecord.CustomerOid), customerOids)) - .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) - .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); - - var orCriteria = Restrictions.Or( - Restrictions.Between(nameof(ServiceRecord.Start), span.StartDateTime, span.EndDateTime), - Restrictions.Between(nameof(ServiceRecord.End), span.StartDateTime, span.EndDateTime)); - - orCriteria = Restrictions.Or(orCriteria, - Restrictions.And( - Restrictions.Le(nameof(ServiceRecord.Start), span.EndDateTime), - Restrictions.Ge(nameof(ServiceRecord.End), span.StartDateTime))); - - lCriteria.Add(orCriteria); - - var allServiceRecords = lCriteria.List().ToList(); - - var result = new Dictionary>(); - - foreach (var serviceRecord in allServiceRecords) - { - if (serviceDescriptionOids == null || serviceDescriptionOids.Count == 0 || serviceDescriptionOids.Contains(serviceRecord.ServiceDescription.Oid.Value)) - { - result.AddOrUpdateValueInDictionary(serviceRecord.CustomerOid.Value, new List { serviceRecord }); - } - } - - return result; - } - - public bool CheckForAnyServiceRecordsWithDistanceValues(List customerOids, DateTimeSpan span) - { - return FindListOfCustomerServiceRecordsForKilometerauswertung(customerOids, null, span).Any(); - } - - public List GetAllCustomersForEmployee(long? employeeOid) - { - ApplicationUser user; - - if (employeeOid.HasValue) - { - var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); - user = FindUserForEmployee(employee); - } - else - { - if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) - { - user = LoggedInUserOperationContextExt.Current.User; - } - else - { - user = SessionFacade.LoggedInUser; - } - } - - var rights = new List(); - - user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); - - var lCriteria = CreateCriteriaIsActive(); - - if (rights.Contains(UserRightType.ViewAll) || rights.Contains(UserRightType.CustomerView_View)) - { - return lCriteria.List().ToList(); - } - - var result = new List(); - - if (rights.Contains(UserRightType.Customer_ViewMyCustomers)) - { - result = user.Employee.Employee2CustomerList.Select(employee2Customer => employee2Customer.Customer).Distinct().ToList(); - } - - if (rights.Contains(UserRightType.Customer_ViewMyTeams)) - { - var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); - - teams.DoForEach(team => { team.MemberList.DoForEach(member => result.AddRangeIfElementsNotIn(member.Employee2CustomerList.Select(employee2Customer => employee2Customer.Customer))); }); - } - - return result; - } - - // TODO 16.02.2021: Alias für EmployeeOid erstellen? - public IList GetConfirmationReceiptSignaturesByEmployee(long employeeOid, DateTimeSpan timeSpan) - { - var liste = CreateCriteria() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Employee)) - .Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) - //.Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.EmployeeOid), employeeOid)) - .CreateAlias(nameof(ConfirmationReceiptSignature.Employee), "e", JoinType.InnerJoin) - .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "s", JoinType.InnerJoin) - .Add(CreateBetweenDateTimesCriterion(timeSpan.StartDateTime, timeSpan.EndDateTime, "s.Start", "s.End")).List(); - - return liste; - } - - public List GetConfirmationReceiptSignaturesByServiceRecord(long serviceRecordOid) - { - var criteria = CreateCriteriaIsActive() - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") - .Add(Restrictions.Eq("serviceRecord.Oid", serviceRecordOid)); - - return criteria.List().ToList(); - } - - public IList FindEmployeeServiceRecordsForKilometerauswertung(long employeeOid, DateTimeSpan timeSpan) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(ServiceRecord.EmployeeOid), employeeOid)) - .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) - .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); - - var orCriteria = Restrictions.Or( - Restrictions.Between(nameof(ServiceRecord.Start), timeSpan.StartDateTime, timeSpan.EndDateTime), - Restrictions.Between(nameof(ServiceRecord.End), timeSpan.StartDateTime, timeSpan.EndDateTime)); - - orCriteria = Restrictions.Or(orCriteria, - Restrictions.And( - Restrictions.Le(nameof(ServiceRecord.Start), timeSpan.EndDateTime), - Restrictions.Ge(nameof(ServiceRecord.End), timeSpan.StartDateTime))); - - lCriteria.Add(orCriteria); - - return lCriteria.List(); - } - - public Dictionary> FindListOfEmployeeServiceRecordsForKilometerauswertung(List employeeOids, List serviceDescriptionOids, DateTimeSpan span) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.In(nameof(ServiceRecord.EmployeeOid), employeeOids)) - .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) - .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); - - var orCriteria = Restrictions.Or( - Restrictions.Between(nameof(ServiceRecord.Start), span.StartDateTime, span.EndDateTime), - Restrictions.Between(nameof(ServiceRecord.End), span.StartDateTime, span.EndDateTime)); - - orCriteria = Restrictions.Or(orCriteria, - Restrictions.And( - Restrictions.Le(nameof(ServiceRecord.Start), span.EndDateTime), - Restrictions.Ge(nameof(ServiceRecord.End), span.StartDateTime))); - - lCriteria.Add(orCriteria); - - var allServiceRecords = lCriteria.List().ToList(); - - var result = new Dictionary>(); - - foreach (var serviceRecord in allServiceRecords) - { - if (serviceDescriptionOids == null || serviceDescriptionOids.Count == 0 || serviceDescriptionOids.Contains(serviceRecord.ServiceDescription.Oid.Value)) - { - result.AddOrUpdateValueInDictionary(serviceRecord.EmployeeOid.Value, new List { serviceRecord }); - } - } - - return result; - } - - public IList GetAllActiveEmployeesForEmployee(long? employeeOid) - { - ApplicationUser user; - - if (employeeOid.HasValue) - { - var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); - user = FindUserForEmployee(employee); - } - else - { - if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) - { - user = LoggedInUserOperationContextExt.Current.User; - } - else - { - user = SessionFacade.LoggedInUser; - } - } - - if (user.Employee.Oid == null) - { - return new List(); - } - - var rights = new List(); - - user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); - - var lCriteria = CreateCriteriaIsActive(); - - if (rights.Contains(UserRightType.ViewAll) || rights.Contains(UserRightType.EmployeeView_View)) - { - return lCriteria.List().ToList(); - } - - var result = new List(); - - if (rights.Contains(UserRightType.Employee_AllowViewOwnEmployees)) - { - result.AddIfNotIn(user.Employee); - } - - if (rights.Contains(UserRightType.Employee_AllowViewOwnTeam)) - { - var leadingTeams = user.Employee.LeadingTeams; - leadingTeams.DoForEach(team => - { - result.AddIfNotIn(team.Leader); - - result.AddRangeIfElementsNotIn(team.MemberList); - }); - - var teams = FindTeamsOfEmployee(user.Employee.Oid.Value); - teams.DoForEach(team => - { - result.AddIfNotIn(team.Leader); - - result.AddRangeIfElementsNotIn(team.MemberList); - }); - } - - return result; - } - - public IList GetAllQuittierungsbelegStatusForMonth(DateTime start, DateTime ende) - { - DateTime begin = new DateTime(start.Year, start.Month, start.Day); - DateTime end = new DateTime(ende.Year, ende.Month, ende.Day); - - var crit = CreateCriteria(); - crit.Add(Restrictions.Ge("Startdatum", begin)); - crit.Add(Restrictions.Le("Enddatum", end)); - return crit.List(); - } - - public IList GetAllActiveVorlagentabellen() - { - var crit = CreateCriteria(); - crit.Add(Restrictions.Gt("IsActive", 0)); - return crit.List(); - } - - public IList GetAllDokumentvorlagenInFolder(long folderOid) - { - var crit = CreateCriteria(); - crit.Add(Restrictions.Eq("Parent", folderOid)); - - return crit.List(); - } - - // TODO 16.02.2021: Alias für EmployeeOid erstellen? - public bool HasConfirmationReceiptSignaturesByEmployeeAndServiceRecords(long employeeOid, IEnumerable serviceRecordOids) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Employee)) - //.Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.EmployeeOid), employeeOid)) - .CreateAlias(nameof(ConfirmationReceiptSignature.Employee), "e", JoinType.InnerJoin) - .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") - .Add(Restrictions.In("serviceRecord.Oid", serviceRecordOids.ToList())); - - var hasSignatures = criteria.List().Any(); - - return hasSignatures; - } - - public bool HasConfirmationReceiptSignatureByDateAndCustomer(long customerOid, DateTimeSpan timeSpan, SignatureType signatureType) - { - var start = timeSpan.StartDate; - var end = timeSpan.EndDate; - - var timeSpanCriterion = CreateBetweenDateTimesCriterion(start, end, $"serviceRecord.{nameof(ServiceRecord.Start)}", $"serviceRecord.{nameof(ServiceRecord.End)}"); - - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") - .Add(Restrictions.Eq($"serviceRecord.{nameof(ServiceRecord.CustomerOid)}", customerOid)) - .Add(timeSpanCriterion); - - return criteria.List().Any(); - } - - public IList GetAllActiveTeamsForEmployee(long? employeeOid) - { - ApplicationUser user; - var result = new List(); - - if (employeeOid.HasValue) - { - var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); - user = FindUserForEmployee(employee); - } - else - { - if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) - { - user = LoggedInUserOperationContextExt.Current.User; - } - else - { - user = SessionFacade.LoggedInUser; - } - } - - if (user.Employee.Oid == null) - { - return result; - } - - var rights = new List(); - - user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); - - if (rights.Contains(UserRightType.ViewAll) || rights.Contains(UserRightType.TeamView_ViewAll)) - { - return CreateCriteriaIsActive().List(); - } - - if (rights.Contains(UserRightType.TeamView_ViewMyTeams)) - { - result.AddRangeIfElementsNotIn(FindLeadingTeams(user.Employee.Oid.Value)); - result.AddRangeIfElementsNotIn(FindTeamsOfEmployee(user.Employee.Oid.Value)); - - return result; - } - - return result; - } - - // TODO 16.02.2021: Alias für EmployeeOid erstellen? - public IEnumerable FindConfirmationReceiptSignaturesByEmployeeAndServiceRecords(long employeeOid, IEnumerable serviceRecordOids) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Employee)) - //.Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.EmployeeOid), employeeOid)) - .CreateAlias(nameof(ConfirmationReceiptSignature.Employee), "e", JoinType.InnerJoin) - .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") - .Add(Restrictions.In("serviceRecord.Oid", serviceRecordOids.ToList())); - - return criteria.List(); - } - - //public SchedulerAppointment FindRootAppointmentByRecurrenceId(string recurrenceId) - //{ - // if(Guid.TryParse(recurrenceId, out var guid)) - // { - // var criteria = CreateCriteria() - // .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), recurrenceId, MatchMode.Anywhere)) - // .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); - - // return criteria.List().FirstOrDefault(); - // } - - // return null; - //} - - public SchedulerAppointment FindIndexZeroChangedOccurrence(Guid? recurrenceId) - { - if (recurrenceId == null) - { - return null; - } - - var kek = recurrenceId.ToString(); - - var str = $""; - - var criteria = CreateCriteria() - .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), str, MatchMode.Exact)) - .Add(Restrictions.Not(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), "Index=\"", MatchMode.Anywhere))) - .Add(Restrictions.Eq(nameof(Appointment.Type), 3)); - - return criteria.List().FirstOrDefault(); - } - - public string ValidateSchedulerAppointment(DateTime start, DateTime end, IEnumerable employees, IEnumerable customers, List resources, long originator, long? appointmentOid, Guid? recurrenceId = null, int occurrenceIndex = 0, bool shouldSkipResourceAvailability = false) - { - var resourceList = resources; - if (shouldSkipResourceAvailability) - { - resourceList = null; - } - var isOverlapping = OverlappingAppointmentsExist(start, end, employees, customers, resourceList, originator, appointmentOid, recurrenceId?.ToString() ?? "", occurrenceIndex); - - // Die Ressourcen werden auf Verfügbarkeit im ausgewählten Zeitraum geprüft - var info = shouldSkipResourceAvailability ? new Dictionary>() : CheckResourceAvailabilityWithEmployeeInformation(start, end, resources, appointmentOid, recurrenceId, occurrenceIndex); - - var stringBuilder = new StringBuilder(); - - foreach (var resourceName2Intervals in info) - { - stringBuilder.AppendLine($"Die Ressource \"{resourceName2Intervals.Key}\" ist im ausgewählten Zeitraum {start:dd.MM.yyyy HH:mm} bis {end:dd.MM.yyyy HH:mm} bereits gebucht:"); - if (!resourceName2Intervals.Value.All(IsNullOrWhiteSpace)) - { - stringBuilder.Append("\r\n\r\n"); - } - - foreach (var interval in resourceName2Intervals.Value) - { - stringBuilder.AppendLine($"{interval}"); - } - } - - if (isOverlapping) - { - if (info.Any()) - { - stringBuilder.Append("\n\n"); - } - - stringBuilder.Append("Dieser Termin überschneidet sich mit einem anderen bereits existierenden Termin."); - } - - if (info.Any() || isOverlapping) - { - stringBuilder.Append("\n\nMöchten Sie trotzdem speichern?"); - } - - return stringBuilder.ToString(); - } - - public virtual IList FindFileattachmentOids(string text) - { - var q = Session.CreateSQLQuery($"SELECT Oid, bewofolderoid, objectoid, objecttid, path FROM FileAttachment WHERE Path like '%{text}%'"); - - return q.List(); - } - - public List GetActiveSupportConceptsForEmployee(long? employeeOid, CustomerFilterEnum supportConceptFilter) - { - ApplicationUser user; - - if (employeeOid.HasValue) - { - var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); - user = FindUserForEmployee(employee); - } - else - { - if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) - { - user = LoggedInUserOperationContextExt.Current.User; - } - else - { - user = SessionFacade.LoggedInUser; - } - } - - var lCriteria = CreateCriteriaIsActive(); - - var teamCustomerOids = new List(); - - var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); - - teams.DoForEach(team => - { - var customer = FindCustomerOfTeam(team.Oid.Value); - - teamCustomerOids.AddRangeIfElementsNotIn(customer.Select(c => c.Oid.Value)); - }); - - // Der ApplicationUser darf alles Sehen oder alle Hilfepläne - if (user.CheckForAtLeastOneRight(new List { UserRightType.ViewAll, UserRightType.SupportConcept_ViewAllSupportConcepts }) && supportConceptFilter == CustomerFilterEnum.All) - { - return lCriteria.List().ToList(); - } - - var customerOids = user.Employee.Employee2CustomerList.Where(employee2Customer => employee2Customer.Customer.Oid.HasValue && (!employee2Customer.StartDate.HasValue || employee2Customer.StartDate <= DateTime.Now.Date) && (!employee2Customer.EndDate.HasValue || employee2Customer.EndDate >= DateTime.Now.Date)).Select(employee2Customer => employee2Customer.Customer.Oid.Value).Distinct().ToList(); - - // Wählt man "Nur Klienten meiner Teams anzeigen", sollen nicht die Hilfepläne der eigenen Klienten angezeigt werden. - if (supportConceptFilter == CustomerFilterEnum.TeamCustomer) - { - customerOids.Clear(); - } - - // Der ApplicationUser darf die Hilfepläne seiner Teams sehen - if (user.CheckForRight(UserRightType.SupportConcept_ViewMyTeams) && (supportConceptFilter == CustomerFilterEnum.TeamCustomer || supportConceptFilter == CustomerFilterEnum.All)) - { - foreach (var coid in customerOids) - { - if (!teamCustomerOids.Contains(coid)) - { - teamCustomerOids.Add(coid); - } - } - - return GetAllActiveSupportConceptsByCustomers(teamCustomerOids, true).ToList(); - } - - return GetAllActiveSupportConceptsByCustomers(customerOids, true).ToList(); - } - - public IEnumerable GetAllMobileTestAppointments() - { - var c = CreateCriteria() - .Add(Restrictions.Eq(nameof(SchedulerAppointment.Notice), "mob-dev-app")); - - return c.List(); - } - - public bool HasConfirmationReceiptSignature(IList serviceRecordOids, SignatureType signatureType) - { - // Prüfen, ob alle ServiceRecords mit ein und derselben Unterschrift verknüpft sind. - // Eine Unterschrift kann mehrere ServiceRecords in der LinkListe haben, die nicht in der zu prüfenden Oid-Liste sind. - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - - var signatures = c.List().ToList(); - - var result = false; - - if (serviceRecordOids.Any() && signatures.Any()) - { - var blubb = new List(); - signatures.DoForEach(s => - { - s.ServiceRecords.DoForEach(sr => - { - if (sr.Oid.HasValue) - { - blubb.AddIfNotIn(sr.Oid.Value); - } - }); - }); - - result = serviceRecordOids.ContainsSameItemsAs(blubb); - } - - return result; - } - - // ToDo: An neue Rechte anpassen! - // Methode, die herausfindet, ob eine Liste mit ServiceRecordOids zu genau einer Mitarbeiterunterschrift gehört - public ConfirmationReceiptSignature GetConfirmationReceiptSignatureForServiceRecords(List serviceRecordOids, SignatureType signatureType) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) - .AddOrder(Order.Desc(nameof(ConfirmationReceiptSignature.Oid))) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - - var signatures = c.List().ToList(); - - var relatedServiceRecordOids = new List(); - signatures.DoForEach(s => relatedServiceRecordOids.AddRangeIfElementsNotIn(s.ServiceRecords.Select(x => x.Oid.Value))); - - var containsItems = relatedServiceRecordOids.ContainsItems(serviceRecordOids); - - return containsItems ? signatures.FirstOrDefault() : null; - } - - public List LoadConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids, SignatureType signatureType) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - - // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) - c.SetResultTransformer(new DistinctRootEntityResultTransformer()); - - var result = c.List().ToList(); - - return result; - } - - public bool HasConfirmationReceiptSignaturesByCustomerAndServiceRecords(long customerOid, IEnumerable serviceRecordOids) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Customer)) - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.CustomerOid), customerOid)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") - .Add(Restrictions.In("serviceRecord.Oid", serviceRecordOids.ToList())); - - var hasSignatures = criteria.List().Any(); - - return hasSignatures; - } - - public List LoadConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids) - { - var c = CreateCriteriaIsActive() - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - - // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) - c.SetResultTransformer(new DistinctRootEntityResultTransformer()); - - var result = c.List().ToList(); - - return result; - } - - public List LoadServiceRecordOidsWithConfirmationReceiptSignatures(IList serviceRecordOids) - { - var c = CreateCriteriaIsActive() - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - - // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) - c.SetResultTransformer(new DistinctRootEntityResultTransformer()); - - var confirmationReceiptSignatures = c.List().ToList(); - - var result = new List(); - - confirmationReceiptSignatures.DoForEach(crs => crs.ServiceRecords.DoForEach(sr => - { - if (sr.Oid.HasValue) - { - result.AddIfNotIn(sr.Oid.Value); - } - })); - - return result; - } - - public List LoadServiceRecordOidsWithConfirmationReceiptSignatures(IList serviceRecordOids, SignatureType signatureType) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + // Sich wiederholende Termine erzeugen und dabei die Ausnahmen und gelöschten Ausnahmen ignorieren + var interval = new TimeInterval(start, end); + foreach (var recurringAppointment in recurringAppointments) + { + var recurrenceInfo = new RecurrenceInfo(); + recurrenceInfo.FromXml(recurringAppointment.RecurrenceInfo); + + var occurenceCalculator = OccurrenceCalculator.CreateInstance(recurrenceInfo); + + // Das Muster für die Terminserie wird berechnet + var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); + pattern.RecurrenceInfo.FromXml(recurringAppointment.RecurrenceInfo); + pattern.Start = pattern.RecurrenceInfo.Start; + pattern.End = pattern.RecurrenceInfo.End; + + if (!Guid.TryParse(pattern.RecurrenceInfo.Id.ToString(), out var patternId)) + { + continue; + } + + // Die Serientermine werden berechnet (ausnahmslos, d.h. es werden auch bearbeitete und gelöschte Termine erstellt, die herausgefiltert werden müssen). + var occurrences = occurenceCalculator.CalcOccurrences(interval, pattern); + + var occurrenceAppointments = occurrences.GetAppointments(interval); + + foreach (var occurrence in occurrenceAppointments) + { + if (recurringAppointment.EndDate is null || recurringAppointment.StartDate is null) + { + continue; + } + + // Sicher machen + var index = occurrence.RecurrenceIndex; + + var isDeletedOrChanged = changedOccurrences.Any(a => + { + var guid = a.GetRecurrenceIdAndIndex(out var i); + + if (guid is null) + { + return false; + } + + if (guid.Value.Equals(patternId) && index == i) + { + return true; + } + + return false; + }) || deletedOccurrences.Any(a => + { + var guid = a.GetRecurrenceIdAndIndex(out var i); + + if (guid is null) + { + return false; + } + + if (guid.Value.Equals(patternId) && index == i) + { + return true; + } + + return false; + }); + + if (isDeletedOrChanged) + { + continue; + } + + var duration = (recurringAppointment.EndDate.Value - recurringAppointment.StartDate.Value).TotalMinutes; + var isInIntervalTest = start.IsInInterval(end, occurrence.Start, occurrence.Start.AddMinutes(duration)); + + if (!isInIntervalTest) + { + continue; + } + + var occurrenceAppointment = new SchedulerAppointment + { + AllDay = occurrence.AllDay, + CustomerList = recurringAppointment.CustomerList, + Notice = recurringAppointment.Notice, + EmployeeList = recurringAppointment.EmployeeList, + EndDate = occurrence.Start.AddMinutes(duration), + FormerBookingSequenceOid = recurringAppointment.FormerBookingSequenceOid, + IsPrivate = recurringAppointment.IsPrivate, + Location = recurringAppointment.Location, + Originator = recurringAppointment.Originator, + RecurrenceInfo = occurrence.RecurrenceInfo.ToXml(), + ReminderInfo = recurringAppointment.ReminderInfo, + ResourceList = recurringAppointment.ResourceList, + StartDate = occurrence.Start, + Subject = recurringAppointment.Subject ?? Empty, + Type = recurringAppointment.Type + }; + + if (!(recurrenceId is null) && occurrenceIndex.HasValue) + { + var recId = occurrenceAppointment.GetRecurrenceId(); + + if ((recId?.Equals(recurrenceId.Value) ?? false) && index.Equals(occurrenceIndex.Value)) + { + continue; + } + } + + appointments.AddIfNotIn(occurrenceAppointment); + } + } + + appointments.DoForEach(a => a.ResourceList.DoForEach(resources.AddIfNotIn)); + + return resources; + } + + public IList FindCustomerServiceRecordsForKilometerauswertung(long customerOid, DateTimeSpan pSpan) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(ServiceRecord.CustomerOid), customerOid)) + .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) + .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); + + var orCriteria = Restrictions.Or( + Restrictions.Between(nameof(ServiceRecord.Start), pSpan.StartDateTime, pSpan.EndDateTime), + Restrictions.Between(nameof(ServiceRecord.End), pSpan.StartDateTime, pSpan.EndDateTime)); + + orCriteria = Restrictions.Or(orCriteria, + Restrictions.And( + Restrictions.Le(nameof(ServiceRecord.Start), pSpan.EndDateTime), + Restrictions.Ge(nameof(ServiceRecord.End), pSpan.StartDateTime))); + + lCriteria.Add(orCriteria); + + return lCriteria.List(); + } + + public Dictionary> FindListOfCustomerServiceRecordsForKilometerauswertung(List customerOids, List serviceDescriptionOids, DateTimeSpan span) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.In(nameof(ServiceRecord.CustomerOid), customerOids)) + .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) + .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); + + var orCriteria = Restrictions.Or( + Restrictions.Between(nameof(ServiceRecord.Start), span.StartDateTime, span.EndDateTime), + Restrictions.Between(nameof(ServiceRecord.End), span.StartDateTime, span.EndDateTime)); + + orCriteria = Restrictions.Or(orCriteria, + Restrictions.And( + Restrictions.Le(nameof(ServiceRecord.Start), span.EndDateTime), + Restrictions.Ge(nameof(ServiceRecord.End), span.StartDateTime))); + + lCriteria.Add(orCriteria); + + var allServiceRecords = lCriteria.List().ToList(); + + var result = new Dictionary>(); + + foreach (var serviceRecord in allServiceRecords) + { + if (serviceDescriptionOids == null || serviceDescriptionOids.Count == 0 || serviceDescriptionOids.Contains(serviceRecord.ServiceDescription.Oid.Value)) + { + result.AddOrUpdateValueInDictionary(serviceRecord.CustomerOid.Value, new List { serviceRecord }); + } + } + + return result; + } + + public bool CheckForAnyServiceRecordsWithDistanceValues(List customerOids, DateTimeSpan span) + { + return FindListOfCustomerServiceRecordsForKilometerauswertung(customerOids, null, span).Any(); + } + + public List GetAllCustomersForEmployee(long? employeeOid) + { + ApplicationUser user; + + if (employeeOid.HasValue) + { + var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); + user = FindUserForEmployee(employee); + } + else + { + if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) + { + user = LoggedInUserOperationContextExt.Current.User; + } + else + { + user = SessionFacade.LoggedInUser; + } + } + + var rights = new List(); + + user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); + + var lCriteria = CreateCriteriaIsActive(); + + if (rights.Contains(UserRightType.ViewAll) || rights.Contains(UserRightType.CustomerView_View)) + { + return lCriteria.List().ToList(); + } + + var result = new List(); + + if (rights.Contains(UserRightType.Customer_ViewMyCustomers)) + { + result = user.Employee.Employee2CustomerList.Select(employee2Customer => employee2Customer.Customer).Distinct().ToList(); + } + + if (rights.Contains(UserRightType.Customer_ViewMyTeams)) + { + var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); + + teams.DoForEach(team => { team.MemberList.DoForEach(member => result.AddRangeIfElementsNotIn(member.Employee2CustomerList.Select(employee2Customer => employee2Customer.Customer))); }); + } + + return result; + } + + // TODO 16.02.2021: Alias für EmployeeOid erstellen? + public IList GetConfirmationReceiptSignaturesByEmployee(long employeeOid, DateTimeSpan timeSpan) + { + var liste = CreateCriteria() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Employee)) + .Add(Restrictions.Eq(nameof(BeWoEntityBase.IsActive), ActivationTypeId.Active)) + //.Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.EmployeeOid), employeeOid)) + .CreateAlias(nameof(ConfirmationReceiptSignature.Employee), "e", JoinType.InnerJoin) + .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "s", JoinType.InnerJoin) + .Add(CreateBetweenDateTimesCriterion(timeSpan.StartDateTime, timeSpan.EndDateTime, "s.Start", "s.End")).List(); + + return liste; + } + + public List GetConfirmationReceiptSignaturesByServiceRecord(long serviceRecordOid) + { + var criteria = CreateCriteriaIsActive() + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") + .Add(Restrictions.Eq("serviceRecord.Oid", serviceRecordOid)); + + return criteria.List().ToList(); + } + + public IList FindEmployeeServiceRecordsForKilometerauswertung(long employeeOid, DateTimeSpan timeSpan) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(ServiceRecord.EmployeeOid), employeeOid)) + .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) + .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); + + var orCriteria = Restrictions.Or( + Restrictions.Between(nameof(ServiceRecord.Start), timeSpan.StartDateTime, timeSpan.EndDateTime), + Restrictions.Between(nameof(ServiceRecord.End), timeSpan.StartDateTime, timeSpan.EndDateTime)); + + orCriteria = Restrictions.Or(orCriteria, + Restrictions.And( + Restrictions.Le(nameof(ServiceRecord.Start), timeSpan.EndDateTime), + Restrictions.Ge(nameof(ServiceRecord.End), timeSpan.StartDateTime))); + + lCriteria.Add(orCriteria); + + return lCriteria.List(); + } + + public Dictionary> FindListOfEmployeeServiceRecordsForKilometerauswertung(List employeeOids, List serviceDescriptionOids, DateTimeSpan span) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.In(nameof(ServiceRecord.EmployeeOid), employeeOids)) + .Add(Restrictions.IsNotNull(nameof(ServiceRecord.DistanceInMeter))) + .Add(Restrictions.Gt(nameof(ServiceRecord.DistanceInMeter), 0m)); + + var orCriteria = Restrictions.Or( + Restrictions.Between(nameof(ServiceRecord.Start), span.StartDateTime, span.EndDateTime), + Restrictions.Between(nameof(ServiceRecord.End), span.StartDateTime, span.EndDateTime)); + + orCriteria = Restrictions.Or(orCriteria, + Restrictions.And( + Restrictions.Le(nameof(ServiceRecord.Start), span.EndDateTime), + Restrictions.Ge(nameof(ServiceRecord.End), span.StartDateTime))); + + lCriteria.Add(orCriteria); + + var allServiceRecords = lCriteria.List().ToList(); + + var result = new Dictionary>(); + + foreach (var serviceRecord in allServiceRecords) + { + if (serviceDescriptionOids == null || serviceDescriptionOids.Count == 0 || serviceDescriptionOids.Contains(serviceRecord.ServiceDescription.Oid.Value)) + { + result.AddOrUpdateValueInDictionary(serviceRecord.EmployeeOid.Value, new List { serviceRecord }); + } + } + + return result; + } + + public IList GetAllActiveEmployeesForEmployee(long? employeeOid) + { + ApplicationUser user; + + if (employeeOid.HasValue) + { + var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); + user = FindUserForEmployee(employee); + } + else + { + if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) + { + user = LoggedInUserOperationContextExt.Current.User; + } + else + { + user = SessionFacade.LoggedInUser; + } + } + + if (user.Employee.Oid == null) + { + return new List(); + } + + var rights = new List(); + + user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); + + var lCriteria = CreateCriteriaIsActive(); + + if (rights.Contains(UserRightType.ViewAll) || rights.Contains(UserRightType.EmployeeView_View)) + { + return lCriteria.List().ToList(); + } + + var result = new List(); + + if (rights.Contains(UserRightType.Employee_AllowViewOwnEmployees)) + { + result.AddIfNotIn(user.Employee); + } + + if (rights.Contains(UserRightType.Employee_AllowViewOwnTeam)) + { + var leadingTeams = user.Employee.LeadingTeams; + leadingTeams.DoForEach(team => + { + result.AddIfNotIn(team.Leader); + + result.AddRangeIfElementsNotIn(team.MemberList); + }); + + var teams = FindTeamsOfEmployee(user.Employee.Oid.Value); + teams.DoForEach(team => + { + result.AddIfNotIn(team.Leader); + + result.AddRangeIfElementsNotIn(team.MemberList); + }); + } + + return result; + } + + public IList GetAllQuittierungsbelegStatusForMonth(DateTime start, DateTime ende) + { + DateTime begin = new DateTime(start.Year, start.Month, start.Day); + DateTime end = new DateTime(ende.Year, ende.Month, ende.Day); + + var crit = CreateCriteria(); + crit.Add(Restrictions.Ge("Startdatum", begin)); + crit.Add(Restrictions.Le("Enddatum", end)); + return crit.List(); + } + + public IList GetAllActiveVorlagentabellen() + { + var crit = CreateCriteria(); + crit.Add(Restrictions.Gt("IsActive", 0)); + return crit.List(); + } + + public IList GetAllDokumentvorlagenInFolder(long folderOid) + { + var crit = CreateCriteria(); + crit.Add(Restrictions.Eq("Parent", folderOid)); + + return crit.List(); + } + + // TODO 16.02.2021: Alias für EmployeeOid erstellen? + public bool HasConfirmationReceiptSignaturesByEmployeeAndServiceRecords(long employeeOid, IEnumerable serviceRecordOids) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Employee)) + //.Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.EmployeeOid), employeeOid)) + .CreateAlias(nameof(ConfirmationReceiptSignature.Employee), "e", JoinType.InnerJoin) + .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") + .Add(Restrictions.In("serviceRecord.Oid", serviceRecordOids.ToList())); + + var hasSignatures = criteria.List().Any(); + + return hasSignatures; + } + + public bool HasConfirmationReceiptSignatureByDateAndCustomer(long customerOid, DateTimeSpan timeSpan, SignatureType signatureType) + { + var start = timeSpan.StartDate; + var end = timeSpan.EndDate; + + var timeSpanCriterion = CreateBetweenDateTimesCriterion(start, end, $"serviceRecord.{nameof(ServiceRecord.Start)}", $"serviceRecord.{nameof(ServiceRecord.End)}"); + + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") + .Add(Restrictions.Eq($"serviceRecord.{nameof(ServiceRecord.CustomerOid)}", customerOid)) + .Add(timeSpanCriterion); + + return criteria.List().Any(); + } + + public IList GetAllActiveTeamsForEmployee(long? employeeOid) + { + ApplicationUser user; + var result = new List(); + + if (employeeOid.HasValue) + { + var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); + user = FindUserForEmployee(employee); + } + else + { + if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) + { + user = LoggedInUserOperationContextExt.Current.User; + } + else + { + user = SessionFacade.LoggedInUser; + } + } + + if (user.Employee.Oid == null) + { + return result; + } + + var rights = new List(); + + user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); + + if (rights.Contains(UserRightType.ViewAll) || rights.Contains(UserRightType.TeamView_ViewAll)) + { + return CreateCriteriaIsActive().List(); + } + + if (rights.Contains(UserRightType.TeamView_ViewMyTeams)) + { + result.AddRangeIfElementsNotIn(FindLeadingTeams(user.Employee.Oid.Value)); + result.AddRangeIfElementsNotIn(FindTeamsOfEmployee(user.Employee.Oid.Value)); + + return result; + } + + return result; + } + + // TODO 16.02.2021: Alias für EmployeeOid erstellen? + public IEnumerable FindConfirmationReceiptSignaturesByEmployeeAndServiceRecords(long employeeOid, IEnumerable serviceRecordOids) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Employee)) + //.Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.EmployeeOid), employeeOid)) + .CreateAlias(nameof(ConfirmationReceiptSignature.Employee), "e", JoinType.InnerJoin) + .Add(Restrictions.Eq(nameof(BeWoEntityBase.Oid), employeeOid)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") + .Add(Restrictions.In("serviceRecord.Oid", serviceRecordOids.ToList())); + + return criteria.List(); + } + + //public SchedulerAppointment FindRootAppointmentByRecurrenceId(string recurrenceId) + //{ + // if(Guid.TryParse(recurrenceId, out var guid)) + // { + // var criteria = CreateCriteria() + // .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), recurrenceId, MatchMode.Anywhere)) + // .Add(Restrictions.Eq(nameof(Appointment.Type), 1)); + + // return criteria.List().FirstOrDefault(); + // } + + // return null; + //} + + public SchedulerAppointment FindIndexZeroChangedOccurrence(Guid? recurrenceId) + { + if (recurrenceId == null) + { + return null; + } + + var kek = recurrenceId.ToString(); + + var str = $""; + + var criteria = CreateCriteria() + .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), str, MatchMode.Exact)) + .Add(Restrictions.Not(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), "Index=\"", MatchMode.Anywhere))) + .Add(Restrictions.Eq(nameof(Appointment.Type), 3)); + + return criteria.List().FirstOrDefault(); + } + + public string ValidateSchedulerAppointment(DateTime start, DateTime end, IEnumerable employees, IEnumerable customers, List resources, long originator, long? appointmentOid, Guid? recurrenceId = null, int occurrenceIndex = 0, bool shouldSkipResourceAvailability = false) + { + var resourceList = resources; + if (shouldSkipResourceAvailability) + { + resourceList = null; + } + var isOverlapping = OverlappingAppointmentsExist(start, end, employees, customers, resourceList, originator, appointmentOid, recurrenceId?.ToString() ?? "", occurrenceIndex); + + // Die Ressourcen werden auf Verfügbarkeit im ausgewählten Zeitraum geprüft + var info = shouldSkipResourceAvailability ? new Dictionary>() : CheckResourceAvailabilityWithEmployeeInformation(start, end, resources, appointmentOid, recurrenceId, occurrenceIndex); + + var stringBuilder = new StringBuilder(); + + foreach (var resourceName2Intervals in info) + { + stringBuilder.AppendLine($"Die Ressource \"{resourceName2Intervals.Key}\" ist im ausgewählten Zeitraum {start:dd.MM.yyyy HH:mm} bis {end:dd.MM.yyyy HH:mm} bereits gebucht:"); + if (!resourceName2Intervals.Value.All(IsNullOrWhiteSpace)) + { + stringBuilder.Append("\r\n\r\n"); + } + + foreach (var interval in resourceName2Intervals.Value) + { + stringBuilder.AppendLine($"{interval}"); + } + } + + if (isOverlapping) + { + if (info.Any()) + { + stringBuilder.Append("\n\n"); + } + + stringBuilder.Append("Dieser Termin überschneidet sich mit einem anderen bereits existierenden Termin."); + } + + if (info.Any() || isOverlapping) + { + stringBuilder.Append("\n\nMöchten Sie trotzdem speichern?"); + } + + return stringBuilder.ToString(); + } + + public virtual IList FindFileattachmentOids(string text) + { + var q = Session.CreateSQLQuery($"SELECT Oid, bewofolderoid, objectoid, objecttid, path FROM FileAttachment WHERE Path like '%{text}%'"); + + return q.List(); + } + + public List GetActiveSupportConceptsForEmployee(long? employeeOid, CustomerFilterEnum supportConceptFilter) + { + ApplicationUser user; + + if (employeeOid.HasValue) + { + var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); + user = FindUserForEmployee(employee); + } + else + { + if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) + { + user = LoggedInUserOperationContextExt.Current.User; + } + else + { + user = SessionFacade.LoggedInUser; + } + } + + var lCriteria = CreateCriteriaIsActive(); + + var teamCustomerOids = new List(); + + var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); + + teams.DoForEach(team => + { + var customer = FindCustomerOfTeam(team.Oid.Value); + + teamCustomerOids.AddRangeIfElementsNotIn(customer.Select(c => c.Oid.Value)); + }); + + // Der ApplicationUser darf alles Sehen oder alle Hilfepläne + if (user.CheckForAtLeastOneRight(new List { UserRightType.ViewAll, UserRightType.SupportConcept_ViewAllSupportConcepts }) && supportConceptFilter == CustomerFilterEnum.All) + { + return lCriteria.List().ToList(); + } + + var customerOids = user.Employee.Employee2CustomerList.Where(employee2Customer => employee2Customer.Customer.Oid.HasValue && (!employee2Customer.StartDate.HasValue || employee2Customer.StartDate <= DateTime.Now.Date) && (!employee2Customer.EndDate.HasValue || employee2Customer.EndDate >= DateTime.Now.Date)).Select(employee2Customer => employee2Customer.Customer.Oid.Value).Distinct().ToList(); + + // Wählt man "Nur Klienten meiner Teams anzeigen", sollen nicht die Hilfepläne der eigenen Klienten angezeigt werden. + if (supportConceptFilter == CustomerFilterEnum.TeamCustomer) + { + customerOids.Clear(); + } + + // Der ApplicationUser darf die Hilfepläne seiner Teams sehen + if (user.CheckForRight(UserRightType.SupportConcept_ViewMyTeams) && (supportConceptFilter == CustomerFilterEnum.TeamCustomer || supportConceptFilter == CustomerFilterEnum.All)) + { + foreach (var coid in customerOids) + { + if (!teamCustomerOids.Contains(coid)) + { + teamCustomerOids.Add(coid); + } + } + + return GetAllActiveSupportConceptsByCustomers(teamCustomerOids, true).ToList(); + } + + return GetAllActiveSupportConceptsByCustomers(customerOids, true).ToList(); + } + + public IEnumerable GetAllMobileTestAppointments() + { + var c = CreateCriteria() + .Add(Restrictions.Eq(nameof(SchedulerAppointment.Notice), "mob-dev-app")); + + return c.List(); + } + + public bool HasConfirmationReceiptSignature(IList serviceRecordOids, SignatureType signatureType) + { + // Prüfen, ob alle ServiceRecords mit ein und derselben Unterschrift verknüpft sind. + // Eine Unterschrift kann mehrere ServiceRecords in der LinkListe haben, die nicht in der zu prüfenden Oid-Liste sind. + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + + var signatures = c.List().ToList(); + + var result = false; + + if (serviceRecordOids.Any() && signatures.Any()) + { + var blubb = new List(); + signatures.DoForEach(s => + { + s.ServiceRecords.DoForEach(sr => + { + if (sr.Oid.HasValue) + { + blubb.AddIfNotIn(sr.Oid.Value); + } + }); + }); + + result = serviceRecordOids.ContainsSameItemsAs(blubb); + } + + return result; + } + + // ToDo: An neue Rechte anpassen! + // Methode, die herausfindet, ob eine Liste mit ServiceRecordOids zu genau einer Mitarbeiterunterschrift gehört + public ConfirmationReceiptSignature GetConfirmationReceiptSignatureForServiceRecords(List serviceRecordOids, SignatureType signatureType) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) + .AddOrder(Order.Desc(nameof(ConfirmationReceiptSignature.Oid))) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + + var signatures = c.List().ToList(); + + var relatedServiceRecordOids = new List(); + signatures.DoForEach(s => relatedServiceRecordOids.AddRangeIfElementsNotIn(s.ServiceRecords.Select(x => x.Oid.Value))); + + var containsItems = relatedServiceRecordOids.ContainsItems(serviceRecordOids); + + return containsItems ? signatures.FirstOrDefault() : null; + } + + public List LoadConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids, SignatureType signatureType) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + + // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) + c.SetResultTransformer(new DistinctRootEntityResultTransformer()); + + var result = c.List().ToList(); + + return result; + } + + public bool HasConfirmationReceiptSignaturesByCustomerAndServiceRecords(long customerOid, IEnumerable serviceRecordOids) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), SignatureType.Customer)) + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.CustomerOid), customerOid)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecord") + .Add(Restrictions.In("serviceRecord.Oid", serviceRecordOids.ToList())); + + var hasSignatures = criteria.List().Any(); + + return hasSignatures; + } + + public List LoadConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids) + { + var c = CreateCriteriaIsActive() + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + + // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) + c.SetResultTransformer(new DistinctRootEntityResultTransformer()); + + var result = c.List().ToList(); + + return result; + } + + public List LoadServiceRecordOidsWithConfirmationReceiptSignatures(IList serviceRecordOids) + { + var c = CreateCriteriaIsActive() + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + + // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) + c.SetResultTransformer(new DistinctRootEntityResultTransformer()); + + var confirmationReceiptSignatures = c.List().ToList(); + + var result = new List(); + + confirmationReceiptSignatures.DoForEach(crs => crs.ServiceRecords.DoForEach(sr => + { + if (sr.Oid.HasValue) + { + result.AddIfNotIn(sr.Oid.Value); + } + })); + + return result; + } + + public List LoadServiceRecordOidsWithConfirmationReceiptSignatures(IList serviceRecordOids, SignatureType signatureType) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) - c.SetResultTransformer(new DistinctRootEntityResultTransformer()); + // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) + c.SetResultTransformer(new DistinctRootEntityResultTransformer()); - var confirmationReceiptSignatures = c.List().ToList(); + var confirmationReceiptSignatures = c.List().ToList(); - var result = new List(); + var result = new List(); - confirmationReceiptSignatures.DoForEach(crs => crs.ServiceRecords.DoForEach(sr => - { - if (sr.Oid.HasValue) - { - result.AddIfNotIn(sr.Oid.Value); - } - })); + confirmationReceiptSignatures.DoForEach(crs => crs.ServiceRecords.DoForEach(sr => + { + if (sr.Oid.HasValue) + { + result.AddIfNotIn(sr.Oid.Value); + } + })); - return result; - } + return result; + } - public IEnumerable GetServiceRecordsWithoutConfirmationReceiptSignature(IList serviceRecordOids, SignatureType signatureType) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())) - .SetResultTransformer(new DistinctRootEntityResultTransformer()); - - var confirmationReceiptSignatures = c.List().ToList(); - - var serviceRecords = new List(); - - confirmationReceiptSignatures.DoForEach(crs => serviceRecords.AddRangeIfElementsNotIn(crs.ServiceRecords)); - - return serviceRecords; - } - - public InvoiceBase FindMaxInvoiceNumber(string numberPrefix) - { - return CreateCriteriaIsActive() - .Add(Restrictions.Like(InvoiceBase.PropertyName_InvoiceNumber, numberPrefix + "%")) - .List().OrderByDescending(i => i.InvoiceNumber).FirstOrDefault(); - - } - - public List GetActiveCustomersForEmployee(long? employeeOid, CustomerFilterEnum customerFilter, bool ignoreViewAllRight = false) - { - ApplicationUser user; - - if (employeeOid.HasValue) - { - var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); - user = FindUserForEmployee(employee); - } - else - { - user = LoggedInUserOperationContextExt.Current?.User != null ? LoggedInUserOperationContextExt.Current.User : SessionFacade.LoggedInUser; - } - - var lCriteria = CreateCriteriaIsActive(); - - // Der ApplicationUser darf alles sehen - var viewAllRights = new List { UserRightType.CustomerView_View }; - if (!ignoreViewAllRight) - { - viewAllRights.Add(UserRightType.ViewAll); - } - - if (user.CheckForAtLeastOneRight(viewAllRights) && customerFilter == CustomerFilterEnum.All) - { - return lCriteria.List().ToList(); - } - - var customerOids = user.Employee.Employee2CustomerList.Where(employee2Customer => employee2Customer.Customer.Oid.HasValue).Select(employee2Customer => employee2Customer.Customer.Oid.Value).Distinct().ToList(); - - // Der ApplicationUser darf die Klienten seiner Teams sehen - if (user.CheckForRight(UserRightType.Customer_ViewMyTeams) && (customerFilter == CustomerFilterEnum.TeamCustomer || customerFilter == CustomerFilterEnum.All) && (user.Employee?.Oid.HasValue ?? false)) - { - var teamCustomerOids = new List(); - - var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); - - teams.DoForEach(team => - { - if (team.Oid is null) - { - return; - } - - var customer = FindCustomerOfTeam(team.Oid.Value); - - teamCustomerOids.AddRangeIfElementsNotIn(customer.Where(w => w.Oid.HasValue).Select(c => c.Oid.Value)); - }); - - //foreach (var customerOid in customerOids.Where(customerOid => !teamCustomerOids.Contains(customerOid))) - //{ - // teamCustomerOids.Add(customerOid); - //} - - return lCriteria.Add(Restrictions.In(nameof(Customer.Oid), teamCustomerOids.ToArray())).List().ToList(); - } - - // Der ApplicationUser darf nur seine eigenen Klienten sehen - return lCriteria.Add(Restrictions.In(nameof(Customer.Oid), customerOids.ToArray())).List().ToList(); - } - - public IList FindFamilyMemberOids() - { - var q = Session.CreateSQLQuery("SELECT personoid FROM customer2person where istfamilie = 1"); - return q.List(); - } - - public IList FindCustomerOid2Persons(IList personOids) - { - if (personOids == null || personOids.Count == 0) - { - return null; - } - - String oidList = ""; - foreach (var oid in personOids) - { - if (oidList.Length > 0) - { - oidList += ","; - } - oidList += String.Format("{0}", oid); - } - - return GetSqlResult("SELECT oid,personoid,customeroid,istfamilie FROM customer2person where personoid in (" + oidList + ")"); - - } - - public List FindActiveAppointmentsForCustomers(List customerOids, DateTime startDate, DateTime endDate) - { - var customerOidSqlString = string.Empty; - customerOids.DoForEach(oid => customerOidSqlString += $"{oid},"); - customerOidSqlString = customerOidSqlString.Trim(','); - - var sqlQuery = $" {nameof(BeWoEntityBase.Oid)} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({customerOidSqlString})) "; - var customerCriterion = Expression.Sql(sqlQuery); - - var between = CreateBetweenDateTimesCriterion(startDate, endDate, nameof(SchedulerAppointment.StartDate), nameof(SchedulerAppointment.EndDate)); - - var criteria = CreateCriteriaIsActive() - .Add(customerCriterion) - .Add(between) - .Add(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), false)); - - return criteria.List().ToList(); - } - - public List LoadFilteredAllActiveAppointments(long employeeOid, DateTime start, DateTime end, List customerOids) - { - var appointments = LoadFilteredAppointments( - true, - employeeOid, - start, end, - new List(), - customerOids, - new List(), - false, - true, - false, - false, - false, - false, - true); - - return appointments.ToList(); - } - - public List FindServiceRecordsForFlsAuslastungsauswertungByCustomerAndEmployees(long? customerOid, List employeeOids, DateTime start, DateTime end, bool onlyBillableCategories) - { - var c = CreateCriteriaIsActive().Add(Restrictions.Eq(nameof(ServiceRecord.CustomerOid), customerOid)); - - c.Add(Restrictions.In(nameof(ServiceRecord.EmployeeOid), employeeOids)); - - var betweenCriterion = CreateBetweenDateTimesCriterion(start, end, nameof(ServiceRecord.Start), nameof(ServiceRecord.End)); - - c.Add(betweenCriterion); - - if (onlyBillableCategories) - { - c.CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .Add(Restrictions.Eq("sc." + ServiceCategory.PropertyName_IsBillable, true)); - } - - return c.List().ToList(); - } - - public IList FindGeschenkteUrlaubstageByEmpOid(long empOid) - { - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.Eq("Employee", empOid)); - - return criteria.List(); - } - public IList FindGeschenkteUrlaubstageByYear(int year) - { - DateTime start = new DateTime(year, 1, 1).AddTicks(-1); - DateTime end = new DateTime(year, 12, 31).AddDays(1).AddTicks(-1); - - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.Between("Date", start, end)); - - return criteria.List(); - } - - public List GetActiveServiceRecordsBySupportConceptWithServiceCategoryForCustomer(List customerOids, long serviceCategoryOid, int month, int year) - { - var c = CreateCriteriaIsActive() - .Add(Restrictions.In(nameof(SupportConcept.Customer) + ".Oid", customerOids.ToArray())) - .CreateAlias(SupportConcept.PropertyName_ServiceAccountings, "sa", JoinType.InnerJoin) - .CreateAlias("sa." + nameof(ServiceAccounting.ServiceDescription), "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "cat", JoinType.InnerJoin) - .Add(Restrictions.Eq("cat.Oid", serviceCategoryOid)); - - var c2 = CreateCriteriaIsActive() - .Add(Restrictions.In(nameof(SupportConcept.Customer) + ".Oid", customerOids.ToArray())) - .Add(Restrictions.IsEmpty(nameof(SupportConcept.ServiceAccountings))); - - var supportConcepts = c.List().ToList(); - supportConcepts.AddRangeIfElementsNotIn(c2.List()); - - var start = new DateTime(year, month, 1, 0, 0, 0); - var end = start.AddMonths(1).AddSeconds(-1); - - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.In(nameof(ServiceRecord.CustomerOid), customerOids.ToArray())) - .Add(CreateBetweenDateTimesCriterion(start, end, "Start", "End")) - .Add(Restrictions.In(nameof(ServiceRecord.SupportConcept) + ".Oid", supportConcepts.Select(sc => sc.Oid).ToArray())); - - return criteria.List().ToList(); - } - - public List GetCustomersForEmployeeWithServiceRecordsInInterval(DateTime start, DateTime end, long employeeOid) - { - var result = new List(); - - // Customers aus Zeitraum, die ServiceRecords haben, wo der Employee dabei ist. - var serviceRecords = FindEmployeeServiceRecords(employeeOid, new DateTimeSpan(start, end), null, null); - - serviceRecords.DoForEach(sr => - { - if (sr?.Customer != null) - { - result.AddIfNotIn(sr.Customer); - } - }); - - return result; - } - - public List GetCustomersForTeamWithServiceRecordsInInterval(DateTime start, DateTime end, List employeeOids) - { - var result = new List(); - - var serviceRecords = FindEmployeeServiceRecords(employeeOids, new DateTimeSpan(start, end)); - - serviceRecords.DoForEach(sr => - { - if (sr?.Customer != null) - { - result.AddIfNotIn(sr.Customer); - } - }); + public IEnumerable GetServiceRecordsWithoutConfirmationReceiptSignature(IList serviceRecordOids, SignatureType signatureType) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())) + .SetResultTransformer(new DistinctRootEntityResultTransformer()); + + var confirmationReceiptSignatures = c.List().ToList(); + + var serviceRecords = new List(); + + confirmationReceiptSignatures.DoForEach(crs => serviceRecords.AddRangeIfElementsNotIn(crs.ServiceRecords)); + + return serviceRecords; + } + + public InvoiceBase FindMaxInvoiceNumber(string numberPrefix) + { + return CreateCriteriaIsActive() + .Add(Restrictions.Like(InvoiceBase.PropertyName_InvoiceNumber, numberPrefix + "%")) + .List().OrderByDescending(i => i.InvoiceNumber).FirstOrDefault(); + + } + + public List GetActiveCustomersForEmployee(long? employeeOid, CustomerFilterEnum customerFilter, bool ignoreViewAllRight = false) + { + ApplicationUser user; + + if (employeeOid.HasValue) + { + var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); + user = FindUserForEmployee(employee); + } + else + { + user = LoggedInUserOperationContextExt.Current?.User != null ? LoggedInUserOperationContextExt.Current.User : SessionFacade.LoggedInUser; + } + + var lCriteria = CreateCriteriaIsActive(); + + // Der ApplicationUser darf alles sehen + var viewAllRights = new List { UserRightType.CustomerView_View }; + if (!ignoreViewAllRight) + { + viewAllRights.Add(UserRightType.ViewAll); + } + + if (user.CheckForAtLeastOneRight(viewAllRights) && customerFilter == CustomerFilterEnum.All) + { + return lCriteria.List().ToList(); + } + + var customerOids = user.Employee.Employee2CustomerList.Where(employee2Customer => employee2Customer.Customer.Oid.HasValue).Select(employee2Customer => employee2Customer.Customer.Oid.Value).Distinct().ToList(); + + // Der ApplicationUser darf die Klienten seiner Teams sehen + if (user.CheckForRight(UserRightType.Customer_ViewMyTeams) && (customerFilter == CustomerFilterEnum.TeamCustomer || customerFilter == CustomerFilterEnum.All) && (user.Employee?.Oid.HasValue ?? false)) + { + var teamCustomerOids = new List(); + + var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); + + teams.DoForEach(team => + { + if (team.Oid is null) + { + return; + } + + var customer = FindCustomerOfTeam(team.Oid.Value); + + teamCustomerOids.AddRangeIfElementsNotIn(customer.Where(w => w.Oid.HasValue).Select(c => c.Oid.Value)); + }); + + //foreach (var customerOid in customerOids.Where(customerOid => !teamCustomerOids.Contains(customerOid))) + //{ + // teamCustomerOids.Add(customerOid); + //} + + return lCriteria.Add(Restrictions.In(nameof(Customer.Oid), teamCustomerOids.ToArray())).List().ToList(); + } + + // Der ApplicationUser darf nur seine eigenen Klienten sehen + return lCriteria.Add(Restrictions.In(nameof(Customer.Oid), customerOids.ToArray())).List().ToList(); + } + + public IList FindFamilyMemberOids() + { + var q = Session.CreateSQLQuery("SELECT personoid FROM customer2person where istfamilie = 1"); + return q.List(); + } + + public IList FindCustomerOid2Persons(IList personOids) + { + if (personOids == null || personOids.Count == 0) + { + return null; + } + + String oidList = ""; + foreach (var oid in personOids) + { + if (oidList.Length > 0) + { + oidList += ","; + } + oidList += String.Format("{0}", oid); + } + + return GetSqlResult("SELECT oid,personoid,customeroid,istfamilie FROM customer2person where personoid in (" + oidList + ")"); + + } + + public List FindActiveAppointmentsForCustomers(List customerOids, DateTime startDate, DateTime endDate) + { + var customerOidSqlString = string.Empty; + customerOids.DoForEach(oid => customerOidSqlString += $"{oid},"); + customerOidSqlString = customerOidSqlString.Trim(','); + + var sqlQuery = $" {nameof(BeWoEntityBase.Oid)} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({customerOidSqlString})) "; + var customerCriterion = Expression.Sql(sqlQuery); + + var between = CreateBetweenDateTimesCriterion(startDate, endDate, nameof(SchedulerAppointment.StartDate), nameof(SchedulerAppointment.EndDate)); + + var criteria = CreateCriteriaIsActive() + .Add(customerCriterion) + .Add(between) + .Add(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), false)); + + return criteria.List().ToList(); + } + + public List LoadFilteredAllActiveAppointments(long employeeOid, DateTime start, DateTime end, List customerOids) + { + var appointments = LoadFilteredAppointments( + true, + employeeOid, + start, end, + new List(), + customerOids, + new List(), + false, + true, + false, + false, + false, + false, + true); + + return appointments.ToList(); + } + + public List FindServiceRecordsForFlsAuslastungsauswertungByCustomerAndEmployees(long? customerOid, List employeeOids, DateTime start, DateTime end, bool onlyBillableCategories) + { + var c = CreateCriteriaIsActive().Add(Restrictions.Eq(nameof(ServiceRecord.CustomerOid), customerOid)); + + c.Add(Restrictions.In(nameof(ServiceRecord.EmployeeOid), employeeOids)); + + var betweenCriterion = CreateBetweenDateTimesCriterion(start, end, nameof(ServiceRecord.Start), nameof(ServiceRecord.End)); + + c.Add(betweenCriterion); + + if (onlyBillableCategories) + { + c.CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .Add(Restrictions.Eq("sc." + ServiceCategory.PropertyName_IsBillable, true)); + } + + return c.List().ToList(); + } + + public IList FindGeschenkteUrlaubstageByEmpOid(long empOid) + { + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.Eq("Employee", empOid)); + + return criteria.List(); + } + public IList FindGeschenkteUrlaubstageByYear(int year) + { + DateTime start = new DateTime(year, 1, 1).AddTicks(-1); + DateTime end = new DateTime(year, 12, 31).AddDays(1).AddTicks(-1); + + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.Between("Date", start, end)); + + return criteria.List(); + } + + public List GetActiveServiceRecordsBySupportConceptWithServiceCategoryForCustomer(List customerOids, long serviceCategoryOid, int month, int year) + { + var c = CreateCriteriaIsActive() + .Add(Restrictions.In(nameof(SupportConcept.Customer) + ".Oid", customerOids.ToArray())) + .CreateAlias(SupportConcept.PropertyName_ServiceAccountings, "sa", JoinType.InnerJoin) + .CreateAlias("sa." + nameof(ServiceAccounting.ServiceDescription), "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "cat", JoinType.InnerJoin) + .Add(Restrictions.Eq("cat.Oid", serviceCategoryOid)); + + var c2 = CreateCriteriaIsActive() + .Add(Restrictions.In(nameof(SupportConcept.Customer) + ".Oid", customerOids.ToArray())) + .Add(Restrictions.IsEmpty(nameof(SupportConcept.ServiceAccountings))); + + var supportConcepts = c.List().ToList(); + supportConcepts.AddRangeIfElementsNotIn(c2.List()); + + var start = new DateTime(year, month, 1, 0, 0, 0); + var end = start.AddMonths(1).AddSeconds(-1); + + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.In(nameof(ServiceRecord.CustomerOid), customerOids.ToArray())) + .Add(CreateBetweenDateTimesCriterion(start, end, "Start", "End")) + .Add(Restrictions.In(nameof(ServiceRecord.SupportConcept) + ".Oid", supportConcepts.Select(sc => sc.Oid).ToArray())); + + return criteria.List().ToList(); + } + + public List GetCustomersForEmployeeWithServiceRecordsInInterval(DateTime start, DateTime end, long employeeOid) + { + var result = new List(); + + // Customers aus Zeitraum, die ServiceRecords haben, wo der Employee dabei ist. + var serviceRecords = FindEmployeeServiceRecords(employeeOid, new DateTimeSpan(start, end), null, null); + + serviceRecords.DoForEach(sr => + { + if (sr?.Customer != null) + { + result.AddIfNotIn(sr.Customer); + } + }); + + return result; + } + + public List GetCustomersForTeamWithServiceRecordsInInterval(DateTime start, DateTime end, List employeeOids) + { + var result = new List(); + + var serviceRecords = FindEmployeeServiceRecords(employeeOids, new DateTimeSpan(start, end)); + + serviceRecords.DoForEach(sr => + { + if (sr?.Customer != null) + { + result.AddIfNotIn(sr.Customer); + } + }); - return result; - } + return result; + } - public IList FindEmployeeServiceRecords(List employeeOids, DateTimeSpan span) - { - var lCriteria = CreateCriteria() - .Add(Restrictions.In(nameof(ServiceRecord.EmployeeOid), employeeOids)); - - if (span != null) - { - lCriteria.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, span.StartDateTime, span.EndDateTime)); - } - - var result = lCriteria.List().ToList(); - - return result; - } - - public IList FindDiensteForWohnheim(long? whOid) - { - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.Or(Restrictions.Eq("Wohnheim", whOid), Restrictions.IsNull("Wohnheim"))); - - return criteria.List(); // Hier fliegt man raus - } - - public long? GetActiveMedVerListOidForCustomer(long customerOid) - { - // Gültig und MedListType = 0 - return GetActiveMedListByTypeForCustomer(customerOid, false); - } - - public long? GetActiveMedListByTypeForCustomer(long customerOid, bool isBedarfsmedikation) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(Medikamentenverordnungsliste.Gueltig), true)) - .Add(Restrictions.Eq(nameof(Medikamentenverordnungsliste.Customer) + ".Oid", customerOid)) - .Add(Restrictions.Eq(nameof(Medikamentenverordnungsliste.MedListType), isBedarfsmedikation)); - - var list = criteria.UniqueResult(); - - return list?.Oid; - } - - public List LoadOccurrencesByRecurrenceId(string recurrenceId) - { - var criteria = CreateCriteria() - .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), recurrenceId, MatchMode.Anywhere)); + public IList FindEmployeeServiceRecords(List employeeOids, DateTimeSpan span) + { + var lCriteria = CreateCriteria() + .Add(Restrictions.In(nameof(ServiceRecord.EmployeeOid), employeeOids)); + + if (span != null) + { + lCriteria.Add(Restrictions.Between(ServiceRecord.PropertyName_Start, span.StartDateTime, span.EndDateTime)); + } + + var result = lCriteria.List().ToList(); + + return result; + } + + public IList FindDiensteForWohnheim(long? whOid) + { + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.Or(Restrictions.Eq("Wohnheim", whOid), Restrictions.IsNull("Wohnheim"))); + + return criteria.List(); // Hier fliegt man raus + } + + public long? GetActiveMedVerListOidForCustomer(long customerOid) + { + // Gültig und MedListType = 0 + return GetActiveMedListByTypeForCustomer(customerOid, false); + } + + public long? GetActiveMedListByTypeForCustomer(long customerOid, bool isBedarfsmedikation) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(Medikamentenverordnungsliste.Gueltig), true)) + .Add(Restrictions.Eq(nameof(Medikamentenverordnungsliste.Customer) + ".Oid", customerOid)) + .Add(Restrictions.Eq(nameof(Medikamentenverordnungsliste.MedListType), isBedarfsmedikation)); + + var list = criteria.UniqueResult(); + + return list?.Oid; + } + + public List LoadOccurrencesByRecurrenceId(string recurrenceId) + { + var criteria = CreateCriteria() + .Add(Restrictions.Like(nameof(SchedulerAppointment.RecurrenceInfo), recurrenceId, MatchMode.Anywhere)); - var list = criteria.List(); + var list = criteria.List(); - return list.ToList(); - } + return list.ToList(); + } - // TODO: Intervalle werden als frei angezeigt, wenn sie am Ende eines Tages sind und sich mit Serienterminen überschneiden - public Dictionary> FindAppointmentsInRange(int duration, DateTime intervalStart, DateTime intervalEnd, List resourceOids, List customerOids, List employeeOids, long loggedInEmployeeOid, int intervalBuffer = 30, bool skipWeekends = true) - { - var result = new List(); - var intervals = IntervalFinderHelper.CreateIntervals(duration, intervalStart, intervalEnd, skipWeekends, intervalBuffer); + // TODO: Intervalle werden als frei angezeigt, wenn sie am Ende eines Tages sind und sich mit Serienterminen überschneiden + public Dictionary> FindAppointmentsInRange(int duration, DateTime intervalStart, DateTime intervalEnd, List resourceOids, List customerOids, List employeeOids, long loggedInEmployeeOid, int intervalBuffer = 30, bool skipWeekends = true) + { + var result = new List(); + var intervals = IntervalFinderHelper.CreateIntervals(duration, intervalStart, intervalEnd, skipWeekends, intervalBuffer); - // Das subset enthält die zu prüfenden Tage im angegebenen Intervall. - // 04.12.2023 15:00 bis 06.12.2023 12:00 wären 04.12.2023, 05.12.2023, 06.12.2023 im subset. - var subset = IntervalFinderHelper.GenereateIntervalsForChecking(intervalStart, intervalEnd); + // Das subset enthält die zu prüfenden Tage im angegebenen Intervall. + // 04.12.2023 15:00 bis 06.12.2023 12:00 wären 04.12.2023, 05.12.2023, 06.12.2023 im subset. + var subset = IntervalFinderHelper.GenereateIntervalsForChecking(intervalStart, intervalEnd); - // Es werden im subset nach überschneidenden Terminen gesucht. - // - foreach(var dts in subset) - { - var start = dts.StartDate.MergeDatesByDate(intervalStart); - var end = dts.EndDate.MergeDatesByDate(intervalEnd); + // Es werden im subset nach überschneidenden Terminen gesucht. + // + foreach (var dts in subset) + { + var start = dts.StartDate.MergeDatesByDate(intervalStart); + var end = dts.EndDate.MergeDatesByDate(intervalEnd); - var apptmts = LoadAppointmentsForIntervalFinder(start, end, resourceOids, customerOids, employeeOids, loggedInEmployeeOid, skipWeekends); - - result.AddRangeIfElementsNotIn(apptmts); - } - - /* + var apptmts = LoadAppointmentsForIntervalFinder(start, end, resourceOids, customerOids, employeeOids, loggedInEmployeeOid, skipWeekends); + + result.AddRangeIfElementsNotIn(apptmts); + } + + /* Normal = 0, Pattern = 1, Occurrence = 2, @@ -4911,58 +4923,58 @@ WHERE sc.Billable = 1 and sr.StartDate >= '{0:yyyy-MM-dd}' and sr.StartDate < '{ DeletedOccurrence = 4 */ - var changedOccurrences = result.Where(a => a.Type == 3).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); - var deletedOccurrences = result.Where(a => a.Type == 4).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); + var changedOccurrences = result.Where(a => a.Type == 3).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); + var deletedOccurrences = result.Where(a => a.Type == 4).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); - var kek = IntervalFinderHelper.GetRecurrencesForIntervalFinder(result, intervalStart, intervalEnd, changedOccurrences, deletedOccurrences, skipWeekends); + var kek = IntervalFinderHelper.GetRecurrencesForIntervalFinder(result, intervalStart, intervalEnd, changedOccurrences, deletedOccurrences, skipWeekends); - result.AddRange(kek); + result.AddRange(kek); - var freeIntervals = new List(); + var freeIntervals = new List(); - if(intervals.Count > 0) - { - if(result.Count > 0) - { - foreach(var interval in intervals) - { - if(!result.Any(a => a.StartDate.HasValue && a.EndDate.HasValue && a.StartDate.Value.IsInInterval(a.EndDate.Value, interval.StartDate, interval.EndDate))) - { - freeIntervals.Add(interval); - } - } - } - else - { - return IntervalFinderHelper.CreateFreeIntervalsDictionary(intervals); - } - } + if (intervals.Count > 0) + { + if (result.Count > 0) + { + foreach (var interval in intervals) + { + if (!result.Any(a => a.StartDate.HasValue && a.EndDate.HasValue && a.StartDate.Value.IsInInterval(a.EndDate.Value, interval.StartDate, interval.EndDate))) + { + freeIntervals.Add(interval); + } + } + } + else + { + return IntervalFinderHelper.CreateFreeIntervalsDictionary(intervals); + } + } - return IntervalFinderHelper.CreateFreeIntervalsDictionary(freeIntervals); - } + return IntervalFinderHelper.CreateFreeIntervalsDictionary(freeIntervals); + } - public Dictionary> FindAppointmentsInRangeForIntervalFinder(int duration, DateTime intervalStart, DateTime intervalEnd, List resourceOids, List customerOids, List employeeOids, long loggedInEmployeeOid, int intervalBuffer = 30, bool skipWeekends = true) - { - var result = new List(); + public Dictionary> FindAppointmentsInRangeForIntervalFinder(int duration, DateTime intervalStart, DateTime intervalEnd, List resourceOids, List customerOids, List employeeOids, long loggedInEmployeeOid, int intervalBuffer = 30, bool skipWeekends = true) + { + var result = new List(); - var intervals = IntervalFinderHelper.CreateIntervals(duration, intervalStart, intervalEnd, skipWeekends, intervalBuffer); + var intervals = IntervalFinderHelper.CreateIntervals(duration, intervalStart, intervalEnd, skipWeekends, intervalBuffer); - // Das subset enthält die zu prüfenden Tage im angegebenen Intervall. - // 04.12.2023 15:00 bis 06.12.2023 12:00 wären 04.12.2023, 05.12.2023, 06.12.2023 im subset. - var subset = IntervalFinderHelper.GenereateIntervalsForChecking(intervalStart, intervalEnd); + // Das subset enthält die zu prüfenden Tage im angegebenen Intervall. + // 04.12.2023 15:00 bis 06.12.2023 12:00 wären 04.12.2023, 05.12.2023, 06.12.2023 im subset. + var subset = IntervalFinderHelper.GenereateIntervalsForChecking(intervalStart, intervalEnd); - // Es werden im subset nach überschneidenden Terminen gesucht. - foreach(var dts in subset) - { - var start = dts.StartDate.MergeDatesByDate(intervalStart); - var end = dts.EndDate.MergeDatesByDate(intervalEnd); + // Es werden im subset nach überschneidenden Terminen gesucht. + foreach (var dts in subset) + { + var start = dts.StartDate.MergeDatesByDate(intervalStart); + var end = dts.EndDate.MergeDatesByDate(intervalEnd); - var apptmts = LoadAppointmentsForIntervalFinder(start, end, resourceOids, customerOids, employeeOids, loggedInEmployeeOid, skipWeekends); + var apptmts = LoadAppointmentsForIntervalFinder(start, end, resourceOids, customerOids, employeeOids, loggedInEmployeeOid, skipWeekends); - result.AddRangeIfElementsNotIn(apptmts); - } + result.AddRangeIfElementsNotIn(apptmts); + } - /* + /* Normal = 0, Pattern = 1, Occurrence = 2, @@ -4970,345 +4982,345 @@ WHERE sc.Billable = 1 and sr.StartDate >= '{0:yyyy-MM-dd}' and sr.StartDate < '{ DeletedOccurrence = 4 */ - var changedOccurrences = result.Where(a => a.Type == 3).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); - var deletedOccurrences = result.Where(a => a.Type == 4).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); - - var kek = IntervalFinderHelper.GetRecurrencesForIntervalFinder(result, intervalStart, intervalEnd, changedOccurrences, deletedOccurrences, skipWeekends); - - result.AddRange(kek); - - var freeIntervals = new List(); - - if(intervals.Count > 0) - { - if(result.Count > 0) - { - foreach(var interval in intervals) - { - if(!result.Any(a => a.StartDate.HasValue && a.EndDate.HasValue && a.StartDate.Value.IsInInterval(a.EndDate.Value, interval.StartDate, interval.EndDate))) - { - freeIntervals.Add(interval); - } - } - } - else - { - return IntervalFinderHelper.CreateFreeIntervals(intervals, intervalStart, intervalEnd, intervalBuffer, duration); - } - } - - return IntervalFinderHelper.CreateFreeIntervals(freeIntervals, intervalStart, intervalEnd, intervalBuffer, duration); - } - - private IEnumerable LoadAppointmentsForIntervalFinder(DateTime intervalStart, DateTime intervalEnd, IReadOnlyCollection resourceOids, IReadOnlyCollection customerOids, List employeeOids, long loggedInEmployeeOid, bool skipWeekends) - { - var result = new List(); - - if(intervalStart < intervalEnd) - { - var intervals = IntervalFinderHelper.GenerateIntervalsForCriteria(intervalStart, intervalEnd, skipWeekends); - - var intervalRecurrenceCriterias = IntervalFinderHelper.CreateIntervalRecurrenceCriterias(intervals, skipWeekends); - - var or = CreateOrCriteria(intervalRecurrenceCriterias); - - var criteria = CreateCriteriaIsActiveWithAlias("sa") - .Add(Restrictions.Not(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), true))); - - if(intervals.Count > 0) - { - if(intervals.Count > 1) - { - var criterionList = new List(); - - foreach(var dts in intervals) - { - criterionList.AddIfNotIn( - Restrictions.Or( - Restrictions.Between(nameof(SchedulerAppointment.StartDate), dts.StartDate, dts.EndDate), - Restrictions.Or( - Restrictions.Between(nameof(SchedulerAppointment.EndDate), dts.StartDate, dts.EndDate), - Restrictions.And( - Restrictions.Lt(nameof(SchedulerAppointment.StartDate), dts.StartDate), - Restrictions.Gt(nameof(SchedulerAppointment.EndDate), dts.EndDate))) - )); - } - - criteria.Add(Restrictions.Or(or, CreateOrCriteria(criterionList))); - } - else - { - var dts = intervals.FirstOrDefault(); - - if(dts != null) - { - var cri = Restrictions.Or( - Restrictions.Between(nameof(SchedulerAppointment.StartDate), dts.StartDate, dts.EndDate), - Restrictions.Or( - Restrictions.Between(nameof(SchedulerAppointment.EndDate), dts.StartDate, dts.EndDate), - Restrictions.And( - Restrictions.Lt(nameof(SchedulerAppointment.StartDate), dts.StartDate), - Restrictions.Gt(nameof(SchedulerAppointment.EndDate), dts.EndDate))) - ); - - criteria.Add(Restrictions.Or(or, cri)); - } - } - } - - ICriterion resourceCriterion = null; - ICriterion customerCriterion = null; - - if(employeeOids.Count == 0) - { - employeeOids.Add(loggedInEmployeeOid); - } - - var detachedCriteria1 = DetachedCriteria.For() - .Add(Restrictions.In(nameof(Employee2SchedulerAppointment.Employee) + ".Oid", employeeOids)) - .SetProjection(Projections.Property(nameof(Employee2SchedulerAppointment.SchedulerAppointmentOid))); - var employee2SchedCrit = Subqueries.PropertyIn(nameof(BeWoEntityBase.Oid), detachedCriteria1); - - var originatorCrit = Restrictions.In(nameof(SchedulerAppointment.Originator), employeeOids); - - var detachedCriteria2 = DetachedCriteria.For("e2s2") - .SetProjection(Projections.Property(nameof(BeWoEntityBase.Oid))) - .Add(Restrictions.EqProperty("e2s2." + nameof(Employee2SchedulerAppointment.SchedulerAppointmentOid), "sa.Oid")); - - var employee2SchedCrit2 = Subqueries.NotExists(detachedCriteria2); - - var and = Restrictions.And(originatorCrit, employee2SchedCrit2); - - var employeeCriterion = Restrictions.Or(employee2SchedCrit, and); - - if(customerOids?.Count > 0) - { - var customerSql = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({customerOids.ToSeparatedString(",")}))"; - customerCriterion = Expression.Sql(customerSql); - } - - if(resourceOids?.Count > 0) - { - var resourceSql = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp WHERE resourceoid IN ({resourceOids.ToSeparatedString(",")}))"; - resourceCriterion = Expression.Sql(resourceSql); - } - - var listOfCriterias = new List - { - employeeCriterion, - customerCriterion, - resourceCriterion - }; - - if(listOfCriterias.Count > 0) - { - var orCriteria = CreateOrCriteria(listOfCriterias); - - if(orCriteria != null) - { - criteria.Add(orCriteria); - } - } - - var criteriaAsString = criteria.ToString(); - - var appointments = criteria.List().ToList(); - - result.AddRange(appointments); - } - - return result; - } - - private static string GetGeneratedSql(ICriteria criteria) - { - var criteriaImpl = (CriteriaImpl)criteria; - var sessionImpl = (SessionImpl)criteriaImpl.Session; - var factory = (SessionFactoryImpl)sessionImpl.SessionFactory; - var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName); - var loader = new CriteriaLoader((IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters); - - return loader.SqlString.ToString(); - } - - public long GetMaxOidFromFileAttachment() - { - var q = Session.CreateSQLQuery("select max(oid) from fileattachment"); - return q.List().First(); - } - - public IEnumerable GetAllAbsenceTimesInIntervalForCustomers(DateTime start, DateTime end, List customerOids) - { - // Wenn das Enddatum null ist, wird das Ende des Intervalls als Enddatum gesetzt (Ist ja eh read-only). - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.IsNotNull(nameof(AbsenceTime.CustomerOid))) - .Add(Restrictions.Or - (Restrictions.Or(Restrictions.Or( - Restrictions.And(Restrictions.Ge(AbsenceTime.PropertyName_Start, start), Restrictions.Le(AbsenceTime.PropertyName_Start, end)), - Restrictions.Eq(AbsenceTime.PropertyName_Start, start) - ), Restrictions.And(Restrictions.Le(AbsenceTime.PropertyName_Start, start), Restrictions.IsNull(AbsenceTime.PropertyName_End)) - ), Restrictions.And(Restrictions.Lt(AbsenceTime.PropertyName_Start, start), Restrictions.Gt(AbsenceTime.PropertyName_End, start))) - ) - .Add(Restrictions.In(nameof(AbsenceTime.CustomerOid), customerOids)); - - var absenceTimes = criteria.List(); - - return criteria.List(); - } - - public IEnumerable GetAllEmployeeAbsenceTimesInIntervalForEmployee(DateTime start, DateTime end, List employeeOids) - { - // Wenn das Enddatum null ist, wird das Ende des Intervalls als Enddatum gesetzt (Ist ja eh read-only). - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.IsNotNull(nameof(AbsenceTime.EmployeeOid))) - .Add(Restrictions.Or - (Restrictions.Or(Restrictions.Or( - Restrictions.And(Restrictions.Ge(AbsenceTime.PropertyName_Start, start), Restrictions.Le(AbsenceTime.PropertyName_Start, end)), - Restrictions.Eq(AbsenceTime.PropertyName_Start, start) - ), Restrictions.And(Restrictions.Le(AbsenceTime.PropertyName_Start, start), Restrictions.IsNull(AbsenceTime.PropertyName_End)) - ), Restrictions.And(Restrictions.Lt(AbsenceTime.PropertyName_Start, start), Restrictions.Gt(AbsenceTime.PropertyName_End, start))) - ) - .Add(Restrictions.In(nameof(AbsenceTime.EmployeeOid), employeeOids)); - - return criteria.List(); - } - - public List FindAllCustomersForEmployee(long? employeeOid, CustomerFilterEnum customerFilter) - { - ApplicationUser user; - - if (employeeOid.HasValue) - { - var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); - user = FindUserForEmployee(employee); - } - else - { - user = LoggedInUserOperationContextExt.Current?.User != null ? LoggedInUserOperationContextExt.Current.User : SessionFacade.LoggedInUser; - } - - var criteria = CreateCriteria(); - - // Der ApplicationUser darf alles sehen - var viewAllRights = new List { UserRightType.CustomerView_View }; - - if (user.CheckForAtLeastOneRight(viewAllRights) && customerFilter == CustomerFilterEnum.All) - { - return criteria.List().ToList(); - } - - var ownCustomerOids = user.Employee?.Employee2CustomerList.Where(employee2Customer => employee2Customer.Customer.Oid.HasValue).Select(employee2Customer => employee2Customer.Customer.Oid.Value).Distinct().ToList() ?? new List(); - - var customerOids = new List(); - - // Der ApplicationUser darf die Klienten seiner Teams sehen - if (user.CheckForRight(UserRightType.Customer_ViewMyTeams) && (customerFilter == CustomerFilterEnum.TeamCustomer || customerFilter == CustomerFilterEnum.All) && (user.Employee?.Oid.HasValue ?? false)) - { - var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); - - teams.DoForEach(team => - { - if (team.Oid is null) - { - return; - } - - var customer = FindCustomerOfTeam(team.Oid.Value); - - customerOids.AddRangeIfElementsNotIn(customer.Where(w => w.Oid.HasValue).Select(c => c.Oid.Value)); - }); - } - - // Der ApplicationUser darf seine eigenen Klienten sehen. - if (user.CheckForRight(UserRightType.Customer_ViewMyCustomers) && (customerFilter == CustomerFilterEnum.All || customerFilter == CustomerFilterEnum.MyCustomer)) - { - customerOids.AddRangeIfElementsNotIn(ownCustomerOids); - } - - var visibleCustomers = criteria.Add(Restrictions.In(nameof(Customer.Oid), customerOids.ToArray())).List().ToList(); - - return visibleCustomers; - } - - public IList FindAllEmployeesForEmployee(long? employeeOid) - { - ApplicationUser user; - - if (employeeOid.HasValue) - { - var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); - user = FindUserForEmployee(employee); - } - else - { - if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) - { - user = LoggedInUserOperationContextExt.Current.User; - } - else - { - user = SessionFacade.LoggedInUser; - } - } - - if (user.Employee.Oid == null) - { - return new List(); - } - - var rights = new List(); - - user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); - - var criteria = CreateCriteria(); - - if (rights.Contains(UserRightType.EmployeeView_View)) - { - return criteria.List().ToList(); - } - - var result = new List(); - - if (rights.Contains(UserRightType.Employee_AllowViewOwnEmployees)) - { - result.AddIfNotIn(user.Employee); - } - - if (rights.Contains(UserRightType.Employee_AllowViewOwnTeam)) - { - var leadingTeams = user.Employee.LeadingTeams; - - leadingTeams.DoForEach(team => - { - result.AddIfNotIn(team.Leader); - - result.AddRangeIfElementsNotIn(team.MemberList); - }); + var changedOccurrences = result.Where(a => a.Type == 3).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); + var deletedOccurrences = result.Where(a => a.Type == 4).Select(s => BS.Shared.Core.Utils.GetOccurrenceId(s.RecurrenceInfo)).ToList(); + + var kek = IntervalFinderHelper.GetRecurrencesForIntervalFinder(result, intervalStart, intervalEnd, changedOccurrences, deletedOccurrences, skipWeekends); + + result.AddRange(kek); + + var freeIntervals = new List(); + + if (intervals.Count > 0) + { + if (result.Count > 0) + { + foreach (var interval in intervals) + { + if (!result.Any(a => a.StartDate.HasValue && a.EndDate.HasValue && a.StartDate.Value.IsInInterval(a.EndDate.Value, interval.StartDate, interval.EndDate))) + { + freeIntervals.Add(interval); + } + } + } + else + { + return IntervalFinderHelper.CreateFreeIntervals(intervals, intervalStart, intervalEnd, intervalBuffer, duration); + } + } + + return IntervalFinderHelper.CreateFreeIntervals(freeIntervals, intervalStart, intervalEnd, intervalBuffer, duration); + } + + private IEnumerable LoadAppointmentsForIntervalFinder(DateTime intervalStart, DateTime intervalEnd, IReadOnlyCollection resourceOids, IReadOnlyCollection customerOids, List employeeOids, long loggedInEmployeeOid, bool skipWeekends) + { + var result = new List(); + + if (intervalStart < intervalEnd) + { + var intervals = IntervalFinderHelper.GenerateIntervalsForCriteria(intervalStart, intervalEnd, skipWeekends); + + var intervalRecurrenceCriterias = IntervalFinderHelper.CreateIntervalRecurrenceCriterias(intervals, skipWeekends); + + var or = CreateOrCriteria(intervalRecurrenceCriterias); + + var criteria = CreateCriteriaIsActiveWithAlias("sa") + .Add(Restrictions.Not(Restrictions.Eq(nameof(SchedulerAppointment.IsTask), true))); + + if (intervals.Count > 0) + { + if (intervals.Count > 1) + { + var criterionList = new List(); + + foreach (var dts in intervals) + { + criterionList.AddIfNotIn( + Restrictions.Or( + Restrictions.Between(nameof(SchedulerAppointment.StartDate), dts.StartDate, dts.EndDate), + Restrictions.Or( + Restrictions.Between(nameof(SchedulerAppointment.EndDate), dts.StartDate, dts.EndDate), + Restrictions.And( + Restrictions.Lt(nameof(SchedulerAppointment.StartDate), dts.StartDate), + Restrictions.Gt(nameof(SchedulerAppointment.EndDate), dts.EndDate))) + )); + } + + criteria.Add(Restrictions.Or(or, CreateOrCriteria(criterionList))); + } + else + { + var dts = intervals.FirstOrDefault(); + + if (dts != null) + { + var cri = Restrictions.Or( + Restrictions.Between(nameof(SchedulerAppointment.StartDate), dts.StartDate, dts.EndDate), + Restrictions.Or( + Restrictions.Between(nameof(SchedulerAppointment.EndDate), dts.StartDate, dts.EndDate), + Restrictions.And( + Restrictions.Lt(nameof(SchedulerAppointment.StartDate), dts.StartDate), + Restrictions.Gt(nameof(SchedulerAppointment.EndDate), dts.EndDate))) + ); + + criteria.Add(Restrictions.Or(or, cri)); + } + } + } + + ICriterion resourceCriterion = null; + ICriterion customerCriterion = null; + + if (employeeOids.Count == 0) + { + employeeOids.Add(loggedInEmployeeOid); + } + + var detachedCriteria1 = DetachedCriteria.For() + .Add(Restrictions.In(nameof(Employee2SchedulerAppointment.Employee) + ".Oid", employeeOids)) + .SetProjection(Projections.Property(nameof(Employee2SchedulerAppointment.SchedulerAppointmentOid))); + var employee2SchedCrit = Subqueries.PropertyIn(nameof(BeWoEntityBase.Oid), detachedCriteria1); + + var originatorCrit = Restrictions.In(nameof(SchedulerAppointment.Originator), employeeOids); + + var detachedCriteria2 = DetachedCriteria.For("e2s2") + .SetProjection(Projections.Property(nameof(BeWoEntityBase.Oid))) + .Add(Restrictions.EqProperty("e2s2." + nameof(Employee2SchedulerAppointment.SchedulerAppointmentOid), "sa.Oid")); + + var employee2SchedCrit2 = Subqueries.NotExists(detachedCriteria2); + + var and = Restrictions.And(originatorCrit, employee2SchedCrit2); + + var employeeCriterion = Restrictions.Or(employee2SchedCrit, and); + + if (customerOids?.Count > 0) + { + var customerSql = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM customer2newschapp WHERE customeroid IN ({customerOids.ToSeparatedString(",")}))"; + customerCriterion = Expression.Sql(customerSql); + } + + if (resourceOids?.Count > 0) + { + var resourceSql = $"{BeWoEntityBase.PropertyName_Oid} IN (SELECT newschappoid FROM resource2newschapp WHERE resourceoid IN ({resourceOids.ToSeparatedString(",")}))"; + resourceCriterion = Expression.Sql(resourceSql); + } + + var listOfCriterias = new List + { + employeeCriterion, + customerCriterion, + resourceCriterion + }; + + if (listOfCriterias.Count > 0) + { + var orCriteria = CreateOrCriteria(listOfCriterias); + + if (orCriteria != null) + { + criteria.Add(orCriteria); + } + } + + var criteriaAsString = criteria.ToString(); + + var appointments = criteria.List().ToList(); + + result.AddRange(appointments); + } + + return result; + } + + private static string GetGeneratedSql(ICriteria criteria) + { + var criteriaImpl = (CriteriaImpl)criteria; + var sessionImpl = (SessionImpl)criteriaImpl.Session; + var factory = (SessionFactoryImpl)sessionImpl.SessionFactory; + var implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName); + var loader = new CriteriaLoader((IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]), factory, criteriaImpl, implementors[0], sessionImpl.EnabledFilters); + + return loader.SqlString.ToString(); + } + + public long GetMaxOidFromFileAttachment() + { + var q = Session.CreateSQLQuery("select max(oid) from fileattachment"); + return q.List().First(); + } + + public IEnumerable GetAllAbsenceTimesInIntervalForCustomers(DateTime start, DateTime end, List customerOids) + { + // Wenn das Enddatum null ist, wird das Ende des Intervalls als Enddatum gesetzt (Ist ja eh read-only). + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.IsNotNull(nameof(AbsenceTime.CustomerOid))) + .Add(Restrictions.Or + (Restrictions.Or(Restrictions.Or( + Restrictions.And(Restrictions.Ge(AbsenceTime.PropertyName_Start, start), Restrictions.Le(AbsenceTime.PropertyName_Start, end)), + Restrictions.Eq(AbsenceTime.PropertyName_Start, start) + ), Restrictions.And(Restrictions.Le(AbsenceTime.PropertyName_Start, start), Restrictions.IsNull(AbsenceTime.PropertyName_End)) + ), Restrictions.And(Restrictions.Lt(AbsenceTime.PropertyName_Start, start), Restrictions.Gt(AbsenceTime.PropertyName_End, start))) + ) + .Add(Restrictions.In(nameof(AbsenceTime.CustomerOid), customerOids)); + + var absenceTimes = criteria.List(); + + return criteria.List(); + } + + public IEnumerable GetAllEmployeeAbsenceTimesInIntervalForEmployee(DateTime start, DateTime end, List employeeOids) + { + // Wenn das Enddatum null ist, wird das Ende des Intervalls als Enddatum gesetzt (Ist ja eh read-only). + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.IsNotNull(nameof(AbsenceTime.EmployeeOid))) + .Add(Restrictions.Or + (Restrictions.Or(Restrictions.Or( + Restrictions.And(Restrictions.Ge(AbsenceTime.PropertyName_Start, start), Restrictions.Le(AbsenceTime.PropertyName_Start, end)), + Restrictions.Eq(AbsenceTime.PropertyName_Start, start) + ), Restrictions.And(Restrictions.Le(AbsenceTime.PropertyName_Start, start), Restrictions.IsNull(AbsenceTime.PropertyName_End)) + ), Restrictions.And(Restrictions.Lt(AbsenceTime.PropertyName_Start, start), Restrictions.Gt(AbsenceTime.PropertyName_End, start))) + ) + .Add(Restrictions.In(nameof(AbsenceTime.EmployeeOid), employeeOids)); + + return criteria.List(); + } + + public List FindAllCustomersForEmployee(long? employeeOid, CustomerFilterEnum customerFilter) + { + ApplicationUser user; + + if (employeeOid.HasValue) + { + var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); + user = FindUserForEmployee(employee); + } + else + { + user = LoggedInUserOperationContextExt.Current?.User != null ? LoggedInUserOperationContextExt.Current.User : SessionFacade.LoggedInUser; + } + + var criteria = CreateCriteria(); + + // Der ApplicationUser darf alles sehen + var viewAllRights = new List { UserRightType.CustomerView_View }; + + if (user.CheckForAtLeastOneRight(viewAllRights) && customerFilter == CustomerFilterEnum.All) + { + return criteria.List().ToList(); + } + + var ownCustomerOids = user.Employee?.Employee2CustomerList.Where(employee2Customer => employee2Customer.Customer.Oid.HasValue).Select(employee2Customer => employee2Customer.Customer.Oid.Value).Distinct().ToList() ?? new List(); + + var customerOids = new List(); + + // Der ApplicationUser darf die Klienten seiner Teams sehen + if (user.CheckForRight(UserRightType.Customer_ViewMyTeams) && (customerFilter == CustomerFilterEnum.TeamCustomer || customerFilter == CustomerFilterEnum.All) && (user.Employee?.Oid.HasValue ?? false)) + { + var teams = FindAllActiveTeamsOfEmployee(user.Employee.Oid.Value); + + teams.DoForEach(team => + { + if (team.Oid is null) + { + return; + } + + var customer = FindCustomerOfTeam(team.Oid.Value); + + customerOids.AddRangeIfElementsNotIn(customer.Where(w => w.Oid.HasValue).Select(c => c.Oid.Value)); + }); + } + + // Der ApplicationUser darf seine eigenen Klienten sehen. + if (user.CheckForRight(UserRightType.Customer_ViewMyCustomers) && (customerFilter == CustomerFilterEnum.All || customerFilter == CustomerFilterEnum.MyCustomer)) + { + customerOids.AddRangeIfElementsNotIn(ownCustomerOids); + } + + var visibleCustomers = criteria.Add(Restrictions.In(nameof(Customer.Oid), customerOids.ToArray())).List().ToList(); + + return visibleCustomers; + } + + public IList FindAllEmployeesForEmployee(long? employeeOid) + { + ApplicationUser user; + + if (employeeOid.HasValue) + { + var employee = CreateCriteria().Add(Restrictions.Eq(nameof(Employee.Oid), employeeOid)).UniqueResult(); + user = FindUserForEmployee(employee); + } + else + { + if (LoggedInUserOperationContextExt.Current != null && LoggedInUserOperationContextExt.Current.User != null) + { + user = LoggedInUserOperationContextExt.Current.User; + } + else + { + user = SessionFacade.LoggedInUser; + } + } + + if (user.Employee.Oid == null) + { + return new List(); + } + + var rights = new List(); + + user.UserGroups.DoForEach(s => s.Rights.DoForEach(right => rights.AddIfNotIn(right.RightType))); + + var criteria = CreateCriteria(); + + if (rights.Contains(UserRightType.EmployeeView_View)) + { + return criteria.List().ToList(); + } + + var result = new List(); + + if (rights.Contains(UserRightType.Employee_AllowViewOwnEmployees)) + { + result.AddIfNotIn(user.Employee); + } + + if (rights.Contains(UserRightType.Employee_AllowViewOwnTeam)) + { + var leadingTeams = user.Employee.LeadingTeams; + + leadingTeams.DoForEach(team => + { + result.AddIfNotIn(team.Leader); + + result.AddRangeIfElementsNotIn(team.MemberList); + }); - var teams = FindTeamsOfEmployee(user.Employee.Oid.Value); + var teams = FindTeamsOfEmployee(user.Employee.Oid.Value); - teams.DoForEach(team => - { - result.AddIfNotIn(team.Leader); + teams.DoForEach(team => + { + result.AddIfNotIn(team.Leader); - result.AddRangeIfElementsNotIn(team.MemberList); - }); - } + result.AddRangeIfElementsNotIn(team.MemberList); + }); + } - return result; - } - - public List LoadAppointmentsWithServiceRecords(List serviceRecordOids) - { - var c = CreateCriteria() - .CreateAlias(nameof(SchedulerAppointment.ServiceRecordList), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())) - .SetResultTransformer(new DistinctRootEntityResultTransformer()); - - return c.List().ToList(); - } - - /* + return result; + } + + public List LoadAppointmentsWithServiceRecords(List serviceRecordOids) + { + var c = CreateCriteria() + .CreateAlias(nameof(SchedulerAppointment.ServiceRecordList), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())) + .SetResultTransformer(new DistinctRootEntityResultTransformer()); + + return c.List().ToList(); + } + + /* * public bool HasConfirmationReceiptSignature(IList serviceRecordOids, SignatureType signatureType) { // Prüfen, ob alle ServiceRecords mit ein und derselben Unterschrift verknüpft sind. @@ -5343,863 +5355,863 @@ WHERE sc.Billable = 1 and sr.StartDate >= '{0:yyyy-MM-dd}' and sr.StartDate < '{ } */ - public bool CheckForConfirmationReceiptSignatureForServiceRecord(long serviceRecordOid, SignatureType signatureType) - { - var critreria = CreateCriteriaIsActive() - .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecords", JoinType.InnerJoin) - .Add(Restrictions.Eq($"serviceRecords.{nameof(BeWoEntityBase.Oid)}", serviceRecordOid)); + public bool CheckForConfirmationReceiptSignatureForServiceRecord(long serviceRecordOid, SignatureType signatureType) + { + var critreria = CreateCriteriaIsActive() + .Add(Restrictions.Eq(nameof(ConfirmationReceiptSignature.SignatureType), signatureType)) + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "serviceRecords", JoinType.InnerJoin) + .Add(Restrictions.Eq($"serviceRecords.{nameof(BeWoEntityBase.Oid)}", serviceRecordOid)); - var signature = critreria.List().ToList(); + var signature = critreria.List().ToList(); - return signature.Count == 1; - } + return signature.Count == 1; + } - /// - /// Prüft anhand der Oids von Ressourcen deren Verfügbarkeit in einem Zeitraum. - /// Gibt die nicht verfügbaren Ressourcen und Mitarbeiter, die sie gebucht aben zurück für eine detaillierte Fehlermeldung. - /// - /// Die Oids der zu überprüfenden Ressourcen - /// Anfang des zu prüfenden Intervalls - /// Ende des zu prüfenden Intervalls - /// Die Oid des Termins - /// Recurrence Id, falls es sich um einen Serientermin handelt, der keine eigene Oid hat. - /// Occurrence-Index des Serientermins ohne eigene Oid - /// Die im angegebenen Zeitraum belegten Ressourcen mit den Mitarbeitern, die sie gebucht haben - public List FindAppointmentsByResourcesInInterval(List resourceOids, DateTime start, DateTime end, long? selectedAppointmentOid, Guid? recurrenceId = null, int? occurrenceIndex = null) - { - var betweenCriterion = CreateBetweenDateTimesCriterion(start, end, "StartDate", "EndDate"); + /// + /// Prüft anhand der Oids von Ressourcen deren Verfügbarkeit in einem Zeitraum. + /// Gibt die nicht verfügbaren Ressourcen und Mitarbeiter, die sie gebucht aben zurück für eine detaillierte Fehlermeldung. + /// + /// Die Oids der zu überprüfenden Ressourcen + /// Anfang des zu prüfenden Intervalls + /// Ende des zu prüfenden Intervalls + /// Die Oid des Termins + /// Recurrence Id, falls es sich um einen Serientermin handelt, der keine eigene Oid hat. + /// Occurrence-Index des Serientermins ohne eigene Oid + /// Die im angegebenen Zeitraum belegten Ressourcen mit den Mitarbeitern, die sie gebucht haben + public List FindAppointmentsByResourcesInInterval(List resourceOids, DateTime start, DateTime end, long? selectedAppointmentOid, Guid? recurrenceId = null, int? occurrenceIndex = null) + { + var betweenCriterion = CreateBetweenDateTimesCriterion(start, end, "StartDate", "EndDate"); - var c2 = CreateCriteriaIsActive() - //.Add(Restrictions.Not(Restrictions.Eq(nameof(SchedulerAppointment.Type), 4))) - .Add(betweenCriterion); + var c2 = CreateCriteriaIsActive() + //.Add(Restrictions.Not(Restrictions.Eq(nameof(SchedulerAppointment.Type), 4))) + .Add(betweenCriterion); - if (!(selectedAppointmentOid is null)) - { - c2.Add(Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), selectedAppointmentOid))); - } + if (!(selectedAppointmentOid is null)) + { + c2.Add(Restrictions.Not(Restrictions.Eq(nameof(BeWoEntityBase.Oid), selectedAppointmentOid))); + } - c2.CreateAlias(nameof(SchedulerAppointment.ResourceList), "resources", JoinType.InnerJoin) - .Add(Restrictions.In($"resources.{nameof(BeWoEntityBase.Oid)}", resourceOids)); - - var tempAppointments = c2.List().ToList(); - - var isBeingUpdatedToNormalAppointment = false; - Guid? recurrenceIdToIgnore = null; - if (selectedAppointmentOid.HasValue) - { - // Das Pattern wird geladen, bzw. mit der Ausnahme mit Index 0 verglichen - // Wird die Serie in einen Einzeltermin geändert und es existiert eine Ausnahme mit Index 0, sollte die Ausnahme behalten werden und nicht der Root-Termin - var original = DAOFactory.GenericDAO.LoadByID(selectedAppointmentOid.Value); - var originalRecurrenceId = original?.GetRecurrenceId(); + c2.CreateAlias(nameof(SchedulerAppointment.ResourceList), "resources", JoinType.InnerJoin) + .Add(Restrictions.In($"resources.{nameof(BeWoEntityBase.Oid)}", resourceOids)); + + var tempAppointments = c2.List().ToList(); + + var isBeingUpdatedToNormalAppointment = false; + Guid? recurrenceIdToIgnore = null; + if (selectedAppointmentOid.HasValue) + { + // Das Pattern wird geladen, bzw. mit der Ausnahme mit Index 0 verglichen + // Wird die Serie in einen Einzeltermin geändert und es existiert eine Ausnahme mit Index 0, sollte die Ausnahme behalten werden und nicht der Root-Termin + var original = DAOFactory.GenericDAO.LoadByID(selectedAppointmentOid.Value); + var originalRecurrenceId = original?.GetRecurrenceId(); - if (!(originalRecurrenceId is null) && IsNullOrWhiteSpace(recurrenceId?.ToString())) - { - isBeingUpdatedToNormalAppointment = true; - recurrenceIdToIgnore = originalRecurrenceId; - } - } + if (!(originalRecurrenceId is null) && IsNullOrWhiteSpace(recurrenceId?.ToString())) + { + isBeingUpdatedToNormalAppointment = true; + recurrenceIdToIgnore = originalRecurrenceId; + } + } - var appointments = tempAppointments.Where(appointment => - { - if (appointment.RecurrenceInfo is null) - { - return true; - } - - var recId2 = appointment.GetRecurrenceIdAndIndex(out var index); - return !((recurrenceId?.Equals(recId2) ?? false) && occurrenceIndex == index); - }).ToList(); - - - var deletedOccurrences = appointments.Where(app => app.Type == 4).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); - var changedOccurrences = appointments.Where(app => app.Type == 3).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); - - var recurringAppointmentsCriteria = CreateRecurrenceCriteria(start, end).Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 1)); - - var recurringAppointments = recurringAppointmentsCriteria.List().ToList(); - - if (isBeingUpdatedToNormalAppointment) - { - recurringAppointments = recurringAppointments.Where(root => FilterRootAppointment(root, recurrenceIdToIgnore)).ToList(); - - appointments = appointments.Where(root => FilterRootAppointment(root, recurrenceIdToIgnore)).ToList(); - } - - recurringAppointments = recurringAppointments.Where(s => s.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); - - foreach (var appointment in recurringAppointments) - { - var recurrenceInfo = new RecurrenceInfo(); - recurrenceInfo.FromXml(appointment.RecurrenceInfo); - - var occurrenceCalculator = OccurrenceCalculator.CreateInstance(recurrenceInfo); - - var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); - - if (pattern is null) - { - continue; - } - - pattern.RecurrenceInfo.FromXml(appointment.RecurrenceInfo); - pattern.Start = pattern.RecurrenceInfo.Start; - pattern.End = appointment.EndDate.Value; - - var patternId = pattern.RecurrenceInfo.Id.ToString(); - - var interval = new TimeInterval(start, end); - - var occurrences = occurrenceCalculator.CalcOccurrences(interval, pattern); - - foreach (var occurrence in occurrences.GetAppointments(interval)) - { - if (appointment.EndDate is null || appointment.StartDate is null) - { - continue; - } - - // Terminindex in der Serie - var index = occurrence.RecurrenceIndex; - - // Das Ende ist offen, da die Terminserie kein Ende hat. Deshalb wird das Ende berechnet. - var duration = (appointment.EndDate.Value - appointment.StartDate.Value).TotalMinutes; - - var guidParsingSuccessful = Guid.TryParse(occurrence.RecurrenceInfo?.Id?.ToString(), out var occurrenceGuid); - - // Der generierte Serientermin muss sich zeitlich mit dem neuen Termin überschneiden - // und darf nicht in der Liste der geänderten Serientermine oder der Liste der gelöschten Serientermine sein. - var isInIntervalTest = start.IsInInterval(end, occurrence.Start, occurrence.Start.AddMinutes(duration)); - - if (!isInIntervalTest || - changedOccurrences.Any(changedOccurence => changedOccurence.PatternId.Equals(patternId) && changedOccurence.Index == index) || - deletedOccurrences.Any(deletedOccurence => deletedOccurence.PatternId.Equals(patternId) && deletedOccurence.Index == index) || - index == occurrenceIndex && guidParsingSuccessful && recurrenceId != null && recurrenceId.Equals(occurrenceGuid)) - { - continue; - } - - // Prüfen, ob es eine Ausnahme an dem Tag gibt, die zu dem Pattern gehört, um das Pattern auszuschließen - var relatedAppointments = FindAppointmentsByRecurrenceId(new List { recurrenceInfo.Id.ToString() }, true); - var relatedAppointmentsInInterval = relatedAppointments.Where(a => - { - if (a.StartDate == null || a.EndDate == null) - { - return false; - } - - var myStart = a.StartDate.Value.Date; - var myEnd = a.EndDate.Value.Date; - - var isInInterval = start.Date.InBetween(myStart.GetShortDateTime(), myEnd, true); - - return isInInterval && a.Type != 4; - }).ToList(); - - var hasToStop = false; - - // Prüfen, ob es sich bei dem Termin für den Überschneidungen gesucht werden, um zu unterscheiden, ob ein Serientermin in einen normalen geändert wird. - var root = FindRootAppointmentByRecurrenceId(recurrenceInfo.Id.ToString()); - if (root.Oid != null && selectedAppointmentOid != null && root.Oid == selectedAppointmentOid && root.RecurrenceInfo != null && IsNullOrWhiteSpace(recurrenceId?.ToString())) - { - hasToStop = true; - } - - // Indices und Ids der RecurrenceInfo vergleichen. Stimmen sie überein, dann wird das generiert Serienelement ignoriert. - if (occurrence.RecurrenceInfo?.Id != null && !hasToStop) - { - if (Guid.TryParse(occurrence.RecurrenceInfo.Id.ToString(), out var guid)) - { - foreach (var relatedAppointment in relatedAppointmentsInInterval) - { - var relatedAppointmentRecurrenceId = relatedAppointment.GetRecurrenceIdAndIndex(out var relatedAppointmentRecurrenceIndex); - - if (relatedAppointmentRecurrenceId != null) - { - if (guid.Equals(relatedAppointmentRecurrenceId) && relatedAppointmentRecurrenceIndex.Equals(occurrence.RecurrenceIndex)) - { - hasToStop = true; - break; - } - } - } - } - } - - if (hasToStop) - { - continue; - } - - var recurringAppointment = new SchedulerAppointment - { - AllDay = occurrence.AllDay, - CustomerList = appointment.CustomerList, - Notice = appointment.Notice, - EmployeeList = appointment.EmployeeList, - EndDate = occurrence.Start.AddMinutes(duration), - FormerBookingSequenceOid = appointment.FormerBookingSequenceOid, - IsPrivate = appointment.IsPrivate, - Location = appointment.Location, - Originator = appointment.Originator, - RecurrenceInfo = occurrence.RecurrenceInfo.ToXml(), - ReminderInfo = appointment.ReminderInfo, - ResourceList = appointment.ResourceList, - StartDate = occurrence.Start, - Subject = appointment.Subject ?? "", - Type = appointment.Type - }; - - appointments.AddIfNotIn(recurringAppointment); - } - } - - return appointments.Where(appointment => appointment.Type != 4).OrderBy(appointment => appointment.StartDate).ToList(); - } - - private static bool FilterRootAppointment(SchedulerAppointment root, Guid? recurrenceIdToIgnore) - { - var recId = root.GetRecurrenceId(); - - if (recId is null || recurrenceIdToIgnore is null) - { - return true; - } - - return !recId.Equals(recurrenceIdToIgnore); - } - - public List LoadAllConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids) - { - var c = CreateCriteria() - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - - // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) - c.SetResultTransformer(new DistinctRootEntityResultTransformer()); - - var result = c.List().ToList(); - - return result; - } - - public Dictionary> CheckResourceAvailabilityWithEmployeeInformation(DateTime start, DateTime end, List resourceOids, long? selectedAppointmentOid, Guid? recurrenceId = null, int occurrenceIndex = 0) - { - var appointments = FindAppointmentsByResourcesInInterval(resourceOids, start, end, selectedAppointmentOid, recurrenceId, occurrenceIndex); - - var user = LoggedInUserOperationContextExt.Current?.User ?? SessionFacade.LoggedInUser; - - var result = new Dictionary>(); - - if (user is null) - { - return result; - } - - var loggedInEmployee = user.Employee; - - var hasRightToViewEmployeeAppointments = user.CheckForRight(UserRightType.KalenderMitarbeitertermineAnsehen); - var hasRightToViewResourceAppointments = user.CheckForRight(UserRightType.KalenderRessourcentermineAnsehen); - - var dictionary = new Dictionary>(); - - foreach (var appointment in appointments) - { - foreach (var resource in appointment.ResourceList) - { - dictionary.AddOrUpdateValueInDictionary(resource, appointment); - } - } - - foreach (var resource2Appointments in dictionary) - { - foreach (var appointment in resource2Appointments.Value) - { - var originator = appointment.Originator; - var employee2Appointments = appointment.EmployeeList; - - var isOwnAppointment = (originator?.Equals(loggedInEmployee) ?? false) || employee2Appointments.ToList().Any(e2a => e2a.Employee.Equals(loggedInEmployee)); - - // Wenn isOwnAppointment true ist, darf der Benutzer die Uhrzeiten und die Mitarbeiter sehen. Ansonsten müssen die Rechte geprüft werden. - if (isOwnAppointment || hasRightToViewEmployeeAppointments) // Es werden Zeit und Mitarbeiter angezeigt - { - result.AddOrUpdateValueInDictionary(resource2Appointments.Key.Name, $"{CreateDateTimeInfoFromAppointment(appointment.StartDate, appointment.EndDate, appointment.AllDay)} von {originator}"); - } - else if (hasRightToViewResourceAppointments && !hasRightToViewEmployeeAppointments) // Nur die Uhrzeit anzeigen - { - result.AddOrUpdateValueInDictionary(resource2Appointments.Key.Name, $"{CreateDateTimeInfoFromAppointment(appointment.StartDate, appointment.EndDate, appointment.AllDay)}"); - } - else if (!hasRightToViewEmployeeAppointments) // Es werden weder Zeit noch Mitarbeiter angezeigt - { - result.AddOrUpdateValueInDictionary(resource2Appointments.Key.Name, string.Empty); - } - } - } - - return result; - } - - private static string CreateDateTimeInfoFromAppointment(DateTime? start, DateTime? end, bool allDay) - { - if (start.HasValue && end.HasValue && allDay == false) - { - return start.Value.Date == end.Value.Date ? - $"{start.Value.ToShortTimeString()} - {end.Value.ToShortTimeString()} " : - $"{start.Value:dd.MM.yyyy HH:mm} - {end.Value:dd.MM.yyyy HH:mm} "; - } - - if (allDay && start.HasValue && end.HasValue) - { - return start.Value.Date == end.Value.Date ? " " : $"{start.Value.ToShortDateString()} - {end.Value.ToShortDateString()} "; - } - - return string.Empty; - } - - public List GetValidationMessagesForMonth(DateTime startDate, DateTime endDate) - { - var criteria = CreateCriteria() - .Add(Restrictions.Gt(ValidationMessage.PropertyName_InsTs, startDate)) - .Add(Restrictions.Lt(ValidationMessage.PropertyName_InsTs, endDate)); - - var list = criteria.List(); - - return list.ToList(); - } - public List GetServiceRecordForTimeSpan(DateTime startDate, DateTime endDate) - { - var criteria = CreateCriteria() - .Add(Restrictions.Gt(ServiceRecord.PropertyName_Start, startDate)) - .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, endDate)); - - var list = criteria.List(); - - return list.ToList(); - } - - /// - /// VERALTET! FindMostRecentSignatureStatusInfoByServiceRecordOid benutzen! - /// - /// - /// - public ServiceRecordHistory FindMostRecentServiceRecordHistoryEntryByServiceRecordOid(long serviceRecordOid) - { - try - { - var criteira = CreateCriteria() - .Add(Restrictions.Eq(nameof(ServiceRecordHistory.ServiceRecordOid), serviceRecordOid)) - .AddOrder(Order.Desc(nameof(ServiceRecordHistory.InsTs))); - - return criteira.List().FirstOrDefault(); - } - catch (Exception e) - { - return null; - } - } - - // ToDo: Veraltet und wird nicht mehr benutzt! - public Dictionary FindMostRecentServiceRecordHistoryEntryByServiceRecords(List serviceRecordOids) - { - var criteria = CreateCriteria() - .Add(Restrictions.In(nameof(ServiceRecordHistory.ServiceRecordOid), serviceRecordOids)) - .AddOrder(Order.Desc(nameof(ServiceRecordHistory.InsTs))); - - var historyEntries = criteria.List(); - - var result = new Dictionary(); - - foreach (var entry in historyEntries) - { - if (entry.ServiceRecordOid.HasValue && result.ContainsKey(entry.ServiceRecordOid.Value) || entry.ServiceRecordOid is null) - { - continue; - } - - result.AddIfNotIn(new KeyValuePair(entry.ServiceRecordOid.Value, entry)); - } - - return result; - } - - // ToDo: Veraltet und wird nicht mehr benutzt! - public List FindFormerlyLinkedServiceRecords(long confirmationReceiptSignatureOid, long customerOid, long supportConceptOid, long costBearer2SupportConceptOid, string timeSpanString) - { - if (timeSpanString?.Length != 21) - { - return new List(); - } - - var d1 = timeSpanString.Substring(0, 2); - var m1 = timeSpanString.Substring(3, 2); - var d2 = timeSpanString.Substring(11, 2); - var m2 = timeSpanString.Substring(14, 2); - var year = timeSpanString.Substring(17, 4); - - var timeSpanStart = DateTime.Parse($"{year}-{m1}-{d1}"); - var timeSpanEnd = DateTime.Parse($"{year}-{m2}-{d2}"); - - // ToDo: Warum wird geprüft, ob der InsTs im Intervall liegt? - // ToDo: Die ausschließen, die mit einer aktiven ConfirmationReceiptSignature verlinkt sind! - var criteria = CreateCriteria() - //.Add(Restrictions.Between(nameof(ServiceRecord.InsTs), timeSpanStart, timeSpanEnd)) - .Add(Restrictions.Eq(nameof(ServiceRecord.CustomerOid), customerOid)) - .Add(Restrictions.Eq(nameof(ServiceRecord.SupportConcept) + ".Oid", supportConceptOid)) - .Add(Restrictions.Eq(nameof(ServiceRecord.CostBearer2SupportConceptOid), costBearer2SupportConceptOid)) - .Add(Restrictions.Between(nameof(ServiceRecord.Start), timeSpanStart, timeSpanEnd)) - .Add(Restrictions.Between(nameof(ServiceRecord.End), timeSpanStart, timeSpanEnd)) - //.Add(Expression.Sql(new SqlString($"this_.Oid NOT IN (SELECT ServiceRecordOid FROM confirmationreceiptsignature2servicerecord WHERE ConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid})"))); - .Add(Expression.Sql(new SqlString($"this_.Oid NOT IN (SELECT ServiceRecordOid FROM confirmationreceiptsignature2servicerecord WHERE ConfirmationReceiptSignatureOid IN (SELECT ConfirmationReceiptSignatureOid FROM confirmationreceiptsignature WHERE IsActive = 1))"))); - - return criteria.List().ToList(); - } - - public List LoadAllActiveConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids) - { - var c = CreateCriteriaIsActive() - .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) - .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); - - // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) - c.SetResultTransformer(new DistinctRootEntityResultTransformer()); - - var result = c.List().ToList(); - - return result; - } - - public List FindFormerlyLinkedServiceRecordsBySignatureOid(long confirmationReceiptSignatureOid) - { - var sql = new SqlString($"this_.Oid NOT IN (SELECT ServiceRecordOid FROM confirmationreceiptsignature2servicerecord WHERE ConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid}) AND " + - $"this_.Oid IN (SELECT ServiceRecordOid FROM servicerecordhistory WHERE CustomerConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid} OR EmployeeConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid})"); - - var criteria = CreateCriteria() - .Add(Expression.Sql(sql)); - - return criteria.List().ToList(); - } - - public SignatureStateInfoFromServiceRecordHistoryEntry FindMostRecentSignatureStatusInfoByServiceRecordOid(long serviceRecordOid) - { - var sqlQuery = Session.CreateSQLQuery($"SELECT * FROM ServiceRecordHistory WHERE ServiceRecordOid = {serviceRecordOid} ORDER BY InsTs DESC LIMIT 1") - .AddScalar("CustomerConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) - .AddScalar("EmployeeConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) - .AddScalar("ServiceRecordSignatureStateType", NHibernateUtil.Int32) - .AddScalar("CustomerConfirmationReceiptSignatureOid", NHibernateUtil.Int64) - .AddScalar("EmployeeConfirmationReceiptSignatureOid", NHibernateUtil.Int64); - - var objectsList = sqlQuery.List().ToList(); - - var row = objectsList.FirstOrDefault(); - - if (row is null || row.Length != 5) - { - return null; - } - - var customerConfirmationReceiptSignatureState = (SignatureStateType)row[0]; - var employeeConfirmationReceiptSignatureState = (SignatureStateType)row[1]; - var serviceRecordSignatureStateType = (SignatureStateType)row[2]; - var customerConfirmationReceiptSignatureOid = (long?)row[3]; - var employeeConfirmationReceiptSignatureOid = (long?)row[4]; - - return new SignatureStateInfoFromServiceRecordHistoryEntry(customerConfirmationReceiptSignatureState, employeeConfirmationReceiptSignatureState, serviceRecordSignatureStateType, customerConfirmationReceiptSignatureOid, employeeConfirmationReceiptSignatureOid); - } - - public Dictionary FindMostRecentSignatureStatusInfoByServiceRecords(List serviceRecordOids) - { - var result = new Dictionary(); - - if (serviceRecordOids is null || serviceRecordOids.Count == 0) - { - return result; - } - - var sqlQuery = Session.CreateSQLQuery($"SELECT * FROM servicerecordhistory WHERE ServiceRecordOid IN ({serviceRecordOids.Aggregate(string.Empty, (current, item) => current + $"{item},").TrimEnd(',')}) ORDER BY InsTs DESC") - .AddScalar("ServiceRecordOid", NHibernateUtil.Int64) - .AddScalar("CustomerConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) - .AddScalar("EmployeeConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) - .AddScalar("ServiceRecordSignatureStateType", NHibernateUtil.Int32) - .AddScalar("CustomerConfirmationReceiptSignatureOid", NHibernateUtil.Int64) - .AddScalar("EmployeeConfirmationReceiptSignatureOid", NHibernateUtil.Int64); - - var objectsList = sqlQuery.List().ToList(); - - foreach (var obj in objectsList) - { - if (obj?.Length != 6) - { - continue; - } - - var serviceRecordOid = (long?)obj[0]; - - if (serviceRecordOid is null || result.ContainsKey(serviceRecordOid.Value)) - { - continue; - } - - var customerConfirmationReceiptSignatureState = (SignatureStateType)obj[1]; - var employeeConfirmationReceiptSignatureState = (SignatureStateType)obj[2]; - var serviceRecordSignatureStateType = (SignatureStateType)obj[3]; - var customerConfirmationReceiptSignatureOid = (long?)obj[4]; - var employeeConfirmationReceiptSignatureOid = (long?)obj[5]; + var appointments = tempAppointments.Where(appointment => + { + if (appointment.RecurrenceInfo is null) + { + return true; + } + + var recId2 = appointment.GetRecurrenceIdAndIndex(out var index); + return !((recurrenceId?.Equals(recId2) ?? false) && occurrenceIndex == index); + }).ToList(); + + + var deletedOccurrences = appointments.Where(app => app.Type == 4).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); + var changedOccurrences = appointments.Where(app => app.Type == 3).Select(app => BS.Shared.Core.Utils.GetOccurrenceId(app.RecurrenceInfo)).ToList(); + + var recurringAppointmentsCriteria = CreateRecurrenceCriteria(start, end).Add(Restrictions.Eq(nameof(SchedulerAppointment.Type), 1)); + + var recurringAppointments = recurringAppointmentsCriteria.List().ToList(); + + if (isBeingUpdatedToNormalAppointment) + { + recurringAppointments = recurringAppointments.Where(root => FilterRootAppointment(root, recurrenceIdToIgnore)).ToList(); + + appointments = appointments.Where(root => FilterRootAppointment(root, recurrenceIdToIgnore)).ToList(); + } + + recurringAppointments = recurringAppointments.Where(s => s.ResourceList.Any(r => r.Oid.HasValue && resourceOids.Contains(r.Oid.Value))).ToList(); + + foreach (var appointment in recurringAppointments) + { + var recurrenceInfo = new RecurrenceInfo(); + recurrenceInfo.FromXml(appointment.RecurrenceInfo); + + var occurrenceCalculator = OccurrenceCalculator.CreateInstance(recurrenceInfo); + + var pattern = StaticAppointmentFactory.CreateAppointment(AppointmentType.Pattern); + + if (pattern is null) + { + continue; + } + + pattern.RecurrenceInfo.FromXml(appointment.RecurrenceInfo); + pattern.Start = pattern.RecurrenceInfo.Start; + pattern.End = appointment.EndDate.Value; + + var patternId = pattern.RecurrenceInfo.Id.ToString(); + + var interval = new TimeInterval(start, end); + + var occurrences = occurrenceCalculator.CalcOccurrences(interval, pattern); + + foreach (var occurrence in occurrences.GetAppointments(interval)) + { + if (appointment.EndDate is null || appointment.StartDate is null) + { + continue; + } + + // Terminindex in der Serie + var index = occurrence.RecurrenceIndex; + + // Das Ende ist offen, da die Terminserie kein Ende hat. Deshalb wird das Ende berechnet. + var duration = (appointment.EndDate.Value - appointment.StartDate.Value).TotalMinutes; + + var guidParsingSuccessful = Guid.TryParse(occurrence.RecurrenceInfo?.Id?.ToString(), out var occurrenceGuid); + + // Der generierte Serientermin muss sich zeitlich mit dem neuen Termin überschneiden + // und darf nicht in der Liste der geänderten Serientermine oder der Liste der gelöschten Serientermine sein. + var isInIntervalTest = start.IsInInterval(end, occurrence.Start, occurrence.Start.AddMinutes(duration)); + + if (!isInIntervalTest || + changedOccurrences.Any(changedOccurence => changedOccurence.PatternId.Equals(patternId) && changedOccurence.Index == index) || + deletedOccurrences.Any(deletedOccurence => deletedOccurence.PatternId.Equals(patternId) && deletedOccurence.Index == index) || + index == occurrenceIndex && guidParsingSuccessful && recurrenceId != null && recurrenceId.Equals(occurrenceGuid)) + { + continue; + } + + // Prüfen, ob es eine Ausnahme an dem Tag gibt, die zu dem Pattern gehört, um das Pattern auszuschließen + var relatedAppointments = FindAppointmentsByRecurrenceId(new List { recurrenceInfo.Id.ToString() }, true); + var relatedAppointmentsInInterval = relatedAppointments.Where(a => + { + if (a.StartDate == null || a.EndDate == null) + { + return false; + } + + var myStart = a.StartDate.Value.Date; + var myEnd = a.EndDate.Value.Date; + + var isInInterval = start.Date.InBetween(myStart.GetShortDateTime(), myEnd, true); + + return isInInterval && a.Type != 4; + }).ToList(); + + var hasToStop = false; + + // Prüfen, ob es sich bei dem Termin für den Überschneidungen gesucht werden, um zu unterscheiden, ob ein Serientermin in einen normalen geändert wird. + var root = FindRootAppointmentByRecurrenceId(recurrenceInfo.Id.ToString()); + if (root.Oid != null && selectedAppointmentOid != null && root.Oid == selectedAppointmentOid && root.RecurrenceInfo != null && IsNullOrWhiteSpace(recurrenceId?.ToString())) + { + hasToStop = true; + } + + // Indices und Ids der RecurrenceInfo vergleichen. Stimmen sie überein, dann wird das generiert Serienelement ignoriert. + if (occurrence.RecurrenceInfo?.Id != null && !hasToStop) + { + if (Guid.TryParse(occurrence.RecurrenceInfo.Id.ToString(), out var guid)) + { + foreach (var relatedAppointment in relatedAppointmentsInInterval) + { + var relatedAppointmentRecurrenceId = relatedAppointment.GetRecurrenceIdAndIndex(out var relatedAppointmentRecurrenceIndex); + + if (relatedAppointmentRecurrenceId != null) + { + if (guid.Equals(relatedAppointmentRecurrenceId) && relatedAppointmentRecurrenceIndex.Equals(occurrence.RecurrenceIndex)) + { + hasToStop = true; + break; + } + } + } + } + } + + if (hasToStop) + { + continue; + } + + var recurringAppointment = new SchedulerAppointment + { + AllDay = occurrence.AllDay, + CustomerList = appointment.CustomerList, + Notice = appointment.Notice, + EmployeeList = appointment.EmployeeList, + EndDate = occurrence.Start.AddMinutes(duration), + FormerBookingSequenceOid = appointment.FormerBookingSequenceOid, + IsPrivate = appointment.IsPrivate, + Location = appointment.Location, + Originator = appointment.Originator, + RecurrenceInfo = occurrence.RecurrenceInfo.ToXml(), + ReminderInfo = appointment.ReminderInfo, + ResourceList = appointment.ResourceList, + StartDate = occurrence.Start, + Subject = appointment.Subject ?? "", + Type = appointment.Type + }; + + appointments.AddIfNotIn(recurringAppointment); + } + } + + return appointments.Where(appointment => appointment.Type != 4).OrderBy(appointment => appointment.StartDate).ToList(); + } + + private static bool FilterRootAppointment(SchedulerAppointment root, Guid? recurrenceIdToIgnore) + { + var recId = root.GetRecurrenceId(); + + if (recId is null || recurrenceIdToIgnore is null) + { + return true; + } + + return !recId.Equals(recurrenceIdToIgnore); + } + + public List LoadAllConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids) + { + var c = CreateCriteria() + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + + // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) + c.SetResultTransformer(new DistinctRootEntityResultTransformer()); + + var result = c.List().ToList(); + + return result; + } + + public Dictionary> CheckResourceAvailabilityWithEmployeeInformation(DateTime start, DateTime end, List resourceOids, long? selectedAppointmentOid, Guid? recurrenceId = null, int occurrenceIndex = 0) + { + var appointments = FindAppointmentsByResourcesInInterval(resourceOids, start, end, selectedAppointmentOid, recurrenceId, occurrenceIndex); + + var user = LoggedInUserOperationContextExt.Current?.User ?? SessionFacade.LoggedInUser; + + var result = new Dictionary>(); + + if (user is null) + { + return result; + } + + var loggedInEmployee = user.Employee; + + var hasRightToViewEmployeeAppointments = user.CheckForRight(UserRightType.KalenderMitarbeitertermineAnsehen); + var hasRightToViewResourceAppointments = user.CheckForRight(UserRightType.KalenderRessourcentermineAnsehen); + + var dictionary = new Dictionary>(); + + foreach (var appointment in appointments) + { + foreach (var resource in appointment.ResourceList) + { + dictionary.AddOrUpdateValueInDictionary(resource, appointment); + } + } + + foreach (var resource2Appointments in dictionary) + { + foreach (var appointment in resource2Appointments.Value) + { + var originator = appointment.Originator; + var employee2Appointments = appointment.EmployeeList; + + var isOwnAppointment = (originator?.Equals(loggedInEmployee) ?? false) || employee2Appointments.ToList().Any(e2a => e2a.Employee.Equals(loggedInEmployee)); + + // Wenn isOwnAppointment true ist, darf der Benutzer die Uhrzeiten und die Mitarbeiter sehen. Ansonsten müssen die Rechte geprüft werden. + if (isOwnAppointment || hasRightToViewEmployeeAppointments) // Es werden Zeit und Mitarbeiter angezeigt + { + result.AddOrUpdateValueInDictionary(resource2Appointments.Key.Name, $"{CreateDateTimeInfoFromAppointment(appointment.StartDate, appointment.EndDate, appointment.AllDay)} von {originator}"); + } + else if (hasRightToViewResourceAppointments && !hasRightToViewEmployeeAppointments) // Nur die Uhrzeit anzeigen + { + result.AddOrUpdateValueInDictionary(resource2Appointments.Key.Name, $"{CreateDateTimeInfoFromAppointment(appointment.StartDate, appointment.EndDate, appointment.AllDay)}"); + } + else if (!hasRightToViewEmployeeAppointments) // Es werden weder Zeit noch Mitarbeiter angezeigt + { + result.AddOrUpdateValueInDictionary(resource2Appointments.Key.Name, string.Empty); + } + } + } + + return result; + } + + private static string CreateDateTimeInfoFromAppointment(DateTime? start, DateTime? end, bool allDay) + { + if (start.HasValue && end.HasValue && allDay == false) + { + return start.Value.Date == end.Value.Date ? + $"{start.Value.ToShortTimeString()} - {end.Value.ToShortTimeString()} " : + $"{start.Value:dd.MM.yyyy HH:mm} - {end.Value:dd.MM.yyyy HH:mm} "; + } + + if (allDay && start.HasValue && end.HasValue) + { + return start.Value.Date == end.Value.Date ? " " : $"{start.Value.ToShortDateString()} - {end.Value.ToShortDateString()} "; + } + + return string.Empty; + } + + public List GetValidationMessagesForMonth(DateTime startDate, DateTime endDate) + { + var criteria = CreateCriteria() + .Add(Restrictions.Gt(ValidationMessage.PropertyName_InsTs, startDate)) + .Add(Restrictions.Lt(ValidationMessage.PropertyName_InsTs, endDate)); + + var list = criteria.List(); + + return list.ToList(); + } + public List GetServiceRecordForTimeSpan(DateTime startDate, DateTime endDate) + { + var criteria = CreateCriteria() + .Add(Restrictions.Gt(ServiceRecord.PropertyName_Start, startDate)) + .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, endDate)); + + var list = criteria.List(); + + return list.ToList(); + } + + /// + /// VERALTET! FindMostRecentSignatureStatusInfoByServiceRecordOid benutzen! + /// + /// + /// + public ServiceRecordHistory FindMostRecentServiceRecordHistoryEntryByServiceRecordOid(long serviceRecordOid) + { + try + { + var criteira = CreateCriteria() + .Add(Restrictions.Eq(nameof(ServiceRecordHistory.ServiceRecordOid), serviceRecordOid)) + .AddOrder(Order.Desc(nameof(ServiceRecordHistory.InsTs))); + + return criteira.List().FirstOrDefault(); + } + catch (Exception e) + { + return null; + } + } + + // ToDo: Veraltet und wird nicht mehr benutzt! + public Dictionary FindMostRecentServiceRecordHistoryEntryByServiceRecords(List serviceRecordOids) + { + var criteria = CreateCriteria() + .Add(Restrictions.In(nameof(ServiceRecordHistory.ServiceRecordOid), serviceRecordOids)) + .AddOrder(Order.Desc(nameof(ServiceRecordHistory.InsTs))); + + var historyEntries = criteria.List(); + + var result = new Dictionary(); + + foreach (var entry in historyEntries) + { + if (entry.ServiceRecordOid.HasValue && result.ContainsKey(entry.ServiceRecordOid.Value) || entry.ServiceRecordOid is null) + { + continue; + } + + result.AddIfNotIn(new KeyValuePair(entry.ServiceRecordOid.Value, entry)); + } + + return result; + } + + // ToDo: Veraltet und wird nicht mehr benutzt! + public List FindFormerlyLinkedServiceRecords(long confirmationReceiptSignatureOid, long customerOid, long supportConceptOid, long costBearer2SupportConceptOid, string timeSpanString) + { + if (timeSpanString?.Length != 21) + { + return new List(); + } + + var d1 = timeSpanString.Substring(0, 2); + var m1 = timeSpanString.Substring(3, 2); + var d2 = timeSpanString.Substring(11, 2); + var m2 = timeSpanString.Substring(14, 2); + var year = timeSpanString.Substring(17, 4); + + var timeSpanStart = DateTime.Parse($"{year}-{m1}-{d1}"); + var timeSpanEnd = DateTime.Parse($"{year}-{m2}-{d2}"); + + // ToDo: Warum wird geprüft, ob der InsTs im Intervall liegt? + // ToDo: Die ausschließen, die mit einer aktiven ConfirmationReceiptSignature verlinkt sind! + var criteria = CreateCriteria() + //.Add(Restrictions.Between(nameof(ServiceRecord.InsTs), timeSpanStart, timeSpanEnd)) + .Add(Restrictions.Eq(nameof(ServiceRecord.CustomerOid), customerOid)) + .Add(Restrictions.Eq(nameof(ServiceRecord.SupportConcept) + ".Oid", supportConceptOid)) + .Add(Restrictions.Eq(nameof(ServiceRecord.CostBearer2SupportConceptOid), costBearer2SupportConceptOid)) + .Add(Restrictions.Between(nameof(ServiceRecord.Start), timeSpanStart, timeSpanEnd)) + .Add(Restrictions.Between(nameof(ServiceRecord.End), timeSpanStart, timeSpanEnd)) + //.Add(Expression.Sql(new SqlString($"this_.Oid NOT IN (SELECT ServiceRecordOid FROM confirmationreceiptsignature2servicerecord WHERE ConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid})"))); + .Add(Expression.Sql(new SqlString($"this_.Oid NOT IN (SELECT ServiceRecordOid FROM confirmationreceiptsignature2servicerecord WHERE ConfirmationReceiptSignatureOid IN (SELECT ConfirmationReceiptSignatureOid FROM confirmationreceiptsignature WHERE IsActive = 1))"))); + + return criteria.List().ToList(); + } + + public List LoadAllActiveConfirmationReceiptSignaturesByServiceRecordOids(IList serviceRecordOids) + { + var c = CreateCriteriaIsActive() + .CreateAlias(nameof(ConfirmationReceiptSignature.ServiceRecords), "sr", JoinType.InnerJoin) + .Add(Restrictions.In($"sr.{nameof(BeWoEntityBase.Oid)}", serviceRecordOids.ToArray())); + + // Der ResultTransformer erzeugt ein SELECT DISTINCT für den Roottypen (ConfirmationReceiptSignature) + c.SetResultTransformer(new DistinctRootEntityResultTransformer()); + + var result = c.List().ToList(); + + return result; + } + + public List FindFormerlyLinkedServiceRecordsBySignatureOid(long confirmationReceiptSignatureOid) + { + var sql = new SqlString($"this_.Oid NOT IN (SELECT ServiceRecordOid FROM confirmationreceiptsignature2servicerecord WHERE ConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid}) AND " + + $"this_.Oid IN (SELECT ServiceRecordOid FROM servicerecordhistory WHERE CustomerConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid} OR EmployeeConfirmationReceiptSignatureOid = {confirmationReceiptSignatureOid})"); + + var criteria = CreateCriteria() + .Add(Expression.Sql(sql)); + + return criteria.List().ToList(); + } + + public SignatureStateInfoFromServiceRecordHistoryEntry FindMostRecentSignatureStatusInfoByServiceRecordOid(long serviceRecordOid) + { + var sqlQuery = Session.CreateSQLQuery($"SELECT * FROM ServiceRecordHistory WHERE ServiceRecordOid = {serviceRecordOid} ORDER BY InsTs DESC LIMIT 1") + .AddScalar("CustomerConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) + .AddScalar("EmployeeConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) + .AddScalar("ServiceRecordSignatureStateType", NHibernateUtil.Int32) + .AddScalar("CustomerConfirmationReceiptSignatureOid", NHibernateUtil.Int64) + .AddScalar("EmployeeConfirmationReceiptSignatureOid", NHibernateUtil.Int64); + + var objectsList = sqlQuery.List().ToList(); + + var row = objectsList.FirstOrDefault(); + + if (row is null || row.Length != 5) + { + return null; + } + + var customerConfirmationReceiptSignatureState = (SignatureStateType)row[0]; + var employeeConfirmationReceiptSignatureState = (SignatureStateType)row[1]; + var serviceRecordSignatureStateType = (SignatureStateType)row[2]; + var customerConfirmationReceiptSignatureOid = (long?)row[3]; + var employeeConfirmationReceiptSignatureOid = (long?)row[4]; + + return new SignatureStateInfoFromServiceRecordHistoryEntry(customerConfirmationReceiptSignatureState, employeeConfirmationReceiptSignatureState, serviceRecordSignatureStateType, customerConfirmationReceiptSignatureOid, employeeConfirmationReceiptSignatureOid); + } + + public Dictionary FindMostRecentSignatureStatusInfoByServiceRecords(List serviceRecordOids) + { + var result = new Dictionary(); + + if (serviceRecordOids is null || serviceRecordOids.Count == 0) + { + return result; + } + + var sqlQuery = Session.CreateSQLQuery($"SELECT * FROM servicerecordhistory WHERE ServiceRecordOid IN ({serviceRecordOids.Aggregate(string.Empty, (current, item) => current + $"{item},").TrimEnd(',')}) ORDER BY InsTs DESC") + .AddScalar("ServiceRecordOid", NHibernateUtil.Int64) + .AddScalar("CustomerConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) + .AddScalar("EmployeeConfirmationReceiptSignatureStateType", NHibernateUtil.Int32) + .AddScalar("ServiceRecordSignatureStateType", NHibernateUtil.Int32) + .AddScalar("CustomerConfirmationReceiptSignatureOid", NHibernateUtil.Int64) + .AddScalar("EmployeeConfirmationReceiptSignatureOid", NHibernateUtil.Int64); + + var objectsList = sqlQuery.List().ToList(); + + foreach (var obj in objectsList) + { + if (obj?.Length != 6) + { + continue; + } + + var serviceRecordOid = (long?)obj[0]; + + if (serviceRecordOid is null || result.ContainsKey(serviceRecordOid.Value)) + { + continue; + } + + var customerConfirmationReceiptSignatureState = (SignatureStateType)obj[1]; + var employeeConfirmationReceiptSignatureState = (SignatureStateType)obj[2]; + var serviceRecordSignatureStateType = (SignatureStateType)obj[3]; + var customerConfirmationReceiptSignatureOid = (long?)obj[4]; + var employeeConfirmationReceiptSignatureOid = (long?)obj[5]; - result.AddIfNotIn(new KeyValuePair(serviceRecordOid.Value, new SignatureStateInfoFromServiceRecordHistoryEntry(customerConfirmationReceiptSignatureState, employeeConfirmationReceiptSignatureState, serviceRecordSignatureStateType, customerConfirmationReceiptSignatureOid, employeeConfirmationReceiptSignatureOid))); - } + result.AddIfNotIn(new KeyValuePair(serviceRecordOid.Value, new SignatureStateInfoFromServiceRecordHistoryEntry(customerConfirmationReceiptSignatureState, employeeConfirmationReceiptSignatureState, serviceRecordSignatureStateType, customerConfirmationReceiptSignatureOid, employeeConfirmationReceiptSignatureOid))); + } - return result; - } + return result; + } - #region MoK-Zeiterfassungspagination - public IEnumerable FindServiceRecordsForDaysPaginated(long? costBearer2SupportConceptOid, int dayCount, long? employeeOid, int firstResult, int maxResults, out int rowCount) - { - var minStart = DateTime.Now.GetShortDateTime().AddDays(-dayCount); - var criteria = CreateCriteriaIsActive(); - var rowCountCirteria = CreateCriteriaIsActive(); + #region MoK-Zeiterfassungspagination + public IEnumerable FindServiceRecordsForDaysPaginated(long? costBearer2SupportConceptOid, int dayCount, long? employeeOid, int firstResult, int maxResults, out int rowCount) + { + var minStart = DateTime.Now.GetShortDateTime().AddDays(-dayCount); + var criteria = CreateCriteriaIsActive(); + var rowCountCirteria = CreateCriteriaIsActive(); - if(costBearer2SupportConceptOid.HasValue) - { - var groupOidsQuery = Session.CreateSQLQuery($"SELECT MIN(Oid) FROM servicerecord WHERE CostBearer2SupportConceptOid = {costBearer2SupportConceptOid} GROUP BY GroupOid"); - var groupOids = groupOidsQuery.List().ToArray(); + if (costBearer2SupportConceptOid.HasValue) + { + var groupOidsQuery = Session.CreateSQLQuery($"SELECT MIN(Oid) FROM servicerecord WHERE CostBearer2SupportConceptOid = {costBearer2SupportConceptOid} GROUP BY GroupOid"); + var groupOids = groupOidsQuery.List().ToArray(); - criteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); - rowCountCirteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); + criteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); + rowCountCirteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costBearer2SupportConceptOid)); - criteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); - rowCountCirteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); - } - else - { - criteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + criteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); + rowCountCirteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); + } + else + { + criteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - rowCountCirteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - } + rowCountCirteria.Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, employeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + } - if(dayCount > 0) - { - criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minStart)); - rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minStart)); - } + if (dayCount > 0) + { + criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minStart)); + rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minStart)); + } - criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); + criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); - rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; + rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; - var serviceRecords = criteria.SetFirstResult(firstResult).SetMaxResults(maxResults).Future(); + var serviceRecords = criteria.SetFirstResult(firstResult).SetMaxResults(maxResults).Future(); - return serviceRecords; - } + return serviceRecords; + } - public IEnumerable FindEmployeeServiceRecordsWithoutCustomerPaginated(long pEmployeeOid, long? days, int firstResult, int maxResults, out int rowCount) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + public IEnumerable FindEmployeeServiceRecordsWithoutCustomerPaginated(long pEmployeeOid, long? days, int firstResult, int maxResults, out int rowCount) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - var rowCountCirteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + var rowCountCirteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - if (days.HasValue) - { - var minDate = DateTime.Now.Date.AddDays(-1 * days.Value); - criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); - rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); - } + if (days.HasValue) + { + var minDate = DateTime.Now.Date.AddDays(-1 * days.Value); + criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); + rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, minDate)); + } - criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); + criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); - rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; + rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; - return criteria.SetFirstResult(firstResult).SetMaxResults(maxResults).Future(); - } + return criteria.SetFirstResult(firstResult).SetMaxResults(maxResults).Future(); + } - public IEnumerable FindServiceRecordsDetailsForLastDaysWithStartEndDatePaginated(long costbearer2SupportConcept, DateTime start, DateTime ende, int firstResult, int maxResults, out int rowCount) - { - var groupOidsQuery = Session.CreateSQLQuery($"SELECT MIN(Oid) FROM servicerecord WHERE CostBearer2SupportConceptOid = {costbearer2SupportConcept} GROUP BY GroupOid"); - var groupOids = groupOidsQuery.List().ToArray(); + public IEnumerable FindServiceRecordsDetailsForLastDaysWithStartEndDatePaginated(long costbearer2SupportConcept, DateTime start, DateTime ende, int firstResult, int maxResults, out int rowCount) + { + var groupOidsQuery = Session.CreateSQLQuery($"SELECT MIN(Oid) FROM servicerecord WHERE CostBearer2SupportConceptOid = {costbearer2SupportConcept} GROUP BY GroupOid"); + var groupOids = groupOidsQuery.List().ToArray(); - var criteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); + var criteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); - var rowCountCirteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); + var rowCountCirteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_CostBearer2SupportConceptOid, costbearer2SupportConcept)); - var max = ende.Date.AddDays(1); + var max = ende.Date.AddDays(1); - criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) - .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); + criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) + .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); - rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) - .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); + rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) + .Add(Restrictions.Lt(ServiceRecord.PropertyName_Start, max.Date)); - criteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); - rowCountCirteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); + criteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); + rowCountCirteria.Add(Restrictions.Or(Restrictions.IsNull(nameof(ServiceRecord.GroupOid)), Restrictions.In(nameof(ServiceRecord.Oid), groupOids))); - criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); + criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); - rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; + rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; - var result = criteria.CreateAlias(ServiceRecord.PropertyName_ValueList, "vl", JoinType.LeftOuterJoin) - .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) - .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) - .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin) - .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.InnerJoin) - .SetFirstResult(firstResult) - .SetMaxResults(maxResults) - .Future(); + var result = criteria.CreateAlias(ServiceRecord.PropertyName_ValueList, "vl", JoinType.LeftOuterJoin) + .CreateAlias(ServiceRecord.PropertyName_ServiceDescription, "sd", JoinType.InnerJoin) + .CreateAlias("sd." + ServiceDescription.PropertyName_ServiceCategory, "sc", JoinType.InnerJoin) + .CreateAlias(ServiceRecord.PropertyName_Employee, "e", JoinType.InnerJoin) + .CreateCriteria("e." + Employee.PropertyName_Person, JoinType.InnerJoin) + .SetFirstResult(firstResult) + .SetMaxResults(maxResults) + .Future(); - return result; - } + return result; + } - public IEnumerable FindEmployeeServiceRecordsWithoutCustomerWithStartEndDatePaginated(long pEmployeeOid, DateTime start, DateTime ende, int firstResult, int maxResults, out int rowCount) - { + public IEnumerable FindEmployeeServiceRecordsWithoutCustomerWithStartEndDatePaginated(long pEmployeeOid, DateTime start, DateTime ende, int firstResult, int maxResults, out int rowCount) + { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + var criteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - var rowCountCirteria = CreateCriteria() - .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) - .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); + var rowCountCirteria = CreateCriteria() + .Add(Restrictions.Eq(ServiceRecord.PropertyName_EmployeeOid, pEmployeeOid)) + .Add(Restrictions.IsNull(ServiceRecord.PropertyName_CostBearer2SupportConceptOid)); - var max = ende.Date.AddDays(1); + var max = ende.Date.AddDays(1); - criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) - .Add(Restrictions.Lt(ServiceRecord.PropertyName_End, max.Date)); + criteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) + .Add(Restrictions.Lt(ServiceRecord.PropertyName_End, max.Date)); - rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) - .Add(Restrictions.Lt(ServiceRecord.PropertyName_End, max.Date)); + rowCountCirteria.Add(Restrictions.Ge(ServiceRecord.PropertyName_Start, start.Date)) + .Add(Restrictions.Lt(ServiceRecord.PropertyName_End, max.Date)); - criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); + criteria.AddOrder(Order.Desc(nameof(ServiceRecord.Start))).AddOrder(Order.Desc(nameof(ServiceRecord.End))).AddOrder(Order.Desc(nameof(BeWoEntityBase.InsTs))); - rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; + rowCount = rowCountCirteria.SetProjection(Projections.RowCount()).FutureValue().Value; - return criteria.SetFirstResult(firstResult).SetMaxResults(maxResults).Future(); - } - #endregion + return criteria.SetFirstResult(firstResult).SetMaxResults(maxResults).Future(); + } + #endregion - public Signature LoadSignatureByTransaktionsOid(long transaktionsOid) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(Signature.BargeldtransaktionsOid), transaktionsOid)); + public Signature LoadSignatureByTransaktionsOid(long transaktionsOid) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(Signature.BargeldtransaktionsOid), transaktionsOid)); - return criteria.List().FirstOrDefault(); - } + return criteria.List().FirstOrDefault(); + } - public List LoadSignatureOidsByTransaktionOid(long transactionOid) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(Signature.BargeldtransaktionsOid), transactionOid)); + public List LoadSignatureOidsByTransaktionOid(long transactionOid) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(Signature.BargeldtransaktionsOid), transactionOid)); - return criteria.List().Select(s => s.Oid.Value).ToList(); - } + return criteria.List().Select(s => s.Oid.Value).ToList(); + } - public List LoadSignaturesByTransactionOids(List transactionOids) - { - var criteria = CreateCriteria() - .Add(Restrictions.In(nameof(Signature.BargeldtransaktionsOid), transactionOids)); + public List LoadSignaturesByTransactionOids(List transactionOids) + { + var criteria = CreateCriteria() + .Add(Restrictions.In(nameof(Signature.BargeldtransaktionsOid), transactionOids)); - return criteria.List().ToList(); - } + return criteria.List().ToList(); + } - public List LoadBargeldtransaktionshistoryEntries(long transaktionsOid) - { - var criteria = CreateCriteria() - .Add(Restrictions.Eq(nameof(Bargeldtransaktionshistory.BargeldtransaktionOid), transaktionsOid)); + public List LoadBargeldtransaktionshistoryEntries(long transaktionsOid) + { + var criteria = CreateCriteria() + .Add(Restrictions.Eq(nameof(Bargeldtransaktionshistory.BargeldtransaktionOid), transaktionsOid)); - return criteria.List().ToList(); - } + return criteria.List().ToList(); + } - public int GetNextDatenaustauschreferenz(string datenannahmestelle) - { - var criteria = CreateCriteria() - .Add(Restrictions.Where(x => x.SentApp8Success && x.IKDatenannahmestelle == datenannahmestelle)) - .SetProjection(Projections.Max("Datenaustauschreferenz")); + public int GetNextDatenaustauschreferenz(string datenannahmestelle) + { + var criteria = CreateCriteria() + .Add(Restrictions.Where(x => x.SentApp8Success && x.IKDatenannahmestelle == datenannahmestelle)) + .SetProjection(Projections.Max("Datenaustauschreferenz")); - var t = criteria.List().SingleOrDefault(); + var t = criteria.List().SingleOrDefault(); - return t + 1 ?? 1; - } + return t + 1 ?? 1; + } - public int GetNextTransfernummer(string datenannahmestelle) - { - var criteria = CreateCriteria() - .Add(Restrictions.Where(x => x.SentApp8Success && x.IKDatenannahmestelle == datenannahmestelle)) - .SetProjection(Projections.Max("Transfernummer")); + public int GetNextTransfernummer(string datenannahmestelle) + { + var criteria = CreateCriteria() + .Add(Restrictions.Where(x => x.SentApp8Success && x.IKDatenannahmestelle == datenannahmestelle)) + .SetProjection(Projections.Max("Transfernummer")); - var t = criteria.List().SingleOrDefault(); - - return t + 1 ?? 0; - } - - public List GetAllOrganisationByIKKrankenkasse(string ikkrankenkasse) - { - var criteria = CreateCriteria() - .Add(Restrictions.Where(x => x.IKKrankenkasse == ikkrankenkasse)); - - return criteria.List().ToList(); - } - - public List LoadBargeldtransaktionshistoryEntriesByTransaktionsOids(List transaktionsOids) - { - var criteria = CreateCriteriaIsActive() - .Add(Restrictions.In(nameof(Bargeldtransaktionshistory.BargeldtransaktionOid), transaktionsOids)); - - return criteria.List().ToList(); - } - - public List GetGoalCategoriesByOids(List oids) - { - var criteria = CreateCriteriaIsActive() - .Add( - Restrictions.Or( - Restrictions.Eq(nameof(ValueListEntry.Type), ValueListEntryType.SupportConceptGoalCategoryType), - Restrictions.Eq(nameof(ValueListEntry.Type), ValueListEntryType.SupportConceptIndividualGoalCategoryType))) - .AddOrder(Order.Asc(nameof(ValueListEntry.Value))); - - return criteria.List().OrderBy(valueListEntry => $"{valueListEntry.Abbreviation}-{valueListEntry.Value}").ToList(); - } - - public List FindSupportConceptsByCostbearer2SupportConceptRelOids(List costbearer2SupportConceptRelOids) - { - var criteria = CreateCriteria() - .CreateAlias(nameof(SupportConcept.CostBearer2SupportConceptList), "cb2Sc", JoinType.InnerJoin) - .Add(Restrictions.In($"cb2Sc.{nameof(BeWoEntityBase.Oid)}", costbearer2SupportConceptRelOids.ToArray())); - - return criteria.List().ToList(); - } - - public virtual IList FindCustomersOfTeams(IEnumerable teamOids) - { - return CreateCriteriaIsActiveOrArchived() - .CreateCriteria(nameof(Customer.Team2CustomerList), JoinType.InnerJoin) - .Add(Restrictions.In(nameof(Team2Customer.TeamOid), teamOids.ToArray())) - .List(); - } - - public List FindCustomersForPaginatedQb(int firstResult, int maxResults, bool checkTeamCustomerRights, DateTime start, DateTime end, out int rowCount) - { - var user = LoggedInUserOperationContextExt.Current?.User ?? SessionFacade.LoggedInUser; - - var rights = new List(); - foreach(var userGroup in user.UserGroups) - { - rights.AddRangeIfElementsNotIn(userGroup.Rights.Select(rightRelation => rightRelation.RightType)); - } - - var hasRightCustomerViewView = rights.Contains(UserRightType.CustomerView_View); - var hasRightCustomerViewMyTeams = rights.Contains(UserRightType.Customer_ViewMyTeams); - - List customers = null; - rowCount = 0; - - if(!hasRightCustomerViewView) - { - customers = new List(); - - ICriteria criteria; - if(checkTeamCustomerRights && hasRightCustomerViewMyTeams) - { - criteria = CreateCriteriaIsActiveOrArchived() - .CreateCriteria(nameof(Customer.Team2CustomerList), JoinType.InnerJoin) - .Add(Restrictions.In(nameof(Team2Customer.TeamOid), user.Employee.LeadingTeams.Select(team => team.Oid.Value).ToArray())); - - rowCount = GetRowCountForQuittierungsbelegPagination(criteria.List().Select(c => c.Oid.Value).Distinct().ToArray(), start, end); - - var teamCustomers = criteria - .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) - .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) - .SetFirstResult(firstResult) - .SetMaxResults(maxResults) - .Future() - .ToList(); - - customers.AddRangeIfElementsNotIn(teamCustomers); - } - else - { - var allOwnCustomerOids = user.Employee.Employee2CustomerList.Select(e2C => e2C.Customer.Oid.Value).ToList(); - - criteria = CreateCriteria() - .Add(Restrictions.In(nameof(BeWoEntityBase.Oid), allOwnCustomerOids)); - - rowCount = GetRowCountForQuittierungsbelegPagination(criteria.List().Select(customer => customer.Oid.Value).Distinct().ToArray(), start, end); - - var paginatedOwnCustomers = criteria - .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) - .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) - .SetFirstResult(firstResult) - .SetMaxResults(maxResults) - .Future() - .ToList(); - - customers.AddRangeIfElementsNotIn(paginatedOwnCustomers); - } - } - - if(customers != null) - { - return customers; - } - - var customerOids = CreateCriteriaIsActive().List().Select(customer => customer.Oid.Value).Distinct().ToArray(); - - rowCount = GetRowCountForQuittierungsbelegPagination(customerOids, start, end); - - customers = CreateCriteriaIsActive() - .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) - .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) - .SetFirstResult(firstResult) - .SetMaxResults(maxResults) - .Future() - .ToList(); - - return customers; - } - - public List FindCustomersForPaginatedQbByOids(int firstResult, int maxResults, long[] customerOids, DateTime start, DateTime end, out int rowCount) - { - rowCount = GetRowCountForQuittierungsbelegPagination(customerOids, start, end); - - return CreateCriteriaIsActive() - .Add(Restrictions.In(nameof(BeWoEntityBase.Oid), customerOids)) - .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) - .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) - .SetFirstResult(firstResult) - .SetMaxResults(maxResults) - .Future() - .ToList(); - } - - private int GetRowCountForQuittierungsbelegPagination(long[] customerOids, DateTime start, DateTime end) - { - var customerCountWithQuittierungsbelegInSpan = CreateCriteriaIsActive() - .Add(Restrictions.In(nameof(BeWoEntityBase.Oid), customerOids)) - .CreateAlias(nameof(Customer.ServiceRecordList), "sr", JoinType.InnerJoin) - .Add(Restrictions.Between($"sr.{nameof(ServiceRecord.Start)}", start, end)) - .SetProjection(Projections.CountDistinct(nameof(BeWoEntityBase.Oid))).FutureValue().Value; - - return customerCountWithQuittierungsbelegInSpan; - } - - public long GetServiceRecordCountForServiceCategory(long catOid) - { - var sql = $"SELECT COUNT(sr.oid) FROM ServiceRecord sr join ServiceDescription sd on sr.ServiceDescriptionOid = sd.Oid WHERE sd.ServiceCategoryOid = {catOid}"; - var q = Session.CreateSQLQuery(sql); - return q.List().First(); - } - - public long GetServiceRecordCountForServiceDescription(long descOid) - { - var sql = $"SELECT COUNT(sr.oid) FROM ServiceRecord sr WHERE sr.ServiceDescriptionOid = {descOid}"; - var q = Session.CreateSQLQuery(sql); - return q.List().First(); - } - } + var t = criteria.List().SingleOrDefault(); + + return t + 1 ?? 0; + } + + public List GetAllOrganisationByIKKrankenkasse(string ikkrankenkasse) + { + var criteria = CreateCriteria() + .Add(Restrictions.Where(x => x.IKKrankenkasse == ikkrankenkasse)); + + return criteria.List().ToList(); + } + + public List LoadBargeldtransaktionshistoryEntriesByTransaktionsOids(List transaktionsOids) + { + var criteria = CreateCriteriaIsActive() + .Add(Restrictions.In(nameof(Bargeldtransaktionshistory.BargeldtransaktionOid), transaktionsOids)); + + return criteria.List().ToList(); + } + + public List GetGoalCategoriesByOids(List oids) + { + var criteria = CreateCriteriaIsActive() + .Add( + Restrictions.Or( + Restrictions.Eq(nameof(ValueListEntry.Type), ValueListEntryType.SupportConceptGoalCategoryType), + Restrictions.Eq(nameof(ValueListEntry.Type), ValueListEntryType.SupportConceptIndividualGoalCategoryType))) + .AddOrder(Order.Asc(nameof(ValueListEntry.Value))); + + return criteria.List().OrderBy(valueListEntry => $"{valueListEntry.Abbreviation}-{valueListEntry.Value}").ToList(); + } + + public List FindSupportConceptsByCostbearer2SupportConceptRelOids(List costbearer2SupportConceptRelOids) + { + var criteria = CreateCriteria() + .CreateAlias(nameof(SupportConcept.CostBearer2SupportConceptList), "cb2Sc", JoinType.InnerJoin) + .Add(Restrictions.In($"cb2Sc.{nameof(BeWoEntityBase.Oid)}", costbearer2SupportConceptRelOids.ToArray())); + + return criteria.List().ToList(); + } + + public virtual IList FindCustomersOfTeams(IEnumerable teamOids) + { + return CreateCriteriaIsActiveOrArchived() + .CreateCriteria(nameof(Customer.Team2CustomerList), JoinType.InnerJoin) + .Add(Restrictions.In(nameof(Team2Customer.TeamOid), teamOids.ToArray())) + .List(); + } + + public List FindCustomersForPaginatedQb(int firstResult, int maxResults, bool checkTeamCustomerRights, DateTime start, DateTime end, out int rowCount) + { + var user = LoggedInUserOperationContextExt.Current?.User ?? SessionFacade.LoggedInUser; + + var rights = new List(); + foreach (var userGroup in user.UserGroups) + { + rights.AddRangeIfElementsNotIn(userGroup.Rights.Select(rightRelation => rightRelation.RightType)); + } + + var hasRightCustomerViewView = rights.Contains(UserRightType.CustomerView_View); + var hasRightCustomerViewMyTeams = rights.Contains(UserRightType.Customer_ViewMyTeams); + + List customers = null; + rowCount = 0; + + if (!hasRightCustomerViewView) + { + customers = new List(); + + ICriteria criteria; + if (checkTeamCustomerRights && hasRightCustomerViewMyTeams) + { + criteria = CreateCriteriaIsActiveOrArchived() + .CreateCriteria(nameof(Customer.Team2CustomerList), JoinType.InnerJoin) + .Add(Restrictions.In(nameof(Team2Customer.TeamOid), user.Employee.LeadingTeams.Select(team => team.Oid.Value).ToArray())); + + rowCount = GetRowCountForQuittierungsbelegPagination(criteria.List().Select(c => c.Oid.Value).Distinct().ToArray(), start, end); + + var teamCustomers = criteria + .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) + .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) + .SetFirstResult(firstResult) + .SetMaxResults(maxResults) + .Future() + .ToList(); + + customers.AddRangeIfElementsNotIn(teamCustomers); + } + else + { + var allOwnCustomerOids = user.Employee.Employee2CustomerList.Select(e2C => e2C.Customer.Oid.Value).ToList(); + + criteria = CreateCriteria() + .Add(Restrictions.In(nameof(BeWoEntityBase.Oid), allOwnCustomerOids)); + + rowCount = GetRowCountForQuittierungsbelegPagination(criteria.List().Select(customer => customer.Oid.Value).Distinct().ToArray(), start, end); + + var paginatedOwnCustomers = criteria + .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) + .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) + .SetFirstResult(firstResult) + .SetMaxResults(maxResults) + .Future() + .ToList(); + + customers.AddRangeIfElementsNotIn(paginatedOwnCustomers); + } + } + + if (customers != null) + { + return customers; + } + + var customerOids = CreateCriteriaIsActive().List().Select(customer => customer.Oid.Value).Distinct().ToArray(); + + rowCount = GetRowCountForQuittierungsbelegPagination(customerOids, start, end); + + customers = CreateCriteriaIsActive() + .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) + .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) + .SetFirstResult(firstResult) + .SetMaxResults(maxResults) + .Future() + .ToList(); + + return customers; + } + + public List FindCustomersForPaginatedQbByOids(int firstResult, int maxResults, long[] customerOids, DateTime start, DateTime end, out int rowCount) + { + rowCount = GetRowCountForQuittierungsbelegPagination(customerOids, start, end); + + return CreateCriteriaIsActive() + .Add(Restrictions.In(nameof(BeWoEntityBase.Oid), customerOids)) + .CreateAlias(nameof(Customer.Person), "p", JoinType.InnerJoin) + .AddOrder(Order.Asc($"p.{nameof(Person.LastName)}")) + .SetFirstResult(firstResult) + .SetMaxResults(maxResults) + .Future() + .ToList(); + } + + private int GetRowCountForQuittierungsbelegPagination(long[] customerOids, DateTime start, DateTime end) + { + var customerCountWithQuittierungsbelegInSpan = CreateCriteriaIsActive() + .Add(Restrictions.In(nameof(BeWoEntityBase.Oid), customerOids)) + .CreateAlias(nameof(Customer.ServiceRecordList), "sr", JoinType.InnerJoin) + .Add(Restrictions.Between($"sr.{nameof(ServiceRecord.Start)}", start, end)) + .SetProjection(Projections.CountDistinct(nameof(BeWoEntityBase.Oid))).FutureValue().Value; + + return customerCountWithQuittierungsbelegInSpan; + } + + public long GetServiceRecordCountForServiceCategory(long catOid) + { + var sql = $"SELECT COUNT(sr.oid) FROM ServiceRecord sr join ServiceDescription sd on sr.ServiceDescriptionOid = sd.Oid WHERE sd.ServiceCategoryOid = {catOid}"; + var q = Session.CreateSQLQuery(sql); + return q.List().First(); + } + + public long GetServiceRecordCountForServiceDescription(long descOid) + { + var sql = $"SELECT COUNT(sr.oid) FROM ServiceRecord sr WHERE sr.ServiceDescriptionOid = {descOid}"; + var q = Session.CreateSQLQuery(sql); + return q.List().First(); + } + } } diff --git a/Host/GkvAbrechnungClient.aspx.cs b/Host/GkvAbrechnungClient.aspx.cs index 500ce7f2e..2e97628ae 100644 --- a/Host/GkvAbrechnungClient.aspx.cs +++ b/Host/GkvAbrechnungClient.aspx.cs @@ -54,7 +54,7 @@ namespace Host ClientResult(GkvSender.DeserializeRequest(str, SendInvalidInputResponse)); return; case RequestType.GkvClientSum: - ClientSum(GkvSender.DeserializeRequest(str, SendInvalidInputResponse)); + ClientSum(GkvSender.DeserializeRequest(str, SendInvalidInputResponse)); return; default: SendErrorResponse(INVALID_INPUT + " 4"); @@ -100,16 +100,43 @@ namespace Host SendResponse(response); } - private void ClientSum(GkvClientSumRequest req) + private void ClientSum(GkvClientSumRequestJson req) { - if (req.Start is null || req.End is null || req.Tenant is null) + if (req.Tenant is null) SendInvalidInputResponse(); - var start = req.Start.Value; - var end = req.End.Value; - if (req.Start > req.End) SendInvalidInputResponse(); + + // Response + var response = new GkvClientSumResponseJson(); + + try + { + var service = new AccountingServiceImp(); + + var invoices = service.GetCompactGkvAbrechnungByTransferDateRange(req.Start, req.End); + + if(invoices is object && invoices.Count > 0) + { + response.CompactGkvAbrechnungen = invoices.ToArray(); + response.Success = true; + } + else + { + response.Message = "no records"; + } + } + catch (GkvException e) + { + response.Message = e.Message; + } + catch (Exception e) + { + response.Message = e.Message; + } + + SendResponse(response); } #region Senden diff --git a/Service/DCEntityMapper/CompactGkvAbrechnungDC_GkvAbrechnung.cs b/Service/DCEntityMapper/CompactGkvAbrechnungDC_GkvAbrechnung.cs new file mode 100644 index 000000000..a643c406a --- /dev/null +++ b/Service/DCEntityMapper/CompactGkvAbrechnungDC_GkvAbrechnung.cs @@ -0,0 +1,46 @@ +using BeWo.Data.Entities; +using BS.Shared.DataContracts.Compact; +using BS.Shared.Interface; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BeWo.Service.DCEntityMapper +{ + public class CompactGkvAbrechnungDC_GkvAbrechnung : AbstractIDCEntityMapper + { + public override CompactGkvAbrechnungDC MergeWithDC(GkvAbrechnung pEntity, CompactGkvAbrechnungDC pDataContract) + { + pDataContract.GkvAbrechnungOid = pEntity.Oid.Value; + pDataContract.GkvAbrechnungErstelltAm = pEntity.ErstelltAm; + pDataContract.GkvAbrechnungBetrag = pEntity.Betrag; + + if(pEntity.LastTransferProtokoll is GkvTransferProtokoll protokoll) + { + pDataContract.GkvProtokollZuletztGesendet = protokoll.ErstelltAm; + pDataContract.GkvProtokollSentDakotaSuccess = protokoll.SentDakotaSuccess; + pDataContract.GkvProtokollResultType = protokoll.ResultType; + pDataContract.GkvProtokollResultDatum = protokoll.Fehlerdatum; + + if(string.IsNullOrWhiteSpace(protokoll.Fehlertitel)) + pDataContract.GkvProtokollResultMessage = protokoll.Fehlernachricht; + else + pDataContract.GkvProtokollResultMessage = protokoll.Fehlertitel + ": " + protokoll.Fehlernachricht; + } + + return pDataContract; + } + + public override GkvAbrechnung MergeWithEntity(CompactGkvAbrechnungDC pDataContract, GkvAbrechnung pEntity) + { + throw new NotImplementedException(); + } + + protected override bool AreDCAndEntityEqual(CompactGkvAbrechnungDC pDC, GkvAbrechnung pEntity) + { + return pDC.GkvAbrechnungOid == pEntity.Oid; + } + } +} diff --git a/Service/DCEntityMapper/MapperFactory.cs b/Service/DCEntityMapper/MapperFactory.cs index 1f709c4cc..21238db1f 100644 --- a/Service/DCEntityMapper/MapperFactory.cs +++ b/Service/DCEntityMapper/MapperFactory.cs @@ -310,6 +310,8 @@ namespace BeWo.Service.DCEntityMapper private static AiSettingsDC_AiSettings _AiSettingsDC_AiSettings; + private static CompactGkvAbrechnungDC_GkvAbrechnung _CompactGkvAbrechnungDC_GkvAbrechnung; + public static MedRecordDC_MedRecord MedRecordDC_MedRecord => _MedRecordDC_MedRecord ?? (_MedRecordDC_MedRecord = new MedRecordDC_MedRecord()); @@ -778,6 +780,9 @@ namespace BeWo.Service.DCEntityMapper public static AiSettingsDC_AiSettings AiSettingsDC_AiSettings => _AiSettingsDC_AiSettings ?? (_AiSettingsDC_AiSettings = new AiSettingsDC_AiSettings()); + + public static CompactGkvAbrechnungDC_GkvAbrechnung CompactGkvAbrechnungDC_GkvAbrechnung => + _CompactGkvAbrechnungDC_GkvAbrechnung ?? (_CompactGkvAbrechnungDC_GkvAbrechnung = new CompactGkvAbrechnungDC_GkvAbrechnung()); public static BankAccountDC_BankAccount BankAccountDC_BankAccount { get; } = new BankAccountDC_BankAccount(); diff --git a/Service/Service.csproj b/Service/Service.csproj index afb041a13..dbb4aaf0d 100644 --- a/Service/Service.csproj +++ b/Service/Service.csproj @@ -227,6 +227,7 @@ + diff --git a/Service/ServiceImplementations/AccountingServiceImp.cs b/Service/ServiceImplementations/AccountingServiceImp.cs index fca11052b..c750a9e68 100644 --- a/Service/ServiceImplementations/AccountingServiceImp.cs +++ b/Service/ServiceImplementations/AccountingServiceImp.cs @@ -813,6 +813,34 @@ namespace BeWo.Service.ServiceImplementations throw Utils.CreateBeWoFaultException(e); } } + public List GetCompactGkvAbrechnungByTransferDateRange(DateTime? start, DateTime? end) + { + try + { + var entities = DAOFactory.SearchDAO.GetGkvTransferProtokollByDateRange(start, end); + + var filter = entities.Where(x => x.SentDakotaSuccess); + + var oids = filter.Select(x => x.GkvAbrechnungOid).Distinct(); + + if (!oids.Any()) + return null; + + var list = new List(); + + foreach (var oid in oids) + { + var abrechnung = DAOFactory.GenericDAO.LoadByID(oid); + list.Add(abrechnung); + } + + return MapperFactory.CompactGkvAbrechnungDC_GkvAbrechnung.MapToNewDCs(list); + } + catch (Exception e) + { + throw Utils.CreateBeWoFaultException(e); + } + } public GkvAbrechnungCreateResponseDC CreateNewGkvAbrechnung(GkvAbrechnungCreateRequestDC request) { diff --git a/Shared/BeWoEntityEnums.cs b/Shared/BeWoEntityEnums.cs index c2d05b717..bf6664b1c 100644 --- a/Shared/BeWoEntityEnums.cs +++ b/Shared/BeWoEntityEnums.cs @@ -1274,6 +1274,7 @@ namespace BS.Shared public enum GkvTransferResultType { + Waiting = -1, Success = 0, // Kein Fehler FailSoft = 1, // Kann erneut senden FailFatal = 2, // Kann nicht erneut senden diff --git a/Shared/DataContracts/Compact/CompactGkvAbrechnungDC.cs b/Shared/DataContracts/Compact/CompactGkvAbrechnungDC.cs new file mode 100644 index 000000000..736818f6d --- /dev/null +++ b/Shared/DataContracts/Compact/CompactGkvAbrechnungDC.cs @@ -0,0 +1,38 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace BS.Shared.DataContracts.Compact +{ + [DataContract] + public class CompactGkvAbrechnungDC : IDataContract + { + [JsonProperty("gkvioid")] + [DataMember] public long GkvAbrechnungOid { get; set; } + + [JsonProperty("gkvicreated")] + [DataMember] public DateTime GkvAbrechnungErstelltAm { get; set; } + + [JsonProperty("gkvisum")] + [DataMember] public decimal GkvAbrechnungBetrag { get; set; } + + [JsonProperty("sentdatetime")] + [DataMember] public DateTime? GkvProtokollZuletztGesendet { get; set; } + + [JsonProperty("sentdakotasuccess")] + [DataMember] public bool GkvProtokollSentDakotaSuccess { get; set; } + + [JsonProperty("resulttype")] + [DataMember] public GkvTransferResultType? GkvProtokollResultType { get; set; } + + [JsonProperty("resultmessage")] + [DataMember] public string GkvProtokollResultMessage { get; set; } + + [JsonProperty("resultdatetime")] + [DataMember] public DateTime? GkvProtokollResultDatum { get; set; } + } +} diff --git a/Shared/DataContracts/GkvAbrechnung/GkvClientResultRequestDC.cs b/Shared/DataContracts/GkvAbrechnung/GkvClientResultRequestDC.cs index 700b55faa..4d292d07d 100644 --- a/Shared/DataContracts/GkvAbrechnung/GkvClientResultRequestDC.cs +++ b/Shared/DataContracts/GkvAbrechnung/GkvClientResultRequestDC.cs @@ -12,6 +12,7 @@ namespace BS.Shared.DataContracts.GkvAbrechnung public GkvClientResultRequestDC() : base(RequestType.GkvClientResult) { } + [DataMember] public long UserOid { get; set; } [DataMember] public IList ResultDCs { get; set; } diff --git a/Shared/DataContracts/GkvAbrechnung/GkvClientSumRequest.cs b/Shared/DataContracts/GkvAbrechnung/GkvClientSumRequestJson.cs similarity index 52% rename from Shared/DataContracts/GkvAbrechnung/GkvClientSumRequest.cs rename to Shared/DataContracts/GkvAbrechnung/GkvClientSumRequestJson.cs index 7d5a29f00..b37a9f62c 100644 --- a/Shared/DataContracts/GkvAbrechnung/GkvClientSumRequest.cs +++ b/Shared/DataContracts/GkvAbrechnung/GkvClientSumRequestJson.cs @@ -8,17 +8,17 @@ using System.Threading.Tasks; namespace BS.Shared.DataContracts.GkvAbrechnung { - public class GkvClientSumRequest : GkvClientRequestDC + public class GkvClientSumRequestJson : GkvClientRequestDC { - public GkvClientSumRequest() : base(RequestType.GkvClientSum) + public GkvClientSumRequestJson() : base(RequestType.GkvClientSum) { } - [JsonProperty("start")] - [DataMember] public DateTime? Start { get; set; } + [JsonProperty("start")] + public DateTime? Start { get; set; } [JsonProperty("end")] - [DataMember] public DateTime? End { get; set; } + public DateTime? End { get; set; } } } diff --git a/Shared/DataContracts/GkvAbrechnung/GkvClientSumResponseJson.cs b/Shared/DataContracts/GkvAbrechnung/GkvClientSumResponseJson.cs new file mode 100644 index 000000000..84b69f2c5 --- /dev/null +++ b/Shared/DataContracts/GkvAbrechnung/GkvClientSumResponseJson.cs @@ -0,0 +1,22 @@ +using BS.Shared.DataContracts.Compact; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace BS.Shared.DataContracts.GkvAbrechnung +{ + public class GkvClientSumResponseJson : GkvResponseDC + { + public GkvClientSumResponseJson() + { + + } + + [JsonProperty("gkvinvoices")] + [DataMember] public CompactGkvAbrechnungDC[] CompactGkvAbrechnungen { get; set; } + } +} diff --git a/Shared/Shared.csproj b/Shared/Shared.csproj index fe04441f7..d4f1b8aea 100644 --- a/Shared/Shared.csproj +++ b/Shared/Shared.csproj @@ -179,9 +179,11 @@ + - + +