protected static FR_L5S_CAfS_1141 Execute(DbConnection Connection, DbTransaction Transaction, P_L5S_CAfS_1141 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_L5S_CAfS_1141();

            returnValue.Result = new L5S_CAfS_1141();

            var slot = ORM_PPS_TSK_BOK_BookableTimeSlot.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_BookableTimeSlot.Query()
            {
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false,
                PPS_TSK_BOK_BookableTimeSlotID = Parameter.SlotID
            }).Single();

            var resourceCombinations = ORM_PPS_TSK_BOK_AvailableResourceCombination.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_AvailableResourceCombination.Query()
            {
                Tenant_RefID           = securityTicket.TenantID,
                IsDeleted              = false,
                BookableTimeSlot_RefID = slot.PPS_TSK_BOK_BookableTimeSlotID,
                IsAvailable            = true
            }).ToArray();

            Dictionary <Guid, List <ORM_PPS_TSK_BOK_StaffResource> >  staffResourcePerCombination  = new Dictionary <Guid, List <ORM_PPS_TSK_BOK_StaffResource> >();
            Dictionary <Guid, List <ORM_PPS_TSK_BOK_DeviceResource> > deviceResourcePerCombination = new Dictionary <Guid, List <ORM_PPS_TSK_BOK_DeviceResource> >();

            foreach (var resourceCombination in resourceCombinations)
            {
                var staffResources = ORM_PPS_TSK_BOK_StaffResource.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_StaffResource.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    AvailableResourceCombination_RefID = resourceCombination.PPS_TSK_BOK_AvailableResourceCombinationID
                }).ToList();
                staffResourcePerCombination.Add(resourceCombination.PPS_TSK_BOK_AvailableResourceCombinationID, staffResources);

                var deviceResources = ORM_PPS_TSK_BOK_DeviceResource.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_DeviceResource.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    AvailableResourceCombination_RefID = resourceCombination.PPS_TSK_BOK_AvailableResourceCombinationID
                }).ToList();
                deviceResourcePerCombination.Add(resourceCombination.PPS_TSK_BOK_AvailableResourceCombinationID, deviceResources);
            }

            L5TE_GSAfT_1645[] allEmployeesDB = cls_Get_Staff_with_Availability_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;
            ORM_HEC_Doctor[]  hecDoctorsDB   = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            }).ToArray();
            ORM_HEC_Doctor_AssignableAppointmentType[] hecDoctor2ATDB = ORM_HEC_Doctor_AssignableAppointmentType.Query.Search(Connection, Transaction, new ORM_HEC_Doctor_AssignableAppointmentType.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            }).ToArray();
            L5TE_GTEFAS_1440[] allStaffExceptions   = cls_Get_TimeExceptionsForAllStaff.Invoke(Connection, Transaction, securityTicket).Result;
            L3P_GPfT_1537[]    professionsForTenant = cls_Get_Professions_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;

            //Parallel.Invoke(

            //    () =>
            //    {
            //        allEmployeesDB = cls_Get_Staff_with_Availability_for_TenantID.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        allStaffExceptions = cls_Get_TimeExceptionsForAllStaff.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        hecDoctorsDB = ORM_HEC_Doctor.Query.Search(Transaction.Connection.ConnectionString, new ORM_HEC_Doctor.Query() { Tenant_RefID = securityTicket.TenantID, IsDeleted = false }).ToArray();
            //    },

            //    () =>
            //    {
            //        hecDoctor2ATDB = ORM_HEC_Doctor_AssignableAppointmentType.Query.Search(Transaction.Connection.ConnectionString, new ORM_HEC_Doctor_AssignableAppointmentType.Query() { Tenant_RefID = securityTicket.TenantID, IsDeleted = false }).ToArray();
            //    },

            //    () =>
            //    {
            //        professionsForTenant = cls_Get_Professions_for_TenantID.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    }
            //);

            var usedStaffIDs = new List <Guid>();
            foreach (var staffCombo in staffResourcePerCombination)
            {
                foreach (var item in staffCombo.Value)
                {
                    if (!usedStaffIDs.Contains(item.CMN_BPT_EMP_Employee_RefID))
                    {
                        usedStaffIDs.Add(item.CMN_BPT_EMP_Employee_RefID);
                    }
                }
            }

            L5TE_GSAfT_1645[] employeesFromPracticeDB = allEmployeesDB.Where(e => usedStaffIDs.Contains(e.CMN_BPT_EMP_EmployeeID)).ToArray();
            var          staff = ModelConvertor.ConvertStaffDBData(slot.Office_RefID, employeesFromPracticeDB, hecDoctorsDB, hecDoctor2ATDB, allStaffExceptions, professionsForTenant);
            List <Staff> staffForThisAppointmentType = new List <Staff>(staff.Where(s => s.AvailableAppointmentTypeIds.Contains(slot.TaskTemplate_RefID)));
            TimeSlot     ts = new TimeSlot()
            {
                PeriodStart = slot.FreeInterval_Start, PeriodEnd = slot.FreeInterval_End
            };

            Dictionary <Guid, bool> combination2webBookable = new Dictionary <Guid, bool>();

            foreach (var staffCombo in staffResourcePerCombination)
            {
                bool isComboWebBookable = true;
                foreach (var item in staffCombo.Value)
                {
                    var employee = staffForThisAppointmentType.Single(s => s.ID == item.CMN_BPT_EMP_Employee_RefID);
                    if (!StaffAvailabiltyCalculations.IsStaffWebBookableInThisTameRange(employee, ts))
                    {
                        isComboWebBookable = false;
                        break;
                    }
                }

                combination2webBookable.Add(staffCombo.Key, isComboWebBookable);
            }

            var firstWebBookableCombID = combination2webBookable.First(f => f.Value).Key;

            var paramDevice = new List <P_L5TA_STI_1037_Device>();
            foreach (var instanceID in deviceResourcePerCombination[firstWebBookableCombID].Select(s => s.PPS_DEV_Device_Instance_RefID))
            {
                paramDevice.Add(new P_L5TA_STI_1037_Device()
                {
                    PPS_DEV_Device_Instance_RefID = instanceID
                });
            }

            var paramStaff = new List <P_L5TA_STI_1037_Employee>();
            foreach (var staffCombo in staffResourcePerCombination[firstWebBookableCombID])
            {
                paramStaff.Add(new P_L5TA_STI_1037_Employee()
                {
                    CMN_BPT_EMP_Employee_RefID = staffCombo.CMN_BPT_EMP_Employee_RefID,
                    CreatedFrom_TaskTemplate_RequiredStaff_RefID = staffCombo.CreatedFor_TaskTemplateRequiredStaff_RefID
                });
            }

            P_L5TA_STI_1037 param = new P_L5TA_STI_1037()
            {
                Patient = new P_L5TA_STI_1037_Patient()
                {
                    Patient_RefID = Parameter.Patient_RefID
                },
                Office = new P_L5TA_STI_1037_Office()
                {
                    CMN_STR_Office_RefID = slot.Office_RefID
                },
                IsWebBooking           = true,
                PlannedStartDate       = slot.FreeInterval_Start,
                PlannedDuration_in_sec = (int)(slot.FreeInterval_End - slot.FreeInterval_Start).TotalSeconds,
                TaskTemplate_RefID     = slot.TaskTemplate_RefID,
                Devices  = paramDevice.ToArray(),
                Employee = paramStaff.ToArray()
            };

            var result = cls_Save_TaskInstance.Invoke(Connection, Transaction, param, securityTicket).Result;

            var selected = resourceCombinations.First(f => f.PPS_TSK_BOK_AvailableResourceCombinationID == firstWebBookableCombID);
            selected.IsAvailable = false;
            selected.Save(Connection, Transaction);


            if (combination2webBookable.Where(f => f.Value).Count() == 1) // ako je to jedina web bookable onda promeni tip
            {
                var standardAvailabilityType = ORM_CMN_CAL_AVA_Availability_Type.Query.Search(Connection, Transaction, new ORM_CMN_CAL_AVA_Availability_Type.Query()
                {
                    GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(AvailabilityType.Standard),
                    Tenant_RefID             = securityTicket.TenantID,
                    IsDeleted = false
                }).Single();

                var slot2ATs = ORM_PPS_TSK_BOK_BookableTimeSlots_2_AvailabilityType.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_BookableTimeSlots_2_AvailabilityType.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    PPS_TSK_BOK_BookableTimeSlot_RefID = slot.PPS_TSK_BOK_BookableTimeSlotID
                }).Single();

                slot2ATs.CMN_CAL_AVA_Availability_TypeID = standardAvailabilityType.CMN_CAL_AVA_Availability_TypeID;
                slot2ATs.Save(Connection, Transaction);
            }

            returnValue.Result.ID = result.ID;

            return(returnValue);

            #endregion UserCode
        }
        protected static FR_L5S_SUSfP_1708 Execute(DbConnection Connection, DbTransaction Transaction, P_L5S_SUSfP_1708 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_L5S_SUSfP_1708();

            //ucitati sve potrebne podatke
            L5ATW_ANfTID_1855[]  appointmnetTypesDB    = null;
            L5TE_GNWTfOID_1506[] officeNonWorkingTimes = null;
            L5TE_GSHfOID_1540[]  officeStandardHours   = null;
            L5TE_GSAfT_1645[]    allEmployeesDB        = null;
            L5TE_GTEFAS_1440[]   allStaffExceptions    = null;
            L5TE_GDAfT_1844[]    devices      = null;
            ORM_HEC_Doctor[]     hecDoctorsDB = null;
            ORM_HEC_Doctor_AssignableAppointmentType[] hecDoctor2ATDB = null;
            ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability[] ppsTaskTemplate2Office = null;
            L5BTS_GBSfPID_1141[] slotsAndCombinationForPractice = null;
            L3P_GPfT_1537[]      professionsForTenant           = null;

            //Parallel.Invoke(

            //    () =>
            //    {
            //        appointmnetTypesDB = cls_Get_AppointmentTypeWeb_Name_for_TenantID.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        officeNonWorkingTimes = cls_Get_NonWorkingTimesforOfficeID.Invoke(Transaction.Connection.ConnectionString, new P_L5TE_GNWTfOID_1506() { OfficeID = Parameter.PracticeID }, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        officeStandardHours = cls_Get_StandardHours_for_OfficeID.Invoke(Transaction.Connection.ConnectionString, new P_L5TE_GSHfOID_1540() { OfficeID = Parameter.PracticeID }, securityTicket).Result;
            //    }
            //    ,

            //    () =>
            //    {
            //        allEmployeesDB = cls_Get_Staff_with_Availability_for_TenantID.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        allStaffExceptions = cls_Get_TimeExceptionsForAllStaff.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        devices = cls_Get_Devices_Availability_for_TenantID.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        hecDoctorsDB = ORM_HEC_Doctor.Query.Search(Transaction.Connection.ConnectionString, new ORM_HEC_Doctor.Query() { Tenant_RefID = securityTicket.TenantID, IsDeleted = false }).ToArray();
            //    },

            //    () =>
            //    {
            //        hecDoctor2ATDB = ORM_HEC_Doctor_AssignableAppointmentType.Query.Search(Transaction.Connection.ConnectionString, new ORM_HEC_Doctor_AssignableAppointmentType.Query() { Tenant_RefID = securityTicket.TenantID, IsDeleted = false }).ToArray();
            //    },

            //    () =>
            //    {
            //        ppsTaskTemplate2Office = ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability.Query.Search(Transaction.Connection.ConnectionString, new ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability.Query() { Tenant_RefID = securityTicket.TenantID, IsDeleted = false, CMN_STR_Office_RefID = Parameter.PracticeID }).ToArray();
            //    },

            //    () =>
            //    {
            //        slotsAndCombinationForPractice = cls_Get_BookableSlots_for_PracticeID.Invoke(Transaction.Connection.ConnectionString, new P_L5BTS_GBSfPID_1141() { OfficeID = Parameter.PracticeID, AvaTypeMatchingID = EnumUtils.GetEnumDescription(AvailabilityType.WebBooking) }, securityTicket).Result;
            //    },

            //    () =>
            //    {
            //        professionsForTenant = cls_Get_Professions_for_TenantID.Invoke(Transaction.Connection.ConnectionString, securityTicket).Result;
            //    }
            //);

            appointmnetTypesDB    = cls_Get_AllAppointmentTypes_Name_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;
            officeNonWorkingTimes = cls_Get_NonWorkingTimesforOfficeID.Invoke(Connection, Transaction, new P_L5TE_GNWTfOID_1506()
            {
                OfficeID = Parameter.PracticeID
            }, securityTicket).Result;
            officeStandardHours = cls_Get_StandardHours_for_OfficeID.Invoke(Connection, Transaction, new P_L5TE_GSHfOID_1540()
            {
                OfficeID = Parameter.PracticeID
            }, securityTicket).Result;
            allEmployeesDB     = cls_Get_Staff_with_Availability_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;
            allStaffExceptions = cls_Get_TimeExceptionsForAllStaff.Invoke(Connection, Transaction, securityTicket).Result;
            devices            = cls_Get_Devices_Availability_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;
            hecDoctorsDB       = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            }).ToArray();
            hecDoctor2ATDB = ORM_HEC_Doctor_AssignableAppointmentType.Query.Search(Connection, Transaction, new ORM_HEC_Doctor_AssignableAppointmentType.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
            }).ToArray();
            ppsTaskTemplate2Office = ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability.Query()
            {
                Tenant_RefID = securityTicket.TenantID, IsDeleted = false, CMN_STR_Office_RefID = Parameter.PracticeID
            }).ToArray();
            slotsAndCombinationForPractice = cls_Get_BookableSlots_for_PracticeID.Invoke(Connection, Transaction, new P_L5BTS_GBSfPID_1141()
            {
                OfficeID = Parameter.PracticeID
            }, securityTicket).Result;
            professionsForTenant = cls_Get_Professions_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;
            L5TE_GSAfT_1645[] employeesFromPracticeDB = allEmployeesDB.Where(e => e.Offices != null && e.Offices.FirstOrDefault(o => o.OfficeID == Parameter.PracticeID) != null).ToArray();


            //prepakuj podatke u zeljeni model
            var practice = ModelConvertor.ConvertPracticeDBData(Parameter.PracticeID, officeNonWorkingTimes, officeStandardHours, appointmnetTypesDB.Where(w => ppsTaskTemplate2Office.Select(s => s.PPS_TSK_Task_Template_RefID).Contains(w.PPS_TSK_Task_TemplateID)).ToArray());
            practice.Staff   = ModelConvertor.ConvertStaffDBData(Parameter.PracticeID, employeesFromPracticeDB, hecDoctorsDB, hecDoctor2ATDB, allStaffExceptions, professionsForTenant);
            practice.Devices = ModelConvertor.ConvertDevice(devices.Where(d => d.CMN_STR_Office_RefID == Parameter.PracticeID).ToArray());

            foreach (var appointmentType in practice.AppointmentTypes)
            {
                List <Staff> staffForThisAppointmentType = new List <Staff>(practice.Staff.Where(s => s.AvailableAppointmentTypeIds.Contains(appointmentType.ID)));

                var  persistedSlotsForAT = slotsAndCombinationForPractice.Where(w => w.TaskTemplate_RefID == appointmentType.ID).ToArray();
                bool needDevices         = appointmentType.RequiredDeviceTypes != null && appointmentType.RequiredDeviceTypes.Count > 0;

                //ucititati sve appointmente tog tipa u praksi
                var scheduledAppParam = new P_L5A_GAABDfObTfD_1915()
                {
                    FromDate       = DateTime.Now.AddDays(-1),
                    OfficeID       = Parameter.PracticeID,
                    TaskTemplateID = appointmentType.ID
                };
                var scheduledAppointmentsDB = cls_Get_AllAppointment_BaseData_for_Office_by_Type_from_Date.Invoke(Connection, Transaction, scheduledAppParam, securityTicket).Result;

                //ucitane appointmente prebaciti u zeljeni model
                var scheduledAppointments = ModelConvertor.ConvertAppointments(scheduledAppointmentsDB);

                var posibleResourceCombinations = new List <ResourceCombination>();

                //iskalkulisati sve moguce kombinacije osoblja za zelejni tip appointmenta
                var staffCombinations             = StaffAvailabiltyCalculations.GetFilteredStaffForAppointmentTypeBySkills(staffForThisAppointmentType, appointmentType);
                var weekFramesPerStaffCombination = new Dictionary <Guid, List <RangeIntersection> >();
                foreach (var comb in staffCombinations)
                {
                    weekFramesPerStaffCombination.Add(comb.ID, StaffAvailabiltyCalculations.CalculateWeekAvailableFramesForStaffCombination(comb.Data, practice.Availabilities));
                }


                //iskalkulisati sve moguce kombinacije osoblja za zelejni tip appointmenta
                if (needDevices)
                {
                    var deviceInstanceCombinations     = DeviceAvailabilityCalculations.GetFilteredDeviceForAppointmentType(practice.Devices, appointmentType);
                    var weekFramesPerDeviceCombination = new Dictionary <Guid, List <RangeIntersection> >();
                    foreach (var comb in deviceInstanceCombinations)
                    {
                        var allAbilities = comb.Data.Select(s => s.Availabilities).ToList();
                        allAbilities.Add(practice.Availabilities);
                        weekFramesPerDeviceCombination.Add(comb.ID, StaffAvailabiltyCalculations.FindAllIntersections(allAbilities));
                    }

                    foreach (var deviceCombination in weekFramesPerDeviceCombination)
                    {
                        foreach (var staffCombination in weekFramesPerStaffCombination)
                        {
                            var allIntersects = new List <List <RangeIntersection> >();
                            allIntersects.Add(staffCombination.Value);
                            allIntersects.Add(deviceCombination.Value);
                            var resourceCombinationIntersections = StaffAvailabiltyCalculations.FindAllIntersections(allIntersects);
                            if (resourceCombinationIntersections.Count > 0)
                            {
                                posibleResourceCombinations.Add(new ResourceCombination()
                                {
                                    AppointmentTypeID          = appointmentType.ID,
                                    OfficeID                   = Parameter.PracticeID,
                                    StaffCombination           = staffCombinations.Single(s => s.ID == staffCombination.Key),
                                    DeviceInstancesCombination = deviceInstanceCombinations.Single(s => s.ID == deviceCombination.Key),
                                    TimeIntersections          = resourceCombinationIntersections,
                                    IsDeviceNeeded             = true
                                });
                            }
                        }
                    }
                }
                else
                {
                    foreach (var staffCombination in weekFramesPerStaffCombination)
                    {
                        posibleResourceCombinations.Add(new ResourceCombination()
                        {
                            AppointmentTypeID = appointmentType.ID,
                            OfficeID          = Parameter.PracticeID,
                            StaffCombination  = staffCombinations.Single(s => s.ID == staffCombination.Key),
                            TimeIntersections = staffCombination.Value
                        });
                    }
                }

                //pranaci validne slotove od postojecih
                List <TimeSlot> calculatedSlots = new List <TimeSlot>();

                foreach (var combination in posibleResourceCombinations)
                {
                    //slotovi za narednih 6 meseci u odnosu na nedeljne slotove - izuzeci

                    var combinationSlots = TimeRangeUtils.CalculateTimeFramesFromRanges(combination.TimeIntersections, appointmentType.DurationInSec);
                    var exceptions       = new List <ExceptionTime>(practice.Exceptions);
                    exceptions.AddRange(combination.StaffCombination.Data.Select(select => select.Staff).SelectMany(c => c.Exceptions).ToList());
                    if (combination.IsDeviceNeeded)
                    {
                        exceptions.AddRange(combination.DeviceInstancesCombination.Data.SelectMany(s => s.Exceptions).ToList());
                    }
                    var makeSlotsForNext3Months = StaffAvailabiltyCalculations.MakeSlotsForPeriod(combinationSlots, exceptions, DateTime.Now, DateTime.Now.AddMonths(3));

                    var thisCombinationAppointments = scheduledAppointments.Where(w => w.StaffIDs.Intersect(combination.StaffCombination.Data.Select(s => s.Staff.ID)).Any()).ToList();
                    if (needDevices)
                    {
                        thisCombinationAppointments = thisCombinationAppointments.Where(w => w.DeviceInstanceIDs.Intersect(combination.DeviceInstancesCombination.Data.Select(s => s.ID)).Any()).ToList();
                    }

                    foreach (var slot in makeSlotsForNext3Months)
                    {
                        if (!TimeRangeUtils.SlotOverlapingWithAppontmentArray(slot, thisCombinationAppointments))
                        {
                            var slotMatch = calculatedSlots.FirstOrDefault(s => s.PeriodStart == slot.PeriodStart && s.PeriodEnd == slot.PeriodEnd);

                            if (!TimeRangeUtils.SlotOverlapingWithSlotArray(slot, calculatedSlots))
                            {
                                if (slotMatch == null)
                                {
                                    slot.ResourceCombination.Add(combination);
                                    calculatedSlots.Add(slot);
                                }
                                else
                                {
                                    slotMatch.ResourceCombination.Add(combination);
                                }
                            }
                            else
                            {
                                if (slotMatch != null)
                                {
                                    slotMatch.ResourceCombination.Add(combination);
                                }
                            }
                        }
                    }
                }

                var updatedSlotIDs = new List <Guid>();
                var slotParam      = new List <P_L5BTS_CSwRC_1156_Slot>();
                foreach (var slot in calculatedSlots)
                {
                    var persistedSlot = persistedSlotsForAT.FirstOrDefault(f => f.FreeInterval_Start == slot.PeriodStart && f.FreeInterval_End == slot.PeriodEnd);
                    if (persistedSlot != null) // postoji takav slot u bazi
                    {
                        updatedSlotIDs.Add(persistedSlot.PPS_TSK_BOK_BookableTimeSlotID);
                        var keepCombinationsIDs = new List <Guid>();

                        bool isSlotWebBookable = false;
                        var  combinationList   = new List <P_L5BTS_CSwRC_1156_Slot_Combination>();


                        foreach (var slotCombination in slot.ResourceCombination)
                        {
                            bool isCombinaitonWebBookable = true;

                            // da li je vidljiv za web bookovanje
                            foreach (var staff in slotCombination.StaffCombination.Data)
                            {
                                if (isCombinaitonWebBookable)
                                {
                                    if (!StaffAvailabiltyCalculations.IsStaffWebBookableInThisTameRange(staff.Staff, slot))
                                    {
                                        isCombinaitonWebBookable = false;
                                    }
                                }
                            }


                            if (!isSlotWebBookable && isCombinaitonWebBookable)
                            {
                                isSlotWebBookable = true;
                            }

                            // proveri da li vec postoji takva kobinacija u bazi
                            bool thisCombinationMatchedWithSomePersisted = false;
                            foreach (var persistedCombination in persistedSlot.Combinations)
                            {
                                if (CombinationUtils.CompareCombinations(slotCombination, persistedCombination))
                                {
                                    thisCombinationMatchedWithSomePersisted = true;
                                    keepCombinationsIDs.Add(persistedCombination.PPS_TSK_BOK_AvailableResourceCombinationID);
                                    break;
                                }
                            }


                            if (thisCombinationMatchedWithSomePersisted)                                                                                                                                  // ako postoji preskoci je
                            {
                                if ((persistedSlot.SlotType.GlobalPropertyMatchingID == EnumUtils.GetEnumDescription(AvailabilityType.WebBooking)) != isSlotWebBookable && appointmentType.IsWebBookable) // ako nije isti tip slota
                                {
                                    slotParam.Add(new P_L5BTS_CSwRC_1156_Slot()
                                    {
                                        Combinations  = combinationList.ToArray(),
                                        End           = slot.PeriodEnd,
                                        Start         = slot.PeriodStart,
                                        SlotID        = persistedSlot.PPS_TSK_BOK_BookableTimeSlotID,
                                        IsWebBookable = isSlotWebBookable && appointmentType.IsWebBookable
                                    });
                                }
                                continue;
                            }



                            var staffList          = new List <P_L5BTS_CSwRC_1156_Slot_Combination_Staff>();
                            var deviceInstanceList = new List <P_L5BTS_CSwRC_1156_Slot_Combination_DeviceInstance>();
                            foreach (var staff in slotCombination.StaffCombination.Data)
                            {
                                staffList.Add(new P_L5BTS_CSwRC_1156_Slot_Combination_Staff()
                                {
                                    CreatedFor_TaskTemplateRequiredStaff_RefID = staff.ID,
                                    StaffID = staff.Staff.ID
                                });
                                //if (isWebBookable)
                                //    if (!StaffAvailabiltyCalculations.IsStaffWebBookableInThisTameRange(staff.Staff, slot))
                                //        isWebBookable = false;
                            }
                            if (slotCombination.IsDeviceNeeded)
                            {
                                foreach (var deviceInstance in slotCombination.DeviceInstancesCombination.Data)
                                {
                                    deviceInstanceList.Add(new P_L5BTS_CSwRC_1156_Slot_Combination_DeviceInstance()
                                    {
                                        DeviceInstanceID = deviceInstance.ID
                                    });
                                }
                            }

                            combinationList.Add(new P_L5BTS_CSwRC_1156_Slot_Combination()
                            {
                                DeviceInstance = deviceInstanceList.ToArray(),
                                Staff          = staffList.ToArray()
                            });
                        }

                        if (combinationList.Count > 0 ||
                            ((persistedSlot.SlotType.GlobalPropertyMatchingID == EnumUtils.GetEnumDescription(AvailabilityType.WebBooking)) != isSlotWebBookable && appointmentType.IsWebBookable) ||
                            keepCombinationsIDs.Count != persistedSlot.Combinations.Count())
                        {
                            slotParam.Add(new P_L5BTS_CSwRC_1156_Slot()
                            {
                                Combinations         = combinationList.ToArray(),
                                End                  = slot.PeriodEnd,
                                Start                = slot.PeriodStart,
                                SlotID               = persistedSlot.PPS_TSK_BOK_BookableTimeSlotID,
                                IsWebBookable        = isSlotWebBookable && appointmentType.IsWebBookable,
                                CombinationForDelete = new P_L5BTS_CSwRC_1156_Slot_CombinationsForDelete()
                                {
                                    CombinationIDs = persistedSlot.Combinations.Select(s => s.PPS_TSK_BOK_AvailableResourceCombinationID).Except(keepCombinationsIDs).ToArray()
                                }
                            });
                        }
                    }
                    else // slot ne postoji, napravi novi
                    {
                        bool isSlotWebBookable = false;
                        var  combinationList   = new List <P_L5BTS_CSwRC_1156_Slot_Combination>();
                        foreach (var slotCombination in slot.ResourceCombination)
                        {
                            bool isCombinaitonWebBookable = true;
                            var  staffList          = new List <P_L5BTS_CSwRC_1156_Slot_Combination_Staff>();
                            var  deviceInstanceList = new List <P_L5BTS_CSwRC_1156_Slot_Combination_DeviceInstance>();
                            foreach (var staff in slotCombination.StaffCombination.Data)
                            {
                                staffList.Add(new P_L5BTS_CSwRC_1156_Slot_Combination_Staff()
                                {
                                    CreatedFor_TaskTemplateRequiredStaff_RefID = staff.ID,
                                    StaffID = staff.Staff.ID
                                });
                                if (isCombinaitonWebBookable)
                                {
                                    if (!StaffAvailabiltyCalculations.IsStaffWebBookableInThisTameRange(staff.Staff, slot))
                                    {
                                        isCombinaitonWebBookable = false;
                                    }
                                }
                            }
                            if (slotCombination.IsDeviceNeeded)
                            {
                                foreach (var deviceInstance in slotCombination.DeviceInstancesCombination.Data)
                                {
                                    deviceInstanceList.Add(new P_L5BTS_CSwRC_1156_Slot_Combination_DeviceInstance()
                                    {
                                        DeviceInstanceID = deviceInstance.ID
                                    });
                                }
                            }

                            combinationList.Add(new P_L5BTS_CSwRC_1156_Slot_Combination()
                            {
                                DeviceInstance = deviceInstanceList.ToArray(),
                                Staff          = staffList.ToArray()
                            });

                            if (!isSlotWebBookable && isCombinaitonWebBookable)
                            {
                                isSlotWebBookable = true;
                            }
                        }

                        slotParam.Add(new P_L5BTS_CSwRC_1156_Slot()
                        {
                            Combinations  = combinationList.ToArray(),
                            End           = slot.PeriodEnd,
                            Start         = slot.PeriodStart,
                            SlotID        = Guid.NewGuid(),
                            IsWebBookable = isSlotWebBookable && appointmentType.IsWebBookable
                        });
                    }
                }

                var createSlotBulkParam = new P_L5BTS_CSwRC_1156()
                {
                    AppointmentTypeID = appointmentType.ID,
                    OfficeID          = Parameter.PracticeID,
                    Slots             = slotParam.ToArray()
                };

                var persistedSlotForDeleteIDs = persistedSlotsForAT.Where(s => !updatedSlotIDs.Contains(s.PPS_TSK_BOK_BookableTimeSlotID)).Select(s => s.PPS_TSK_BOK_BookableTimeSlotID).ToArray();
                cls_Delete_Slots.Invoke(Connection, Transaction, new P_L5BTS_DS_1510()
                {
                    SlotIDs = persistedSlotForDeleteIDs
                }, securityTicket);
                cls_Create_Slots_with_ResourceCombinations.Invoke(Connection, Transaction, createSlotBulkParam, securityTicket);
            }

            return(returnValue);

            #endregion UserCode
        }
Beispiel #3
0
        protected static FR_L5BTS_STI_1331 Execute(DbConnection Connection, DbTransaction Transaction, P_L5BTS_STI_1331 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_L5BTS_STI_1331()
            {
                Result = new L5BTS_STI_1331()
            };

            //Put your code here
            #region Save

            var webAvailabilityType = ORM_CMN_CAL_AVA_Availability_Type.Query.Search(Connection, Transaction, new ORM_CMN_CAL_AVA_Availability_Type.Query
            {
                IsDeleted                = false,
                Tenant_RefID             = securityTicket.TenantID,
                GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(AvailabilityType.WebBooking)
            }).First();


            var standardAvailabilityType = ORM_CMN_CAL_AVA_Availability_Type.Query.Search(Connection, Transaction, new ORM_CMN_CAL_AVA_Availability_Type.Query
            {
                IsDeleted                = false,
                Tenant_RefID             = securityTicket.TenantID,
                GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(AvailabilityType.Standard)
            }).First();

            if (Parameter.PPS_TSK_TaskID == Guid.Empty)
            {
                //=====================New Task=====================
                ORM_PPS_TSK_Task task = new ORM_PPS_TSK_Task();
                task.PPS_TSK_TaskID = Guid.NewGuid();
                var newTaskIdentifierNumber = ORM_PPS_TSK_Task.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task.Query
                {
                    Tenant_RefID = securityTicket.TenantID
                }).Count;

                task.TaskIdentifier = (++newTaskIdentifierNumber).ToString();
                task.DisplayName    = "AT" + task.TaskIdentifier;
                task.InstantiatedFrom_TaskTemplate_RefID = Parameter.TaskTemplate_RefID;
                task.PlannedStartDate       = Parameter.PlannedStartDate;
                task.PlannedDuration_in_sec = Parameter.PlannedDuration_in_sec;
                task.IsDeleted    = false;
                task.Tenant_RefID = securityTicket.TenantID;
                //=====================Selected availability types=====================

                ORM_PPRS_TSK_Task_SelectedAvailabilityType selectedTypes = new ORM_PPRS_TSK_Task_SelectedAvailabilityType();
                selectedTypes.PPRS_TSK_Task_SelectedAvailabilityTypeID = Guid.NewGuid();
                selectedTypes.PPS_TSK_Task_RefID = task.PPS_TSK_TaskID;
                selectedTypes.CMN_CAL_AVA_Availability_Type_RefID = Parameter.IsWebBooking ? webAvailabilityType.CMN_CAL_AVA_Availability_TypeID : standardAvailabilityType.CMN_CAL_AVA_Availability_TypeID;
                selectedTypes.IsDeleted    = false;
                selectedTypes.Tenant_RefID = securityTicket.TenantID;
                selectedTypes.Save(Connection, Transaction);
                //=====================New Employee=====================
                if (Parameter.Employee != null && Parameter.Employee.Count() > 0)
                {
                    foreach (var employeeParam in Parameter.Employee)
                    {
                        ORM_PPS_TSK_Task_StaffBooking staff = new ORM_PPS_TSK_Task_StaffBooking();
                        staff.PPS_TSK_Task_StaffBookingsID = Guid.NewGuid();
                        staff.PPS_TSK_Task_RefID           = task.PPS_TSK_TaskID;
                        staff.CMN_BPT_EMP_Employee_RefID   = employeeParam.CMN_BPT_EMP_Employee_RefID;
                        staff.CreatedFrom_TaskTemplate_RequiredStaff_RefID = employeeParam.CreatedFrom_TaskTemplate_RequiredStaff_RefID;
                        staff.IsDeleted    = false;
                        staff.Tenant_RefID = securityTicket.TenantID;
                        staff.Save(Connection, Transaction);
                    }
                }
                //=====================New Device=====================
                if (Parameter.Devices != null && Parameter.Devices.Count() > 0)
                {
                    foreach (var deviceParam in Parameter.Devices)
                    {
                        ORM_PPS_TSK_Task_DeviceBooking device = new ORM_PPS_TSK_Task_DeviceBooking();
                        device.PPS_TSK_Task_DeviceBookingID  = Guid.NewGuid();
                        device.PPS_TSK_Task_RefID            = task.PPS_TSK_TaskID;
                        device.PPS_DEV_Device_Instance_RefID = deviceParam.PPS_DEV_Device_Instance_RefID;
                        device.IsDeleted    = false;
                        device.Tenant_RefID = securityTicket.TenantID;
                        device.Save(Connection, Transaction);
                    }
                }
                //=====================New Office=====================
                if (Parameter.Office != null)
                {
                    ORM_PPS_TSK_Task_OfficeBooking office = new ORM_PPS_TSK_Task_OfficeBooking();
                    office.PPS_TSK_Task_OfficeBookingID = Guid.NewGuid();
                    office.PPS_TSK_Task_RefID           = task.PPS_TSK_TaskID;
                    office.CMN_STR_Office_RefID         = Parameter.Office.CMN_STR_Office_RefID;
                    office.IsDeleted    = false;
                    office.Tenant_RefID = securityTicket.TenantID;
                    office.Save(Connection, Transaction);
                }
                //=====================New Patient=====================
                if (Parameter.Patient != null)
                {
                    ORM_HEC_APP_Appointment appointmnet = new ORM_HEC_APP_Appointment();
                    appointmnet.HEC_APP_AppointmentID  = Guid.NewGuid();
                    appointmnet.Ext_PPS_TSK_Task_RefID = task.PPS_TSK_TaskID;
                    appointmnet.IsDeleted    = false;
                    appointmnet.Tenant_RefID = securityTicket.TenantID;
                    appointmnet.Save(Connection, Transaction);

                    ORM_HEC_ACT_PlannedAction plannedAppointment = new ORM_HEC_ACT_PlannedAction();
                    plannedAppointment.HEC_ACT_PlannedActionID = Guid.NewGuid();
                    plannedAppointment.Appointment_RefID       = appointmnet.HEC_APP_AppointmentID;
                    plannedAppointment.Patient_RefID           = Parameter.Patient.Patient_RefID;
                    plannedAppointment.IsDeleted    = false;
                    plannedAppointment.Tenant_RefID = securityTicket.TenantID;
                    plannedAppointment.Save(Connection, Transaction);
                }
                task.Save(Connection, Transaction);
                returnValue.Result.ID = task.PPS_TSK_TaskID;
            }
            #endregion
            //=====================Edit or Delete=====================
            else
            {
                var task = ORM_PPS_TSK_Task.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task.Query
                {
                    PPS_TSK_TaskID = Parameter.PPS_TSK_TaskID,
                    IsDeleted      = false,
                    Tenant_RefID   = securityTicket.TenantID
                }).Single();
                #region Edit
                if (Parameter.IsDeleted == false)
                {
                    if (task.InstantiatedFrom_TaskTemplate_RefID != Parameter.TaskTemplate_RefID) //changed task template
                    {
                        //=====================First delete old employee and device=====================
                        var employeeForDelete = ORM_PPS_TSK_Task_StaffBooking.Query.SoftDelete(Connection, Transaction, new ORM_PPS_TSK_Task_StaffBooking.Query
                        {
                            PPS_TSK_Task_RefID = Parameter.PPS_TSK_TaskID,
                            IsDeleted          = false,
                            Tenant_RefID       = securityTicket.TenantID
                        });
                        var deviceForDelete = ORM_PPS_TSK_Task_DeviceBooking.Query.SoftDelete(Connection, Transaction, new ORM_PPS_TSK_Task_DeviceBooking.Query
                        {
                            PPS_TSK_Task_RefID = Parameter.PPS_TSK_TaskID,
                            IsDeleted          = false,
                            Tenant_RefID       = securityTicket.TenantID
                        });
                        task.InstantiatedFrom_TaskTemplate_RefID = Parameter.TaskTemplate_RefID;
                        task.PlannedDuration_in_sec = Parameter.PlannedDuration_in_sec;

                        //=====================New Employee=====================
                        if (Parameter.Employee != null && Parameter.Employee.Count() > 0)
                        {
                            foreach (var employeeParam in Parameter.Employee)
                            {
                                ORM_PPS_TSK_Task_StaffBooking staff = new ORM_PPS_TSK_Task_StaffBooking();
                                staff.PPS_TSK_Task_StaffBookingsID = Guid.NewGuid();
                                staff.PPS_TSK_Task_RefID           = task.PPS_TSK_TaskID;
                                staff.CMN_BPT_EMP_Employee_RefID   = employeeParam.CMN_BPT_EMP_Employee_RefID;
                                staff.CreatedFrom_TaskTemplate_RequiredStaff_RefID = employeeParam.CreatedFrom_TaskTemplate_RequiredStaff_RefID;
                                staff.IsDeleted    = false;
                                staff.Tenant_RefID = securityTicket.TenantID;
                                staff.Save(Connection, Transaction);
                            }
                        }
                        //=====================New Device=====================
                        if (Parameter.Devices != null && Parameter.Devices.Count() > 0)
                        {
                            foreach (var deviceParam in Parameter.Devices)
                            {
                                ORM_PPS_TSK_Task_DeviceBooking device = new ORM_PPS_TSK_Task_DeviceBooking();
                                device.PPS_TSK_Task_DeviceBookingID  = Guid.NewGuid();
                                device.PPS_TSK_Task_RefID            = task.PPS_TSK_TaskID;
                                device.PPS_DEV_Device_Instance_RefID = deviceParam.PPS_DEV_Device_Instance_RefID;
                                device.IsDeleted    = false;
                                device.Tenant_RefID = securityTicket.TenantID;
                                device.Save(Connection, Transaction);
                            }
                        }
                    }
                    else //only change existing employee and device
                    {
                        //=====================Edit employee=====================
                        if (Parameter.Employee != null)
                        {
                            foreach (var employeeParam in Parameter.Employee)
                            {
                                var existingEmployee = ORM_PPS_TSK_Task_StaffBooking.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_StaffBooking.Query
                                {
                                    PPS_TSK_Task_StaffBookingsID = employeeParam.PPS_TSK_Task_StaffBookingsID,
                                    IsDeleted    = false,
                                    Tenant_RefID = securityTicket.TenantID
                                }).SingleOrDefault();

                                if (existingEmployee == null) //if employee dont exist (if deleted from other page), create new
                                {
                                    ORM_PPS_TSK_Task_StaffBooking staff = new ORM_PPS_TSK_Task_StaffBooking();
                                    staff.PPS_TSK_Task_StaffBookingsID = Guid.NewGuid();
                                    staff.PPS_TSK_Task_RefID           = task.PPS_TSK_TaskID;
                                    staff.CMN_BPT_EMP_Employee_RefID   = employeeParam.CMN_BPT_EMP_Employee_RefID;
                                    staff.CreatedFrom_TaskTemplate_RequiredStaff_RefID = employeeParam.CreatedFrom_TaskTemplate_RequiredStaff_RefID;
                                    staff.IsDeleted    = false;
                                    staff.Tenant_RefID = securityTicket.TenantID;
                                    staff.Save(Connection, Transaction);
                                }
                                else
                                {
                                    existingEmployee.CMN_BPT_EMP_Employee_RefID = employeeParam.CMN_BPT_EMP_Employee_RefID;
                                    existingEmployee.CreatedFrom_TaskTemplate_RequiredStaff_RefID = employeeParam.CreatedFrom_TaskTemplate_RequiredStaff_RefID;
                                    existingEmployee.Tenant_RefID = securityTicket.TenantID;
                                    existingEmployee.Save(Connection, Transaction);
                                }
                            }
                        }
                        //=====================Edit device=====================
                        if (Parameter.Devices != null)
                        {
                            foreach (var deviceParam in Parameter.Devices)
                            {
                                var existingDevice = ORM_PPS_TSK_Task_DeviceBooking.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_DeviceBooking.Query
                                {
                                    PPS_TSK_Task_DeviceBookingID = deviceParam.PPS_TSK_Task_DeviceBookingID,
                                    IsDeleted    = false,
                                    Tenant_RefID = securityTicket.TenantID
                                }).SingleOrDefault();
                                if (existingDevice == null)
                                {
                                    ORM_PPS_TSK_Task_DeviceBooking device = new ORM_PPS_TSK_Task_DeviceBooking();
                                    device.PPS_TSK_Task_DeviceBookingID  = Guid.NewGuid();
                                    device.PPS_TSK_Task_RefID            = task.PPS_TSK_TaskID;
                                    device.PPS_DEV_Device_Instance_RefID = deviceParam.PPS_DEV_Device_Instance_RefID;
                                    device.IsDeleted    = false;
                                    device.Tenant_RefID = securityTicket.TenantID;
                                    device.Save(Connection, Transaction);
                                }
                                else
                                {
                                    existingDevice.PPS_DEV_Device_Instance_RefID = deviceParam.PPS_DEV_Device_Instance_RefID;
                                    existingDevice.Tenant_RefID = securityTicket.TenantID;
                                    existingDevice.Save(Connection, Transaction);
                                }
                            }
                        }
                    }
                    //=====================Edit other data=====================
                    task.PlannedStartDate = Parameter.PlannedStartDate;

                    //=====================Edit selected availability types=====================
                    var existingAvailabilityType = ORM_PPRS_TSK_Task_SelectedAvailabilityType.Query.Search(Connection, Transaction, new ORM_PPRS_TSK_Task_SelectedAvailabilityType.Query
                    {
                        IsDeleted          = false,
                        Tenant_RefID       = securityTicket.TenantID,
                        PPS_TSK_Task_RefID = task.PPS_TSK_TaskID
                    }).Single();

                    existingAvailabilityType.CMN_CAL_AVA_Availability_Type_RefID = Parameter.IsWebBooking ? webAvailabilityType.CMN_CAL_AVA_Availability_TypeID : standardAvailabilityType.CMN_CAL_AVA_Availability_TypeID;
                    existingAvailabilityType.Save(Connection, Transaction);

                    //=====================Edit Office=====================
                    if (Parameter.Office != null)
                    {
                        var existingOffice = ORM_PPS_TSK_Task_OfficeBooking.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_OfficeBooking.Query
                        {
                            PPS_TSK_Task_OfficeBookingID = Parameter.Office.PPS_TSK_Task_OfficeBookingID,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        }).Single();
                        existingOffice.CMN_STR_Office_RefID = Parameter.Office.CMN_STR_Office_RefID;
                        existingOffice.Tenant_RefID         = securityTicket.TenantID;
                        existingOffice.Save(Connection, Transaction);
                    }
                    //=====================Edit Patient=====================
                    //when inter tenant communication is implemented, this part should be changed.
                    if (Parameter.Patient != null && Parameter.Patient.Patient_RefID != Guid.Empty)
                    {
                        var appointmentForEdit = ORM_HEC_APP_Appointment.Query.Search(Connection, Transaction, new ORM_HEC_APP_Appointment.Query
                        {
                            Ext_PPS_TSK_Task_RefID = task.PPS_TSK_TaskID,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        }).Single();

                        var patientPlannedAppointmentForEdit = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                        {
                            Appointment_RefID = appointmentForEdit.HEC_APP_AppointmentID,
                            Tenant_RefID      = securityTicket.TenantID,
                            IsDeleted         = false
                        }).Single();

                        returnValue.Result.ReplacedPatient = new L5TA_STI_1037_ReplacedPatient()
                        {
                            ID = patientPlannedAppointmentForEdit.Patient_RefID
                        };

                        patientPlannedAppointmentForEdit.Patient_RefID = Parameter.Patient.Patient_RefID;
                        patientPlannedAppointmentForEdit.Save(Connection, Transaction);
                    }
                }
                #endregion
                #region Delete
                else
                {
                    //=====================Delete employee=====================
                    var employeeForDelete = ORM_PPS_TSK_Task_StaffBooking.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_StaffBooking.Query
                    {
                        PPS_TSK_Task_RefID = Parameter.PPS_TSK_TaskID,
                        IsDeleted          = false,
                        Tenant_RefID       = securityTicket.TenantID
                    }).ToArray();
                    foreach (var empForDel in employeeForDelete)
                    {
                        empForDel.IsDeleted = true;
                        empForDel.Save(Connection, Transaction);
                    }
                    //=====================Delete devices=====================
                    var deviceForDelete = ORM_PPS_TSK_Task_DeviceBooking.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_DeviceBooking.Query
                    {
                        PPS_TSK_Task_RefID = Parameter.PPS_TSK_TaskID,
                        IsDeleted          = false,
                        Tenant_RefID       = securityTicket.TenantID
                    }).ToArray();
                    foreach (var devForDel in deviceForDelete)
                    {
                        devForDel.IsDeleted = true;
                        devForDel.Save(Connection, Transaction);
                    }

                    //=====================Delete office=====================
                    var officeForDelete = ORM_PPS_TSK_Task_OfficeBooking.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_OfficeBooking.Query
                    {
                        PPS_TSK_Task_RefID = Parameter.PPS_TSK_TaskID,
                        IsDeleted          = false,
                        Tenant_RefID       = securityTicket.TenantID
                    }).Single();

                    //=====================Delete patient=====================
                    var appointmentForDelete = ORM_HEC_APP_Appointment.Query.Search(Connection, Transaction, new ORM_HEC_APP_Appointment.Query
                    {
                        Ext_PPS_TSK_Task_RefID = task.PPS_TSK_TaskID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).Single();

                    var plannedAction = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                    {
                        Tenant_RefID      = securityTicket.TenantID,
                        Appointment_RefID = appointmentForDelete.HEC_APP_AppointmentID,
                    }).Single();

                    var patientPlannedAppointmentToDelete = ORM_HEC_ACT_PlannedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PlannedAction.Query()
                    {
                        Appointment_RefID = appointmentForDelete.HEC_APP_AppointmentID,
                        Patient_RefID     = plannedAction.Patient_RefID,
                        Tenant_RefID      = securityTicket.TenantID,
                        IsDeleted         = false
                    }).Single();

                    patientPlannedAppointmentToDelete.IsDeleted = true;
                    patientPlannedAppointmentToDelete.Save(Connection, Transaction);

                    appointmentForDelete.IsDeleted = true;
                    appointmentForDelete.Save(Connection, Transaction);

                    task.IsDeleted = true;

                    var firstBookedEmp = employeeForDelete;


                    var slot = ORM_PPS_TSK_BOK_BookableTimeSlot.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_BookableTimeSlot.Query()
                    {
                        Tenant_RefID       = securityTicket.TenantID,
                        FreeInterval_Start = task.PlannedStartDate,
                        TaskTemplate_RefID = task.InstantiatedFrom_TaskTemplate_RefID,
                        Office_RefID       = officeForDelete.CMN_STR_Office_RefID,
                        IsDeleted          = false
                    }).Single();

                    var allCombs = cls_Get_Slot_NotAvaCombiantions_for_SlotID.Invoke(Connection, Transaction, new P_L5BTS_GSNACfSID_1456()
                    {
                        SlotID = slot.PPS_TSK_BOK_BookableTimeSlotID
                    }, securityTicket).Result;

                    L5BTS_GSNACfSID_1456 selecetedComb = null;
                    foreach (var comb in allCombs)
                    {
                        if (!comb.Devices.Select(s => s.PPS_DEV_Device_Instance_RefID).Except(deviceForDelete.Select(s => s.PPS_DEV_Device_Instance_RefID)).Any()
                            &&
                            !comb.Staff.Select(s => s.CMN_BPT_EMP_Employee_RefID).Except(employeeForDelete.Select(s => s.CMN_BPT_EMP_Employee_RefID)).Any())
                        {
                            selecetedComb = comb;
                        }
                    }

                    if (selecetedComb != null)
                    {
                        var comb = ORM_PPS_TSK_BOK_AvailableResourceCombination.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_AvailableResourceCombination.Query()
                        {
                            Tenant_RefID = securityTicket.TenantID,
                            PPS_TSK_BOK_AvailableResourceCombinationID = selecetedComb.PPS_TSK_BOK_AvailableResourceCombinationID,
                        }).Single();

                        if (!comb.IsDeleted)
                        {
                            comb.IsAvailable = true;
                            comb.Save(Connection, Transaction);


                            L5TE_GSAfT_1645[] allEmployeesDB = cls_Get_Staff_with_Availability_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;
                            ORM_HEC_Doctor[]  hecDoctorsDB   = ORM_HEC_Doctor.Query.Search(Connection, Transaction, new ORM_HEC_Doctor.Query()
                            {
                                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
                            }).ToArray();
                            ORM_HEC_Doctor_AssignableAppointmentType[] hecDoctor2ATDB = ORM_HEC_Doctor_AssignableAppointmentType.Query.Search(Connection, Transaction, new ORM_HEC_Doctor_AssignableAppointmentType.Query()
                            {
                                Tenant_RefID = securityTicket.TenantID, IsDeleted = false
                            }).ToArray();
                            L5TE_GTEFAS_1440[] allStaffExceptions      = cls_Get_TimeExceptionsForAllStaff.Invoke(Connection, Transaction, securityTicket).Result;
                            L3P_GPfT_1537[]    professionsForTenant    = cls_Get_Professions_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;
                            L5TE_GSAfT_1645[]  employeesFromPracticeDB = allEmployeesDB.Where(e => employeeForDelete.Select(s => s.CMN_BPT_EMP_Employee_RefID).Contains(e.CMN_BPT_EMP_EmployeeID)).ToArray();
                            var staff = ModelConvertor.ConvertStaffDBData(officeForDelete.CMN_STR_Office_RefID, employeesFromPracticeDB, hecDoctorsDB, hecDoctor2ATDB, allStaffExceptions, professionsForTenant);

                            TimeSlot ts = new TimeSlot()
                            {
                                PeriodStart = slot.FreeInterval_Start, PeriodEnd = slot.FreeInterval_End
                            };
                            bool isComboWebBookable = true;
                            foreach (var item in selecetedComb.Staff)
                            {
                                var employee = staff.Single(s => s.ID == item.CMN_BPT_EMP_Employee_RefID);
                                if (!StaffAvailabiltyCalculations.IsStaffWebBookableInThisTameRange(employee, ts))
                                {
                                    isComboWebBookable = false;
                                    break;
                                }
                            }

                            if (isComboWebBookable)
                            {
                                var slot2ATs = ORM_PPS_TSK_BOK_BookableTimeSlots_2_AvailabilityType.Query.Search(Connection, Transaction, new ORM_PPS_TSK_BOK_BookableTimeSlots_2_AvailabilityType.Query()
                                {
                                    Tenant_RefID = securityTicket.TenantID,
                                    IsDeleted    = false,
                                    PPS_TSK_BOK_BookableTimeSlot_RefID = slot.PPS_TSK_BOK_BookableTimeSlotID
                                }).Single();

                                if (slot2ATs.CMN_CAL_AVA_Availability_TypeID != webAvailabilityType.CMN_CAL_AVA_Availability_TypeID)
                                {
                                    slot2ATs.CMN_CAL_AVA_Availability_TypeID = webAvailabilityType.CMN_CAL_AVA_Availability_TypeID;
                                    slot2ATs.Save(Connection, Transaction);
                                }
                            }
                        }
                    }

                    officeForDelete.IsDeleted = true;
                    officeForDelete.Save(Connection, Transaction);
                }
                #endregion
                task.Save(Connection, Transaction);
                returnValue.Result.ID = task.PPS_TSK_TaskID;
            }

            return(returnValue);

            #endregion UserCode
        }