/// <summary>
 /// Add a new matter
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="matter">Matter details</param>
 /// <returns></returns>
 public MatterReturnValue AddMatter(HostSecurityToken oHostSecurityToken, Matter matter)
 {
     MatterReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oMatterService = new MatterService();
         returnValue = oMatterService.AddMatter(Functions.GetLogonIdFromToken(oHostSecurityToken), matter);
     }
     else
     {
         returnValue = new MatterReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
        /// <summary>
        /// Add a new matter
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="matter">Matter details</param>
        /// <returns></returns>
        public MatterReturnValue AddMatter(Guid logonId, Matter matter)
        {
            MatterReturnValue returnValue = new MatterReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    // Ensure we have permission
                    if (!UserSecuritySettings.GetUserSecuitySettings(182))
                        throw new Exception("You do not have sufficient permissions to carry out this request");

                    // Verify Annual Licence
                    if (!IRIS.Law.PmsBusiness.LicenseDetails.AnnualLicenseIsValid())
                    {
                        throw new Exception("Unable to add Matter. Your Annual Licence has expired or is invalid.");
                    }

                    SrvMatter srvMatter = new SrvMatter();

                    srvMatter.ClientId = matter.ClientId;
                    srvMatter.MatterDescription = matter.Description;
                    srvMatter.MatterPartnerMemberId = matter.PartnerMemberId;
                    srvMatter.FeeEarnerMemberId = matter.FeeEarnerMemberId;
                    srvMatter.WorkCategoryFranchised = matter.Franchised;
                    //Call SetDefaultsOnFeeEarnerMemberId in order to set the userId
                    srvMatter.SetDefaultsOnFeeEarnerMemberId();
                    srvMatter.UFNNumber = matter.UFN;
                    srvMatter.UFNDate = matter.UFNDate;
                    srvMatter.IsPublicFunding = matter.IsPublicFunding;
                    srvMatter.ClientBankId = matter.ClientBankId;
                    srvMatter.OfficeBankId = matter.OfficeBankId;
                    srvMatter.ChargeDescriptionId = matter.ChargeDescriptionId;
                    srvMatter.CurrentWorkTypeId = matter.WorkTypeId;
                    srvMatter.DepartmentId = matter.DepartmentId;
                    srvMatter.BranchId = matter.BranchReference;
                    srvMatter.CourtId = matter.CourtId;
                    srvMatter.MatterTypeId = matter.MatterTypeId;
                    srvMatter.ClientHOUCN = matter.HOUCN;
                    srvMatter.EarnerReference = matter.FeeEarnerReference;
                    srvMatter.ConOrgMemIdCollection = new NameValueCollection();
                    foreach (JointClientCandidateSearchItem client in matter.JointClientCandidates.Rows)
                    {
                        srvMatter.ConOrgMemIdCollection.Add(client.OrganisationId, client.MemberId);
                    }

                    string errorMessage;

                    returnValue.Success = srvMatter.Save(out errorMessage);
                    returnValue.Message = errorMessage;

                    matter.Id = srvMatter.ProjectId;
                    returnValue.Matter = matter;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Message = ex.Message;
            }

            return returnValue;
        }
        /// <summary>
        /// Get one matter
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="projectId">Matter project id</param>
        /// <returns></returns>
        public MatterReturnValue GetMatter(Guid logonId, Guid projectId)
        {
            MatterReturnValue returnValue = new MatterReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                // ApplicationSettings.Instance can now be used to get the
                // ApplicationSettings for this session.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            if (!SrvMatterCommon.WebAllowedToAccessMatter(projectId))
                                throw new Exception("Access denied");
                            break;
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvMatter srvMatter = new SrvMatter();
                    int campaignId = SrvMatterCommon.GetCampaignForProject(projectId);

                    srvMatter.Load(projectId);

                    Matter matter = new Matter();
                    matter.Id = srvMatter.ProjectId;

                    // Load Matter Details
                    matter.Description = srvMatter.MatterDescription;
                    matter.KeyDescription = srvMatter.MatterKeyDescription;
                    matter.FeeEarnerMemberId = srvMatter.FeeEarnerMemberId;
                    matter.PartnerMemberId = srvMatter.MatterPartnerMemberId;
                    matter.WorkTypeId = srvMatter.CurrentWorkTypeId;
                    matter.ClientBankId = srvMatter.ClientBankId;
                    matter.OfficeBankId = srvMatter.OfficeBankId;
                    matter.DepositBankId = srvMatter.MatterDepositBankId;
                    matter.BranchReference = srvMatter.BranchId;
                    matter.DepartmentId = srvMatter.DepartmentId;
                    matter.ChargeDescriptionId = srvMatter.ChargeDescriptionId;
                    matter.CourtId = srvMatter.CourtId;
                    matter.OpenDate = srvMatter.MatterOpenDate;
                    matter.NextReviewDate = srvMatter.MatterNextReviewDate;
                    matter.CostReviewDate = srvMatter.MatterCostReviewDate;
                    matter.LastSavedDate = srvMatter.MatterLastSaved;
                    matter.ClosedDate = srvMatter.MatterClosedDate;
                    matter.DestructDate = srvMatter.MatterDestructDate;
                    matter.FileNo = srvMatter.MatterFileNo;
                    matter.CompletedDate = srvMatter.MatterCompleted;
                    matter.SpanType1Ref = srvMatter.SpanType1;
                    matter.SpanType2Ref = srvMatter.SpanType2;

                    // Load Matter Additional Info
                    matter.Quote = srvMatter.MatterQuote;
                    matter.DisbsLimit = srvMatter.MatterDisbsLimit;
                    matter.TimeLimit = srvMatter.MatterTimeLimit;
                    matter.WIPLimit = srvMatter.MatterWIPLimit;
                    matter.OverallLimit = srvMatter.MatterOverallLimit;
                    matter.Status = srvMatter.MatterStatus;
                    matter.Indicators = srvMatter.MatterIndicators;
                    matter.BankReference = srvMatter.MatterBankReference;
                    matter.CashCollectionId = srvMatter.MatCashCollID;
                    matter.TotalLockup = srvMatter.MatTotalLockup;
                    matter.OurReference = srvMatter.OurReference;
                    matter.PreviousReference = srvMatter.PreviousReference;
                    matter.BusinessSourceId = srvMatter.SourceID;
                    matter.SourceCampaignId = campaignId;
                    matter.PersonDealingId = srvMatter.UserId;
                    matter.SalutationEnvelope = srvMatter.MatterSalutationEnvelope;
                    matter.SalutationLetter = srvMatter.MatterSalutationLetter;
                    matter.LetterHead = srvMatter.MatterLetterHead;

                    // Load Public Funding
                    matter.MatterLegalAided = srvMatter.MatterLegalAided;
                    matter.IsPublicFunding = srvMatter.IsPublicFunding;
                    matter.Franchised = srvMatter.MatterFranchised;
                    matter.isLondonRate = srvMatter.MatterLondonRate;
                    matter.UFNDate = srvMatter.UFNDate;
                    matter.UFN = srvMatter.UFNNumber;
                    matter.PFCertificateNo = srvMatter.MatterPFCertificateNo;
                    matter.PFCertificateNoLimits = srvMatter.MatterPFCertificateLimits;
                    matter.MatterTypeId = srvMatter.MatterTypeId;

                    // Load Client Details
                    Client client = new Client();
                    client.IsMember = srvMatter.IsMember;

                    //Set MemberID for Individual
                    if (client.IsMember)
                    {
                        client.MemberId = srvMatter.ClientId;
                        client.OrganisationId = DataConstants.DummyGuid;
                    }
                    //Set OrganisationId for Organisation
                    else
                    {
                        client.MemberId = DataConstants.DummyGuid;
                        client.OrganisationId = srvMatter.ClientId;
                    }

                    client.Reference = srvMatter.ClientReference;
                    client.FullName = srvMatter.ClientName;
                    client.IsArchived = srvMatter.IsClientArchived;

                    // Get Client Type ID
                    client.TypeId = this.GetClientType(srvMatter.ClientId, srvMatter.ProjectId, srvMatter.IsMember);

                    returnValue.Matter = matter;
                    returnValue.ClientDetails = client;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Message = ex.Message;
            }

            return returnValue;
        }
        /// <summary>
        /// Update an existing matter
        /// </summary>
        /// <param name="logonId">Logon id obtained when logging on to the logon service</param>
        /// <param name="matter">Matter details</param>
        /// <returns></returns>
        public ReturnValue UpdateMatter(Guid logonId, Matter matter)
        {
            ReturnValue returnValue = new ReturnValue();

            try
            {
                // Get the logged on user from the current logons and add their
                // ApplicationSettings the list of concurrent sessions.
                Host.LoadLoggedOnUser(logonId);

                try
                {
                    Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid);
                    switch (UserInformation.Instance.UserType)
                    {
                        case DataConstants.UserType.Staff:
                            // Can do everything
                            break;
                        case DataConstants.UserType.Client:
                        case DataConstants.UserType.ThirdParty:
                            throw new Exception("Access denied");
                        default:
                            throw new Exception("Access denied");
                    }

                    SrvMatter srvMatter = new SrvMatter();
                    srvMatter.Load(matter.Id);

                    // Save Matter Details
                    srvMatter.ProjectId = matter.Id;
                    srvMatter.MatterDescription = matter.Description;
                    srvMatter.MatterKeyDescription = matter.KeyDescription;
                    srvMatter.FeeEarnerMemberId = matter.FeeEarnerMemberId;
                    srvMatter.MatterPartnerMemberId = matter.PartnerMemberId;
                    srvMatter.CurrentWorkTypeId = matter.WorkTypeId;
                    srvMatter.ClientBankId = matter.ClientBankId;
                    srvMatter.OfficeBankId = matter.OfficeBankId;
                    srvMatter.MatterDepositBankId = matter.DepositBankId;
                    srvMatter.BranchId = matter.BranchReference;
                    srvMatter.DepartmentId = matter.DepartmentId;
                    srvMatter.ChargeDescriptionId = matter.ChargeDescriptionId;
                    srvMatter.CourtId = matter.CourtId;
                    srvMatter.MatterOpenDate = matter.OpenDate;
                    srvMatter.MatterNextReviewDate = matter.NextReviewDate;
                    srvMatter.MatterCostReviewDate = matter.CostReviewDate;
                    srvMatter.MatterClosedDate = matter.ClosedDate;
                    srvMatter.MatterDestructDate = matter.DestructDate;
                    srvMatter.MatterFileNo = matter.FileNo;
                    srvMatter.MatterCompleted = matter.CompletedDate;

                    // Save Matter Additional Info
                    srvMatter.MatterQuote = matter.Quote;
                    srvMatter.MatterDisbsLimit = matter.DisbsLimit;
                    srvMatter.MatterTimeLimit = matter.TimeLimit;
                    srvMatter.MatterWIPLimit = matter.WIPLimit;
                    srvMatter.MatterOverallLimit = matter.OverallLimit;
                    srvMatter.MatterStatus = matter.Status;
                    srvMatter.MatterIndicators = matter.Indicators;
                    srvMatter.MatterBankReference = matter.BankReference;
                    srvMatter.MatCashCollID = matter.CashCollectionId;
                    srvMatter.MatTotalLockup = matter.TotalLockup;
                    srvMatter.OurReference = matter.OurReference;
                    srvMatter.PreviousReference = matter.PreviousReference;
                    srvMatter.SourceID = matter.BusinessSourceId;
                    // TODO: Save Campaign Id
                    // = campaignId = matter.SourceCampaignId;
                    srvMatter.UserId = matter.PersonDealingId;
                    srvMatter.MatterSalutationEnvelope = matter.SalutationEnvelope;
                    srvMatter.MatterSalutationLetter = matter.SalutationLetter;
                    srvMatter.MatterLetterHead = matter.LetterHead;

                    //Save Matter Public Funding
                    srvMatter.MatterLegalAided = matter.IsPublicFunding;
                    srvMatter.MatterFranchised = matter.Franchised;
                    srvMatter.MatterLondonRate = matter.isLondonRate;
                    srvMatter.UFNDate = matter.UFNDate;
                    srvMatter.UFNNumber = matter.UFN;
                    srvMatter.MatterPFCertificateNo = matter.PFCertificateNo;
                    srvMatter.MatterPFCertificateLimits = matter.PFCertificateNoLimits;
                    srvMatter.MatterTypeId = matter.MatterTypeId;

                    srvMatter.ClientId = matter.ClientId;

                    string errorMessage;

                    returnValue.Success = srvMatter.Save(out errorMessage);
                    returnValue.Message = errorMessage;
                }
                finally
                {
                    // Remove the logged on user's ApplicationSettings from the
                    // list of concurrent sessions
                    Host.UnloadLoggedOnUser();
                }
            }
            catch (System.Data.SqlClient.SqlException)
            {
                returnValue.Success = false;
                returnValue.Message = Functions.SQLErrorMessage;
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Message = ex.Message;
            }

            return returnValue;
        }
        /// <summary>
        /// Gets the control data to save the matter.
        /// </summary>
        /// <returns></returns>
        private IRIS.Law.WebServiceInterfaces.Matter.Matter GetControlData()
        {
            Guid memberId = (Guid)Session[SessionName.MemberId];
            Guid organisationId = (Guid)Session[SessionName.OrganisationId];
            Guid clientId;
            if (memberId != DataConstants.DummyGuid)
            {
                clientId = memberId;
            }
            else
            {
                clientId = organisationId;
            }

            IRIS.Law.WebServiceInterfaces.Matter.Matter matter = new IRIS.Law.WebServiceInterfaces.Matter.Matter();

            //Get the selected joint client candidates
            List<ListItem> selectedItems = (from item in _chklstClientAssociates.Items.Cast<ListItem>()
                                            where item.Selected
                                            select item).ToList();

            JointClientCandidateSearchItem[] jointCandidates = new JointClientCandidateSearchItem[selectedItems.Count];
            for (int i = 0; i < selectedItems.Count; i++)
            {
                string orgId = selectedItems[i].Value.EndsWith("M") ? DataConstants.DummyGuid.ToString()
                                                : selectedItems[i].Value.Substring(0, 36);
                string memId = selectedItems[i].Value.EndsWith("O") ? DataConstants.DummyGuid.ToString()
                                                : selectedItems[i].Value.Substring(0, 36);
                jointCandidates[i] = new JointClientCandidateSearchItem();
                jointCandidates[i].MemberId = memId;
                jointCandidates[i].OrganisationId = orgId;
            }
            matter.JointClientCandidates = new DataListOfJointClientCandidateSearchItemkPb1ZSG8();
            matter.JointClientCandidates.Rows = jointCandidates;
            matter.ClientId = clientId;
            matter.Description = _txtDescription.Text.Trim();
            matter.PartnerMemberId = new Guid(_ddlSupervisor.SelectedValue);
            matter.FeeEarnerMemberId = new Guid(GetFeeEarnerValueOnIndex(_ddlFeeEarner.SelectedValue, 1));
            if (_ccUFNDate.DateText.Length > 0)
            {
                matter.UFNDate = Convert.ToDateTime(_ccUFNDate.DateText.Trim());
            }
            else
            {
                matter.UFNDate = DataConstants.BlankDate;
            }
            matter.UFN = _txtUFNNumber.Text.Trim();
            matter.IsPublicFunding = _chkPublicFunding.Checked;
            matter.Franchised = _chkSQM.Checked;
            matter.ClientBankId = Convert.ToInt32(_ddlClientBank.SelectedValue);
            matter.OfficeBankId = Convert.ToInt32(_ddlOfficeBank.SelectedValue);
            matter.ChargeDescriptionId = new Guid(GetChargeRateValueOnIndex(_ddlChargeRate.SelectedValue, 0));
            matter.WorkTypeId = new Guid(_ddlWorkType.SelectedValue);
            matter.DepartmentId = Convert.ToInt32(_ddlDepartment.SelectedValue);
            matter.BranchReference = GetBranchValueOnIndex(_ddlBranch.SelectedValue, 0);
            matter.CourtId = Convert.ToInt32(_ddlCourtType.SelectedValue);
            matter.MatterTypeId = Convert.ToInt32(_ddlMatterType.SelectedValue);
            matter.HOUCN = _txtHOUCN.Text.Trim();
            matter.UCN = _txtUCN.Text.Trim();
            matter.FeeEarnerReference = GetFeeEarnerValueOnIndex(_ddlFeeEarner.SelectedValue, 0);

            return matter;
        }