Пример #1
0
	//variables for change colors of each event button. unsched and sched


//	private Calculate calculate;

	void Start()
	{
		GameManager.Calendar.OnCommitmentClicked += Calendar_OnCommitmentClicked;

		buttonImage = GetComponent<Image>();
		startPosition = transform.localPosition;
		com = GetComponent<Commitment>();
	}
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            SetContentView (Resource.Layout.CommitmentDetails);

            webService = WebServiceFactory.Create ();

            //Deserialize the commitment that was passed in
            commitment = JsonSerializer.Deserialize<Commitment> (this.Intent.GetStringExtra ("COMMITMENT"));

            textViewName = FindViewById<TextView> (Resource.Id.textViewName);
            textViewDescription = FindViewById<TextView> (Resource.Id.textViewDescription);
            textViewStartDate = FindViewById<TextView> (Resource.Id.textViewStartDate);
            textViewEndDate = FindViewById<TextView> (Resource.Id.textViewEndDate);
            textViewCluster = FindViewById<TextView> (Resource.Id.textViewCluster);
            buttonCheckIn = FindViewById<Button> (Resource.Id.buttonCheckIn);

            //TODO: Need to add meaningful name/descriptions
            textViewName.Text = "TODO: Put in Name";
            textViewDescription.Text = "TODO: Put in Desc";
            textViewStartDate.Text = commitment.StartDate.ToString ("ddd MMM d, yyyy");
            textViewEndDate.Text = commitment.EndDate.ToString ("ddd MMM d, yyyy");
            textViewCluster.Text = "TODO: Put in Cluster";

            buttonCheckIn.Click += async delegate {

                //TODO: Create confirmation dialog  (Are you sure: Yes/No)

                var confirm = true;

                if (confirm) {
                    var checkedIn = commitment.IsActive;

                    if (checkedIn) {
                        var r = await webService.CheckOutAsync(new CheckOutRequest { Username = App.Settings.SignedInUsername });
                        checkedIn = !(r.Succeeded && r.Result);
                    } else {
                        var r = await webService.CheckInAsync(new CheckInRequest { Username = App.Settings.SignedInUsername });
                        checkedIn = r.Succeeded && r.Result;
                    }

                    buttonCheckIn.Text = checkedIn ? "Check Out" : "Check In";
                    commitment.IsActive = checkedIn;
                }
            };
        }
Пример #3
0
        public static async Task AddCommitment(this AppDbContext db, CommitmentModel model)
        {
            if (await model.Validate(db))
            {
                var commitment = new Commitment
                {
                    Id         = model.id,
                    Location   = model.location,
                    Subject    = model.subject,
                    Body       = model.body,
                    StartDate  = model.startDate,
                    EndDate    = model.endDate,
                    CategoryId = model.category.id
                };

                await db.Commitments.AddAsync(commitment);

                await db.SaveChangesAsync();
            }
        }
        public void SetUp()
        {
            _validator            = new ApproveTransferRequestValidator();
            _commitmentRepository = new Mock <ICommitmentRepository>();
            _v2EventsPublisher    = new Mock <IV2EventsPublisher>();

            var fixture = new Fixture();

            _command    = fixture.Build <ApproveTransferRequestCommand>().Create();
            _commitment = fixture.Build <Commitment>()
                          .With(x => x.TransferSenderId, _command.TransferSenderId)
                          .With(x => x.EmployerAccountId, _command.TransferReceiverId)
                          .With(x => x.TransferApprovalStatus, TransferApprovalStatus.Pending)
                          .With(x => x.EditStatus, EditStatus.Both).Create();

            _commitmentRepository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(_commitment);
            _commitment.Apprenticeships.ForEach(x => x.AgreementStatus = AgreementStatus.ProviderAgreed);

            _sut = new ApproveTransferRequestCommandHandler(_validator, _commitmentRepository.Object, _v2EventsPublisher.Object);
        }
        public async Task ThenCohortTransferStatusIsResetIfRejected()
        {
            //Arrange
            var testCommitment = new Commitment
            {
                ProviderId             = 123,
                TransferApprovalStatus = TransferApprovalStatus.TransferRejected
            };

            _mockCommitmentRepository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(testCommitment);

            //Act
            await _handler.Handle(_validCommand);

            //Assert
            _mockCommitmentRepository.Verify(x => x.UpdateCommitment(It.Is <Commitment>(c =>
                                                                                        c.TransferApprovalStatus == null &&
                                                                                        c.TransferApprovalActionedOn == null
                                                                                        )), Times.Once);
        }
Пример #6
0
        public void AssignToVolunteer_Valid()
        {
            Commitment createdCommitment = null;

            _mockDataService.Setup(s => s.AddCommitment(It.IsAny <Commitment>()))
            .Callback <Commitment>(commitment => createdCommitment = commitment);

            const int personId   = 5;
            const int disasterId = 10;
            var       startDate  = new DateTime(2013, 01, 01);
            var       endDate    = new DateTime(2013, 02, 01);

            _disasterService.AssignToVolunteer(disasterId, personId, startDate, endDate);

            Assert.IsNotNull(createdCommitment);
            Assert.AreEqual(createdCommitment.PersonId, personId);
            Assert.AreEqual(createdCommitment.DisasterId, disasterId);
            Assert.AreEqual(createdCommitment.StartDate, startDate);
            Assert.AreEqual(createdCommitment.EndDate, endDate);
        }
Пример #7
0
        private static void CheckAuthorization(DeleteCommitmentCommand message, Commitment commitment)
        {
            switch (message.Caller.CallerType)
            {
            case CallerType.Provider:
                if (commitment.ProviderId != message.Caller.Id)
                {
                    throw new UnauthorizedException($"Provider {message.Caller.Id} not authorised to access commitment: {message.CommitmentId}, expected provider {commitment.ProviderId}");
                }
                break;

            case CallerType.Employer:
            default:
                if (commitment.EmployerAccountId != message.Caller.Id)
                {
                    throw new UnauthorizedException($"Employer {message.Caller.Id} not authorised to access commitment: {message.CommitmentId}, expected employer {commitment.EmployerAccountId}");
                }
                break;
            }
        }
Пример #8
0
        public void Given()
        {
            _eventsList = new Mock <IApprenticeshipEventsList>();
            _eventsApi  = new Mock <IEventsApi>();
            _publisher  = new ApprenticeshipEventsPublisher(_eventsApi.Object, Mock.Of <ICommitmentsLogger>());

            _commitment = new Commitment
            {
                Id                          = 348957,
                ProviderId                  = 123,
                EmployerAccountId           = 987,
                LegalEntityId               = "LE ID",
                LegalEntityName             = "LE Name",
                LegalEntityOrganisationType = SFA.DAS.Common.Domain.Types.OrganisationType.CompaniesHouse
            };

            _apprenticeship = new Apprenticeship
            {
                EndDate         = DateTime.Now.AddYears(3),
                StartDate       = DateTime.Now.AddDays(1),
                Cost            = 123.45m,
                TrainingCode    = "TRCODE",
                AgreementStatus = Domain.Entities.AgreementStatus.BothAgreed,
                Id            = 34875,
                ULN           = "ULN",
                PaymentStatus = Domain.Entities.PaymentStatus.Active,
                TrainingType  = TrainingType.Framework,
                PaymentOrder  = 213,
                DateOfBirth   = DateTime.Now.AddYears(-18)
            };

            _mockApprenticeshipEvent = new Mock <IApprenticeshipEvent>();
            _mockApprenticeshipEvent.SetupGet(x => x.Apprenticeship).Returns(_apprenticeship);
            _mockApprenticeshipEvent.SetupGet(x => x.Commitment).Returns(_commitment);
            _mockApprenticeshipEvent.SetupGet(x => x.Event).Returns(_event);
            var events = new List <IApprenticeshipEvent> {
                _mockApprenticeshipEvent.Object
            };

            _eventsList.SetupGet(x => x.Events).Returns(events);
        }
Пример #9
0
        public override void SetUp()
        {
            base.SetUp();

            ExampleValidRequest = new PauseApprenticeshipCommand
            {
                AccountId        = 111L,
                ApprenticeshipId = 444L,
                DateOfChange     = DateTime.Now.Date,
                UserName         = "******"
            };

            TestApprenticeship = new Apprenticeship
            {
                CommitmentId  = 123L,
                PaymentStatus = PaymentStatus.Active,
                StartDate     = DateTime.UtcNow.Date.AddMonths(6)
            };

            _testCommitment = new Commitment
            {
                Id = 123L,
                EmployerAccountId = ExampleValidRequest.AccountId
            };

            MockCurrentDateTime.SetupGet(x => x.Now).Returns(DateTime.UtcNow);

            MockApprenticeshipRespository
            .Setup(x => x.GetApprenticeship(It.Is <long>(y => y == ExampleValidRequest.ApprenticeshipId)))
            .ReturnsAsync(TestApprenticeship);

            MockApprenticeshipRespository
            .Setup(x => x.UpdateApprenticeshipStatus(TestApprenticeship.CommitmentId,
                                                     ExampleValidRequest.ApprenticeshipId,
                                                     PaymentStatus.Paused))
            .Returns(Task.FromResult(new object()));

            MockCommitmentRespository.Setup(x => x.GetCommitmentById(
                                                It.Is <long>(c => c == TestApprenticeship.CommitmentId)))
            .ReturnsAsync(_testCommitment);
        }
Пример #10
0
        public async Task ThenIfAnApprenticeshipIsApprovedAndTheLearnerHasAPreviousApprenticeshipStoppedInTheStartMonthAnEventIsPublishedWithTheEffectiveFromDateBeingADayAfterTheStoppedDate()
        {
            var commitment = new Commitment {
                Id = 123L, EmployerAccountId = 444, EmployerCanApproveCommitment = true, EditStatus = EditStatus.EmployerOnly
            };
            var apprenticeship = new Apprenticeship
            {
                AgreementStatus = AgreementStatus.ProviderAgreed,
                PaymentStatus   = PaymentStatus.PendingApproval,
                Id        = 1234,
                StartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 13),
                ULN       = "1234567",
                Cost      = 1000
            };

            commitment.Apprenticeships.Add(apprenticeship);

            _mockCommitmentRespository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(commitment);

            var stoppedDate = apprenticeship.StartDate.Value.AddDays(-5);

            _mockApprenticeshipRespository.Setup(x => x.GetActiveApprenticeshipsByUlns(It.Is <IEnumerable <string> >(y => y.First() == apprenticeship.ULN)))
            .ReturnsAsync(new List <ApprenticeshipResult>
            {
                new ApprenticeshipResult {
                    StartDate = apprenticeship.StartDate.Value.AddMonths(-4), StopDate = apprenticeship.StartDate.Value.AddMonths(-3), Uln = apprenticeship.ULN
                },
                new ApprenticeshipResult {
                    StartDate = apprenticeship.StartDate.Value.AddMonths(-2), StopDate = stoppedDate, Uln = apprenticeship.ULN
                }
            });

            _validCommand.LatestAction = LastAction.Approve;

            await _handler.Handle(_validCommand);

            var expectedStartDate = stoppedDate.AddDays(1);

            _mockApprenticeshipEventsList.Verify(x => x.Add(commitment, apprenticeship, "APPRENTICESHIP-AGREEMENT-UPDATED", expectedStartDate, null), Times.Once);
            _mockApprenticeshipEventsPublisher.Verify(x => x.Publish(_mockApprenticeshipEventsList.Object), Times.Once);
        }
Пример #11
0
        public async Task <long> Create(Commitment commitment)
        {
            _logger.Debug($"Creating commitment with ref: {commitment.Reference}", accountId: commitment.EmployerAccountId, providerId: commitment.ProviderId);

            return(await WithConnection(async connection =>
            {
                long commitmentId;

                var parameters = new DynamicParameters();
                parameters.Add("@reference", commitment.Reference, DbType.String);
                parameters.Add("@legalEntityId", commitment.LegalEntityId, DbType.String);
                parameters.Add("@legalEntityName", commitment.LegalEntityName, DbType.String);
                parameters.Add("@LegalEntityAddress", commitment.LegalEntityAddress, DbType.String);
                parameters.Add("@legalEntityOrganisationType", commitment.LegalEntityOrganisationType, DbType.Int16);
                parameters.Add("@accountId", commitment.EmployerAccountId, DbType.Int64);
                parameters.Add("@providerId", commitment.ProviderId, DbType.Int64);
                parameters.Add("@providerName", commitment.ProviderName, DbType.String);
                parameters.Add("@commitmentStatus", commitment.CommitmentStatus, DbType.Int16);
                parameters.Add("@editStatus", commitment.EditStatus, DbType.Int16);
                parameters.Add("@id", dbType: DbType.Int64, direction: ParameterDirection.Output);
                parameters.Add("@createdOn", _currentDateTime.Now, DbType.DateTime);
                parameters.Add("@lastAction", commitment.LastAction, DbType.Int16);
                parameters.Add("@lastUpdateByEmployerName", commitment.LastUpdatedByEmployerName, DbType.String);
                parameters.Add("@lastUpdateByEmployerEmail", commitment.LastUpdatedByEmployerEmail, DbType.String);

                using (var trans = connection.BeginTransaction())
                {
                    commitmentId = (await connection.QueryAsync <long>(
                                        sql:
                                        "INSERT INTO [dbo].[Commitment](Reference, LegalEntityId, LegalEntityName, LegalEntityAddress, LegalEntityOrganisationType, EmployerAccountId, ProviderId, ProviderName, CommitmentStatus, EditStatus, CreatedOn, LastAction, LastUpdatedByEmployerName, LastUpdatedByEmployerEmail) " +
                                        "VALUES (@reference, @legalEntityId, @legalEntityName, @legalEntityAddress, @legalEntityOrganisationType, @accountId, @providerId, @providerName, @commitmentStatus, @editStatus, @createdOn, @lastAction, @lastUpdateByEmployerName, @lastUpdateByEmployerEmail); " +
                                        "SELECT CAST(SCOPE_IDENTITY() as int);",
                                        param: parameters,
                                        commandType: CommandType.Text,
                                        transaction: trans)).Single();

                    trans.Commit();
                    return commitmentId;
                }
            }));
        }
Пример #12
0
        private IQueryable <Person> GetClusterCoordinatorsForDateQueryable(int disasterId, DateTime date, bool checkedInOnly, IEnumerable <int> inClusterIds)
        {
            if (disasterId <= 0)
            {
                throw new ArgumentException("disasterId must be greater than zero", "disasterId");
            }

            var inClusterIdsArray = inClusterIds?.ToArray() ?? new int[0];
            var hasClusters       = inClusterIdsArray.Length == 0;

            var people = from cc in _dataService.ClusterCoordinators
                         where cc.DisasterId == disasterId
                         join c in Commitment.FilteredByStatus(_dataService.Commitments, checkedInOnly)
                         on cc.PersonId equals c.PersonId
                         where c.DisasterId == disasterId
                         where date >= c.StartDate && date <= c.EndDate
                         where hasClusters || inClusterIdsArray.Any(cid => cid == c.ClusterId)
                         select cc.Person;

            return(people.Distinct());
        }
Пример #13
0
        public async Task ThenIfTheCallerIsTheProviderThenTheCommitmentStatusesAreUpdatedCorrectly()
        {
            var commitment = new Commitment {
                Id = 123L, ProviderId = 444, ProviderCanApproveCommitment = false, EditStatus = EditStatus.ProviderOnly
            };

            _mockCommitmentRespository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(commitment);

            _validCommand.Caller.CallerType = CallerType.Provider;

            await _handler.Handle(_validCommand);

            _mockCommitmentRespository.Verify(
                x =>
                x.UpdateCommitment(It.Is <Commitment>(
                                       y => y.EditStatus == EditStatus.EmployerOnly &&
                                       y.CommitmentStatus == CommitmentStatus.Active &&
                                       y.LastUpdatedByProviderEmail == _validCommand.LastUpdatedByEmail &&
                                       y.LastUpdatedByProviderName == _validCommand.LastUpdatedByName &&
                                       y.LastAction == (Domain.Entities.LastAction)_validCommand.LatestAction)), Times.Once);
        }
Пример #14
0
        public async Task UpdateCommitment(Commitment commitment)
        {
            await WithTransaction(async (connection, transaction) =>
            {
                var parameters = new DynamicParameters();
                parameters.Add("@id", commitment.Id, DbType.Int64);
                parameters.Add("@commitmentStatus", commitment.CommitmentStatus, DbType.Int16);
                parameters.Add("@editStatus", commitment.EditStatus, DbType.Int16);
                parameters.Add("@lastAction", commitment.LastAction, DbType.Int16);
                parameters.Add("@lastUpdatedByEmployerName", commitment.LastUpdatedByEmployerName, DbType.String);
                parameters.Add("@lastUpdatedByEmployerEmail", commitment.LastUpdatedByEmployerEmail, DbType.String);
                parameters.Add("@lastUpdatedByProviderName", commitment.LastUpdatedByProviderName, DbType.String);
                parameters.Add("@lastUpdatedByProviderEmail", commitment.LastUpdatedByProviderEmail, DbType.String);

                await connection.ExecuteAsync(
                    sql: "UpdateCommitment",
                    param: parameters,
                    transaction: transaction,
                    commandType: CommandType.StoredProcedure);
            });
        }
        public async Task ThenTheUpdateV2ApprenticeshipUpdatedApprovedEventIsPublished()
        {
            var testCommitment = new Commitment {
                ProviderId = 1234, Id = 9874, EmployerAccountId = 8457
            };

            _commitment.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(testCommitment);

            var command = new AcceptApprenticeshipChangeCommand
            {
                ApprenticeshipId = _apprenticeship.Id,
                UserId           = "ABC123",
                Caller           = new Caller(555, CallerType.Employer)
            };
            await _sut.Handle(command);

            _v2EventsPublisher.Verify(
                x =>
                x.PublishApprenticeshipUpdatedApproved(
                    It.Is <Commitment>(m => m.Id == testCommitment.Id), It.Is <Apprenticeship>(m => m.Id == _apprenticeship.Id)), Times.Once);
        }
        public void Arrange()
        {
            EventsApi         = new Mock <IEventsApi>();
            CommitmentsLogger = new Mock <ICommitmentsLogger>();

            Service = new ApprenticeshipEvents(EventsApi.Object, CommitmentsLogger.Object);

            Commitment = new Commitment
            {
                Id                               = 348957,
                ProviderId                       = 123,
                EmployerAccountId                = 987,
                LegalEntityId                    = "LE ID",
                LegalEntityName                  = "LE Name",
                LegalEntityOrganisationType      = SFA.DAS.Common.Domain.Types.OrganisationType.CompaniesHouse,
                AccountLegalEntityPublicHashedId = "ALEPHI"
            };

            Apprenticeship = new Apprenticeship
            {
                EndDate         = DateTime.Now.AddYears(3),
                StartDate       = DateTime.Now.AddDays(1),
                PauseDate       = DateTime.Now.AddMonths(1),
                StopDate        = DateTime.Now.AddMonths(2),
                Cost            = 123.45m,
                TrainingCode    = "TRCODE",
                AgreementStatus = Domain.Entities.AgreementStatus.BothAgreed,
                Id            = 34875,
                ULN           = "ULN",
                PaymentStatus = Domain.Entities.PaymentStatus.Active,
                TrainingType  = TrainingType.Framework,
                PaymentOrder  = 213,
                DateOfBirth   = DateTime.Now.AddYears(-18),
                PriceHistory  = new List <Domain.Entities.PriceHistory> {
                    new Domain.Entities.PriceHistory {
                        ApprenticeshipId = 34875, Cost = 123.45m, FromDate = DateTime.Now.AddDays(1), ToDate = null
                    }
                }
            };
        }
Пример #17
0
        internal async Task <bool> CommitmentHasOverlappingApprenticeships(Commitment commitment)
        {
            var potentiallyOverlappingApprenticeships = await GetPotentiallyOverlappingApprenticeships(commitment);

            foreach (var potentiallyOverlappingApprenticeship in potentiallyOverlappingApprenticeships)
            {
                foreach (var commitmentApprenticeship in commitment.Apprenticeships.Where(x => x.ULN == potentiallyOverlappingApprenticeship.Uln))
                {
                    var overlapRequest = new ApprenticeshipOverlapValidationRequest {
                        ApprenticeshipId = commitmentApprenticeship.Id, Uln = commitmentApprenticeship.ULN, StartDate = commitmentApprenticeship.StartDate.Value, EndDate = commitmentApprenticeship.EndDate.Value
                    };
                    var validationFailReason = _overlapRules.DetermineOverlap(overlapRequest, potentiallyOverlappingApprenticeship);

                    if (validationFailReason != ValidationFailReason.None)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #18
0
        public async Task If_CohortIsAChangePartyRequest_Then_CohortWithChangeOfPartyRequestUpdatedEventIsPublished()
        {
            _validCommand.Caller = new Caller
            {
                CallerType = CallerType.Provider,
                Id         = 325
            };

            var commitment = new Commitment {
                Id = 123L, EmployerAccountId = 444, EmployerCanApproveCommitment = true, EditStatus = EditStatus.ProviderOnly, ProviderId = 325, ChangeOfPartyRequestId = 222
            };

            _mockCommitmentRespository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(commitment);

            await _handler.Handle(_validCommand);

            V2EventsPublisher.Verify(x => x.PublishCohortWithChangeOfPartyUpdatedEvent(_validCommand.CommitmentId,
                                                                                       It.Is <UserInfo>(u =>
                                                                                                        u.UserId == _validCommand.UserId &&
                                                                                                        u.UserDisplayName == _validCommand.LastUpdatedByName &&
                                                                                                        u.UserEmail == _validCommand.LastUpdatedByEmail)));
        }
Пример #19
0
        public async Task IfUpdatedByProvider_ThenAProviderSendCohortCommandIsSent()
        {
            _validCommand.Caller = new Caller
            {
                CallerType = CallerType.Provider,
                Id         = 325
            };
            var commitment = new Commitment {
                Id = 123L, EmployerAccountId = 444, EmployerCanApproveCommitment = true, EditStatus = EditStatus.ProviderOnly, ProviderId = 325
            };

            _mockCommitmentRespository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(commitment);

            await _handler.Handle(_validCommand);

            V2EventsPublisher.Verify(x => x.SendProviderSendCohortCommand(_validCommand.CommitmentId,
                                                                          It.Is <string>(m => m == _validCommand.Message),
                                                                          It.Is <UserInfo>(u =>
                                                                                           u.UserId == _validCommand.UserId &&
                                                                                           u.UserDisplayName == _validCommand.LastUpdatedByName &&
                                                                                           u.UserEmail == _validCommand.LastUpdatedByEmail)));
        }
Пример #20
0
        public void ThenTransferSenderFieldsAreMappedCorrectly(CallerType callerType, bool canEmployerApprove, bool canProviderApprove, TransferApprovalStatus transferStatus)
        {
            var commitment = new Commitment
            {
                TransferSenderId                       = 1,
                TransferSenderName                     = "Transfer Sender Org",
                TransferApprovalStatus                 = transferStatus,
                TransferApprovalActionedOn             = new DateTime(2018, 09, 09),
                TransferApprovalActionedByEmployerName = "Name",
                ProviderCanApproveCommitment           = canProviderApprove,
                EmployerCanApproveCommitment           = canEmployerApprove,
            };

            var result = _mapper.MapFrom(commitment, callerType);

            Assert.AreEqual(1, result.TransferSender.Id);
            Assert.AreEqual("Transfer Sender Org", result.TransferSender.Name);
            Assert.AreEqual(transferStatus, (TransferApprovalStatus)result.TransferSender.TransferApprovalStatus);
            Assert.AreEqual(new DateTime(2018, 09, 09), result.TransferSender.TransferApprovalSetOn);
            Assert.AreEqual("Name", result.TransferSender.TransferApprovalSetBy);
            Assert.AreEqual(true, result.CanBeApproved);
        }
        public async Task ThenTheUpdateAcceptedEventIsCreated()
        {
            var testCommitment = new Commitment {
                ProviderId = 1234, Id = 9874, EmployerAccountId = 8457
            };

            _commitment.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(testCommitment);

            var command = new AcceptApprenticeshipChangeCommand
            {
                ApprenticeshipId = 1234,
                UserId           = "ABC123",
                Caller           = new Caller(555, CallerType.Employer)
            };
            await _sut.Handle(command);

            _messagePublisher.Verify(
                x =>
                x.PublishAsync(
                    It.Is <ApprenticeshipUpdateAccepted>(
                        m => m.AccountId == testCommitment.EmployerAccountId && m.ProviderId == testCommitment.ProviderId.Value && m.ApprenticeshipId == command.ApprenticeshipId)), Times.Once);
        }
Пример #22
0
        public void WhenVolunteersExistForMultipleDisastersReturnCorrectDisaster()
        {
            initializeDisasterCollection(disasterWithCommitments, disasterWithNoCommitments);
            initializeVolunteerCollection(personWithCommitments, personWithNoCommitments);

            var secondCommitment = new Commitment
            {
                DisasterId = disasterWithNoVolunteersID,
                Id         = 102,
                PersonId   = personWithNoCommitmentsID,
                StartDate  = new DateTime(2013, 8, 15),
                EndDate    = new DateTime(2013, 8, 20)
            };

            initializeCommitmentCollection(commitment, secondCommitment);

            var underTest = new AdminService(mockService.Object);

            var result = underTest.GetVolunteers(disasterWithCommitments);

            Assert.AreEqual(1, result.Count());
        }
Пример #23
0
        private async Task SaveChange(StopApprenticeshipCommand command, Commitment commitment, Apprenticeship apprenticeship)
        {
            var historyService = new HistoryService(_historyRepository);

            historyService.TrackUpdate(apprenticeship, ApprenticeshipChangeType.ChangeOfStatus.ToString(), null, apprenticeship.Id, CallerType.Employer, command.UserId, apprenticeship.ProviderId, apprenticeship.EmployerAccountId, command.UserName);
            apprenticeship.PaymentStatus = PaymentStatus.Withdrawn;
            apprenticeship.StopDate      = command.DateOfChange;
            apprenticeship.MadeRedundant = command.MadeRedundant;

            await _apprenticeshipRepository.StopApprenticeship(commitment.Id, command.ApprenticeshipId, command.DateOfChange, command.MadeRedundant);

            if (command.DateOfChange == apprenticeship.StartDate)
            {
                await ResolveDataLocksForApprenticeship(apprenticeship.Id);
            }
            else
            {
                await ResolveAnyTriagedCourseDataLocks(command.ApprenticeshipId);
            }

            await historyService.Save();
        }
Пример #24
0
        public ExecutionStatus KeyGenCommit(UInt256 cycle, byte[] commitment, byte[][] encryptedRows,
                                            SystemContractExecutionFrame frame)
        {
            Logger.LogDebug(
                $"KeyGenCommit({commitment.ToHex()}, [{string.Join(", ", encryptedRows.Select(r => r.ToHex()))}])");
            if (cycle.ToBigInteger() != GetConsensusGeneration(frame))
            {
                Logger.LogWarning($"Invalid cycle: {cycle}, now is {GetConsensusGeneration(frame)}");
                return(ExecutionStatus.Ok);
            }

            try
            {
                var c = Commitment.FromBytes(commitment);
                if (!c.IsValid())
                {
                    throw new Exception();
                }
                var n = _nextValidators.Get().Length / CryptoUtils.PublicKeyLength;
                if (c.Degree != (n - 1) / 3)
                {
                    throw new Exception();
                }
                if (encryptedRows.Length != n)
                {
                    throw new Exception();
                }
            }
            catch
            {
                Logger.LogError("GovernanceContract is halted in KeyGenCommit");
                return(ExecutionStatus.ExecutionHalted);
            }

            Emit(GovernanceInterface.EventKeygenCommit, commitment, encryptedRows);
            frame.ReturnValue = new byte[] { };
            frame.UseGas(GasMetering.KeygenCommitCost);
            return(ExecutionStatus.Ok);
        }
        public void Get()
        {
            moq::Mock <RegionCommitments.RegionCommitmentsClient> mockGrpcClient = new moq::Mock <RegionCommitments.RegionCommitmentsClient>(moq::MockBehavior.Strict);
            GetRegionCommitmentRequest request = new GetRegionCommitmentRequest
            {
                Region     = "regionedb20d96",
                Project    = "projectaa6ff846",
                Commitment = "commitment726158e4",
            };
            Commitment expectedResponse = new Commitment
            {
                Id   = 11672635353343658936UL,
                Kind = "kindf7aa39d9",
                Name = "name1c9368b0",
                Plan = Commitment.Types.Plan.TwelveMonth,
                CreationTimestamp = "creation_timestamp235e59a1",
                Category          = Commitment.Types.Category.UndefinedCategory,
                StartTimestamp    = "start_timestamp8aac6e77",
                Region            = "regionedb20d96",
                Resources         =
                {
                    new ResourceCommitment(),
                },
                Status          = Commitment.Types.Status.NotYetActive,
                StatusMessage   = "status_message2c618f86",
                Reservations    = { new Reservation(), },
                Description     = "description2cf9da67",
                LicenseResource = new LicenseResourceCommitment(),
                SelfLink        = "self_link7e87f12d",
                EndTimestamp    = "end_timestamp91060b72",
            };

            mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            RegionCommitmentsClient client = new RegionCommitmentsClientImpl(mockGrpcClient.Object, null);
            Commitment response            = client.Get(request.Project, request.Region, request.Commitment);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
Пример #26
0
        public async Task ShouldPublishApprenticeshipDeletedEvents()
        {
            var testCommitment = new Commitment
            {
                ProviderId      = 123,
                Apprenticeships = new List <Apprenticeship>
                {
                    new Apprenticeship {
                        PaymentStatus = PaymentStatus.PendingApproval
                    },
                    new Apprenticeship {
                        PaymentStatus = PaymentStatus.PendingApproval
                    }
                }
            };

            _mockCommitmentRepository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(testCommitment);

            await _handler.Handle(_validCommand);

            _mockApprenticeshipEvents.Verify(x => x.BulkPublishDeletionEvent(testCommitment, testCommitment.Apprenticeships, "APPRENTICESHIP-DELETED"), Times.Once);
        }
Пример #27
0
        public async Task ThenIfAnApprenticeshipAgreementStatusIsBothAgreedAndTheAgreedOnDateIsAlreadySetTheAgreedOnDateIsNotUpdated()
        {
            var commitment = new Commitment {
                Id = 123L, EmployerAccountId = 444, EmployerCanApproveCommitment = true, EditStatus = EditStatus.EmployerOnly
            };
            var expectedAgreedOnDate = DateTime.Now.AddDays(-10);
            var apprenticeship       = new Apprenticeship {
                AgreementStatus = AgreementStatus.ProviderAgreed, PaymentStatus = PaymentStatus.PendingApproval, Id = 1234, AgreedOn = expectedAgreedOnDate, StartDate = DateTime.Now.AddDays(10), Cost = 1000
            };

            commitment.Apprenticeships.Add(apprenticeship);

            _mockCommitmentRespository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(commitment);

            _mockApprenticeshipRespository.Setup(x => x.GetActiveApprenticeshipsByUlns(It.Is <IEnumerable <string> >(y => y.First() == apprenticeship.ULN))).ReturnsAsync(new List <ApprenticeshipResult>());

            _validCommand.LatestAction = LastAction.Approve;

            await _handler.Handle(_validCommand);

            _mockApprenticeshipRespository.Verify(x => x.UpdateApprenticeshipStatuses(It.Is <List <Apprenticeship> >(y => y.First().AgreedOn.Value == expectedAgreedOnDate)), Times.Once);
        }
        private static void CheckCommitmentStatus(Commitment commitment, RejectTransferRequestCommand command)
        {
            if (commitment.EmployerAccountId != command.TransferReceiverId)
            {
                throw new InvalidOperationException($"Commitment {commitment.Id} has employer account Id {commitment.EmployerAccountId} which doesn't match command receiver Id {command.TransferReceiverId}");
            }

            if (commitment.CommitmentStatus == CommitmentStatus.Deleted)
            {
                throw new InvalidOperationException($"Commitment {commitment.Id} cannot be updated because status is {commitment.CommitmentStatus}");
            }

            if (commitment.TransferApprovalStatus != TransferApprovalStatus.Pending)
            {
                throw new InvalidOperationException($"Transfer Approval for Commitment {commitment.Id} cannot be set because the status is {commitment.TransferApprovalStatus}");
            }

            if (commitment.EditStatus != EditStatus.Both)
            {
                throw new InvalidOperationException($"Transfer Sender {commitment.TransferSenderId} not allowed to reject until both the provider and receiving employer have approved");
            }
        }
Пример #29
0
        public void AssignToVolunteer_ValidForMoreThanOneVolunteerPerDisaster()
        {
            var commitments = new List <Commitment>
            {
                new Commitment
                {
                    PersonId   = 0,
                    StartDate  = new DateTime(2013, 1, 1),
                    EndDate    = new DateTime(2013, 2, 1),
                    DisasterId = 2
                }
            };
            var disasters = new List <Disaster> {
                new Disaster {
                    Id = 2, IsActive = true
                }
            };

            _mockDataService.Setup(s => s.Commitments).Returns(commitments.AsQueryable());
            _mockDataService.Setup(s => s.Disasters).Returns(disasters.AsQueryable());

            const int personId   = 5;
            const int disasterId = 2;
            var       startDate  = DateTime.Today;
            var       endDate    = startDate.AddDays(1);

            Commitment createdCommitment = null;

            _mockDataService.Setup(s => s.AddCommitment(It.IsAny <Commitment>()))
            .Callback <Commitment>(commitment => createdCommitment = commitment);

            _disasterService.AssignToVolunteer(disasterId, personId, startDate, endDate, 1);
            Assert.IsNotNull(createdCommitment);
            Assert.AreEqual(createdCommitment.PersonId, personId);
            Assert.AreEqual(createdCommitment.DisasterId, disasterId);
            Assert.AreEqual(createdCommitment.StartDate, startDate);
            Assert.AreEqual(createdCommitment.EndDate, endDate);
        }
Пример #30
0
	public void Acept_Window(Commitment com){

        string minDay = getDay(com.minTotalDay);
        string maxDay = getDay(com.maxTotalDay);
        string minTime = getTime(com.minTime);
        string maxTime = getTime(com.maxTime);
     
        temp_com = com;
		transform.FindChild("Invitation_Text").gameObject.GetComponent<Text>().text ="A new invitation to "+ com.name;

        if (minDay == maxDay)
        {
            transform.FindChild("MinDayText").gameObject.GetComponent<Text>().text = minDay;
            transform.FindChild("ToDay").gameObject.GetComponent<Text>().text = "";
            transform.FindChild("MaxDayText").gameObject.GetComponent<Text>().text = "";
        }
        else
        {
            transform.FindChild("MinDayText").gameObject.GetComponent<Text>().text = minDay;
            transform.FindChild("ToDay").gameObject.GetComponent<Text>().text = "To";
            transform.FindChild("MaxDayText").gameObject.GetComponent<Text>().text = maxDay;
        }
        if(minTime == maxTime)
        {
            transform.FindChild("MinTimeText").gameObject.GetComponent<Text>().text = minTime;
            transform.FindChild("OrTime").gameObject.GetComponent<Text>().text = "";
            transform.FindChild("MaxTimeText").gameObject.GetComponent<Text>().text = "";

        }
        else
        {
            transform.FindChild("MinTimeText").gameObject.GetComponent<Text>().text = minTime;
            transform.FindChild("OrTime").gameObject.GetComponent<Text>().text = "Or";
            transform.FindChild("MaxTimeText").gameObject.GetComponent<Text>().text = maxTime;
        }
        //pause game
        GameManager.Instance.PauseGame ();
	} 
Пример #31
0
        public void SetUp()
        {
            _mockCommitmentRespository = new Mock <ICommitmentRepository>();
            _mockHashingService        = new Mock <IHashingService>();
            var commandValidator = new CreateCommitmentValidator();

            _mockHistoryRepository = new Mock <IHistoryRepository>();
            _handler = new CreateCommitmentCommandHandler(_mockCommitmentRespository.Object,
                                                          _mockHashingService.Object,
                                                          commandValidator,
                                                          Mock.Of <ICommitmentsLogger>(),
                                                          _mockHistoryRepository.Object);

            Fixture fixture = new Fixture();

            fixture.Customize <Apprenticeship>(ob => ob
                                               .With(x => x.ULN, ApprenticeshipTestDataHelper.CreateValidULN())
                                               .With(x => x.NINumber, ApprenticeshipTestDataHelper.CreateValidNino())
                                               .With(x => x.FirstName, "First name")
                                               .With(x => x.FirstName, "Last name")
                                               .With(x => x.ProviderRef, "Provider ref")
                                               .With(x => x.EmployerRef, null)
                                               .With(x => x.StartDate, DateTime.Now.AddYears(5))
                                               .With(x => x.EndDate, DateTime.Now.AddYears(7))
                                               .With(x => x.DateOfBirth, DateTime.Now.AddYears(-16))
                                               .With(x => x.TrainingCode, string.Empty)
                                               .With(x => x.TrainingName, string.Empty)
                                               );
            _populatedCommitment = fixture.Build <Commitment>().Create();
            _populatedCommitment.Apprenticeships = new List <Apprenticeship>();

            _exampleValidRequest = new CreateCommitmentCommand
            {
                Commitment = _populatedCommitment,
                Caller     = new Caller(1L, CallerType.Employer),
                UserId     = "UserId"
            };
        }
Пример #32
0
        public async Task ThenIfAnApprenticeshipPaymentStatusIsUpdatedTheApprenticeshipStatusesAreUpdated()
        {
            var commitment = new Commitment {
                Id = 123L, EmployerAccountId = 444, EmployerCanApproveCommitment = true, EditStatus = EditStatus.EmployerOnly
            };
            var apprenticeship = new Apprenticeship {
                AgreementStatus = AgreementStatus.NotAgreed, PaymentStatus = PaymentStatus.Active, Id = 1234
            };

            commitment.Apprenticeships.Add(apprenticeship);

            _mockCommitmentRespository.Setup(x => x.GetCommitmentById(It.IsAny <long>())).ReturnsAsync(commitment);

            var updatedApprenticeship = new Apprenticeship();

            _mockApprenticeshipRespository.Setup(x => x.GetApprenticeship(apprenticeship.Id)).ReturnsAsync(updatedApprenticeship);

            _validCommand.LatestAction = LastAction.Approve;

            await _handler.Handle(_validCommand);

            _mockApprenticeshipRespository.Verify(x => x.UpdateApprenticeshipStatuses(It.Is <List <Apprenticeship> >(y => y.First().PaymentStatus == PaymentStatus.PendingApproval)), Times.Once);
        }
        private async Task StoreCommitment(IDbConnection connection, Commitment commitment)
        {
            var parameters = new DynamicParameters();

            parameters.Add("@employerAccountId", commitment.EmployerAccountId, DbType.Int64);
            parameters.Add("@apprenticeshipId", commitment.ApprenticeshipId, DbType.Int64);
            parameters.Add("@learnerId", commitment.LearnerId, DbType.Int64);
            parameters.Add("@startDate", commitment.StartDate, DbType.DateTime);
            parameters.Add("@plannedEndDate", commitment.PlannedEndDate, DbType.DateTime);
            parameters.Add("@actualEndDate", commitment.ActualEndDate, DbType.DateTime);
            parameters.Add("@completionAmount", commitment.CompletionAmount, DbType.Decimal, ParameterDirection.Input, null, 10, 5);
            parameters.Add("@monthlyInstallment", commitment.MonthlyInstallment, DbType.Decimal, ParameterDirection.Input, null, 10, 5);
            parameters.Add("@numberOfInstallments", commitment.NumberOfInstallments, DbType.Int16);
            parameters.Add("@providerId", commitment.ProviderId, DbType.Int64);
            parameters.Add("@providerName", commitment.ProviderName, DbType.String);
            parameters.Add("@apprenticeName", commitment.ApprenticeName, DbType.String);
            parameters.Add("@courseName", commitment.CourseName, DbType.String);
            parameters.Add("@courseLevel", commitment.CourseLevel, DbType.Int32);

            await connection.ExecuteAsync(
                @"MERGE Commitment AS target 
                                    USING(SELECT @employerAccountId, @apprenticeshipId, @learnerId, @startDate, @plannedEndDate, @actualEndDate, @completionAmount, @monthlyInstallment, @numberOfInstallments, @providerId, @providerName, @apprenticeName, @courseName, @courseLevel) 
									AS source(EmployerAccountId, ApprenticeshipId, LearnerId, StartDate, PlannedEndDate, ActualEndDate, CompletionAmount, MonthlyInstallment, NumberOfInstallments, ProviderId, ProviderName, ApprenticeName, CourseName, CourseLevel)
                                    ON(target.ApprenticeshipId = source.ApprenticeshipId)
                                    WHEN MATCHED THEN
                                        UPDATE SET StartDate = source.StartDate, PlannedEndDate = source.PlannedEndDate, 
													CompletionAmount = source.CompletionAmount, MonthlyInstallment = source.MonthlyInstallment,
													NumberOfInstallments = source.NumberOfInstallments, ProviderId = source.ProviderId,
													ProviderName = source.ProviderName, ApprenticeName = source.ApprenticeName,
													CourseName = source.CourseName, CourseLevel = source.CourseLevel,
													LearnerId = source.LearnerId, EmployerAccountId = source.EmployerAccountId
                                    WHEN NOT MATCHED THEN
                                        INSERT(EmployerAccountId, ApprenticeshipId, LearnerId, StartDate, PlannedEndDate, ActualEndDate, CompletionAmount, MonthlyInstallment, NumberOfInstallments, ProviderId, ProviderName, ApprenticeName, CourseName, CourseLevel)
                                        VALUES(source.EmployerAccountId, source.ApprenticeshipId, source.LearnerId, source.StartDate, source.PlannedEndDate, source.ActualEndDate, source.CompletionAmount, source.MonthlyInstallment, source.NumberOfInstallments, source.ProviderId, source.ProviderName, source.ApprenticeName, source.CourseName, source.CourseLevel);",
                parameters,
                commandType : CommandType.Text);
        }
Пример #34
0
	public void AddEventToReview(Commitment newCom)
	{	dailyEvents.Add(newCom);	}
Пример #35
0
	public int FindIndexUnScheduled(Commitment com)
	{	return unscheduledCommitments.IndexOf(com);	}
Пример #36
0
	public void CompleteCommitment(Commitment sender)
	{
		//To be changed later
		//GameManager.People.ChangePlayerStatus(0, 0);
		GameObject.Find("Calendar").GetComponent<DailyReview>().AddEventToReview(sender);
		sender.readValues ();
	}
Пример #37
0
	public static void PlaceUnscheduled(Commitment com)
	{	
		//place every event button's place 
		com.transform.localPosition = new Vector3(startX + (GameManager.Calendar.FindIndexUnScheduled(com) * blockWidth), deckY, 0);
		ShiftDeck();

		}
Пример #38
0
	public void FailedCommitment(Commitment sender)
	{
		RemoveCommitment(sender);
		GameObject.Find("Calendar").GetComponent<DailyReview>().AddEventToReview(sender);
		Drag.ShiftDeck();
	}
Пример #39
0
	public void RemoveCommitment(Commitment com)
	{
		unscheduledCommitments.Remove(com);
		Drag.ShiftDeck();
	}
Пример #40
0
	public void acept_chore_event(Commitment com){
		if (com.curType == CommitmentType.Chore) {
			GameObject	acept_prefab =Instantiate(Resources.Load("Window_Chore_Social"),new Vector3(0, 0, 0),Quaternion.identity) as GameObject;
			acept_prefab.GetComponent<Chore_Acceptance> ().Acept_Window (com);
			GameObject.Find ("SideBar").GetComponent<Sidebar> ().trun_pause_off();

		}
	}
Пример #41
0
	public void UnScheduleCommitment(Commitment com)
	{
		//GameManager.PauseGame ();
		unscheduledCommitments.Add(com);

		scheduledCommitments.Remove(com);

		//display a window ask player accept or refuse a social event 
		//acept_social_event ();
		SortUnScheduled ();
	}
Пример #42
0
	public void CommitmentFocus(Commitment com)
	{
		curState = ClickState.CommitmentFocus;

		int maxTotalDay, minTotalDay, maxTime, minTime;
		com.ReturnTimeRange(out maxTotalDay, out minTotalDay, out maxTime, out minTime);
//		Debug.Log (maxTotalDay);
//		Debug.Log ( minTotalDay);
//		Debug.Log (maxTime);
//		Debug.Log (minTime);

		GameManager.UI.SetDragArea(maxTotalDay, minTotalDay, maxTime, minTime);
	}
Пример #43
0
	public void ScheduleCommitment(Commitment com)
	{
		unscheduledCommitments.Remove(com);
		scheduledCommitments.Add(com);
	}
Пример #44
0
	public void Tutorial(Commitment com)
	{
		if (tutorial == true) {
			 tutorial_circle = Instantiate (Resources.Load ("Sprites/Tutorial_circle")) as GameObject;
			tutorial_circle.transform.SetParent (com.transform,false);
			tutorial_circle.transform.localPosition = new Vector3 (77.1f, -41.5f, 0);
			tutorial = false;

		}

	}
Пример #45
0
	//being called if player clicked on refuse button from the inviation window. 
	public void refuse_social(Commitment com){
		for (int i = 0; i < unscheduledCommitments.Count; i++) {
			if (com == unscheduledCommitments [i]) {
				unscheduledCommitments [i].gameObject.SetActive(false);
				unscheduledCommitments.RemoveAt (i);
				Drag.ShiftDeck ();

			}
		}
	}