Esempio n. 1
0
        public async Task <ExecutionResult> Execute(ExecuteContext <EmptyParameters> context)
        {
            var result = await _busPublisher.SendRequest <ICreateUser, IIdentifierResult>(new CreateUser
            {
                EmailAddress    = "*****@*****.**",
                FullName        = "Default Administrator Account",
                Id              = Guid.NewGuid(),
                IsAdministrator = true,
                IsActive        = true
            });

            if (!result.Successful)
            {
                throw result.ToException();
            }

            var userId = result.Id.Value;

            return(context.CompletedWithVariables(new GuidLog {
                Id = userId
            }, new UserIdParameters()
            {
                UserId = userId
            }));
        }
Esempio n. 2
0
        public async Task <ExecutionResult> Execute(ExecuteContext <UserIdParameters> context)
        {
            var result = await _busPublisher.SendRequest <ICreateAuthenticationMeans, IIdentifierResult>(
                new CreateAuthenticationMeans
            {
                Id         = Guid.NewGuid(),
                Method     = "password",
                ValidSince = DateTimeOffset.UtcNow,
                Value      = "AQAAAAEAACcQAAAAEMBltRflZWAQYQiGzPsZ6Hp4x10Pv4d4uJP1GSr5DOdwYuhqXzUmTyAX8FgUuPssig=="
            }
                );

            if (!result.Successful)
            {
                throw result.ToException();
            }

            var meansId = result.Id.Value;

            return(context.CompletedWithVariables(new GuidLog {
                Id = meansId
            }, new UserIdMeansIdParameters
            {
                UserId = context.Arguments.UserId,
                MeansId = meansId
            }));
        }
Esempio n. 3
0
        public async Task <ExecutionResult> Execute(ExecuteContext <CreationActivityParameters> context)
        {
            var result = await _busPublisher.SendRequest <ICreatePointOfSale, IIdentifierResult>(
                new CreatePointOfSale(context.Arguments.Id, context.Arguments.DisplayName, context.Arguments.ParentAccountingGroupId, context.Arguments.SaleStrategyId, context.Arguments.Features)
                );

            return(result.Successful ? context.Completed(new IdentifierLogEntry(result.Id.Value)) : context.Faulted(result.ToException()));
        }
Esempio n. 4
0
        protected async Task <(Guid, Guid)> RetrieveMeansIdAndUserId(string authMeansMethod, string authMeansValue)
        {
            var meansIdResolution = await _busPublisher.SendRequest <IResolveAuthenticationMeans, IIdentifierResult>(new ResolveAuthenticationMeans(authMeansMethod, authMeansValue));

            if (!meansIdResolution.Successful)
            {
                throw meansIdResolution.ToException();
            }
            else if (!meansIdResolution.Id.HasValue)
            {
                throw new BaristaException("means_id_resolution_failed", "Could not resolve ID of located authentication means");
            }

            var meansId = meansIdResolution.Id.Value;

            var userIdResolution = await _busPublisher.SendRequest <IResolveAuthenticationMeansUserId, IUserIdResolutionResult>(new ResolveAuthenticationMeansUserId(meansId, false));

            if (!userIdResolution.Successful)
            {
                throw new BaristaException("invalid_means", $"Authentication means with ID '{meansId}' is not currently assigned to an user.");
            }
            else if (!userIdResolution.AssignmentId.HasValue)
            {
                throw new BaristaException("assignment_to_user_resolution_failed", $"Could not resolve ID of assignment to user from means '{meansId}'.");
            }
            else if (!userIdResolution.UserId.HasValue)
            {
                throw new BaristaException("user_id_resolution_failed", $"Could not resolve user ID from means '{meansId}'.");
            }

            var assignment = await _idSvc.GetAssignmentToUser(userIdResolution.AssignmentId.Value);

            if (assignment is null)
            {
                throw new BaristaException("invalid_means_assignment_id", $"The user assignment with ID '{userIdResolution.AssignmentId}' (resolved from means with ID '{meansId}') was not found.");
            }

            var now = DateTimeOffset.UtcNow;
            var spendingLimitChecks = assignment.SpendingLimits.ToDictionary(
                sl => sl,
                sl => _acSvc.GetSpendingOfMeans(assignment.Means, sl.Interval == TimeSpan.Zero ? DateTimeOffset.MinValue : now.Subtract(sl.Interval))
                );

            await Task.WhenAll(spendingLimitChecks.Values);

            foreach (var(spendingLimit, actualSpendingTask) in spendingLimitChecks)
            {
                var actualSpending = actualSpendingTask.Result;

                if (actualSpending > spendingLimit.Value)
                {
                    throw new BaristaException("spending_limit_exceeded", $"The swipe was forbidden by the spending limit '{assignment.Id}/{spendingLimit.Id}' with value {spendingLimit.Value} per {spendingLimit.Interval}, current spending in this interval is {actualSpending}");
                }
            }

            return(meansId, userIdResolution.UserId.Value);
        }
Esempio n. 5
0
        public async Task <IOperationResult> HandleAsync(IConfirmSwipe command, ICorrelationContext correlationContext)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var sale = await _accountingService.GetSale(command.SaleId);

            if (sale is null)
            {
                throw new BaristaException("sale_not_found", $"Could not find sale with ID '{command.SaleId}'");
            }
            if (sale.PointOfSaleId != command.PointOfSaleId)
            {
                throw new BaristaException("unauthorized_point_of_sale", $"The sale with ID '{command.SaleId}' was not created by the requesting PoS with ID '{command.PointOfSaleId}'");
            }

            var opResult = await _busPublisher.SendRequest <ChangeSaleStateToConfirmed, IOperationResult>(
                new ChangeSaleStateToConfirmed(command.SaleId, Guid.NewGuid(), "PoS", command.PointOfSaleId)
                );

            if (opResult.Successful)
            {
                return(OperationResult.Ok());
            }
            else
            {
                throw opResult.ToException();
            }
        }
Esempio n. 6
0
        public async Task HandleAsync(ISaleConfirmationTimeoutExpired @event, ICorrelationContext correlationContext)
        {
            var sale = await _accSvc.GetSale(@event.SaleId);

            if (sale is null)
            {
                _logger.LogDebug($"The sale {@event.SaleId} does not exist.");
                return;
            }
            else if (sale.State == "Confirmed" || sale.State == "Cancelled")
            {
                _logger.LogDebug($"The sale {@event.SaleId} is already in a permitted state of {sale.State}.");
                return;
            }

            _logger.LogInformation($"The sale {@event.SaleId} is in a non-final state of {sale.State}, requesting its cancellation.");

            var deletionResult = await _busPublisher.SendRequest(new CancelTimedOutSale(@event.SaleId));

            if (deletionResult.Successful)
            {
                _logger.LogDebug($"The sale {@event.SaleId} was cancelled successfully due to timing out.");
            }
            else
            {
                _logger.LogInformation(deletionResult.ToException(), $"The sale {@event.SaleId} was not cancelled due to timing out.");
            }
        }
        public async Task <ExecutionResult> Execute(ExecuteContext <OwnershipAssignmentParameters> context)
        {
            var result = await _busPublisher.SendRequest <CreateAccountingGroupOwnership, IParentChildIdentifierResult>(
                new CreateAccountingGroupOwnership(context.Arguments.AccountingGroupId, context.Arguments.OwnerUserId)
                );

            return(result.Successful ? context.Completed() : context.Faulted(new Exception(result.ErrorCode)));
        }
        public async Task <ExecutionResult> Execute(ExecuteContext <OwnershipAssignmentParameters> context)
        {
            var result = await _busPublisher.SendRequest <ICreatePointOfSaleUserAuthorization, IParentChildIdentifierResult>(
                new CreatePointOfSaleOwnership(context.Arguments.PointOfSaleId, context.Arguments.OwnerUserId)
                );

            return(result.Successful ? context.Completed() : context.Faulted(result.ToException()));
        }
Esempio n. 9
0
        protected override async Task HandleAsync(Guid posId, JObject messagePayload)
        {
            var cardId     = messagePayload[MessageKey].Value <string>();
            var offersPage = await _offersService.BrowseOffers(new BrowseOffers { AtPointOfSaleId = posId, ValidAt = DateTime.UtcNow, ResultsPerPage = 1 });

            if (offersPage.TotalResults != 1)
            {
                Logger.LogError("The point of sale {posId} must have exactly one valid offer, else swipes cannot be processed", posId);
                return;
            }

            if (!(offersPage.Items?.SingleOrDefault() is Offer offer))
            {
                Logger.LogError("A single offer was expected in the offers result set");
                return;
            }

            var command       = new ProcessSwipe(AuthenticationMeansType, cardId, posId, offer.Id, 1);
            var processResult = await _busPublisher.SendRequest <IProcessSwipe, IIdentifierResult>(command);

            if (!processResult.Successful)
            {
                Logger.LogError(processResult.ToException(), "Could not process swipe");
                return;
            }
            else if (!processResult.Id.HasValue)
            {
                Logger.LogError("Swipe process was successful but did not yield a sale identifier");
                return;
            }

            var dispenseResult = await _busPublisher.SendRequest(new Commands.DispenseProduct(posId, offer.ProductId));

            var confirmResult = await _busPublisher.SendRequest <IConfirmSwipe>(new ConfirmSwipe(posId, processResult.Id.Value));

            if (!confirmResult.Successful)
            {
                Logger.LogError(confirmResult.ToException(), "Could not confirm swipe");
                return;
            }

            Logger.LogInformation($"Successfully handled sale with ID {processResult.Id.Value}");
        }
        protected async Task EnsureRemovalOfSaleBasedOp(Guid saleId)
        {
            var sale = await _accountingService.GetSale(saleId);

            if (sale is null)
            {
                throw new BaristaException("sale_not_found", $"Error retrieving sale with ID {saleId} that supposedly changed state.");
            }

            var offer = await _offersService.GetOffer(sale.OfferId);

            if (offer is null)
            {
                _logger.LogInformation($"The sale {saleId} changed state to cancelled but its offer could not be found");
                return;
            }

            if (!(offer.StockItemId is Guid stockItemId))
            {
                return;
            }

            var autoStockOps = await _stockOperationsService.BrowseSaleBasedStockOperations(new BrowseSaleBasedStockOperations { StockItemId = new Guid[] { stockItemId }, SaleId = sale.Id });

            if (autoStockOps.TotalResults == 0)
            {
                return;
            }
            else if (autoStockOps.TotalResults > 1)
            {
                throw new BaristaException("multiple_stock_ops_per_one_sale", $"Multiple stock operations yielded by query of stockItemId={stockItemId} and saleId={sale.Id}");
            }

            var autoStockOp     = autoStockOps.Items.Single();
            var removalOpResult = await _busPublisher.SendRequest(new DeleteSaleBasedStockOperation(autoStockOp.Id));

            if (!removalOpResult.Successful)
            {
                throw removalOpResult.ToException();
            }
        }
Esempio n. 11
0
        public async Task <ActionResult> Honk()
        {
            var result =
                await _busPublisher.SendRequest <CreateAccountingGroup, IIdentifierResult>(
                    new CreateAccountingGroup(Guid.NewGuid(), "ControllerTest", Guid.Empty));

            if (result.Successful)
            {
                return(new OkObjectResult(result.Id.Value));
            }
            else
            {
                return(BadRequest(result.ErrorCode));
            }
        }
Esempio n. 12
0
        public async Task <ExecutionResult> Execute(ExecuteContext <UserIdMeansIdParameters> context)
        {
            var result = await _busPublisher.SendRequest <ICreateAssignmentToUser, IIdentifierResult>(new CreateAssignmentToUser
            {
                Id         = Guid.NewGuid(),
                IsShared   = false,
                MeansId    = context.Arguments.MeansId,
                UserId     = context.Arguments.UserId,
                ValidSince = DateTimeOffset.UtcNow
            });

            if (!result.Successful)
            {
                throw result.ToException();
            }

            return(context.Completed());
        }
Esempio n. 13
0
        public async Task <IOperationResult> HandleAsync(ICancelTimedOutSale command, ICorrelationContext correlationContext)
        {
            var sale = await _queryDispatcher.QueryAsync(new GetSale(command.SaleId));

            if (sale is null)
            {
                return(new OperationResult("sale_not_found", $"Could not find sale with ID '{command.SaleId}'"));
            }

            if (sale.State != SaleState.FundsReserved.ToString())
            {
                return(new OperationResult("sale_not_in_appropriate_state", $"The sale with ID '{command.SaleId}' is in the state '{sale.State}', cancellation can only happen in the {nameof(SaleState.FundsReserved)}"));
            }

            var newSaleStateChange = await _busPublisher.SendRequest <ICreateSaleStateChange, IIdentifierResult>(
                new CreateSaleStateChange(command.SaleId, Guid.NewGuid(), "Timeout", "Cancelled", null, null)
                );

            return(newSaleStateChange);
        }
Esempio n. 14
0
 protected override async Task <IOperationResult> RemedyAsync(PointOfSaleIdParameters args, Guid inconsistentEntityId)
 => await _busPublisher.SendRequest(new DeleteOffer(inconsistentEntityId));
 protected override async Task <IOperationResult> RemedyAsync(AccountingGroupIdParameters args, Guid userId)
 => (await _busPublisher.SendRequest(new DeleteAccountingGroupUserAuthorization(args.AccountingGroupId, userId)));
Esempio n. 16
0
 protected async Task UpdateHashedPasswordAsync(Guid passwordMeansId, string newHashedApiKey)
 => await _busPublisher.SendRequest <UpdateAuthenticationMeansValue, IOperationResult>(new UpdateAuthenticationMeansValue(passwordMeansId, newHashedApiKey));
Esempio n. 17
0
 protected override async Task <IOperationResult> RemedyAsync(StockItemIdParameters args, Guid inconsistentEntityId)
 => await _busPublisher.SendRequest(new DeleteManualStockOperation(inconsistentEntityId));
 protected override async Task <IOperationResult> RemedyAsync(UserIdParameters args, Guid inconsistentEntityId)
 => await _busPublisher.SendRequest(new DeleteAccountingGroupUserAuthorization(inconsistentEntityId, args.UserId));
 protected override async Task HandleAsync(Guid posId, JObject messagePayload)
 => await _busPublisher.SendRequest(new SetPointOfSaleKeyValue(posId, MessageKey, messagePayload[MessageKey].Value <string>()));
 protected override async Task UpdateHashedPasswordAsync(AuthenticationMeansWithValue passwordContainer, string newHashedApiKey)
 => await _busPublisher.SendRequest <UpdateAuthenticationMeansValue, IOperationResult>(new UpdateAuthenticationMeansValue(passwordContainer.Id, newHashedApiKey));
Esempio n. 21
0
 protected override async Task <IOperationResult> RemedyAsync(AuthenticationMeansIdParameters args, Guid inconsistentEntityId)
 => await _busPublisher.SendRequest(new DeleteAssignmentToUser(inconsistentEntityId));
Esempio n. 22
0
 protected override async Task <IOperationResult> RemedyAsync(StockItemIdParameters args, Guid inconsistentEntityId)
 => await _busPublisher.SendRequest(new UnsetOfferStockItemReference(inconsistentEntityId, args.StockItemId));