コード例 #1
0
        public async Task <Result> Handle(DeleteRecallsCommand request, CancellationToken token)
        {
            var recalls = await _context.Recalls
                          .Where(b => request.RecallIds.Contains(b.Id))
                          .ToListAsync(token);

            if (recalls == null || !recalls.Any())
            {
                return(Failure("Les campagnes de rappel sont introuvables."));
            }

            foreach (var recall in recalls)
            {
                if (recall.Status != RecallStatus.Waiting && recall.Status != RecallStatus.Ready)
                {
                    throw SheaftException.BadRequest("Impossible de supprimer une campagne qui a été envoyée.");
                }

                _context.Remove(recall);
            }

            await _context.SaveChangesAsync(token);

            return(Success());
        }
コード例 #2
0
ファイル: Observation.cs プロジェクト: sheaft-app/api
        public void SetProducts(IEnumerable <Product> products)
        {
            if (products == null || !products.Any())
            {
                return;
            }

            if (products.Any(p => p.ProducerId != ProducerId))
            {
                throw SheaftException.BadRequest("Une observation est liée au producteur, les produits doivent donc lui être liés.");
            }

            var existingProductIds = Products?.Select(b => b.ProductId).ToList() ?? new List <Guid>();
            var newProductIds      = products.Select(b => b.Id);
            var productIdsToRemove = existingProductIds.Except(newProductIds);

            if (productIdsToRemove.Any())
            {
                RemoveProducts(Products?.Where(b => productIdsToRemove.Contains(b.ProductId)).Select(b => b.Product)
                               .ToList());
            }

            existingProductIds = Products?.Select(b => b.ProductId).ToList() ?? new List <Guid>();
            var productIdsToAdd = newProductIds.Except(existingProductIds);

            if (productIdsToAdd.Any())
            {
                AddProducts(products.Where(b => productIdsToAdd.Contains(b.Id)).ToList());
            }

            Refresh();
        }
コード例 #3
0
ファイル: Observation.cs プロジェクト: sheaft-app/api
        public void SetBatches(IEnumerable <Batch> batches)
        {
            if (batches == null || !batches.Any())
            {
                return;
            }

            if (batches.Any(p => p.ProducerId != ProducerId))
            {
                throw SheaftException.BadRequest("Une observation est liée au producteur, les lots doivent donc lui être liés.");
            }

            var existingBatchIds = Batches?.Select(b => b.BatchId).ToList() ?? new List <Guid>();
            var newBatchIds      = batches.Select(b => b.Id);
            var batchIdsToRemove = existingBatchIds.Except(newBatchIds);

            if (batchIdsToRemove.Any())
            {
                RemoveBatches(Batches?.Where(b => batchIdsToRemove.Contains(b.BatchId)).Select(b => b.Batch).ToList());
            }

            existingBatchIds = Batches?.Select(b => b.BatchId).ToList() ?? new List <Guid>();
            var batchIdsToAdd = newBatchIds.Except(existingBatchIds);

            if (batchIdsToAdd.Any())
            {
                AddBatches(batches.Where(b => batchIdsToAdd.Contains(b.Id)).ToList());
            }

            Refresh();
        }
コード例 #4
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken,
                                             RequestHandlerDelegate <TResponse> next)
        {
            var type = typeof(TRequest).Name;

            try
            {
                return(await next());
            }
            catch (SheaftException sheaftException)
            {
                _logger.LogError(sheaftException, $"Sheaft error on executing {type} : {sheaftException.Message}");
                throw;
            }
            catch (DbUpdateConcurrencyException dbUpdateConcurrency)
            {
                _logger.LogError(dbUpdateConcurrency,
                                 $"DbConcurrency error on executing {type} : {dbUpdateConcurrency.Message}");

                throw SheaftException.Conflict(dbUpdateConcurrency);
            }
            catch (DbUpdateException dbUpdate)
            {
                _logger.LogError(dbUpdate, $"DbUpdate error on executing {type} : {dbUpdate.Message}");

                if (dbUpdate.InnerException != null &&
                    dbUpdate.InnerException.Message.Contains("duplicate key row"))
                {
                    throw SheaftException.AlreadyExists(dbUpdate);
                }

                throw SheaftException.BadRequest(dbUpdate);
            }
            catch (NotSupportedException notSupported)
            {
                _logger.LogError(notSupported, $"Not supported error on executing {type} : {notSupported.Message}");
                throw SheaftException.Unexpected(notSupported);
            }
            catch (InvalidOperationException invalidOperation)
            {
                if (invalidOperation.Source == "Microsoft.EntityFrameworkCore" &&
                    invalidOperation.Message.StartsWith("Enumerator failed to MoveNextAsync"))
                {
                    _logger.LogWarning(invalidOperation, $"Entity not found while processing {type}");
                    throw SheaftException.NotFound(invalidOperation);
                }

                _logger.LogError(invalidOperation,
                                 $"Invalid operation error on executing {type} : {invalidOperation.Message}");

                throw SheaftException.Unexpected(invalidOperation);
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unexpected error on executing {type} : {e.Message}");
                throw SheaftException.Unexpected(e);
            }
        }
コード例 #5
0
        public async Task Handle(DomainEventNotification <PickingFormGeneratedEvent> notification,
                                 CancellationToken token)
        {
            var @event  = notification.DomainEvent;
            var picking = await _context.Pickings.SingleAsync(d => d.Id == @event.PickingId, token);

            if (picking.Status == PickingStatus.Completed)
            {
                return;
            }

            var producer = await _context.Producers.SingleAsync(u => u.Id == picking.ProducerId, token);

            var blobResult = await _blobService.DownloadPickingAsync(picking.PickingFormUrl, token);

            if (!blobResult.Succeeded)
            {
                throw SheaftException.BadRequest(blobResult.Exception);
            }

            await _signalrService.SendNotificationToUserAsync(picking.ProducerId, nameof(PickingFormGeneratedEvent),
                                                              new { Url = picking.PickingFormUrl });

            await _emailService.SendTemplatedEmailAsync(
                producer.Email,
                producer.Name,
                picking.Name,
                nameof(PickingFormGeneratedEvent),
                new PickingMailerModel
            {
                UserName    = producer.FirstName,
                DownloadUrl = picking.PickingFormUrl,
                Name        = producer.Name,
            },
                new List <EmailAttachmentDto>
            {
                new EmailAttachmentDto()
                {
                    Content = blobResult.Data,
                    Name    = $"Preparation_{picking.CreatedOn:dd/MM/yyyy}.xlsx",
                }
            },
                true,
                token);
        }
コード例 #6
0
ファイル: ConfirmOrderCommand.cs プロジェクト: sheaft-app/api
        public async Task <Result <IEnumerable <Guid> > > Handle(ConfirmOrderCommand request, CancellationToken token)
        {
            var order = await _context.Orders.SingleAsync(e => e.Id == request.OrderId, token);

            if (order.User == null)
            {
                throw SheaftException.BadRequest("Impossible de confirmer le panier, l'utilisateur est requis.");
            }

            if (order.Processed)
            {
                return(Success(order.PurchaseOrders.Select(po => po.Id)));
            }

            using (var transaction = await _context.BeginTransactionAsync(token))
            {
                var purchaseOrderIds = new List <Result <Guid> >();
                order.SetStatus(OrderStatus.Confirmed);
                order.SetAsProcessed();

                var producerIds = order.Products.Select(p => p.Producer.Id).Distinct();
                foreach (var producerId in producerIds)
                {
                    var result = await _mediatr.Process(new CreatePurchaseOrderFromOrderCommand(request.RequestUser)
                    {
                        OrderId          = order.Id,
                        ProducerId       = producerId,
                        SkipNotification = true
                    }, token);

                    purchaseOrderIds.Add(result);
                }

                if (purchaseOrderIds.Any(p => !p.Succeeded))
                {
                    return(Failure <IEnumerable <Guid> >(purchaseOrderIds.First(p => !p.Succeeded)));
                }

                await _context.SaveChangesAsync(token);

                await transaction.CommitAsync(token);

                var preAuthorization = await _context.PreAuthorizations.SingleOrDefaultAsync(p =>
                                                                                             p.OrderId == order.Id && p.Status == PreAuthorizationStatus.Succeeded, token);

                if (preAuthorization == null)
                {
                    return(Success(purchaseOrderIds.Select(p => p.Data)));
                }

                var expirationDate = preAuthorization.ExpirationDate ?? preAuthorization.CreatedOn.AddDays(7);
                var diff           = expirationDate.AddDays(-2) - DateTimeOffset.Now;

                _mediatr.Schedule(new CreatePreAuthorizedPayinCommand(request.RequestUser)
                {
                    PreAuthorizationId = preAuthorization.Id
                }, TimeSpan.FromMinutes(diff.TotalMinutes));

                return(Success(purchaseOrderIds.Select(p => p.Data)));
            }
        }