Example #1
0
        public void AcceptAgreement(DeliveryMode delivery, ProfileKind acceptedByKind)
        {
            if (Status != AgreementStatus.WaitingForProducerApproval &&
                Status != AgreementStatus.WaitingForStoreApproval)
            {
                throw SheaftException.Validation("Le partenariat ne peut pas être accepté, il n'est en attente d'acceptation.");
            }

            if (Status == AgreementStatus.WaitingForProducerApproval && acceptedByKind != ProfileKind.Producer)
            {
                throw SheaftException.Validation("Le partenariat doit être accepté par le producteur.");
            }

            if (Status == AgreementStatus.WaitingForStoreApproval && acceptedByKind != ProfileKind.Store)
            {
                throw SheaftException.Validation("Le partenariat doit être accepté par le magasin.");
            }

            if (delivery != null)
            {
                ChangeDelivery(delivery);
            }

            if (!DeliveryModeId.HasValue)
            {
                throw SheaftException.Validation("Le partenariat doit avoir un mode de livraison rattaché.");
            }

            Store.IncreaseProducersCount();

            Status = AgreementStatus.Accepted;
            DomainEvents.Add(new AgreementAcceptedEvent(Id, acceptedByKind));
        }
Example #2
0
        public Agreement(Guid id, Store store, Producer producer, ProfileKind createdByKind, DeliveryMode delivery = null)
        {
            Id             = id;
            StoreId        = store.Id;
            Store          = store;
            CreatedByKind  = createdByKind;
            DeliveryModeId = delivery?.Id;
            DeliveryMode   = delivery;
            ProducerId     = producer.Id;
            Producer       = producer;

            if (CreatedByKind == ProfileKind.Store)
            {
                Status = AgreementStatus.WaitingForProducerApproval;
            }
            else
            {
                Status = AgreementStatus.WaitingForStoreApproval;
                if (delivery == null)
                {
                    throw SheaftException.Validation("Le mode de livraison est requis pour créer un partenariat avec un magasin.");
                }
            }

            DomainEvents = new List <DomainEvent> {
                new AgreementCreatedEvent(Id, createdByKind)
            };
        }
Example #3
0
        public async Task <IActionResult> Edit(Guid id, CancellationToken token)
        {
            var entity = await _context.Users.OfType <User>()
                         .AsNoTracking()
                         .Where(c => c.Id == id)
                         .SingleOrDefaultAsync(token);

            if (entity == null)
            {
                throw SheaftException.NotFound();
            }

            var controller = string.Empty;

            switch (entity.Kind)
            {
            case ProfileKind.Consumer:
                controller = "Consumers";
                break;

            case ProfileKind.Producer:
                controller = "Producers";
                break;

            case ProfileKind.Store:
                controller = "Stores";
                break;
            }

            return(RedirectToAction("Edit", controller, new { id }));
        }
Example #4
0
        public async Task <IActionResult> Edit(Guid id, CancellationToken token)
        {
            var requestUser = await GetRequestUserAsync(token);

            if (!requestUser.IsImpersonating())
            {
                return(RedirectToAction("Impersonate", "Account"));
            }

            var entity = await _context.Products
                         .AsNoTracking()
                         .Where(c => c.Id == id)
                         .ProjectTo <ProductViewModel>(_configurationProvider)
                         .SingleOrDefaultAsync(token);

            if (entity == null)
            {
                throw SheaftException.NotFound();
            }

            ViewBag.Tags = await GetTags(token);

            ViewBag.Returnables = await GetReturnables(requestUser, token);

            return(View(entity));
        }
Example #5
0
        public async Task <IActionResult> Edit(Guid id, CancellationToken token)
        {
            var entity = await _context.Users
                         .AsNoTracking()
                         .Where(c => c.Id == id)
                         .SingleOrDefaultAsync(token);

            if (entity == null)
            {
                throw SheaftException.NotFound();
            }

            if (entity.Kind == ProfileKind.Consumer)
            {
                return(RedirectToAction("Edit", "Consumers", new { id }));
            }

            if (entity.Kind == ProfileKind.Producer)
            {
                return(RedirectToAction("Edit", "Producers", new { id }));
            }

            if (entity.Kind == ProfileKind.Store)
            {
                return(RedirectToAction("Edit", "Stores", new { id }));
            }

            return(RedirectToAction("Index", "Dashboard"));
        }
Example #6
0
        public void SetVat(decimal?newVat)
        {
            if (Producer.NotSubjectToVat)
            {
                newVat = 0;
            }

            if (!newVat.HasValue)
            {
                throw SheaftException.Validation("La TVA est requise.");
            }

            if (newVat < 0)
            {
                throw SheaftException.Validation("La TVA ne peut être inférieure à 0%.");
            }

            if (newVat > 100)
            {
                throw SheaftException.Validation("La TVA ne peut être supérieure à 100%.");
            }

            Vat = newVat.Value;
            RefreshPrices();
        }
Example #7
0
        protected Address(string line1, string line2, string zipcode, string city, CountryIsoCode country)
        {
            if (string.IsNullOrWhiteSpace(line1))
            {
                throw SheaftException.Validation("La ligne d'adresse est requise.");
            }

            if (string.IsNullOrWhiteSpace(zipcode))
            {
                throw SheaftException.Validation("Le code postal est requis.");
            }

            if (string.IsNullOrWhiteSpace(city))
            {
                throw SheaftException.Validation("La ville est requise.");
            }

            Line1   = line1;
            Line2   = line2;
            City    = city;
            Country = country;

            if (zipcode.Length == 5)
            {
                Zipcode = zipcode;
            }
        }
Example #8
0
        public async Task <IActionResult> Edit(Guid id, CancellationToken token)
        {
            var entity = await _context.BankAccounts
                         .SingleOrDefaultAsync(c => c.Id == id, token);

            if (entity == null)
            {
                throw SheaftException.NotFound();
            }

            ViewBag.Countries = await GetCountries(token);

            return(View(new BankAccountViewModel
            {
                Id = entity.Id,
                Identifier = entity.Identifier,
                BIC = entity.BIC,
                IBAN = entity.IBAN,
                IsActive = entity.IsActive,
                Name = entity.Name,
                Owner = entity.Owner,
                OwnerId = entity.UserId,
                Address = new AddressViewModel
                {
                    Line1 = entity.Line1,
                    Line2 = entity.Line2,
                    City = entity.City,
                    Zipcode = entity.Zipcode,
                    Country = entity.Country
                }
            }));
        }
Example #9
0
        public void SetConditioning(ConditioningKind conditioning, decimal quantity,
                                    UnitKind unit = UnitKind.NotSpecified)
        {
            if (conditioning == ConditioningKind.Not_Specified)
            {
                throw SheaftException.Validation("Le conditionnement est requis.");
            }

            if (conditioning != ConditioningKind.Bulk)
            {
                unit = UnitKind.NotSpecified;
            }

            if (conditioning == ConditioningKind.Bouquet || conditioning == ConditioningKind.Bunch)
            {
                quantity = 1;
            }

            if (quantity <= 0)
            {
                throw SheaftException.Validation("La quantité par conditionnement ne peut pas être inférieure à 0.");
            }

            if (conditioning == ConditioningKind.Bulk && unit == UnitKind.NotSpecified)
            {
                throw SheaftException.Validation("L'unité du type de conditionnement est requis.");
            }

            Conditioning    = conditioning;
            QuantityPerUnit = quantity;
            Unit            = unit;

            RefreshPrices();
        }
Example #10
0
        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();
        }
Example #11
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());
        }
Example #12
0
        public void SetDeliveryFees(DeliveryFeesApplication?feesApplication, decimal?fees, decimal?minAmount)
        {
            if (fees is <= 0)
            {
                throw SheaftException.Validation("Le forfait de livraison doit être supérieur à 0€");
            }

            if (minAmount is <= 0)
            {
                throw SheaftException.Validation("Le montant minimum de commande pour appliquer le forfait doit être supérieur à 0€");
            }

            if (feesApplication is DeliveryFeesApplication.TotalLowerThanPurchaseOrderAmount && !minAmount.HasValue)
            {
                throw SheaftException.Validation("Le montant minimum de commande pour appliquer le forfait est requis.");
            }

            if (feesApplication is DeliveryFeesApplication.TotalLowerThanPurchaseOrderAmount && minAmount < AcceptPurchaseOrdersWithAmountGreaterThan)
            {
                throw SheaftException.Validation("Le montant minimum de commande pour appliquer le forfait de livraison doit être supérieur au montant minimum d'acceptation de commande.");
            }

            ApplyDeliveryFeesWhen = feesApplication;
            DeliveryFeesMinPurchaseOrdersAmount = minAmount;

            DeliveryFeesWholeSalePrice = fees.HasValue ? Math.Round(fees.Value, 2, MidpointRounding.AwayFromZero) : null;
            DeliveryFeesVatPrice       = DeliveryFeesWholeSalePrice.HasValue ? Math.Round(DeliveryFeesWholeSalePrice.Value * 0.20m, 2, MidpointRounding.AwayFromZero) : null;
            DeliveryFeesOnSalePrice    = DeliveryFeesWholeSalePrice.HasValue && DeliveryFeesVatPrice.HasValue ? Math.Round(DeliveryFeesWholeSalePrice.Value * 1.20m, 2, MidpointRounding.AwayFromZero) : null;
        }
Example #13
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken,
                                             RequestHandlerDelegate <TResponse> next)
        {
            if (request.RequestUser == null)
            {
                throw SheaftException.Unexpected("The requestUser must be assigned for the command.");
            }

            var requestName = typeof(TRequest).Name;

            _logger.LogInformation("Processing request: {Name} for {@UserId}", requestName, request.RequestUser.Name);

            using (var scope = _logger.BeginScope(new Dictionary <string, object>
            {
                ["RequestId"] = request.RequestUser.RequestId,
                ["UserIdentifier"] = request.RequestUser.Id.ToString("N"),
                ["UserEmail"] = request.RequestUser.Email,
                ["UserName"] = request.RequestUser.Name,
                ["Roles"] = string.Join(';', request.RequestUser.Roles),
                ["IsAuthenticated"] = request.RequestUser.IsAuthenticated().ToString(),
                ["Command"] = requestName,
                ["Data"] = JsonConvert.SerializeObject(request),
            }))
            {
                return(await next());
            }
        }
Example #14
0
        public async Task <IActionResult> Edit(Guid id, CancellationToken token)
        {
            var entity = await _context.Agreements
                         .AsNoTracking()
                         .Where(c => c.Id == id)
                         .ProjectTo <AgreementViewModel>(_configurationProvider)
                         .SingleOrDefaultAsync(token);

            if (entity == null)
            {
                throw SheaftException.NotFound();
            }

            var deliveries = await _context.DeliveryModes
                             .Where(d => d.ProducerId == entity.Producer.Id && (int)d.Kind > 4)
                             .ToListAsync(token);

            var catalogs = await _context.Catalogs
                           .Where(d => d.ProducerId == entity.Producer.Id && d.Kind == CatalogKind.Stores)
                           .ToListAsync(token);

            ViewBag.Deliveries = deliveries.Select(d => new SelectListItem(d.Name, d.Id.ToString("D"))).ToList();
            ViewBag.Catalogs   = catalogs.Select(d => new SelectListItem(d.Name, d.Id.ToString("D"))).ToList();

            return(View(entity));
        }
Example #15
0
        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();
        }
Example #16
0
        public void AddPurchaseOrders(IEnumerable <PurchaseOrder> purchaseOrders)
        {
            if (purchaseOrders == null || !purchaseOrders.Any())
            {
                throw SheaftException.Validation("La préparation requiert une commande à minima.");
            }

            if (purchaseOrders.Any(po =>
                                   po.Status != PurchaseOrderStatus.Waiting && po.Status != PurchaseOrderStatus.Accepted &&
                                   po.Status != PurchaseOrderStatus.Processing))
            {
                throw SheaftException.Validation(
                          "Seule des commandes en attente ou acceptées peuvent être ajoutées à une préparation.");
            }

            if (Status == PickingStatus.Completed)
            {
                throw SheaftException.Validation(
                          "Impossible de modifier les commandes d'une préparation qui est terminée.");
            }

            PurchaseOrders ??= new List <PurchaseOrder>();
            foreach (var purchaseOrder in purchaseOrders)
            {
                if (purchaseOrder.PickingId.HasValue)
                {
                    purchaseOrder.Picking.RemovePurchaseOrders(new List <PurchaseOrder> {
                        purchaseOrder
                    });
                }

                if (purchaseOrder.Status == PurchaseOrderStatus.Waiting)
                {
                    purchaseOrder.Accept(true);
                }

                PurchaseOrders.Add(purchaseOrder);
            }

            ProductsToPrepare ??= new List <PickingProduct>();
            foreach (var purchaseOrder in purchaseOrders)
            {
                foreach (var purchaseOrderProduct in purchaseOrder.Products)
                {
                    ProductsToPrepare.Add(new PickingProduct(purchaseOrderProduct, purchaseOrder.Id,
                                                             purchaseOrderProduct.Quantity));
                }
            }

            if (Status == PickingStatus.InProgress)
            {
                foreach (var purchaseOrder in purchaseOrders)
                {
                    purchaseOrder.SetStatus(PurchaseOrderStatus.Processing, true);
                }
            }

            Refresh();
        }
Example #17
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);
            }
        }
Example #18
0
        public void Pause()
        {
            if (Status != PickingStatus.InProgress)
            {
                throw SheaftException.Validation("La préparation n'est pas en cours de traitement.");
            }

            Status = PickingStatus.Paused;
        }
Example #19
0
        public void SetName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw SheaftException.Validation("Le nom du mode de livraison est requis.");
            }

            Name = name;
        }
Example #20
0
        public void SetAcceptPurchaseOrdersWithAmountGreaterThan(decimal?amount)
        {
            if (amount is < 0)
            {
                throw SheaftException.Validation("Le montant minimum de commande doit être supérieur ou égal à 0€");
            }

            AcceptPurchaseOrdersWithAmountGreaterThan = amount;
        }
Example #21
0
        public void SetCommand <T>(T command) where T : class
        {
            if (command == null)
            {
                throw SheaftException.Validation("La commande à executer par cette tâche est requise.");
            }

            Command = JsonConvert.SerializeObject(command);
        }
Example #22
0
        public void SetAsProcessed()
        {
            if (Processed)
            {
                throw SheaftException.Conflict("Cette transaction a déjà été traitée.");
            }

            Processed = true;
        }
Example #23
0
        protected void SetUserName(string name)
        {
            if (name.IsNotNullAndIsEmptyOrWhiteSpace())
            {
                throw SheaftException.Validation("Le nom d'utilisateur est requis.");
            }

            Name = name;
        }
Example #24
0
        public void SetEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                throw SheaftException.Validation("L'email de contact de l'entreprise est requis.");
            }

            Email = email;
        }
Example #25
0
        public void SetEmail(string email)
        {
            if (email.IsNotNullAndIsEmptyOrWhiteSpace())
            {
                throw SheaftException.Validation("L'email est requis.");
            }

            Email = email;
        }
Example #26
0
        public override void SetKind(LegalKind kind)
        {
            if (kind != LegalKind.Natural)
            {
                throw SheaftException.Validation("Le statut légal de l'entité doit être de type personnel.");
            }

            base.SetKind(kind);
        }
Example #27
0
        public void SetVatIdentifier(string vatNumber)
        {
            if (vatNumber.IsNotNullAndIsEmptyOrWhiteSpace())
            {
                throw SheaftException.Validation("Le numéro de TVA est requis.");
            }

            VatIdentifier = vatNumber;
        }
Example #28
0
        public override void SetKind(LegalKind kind)
        {
            if (kind == LegalKind.Natural)
            {
                throw SheaftException.Validation("Une statut légal d'une société ne peut pas être de type personnel.");
            }

            base.SetKind(kind);
        }
Example #29
0
        public void SetReference(string reference)
        {
            if (string.IsNullOrWhiteSpace(reference))
            {
                throw SheaftException.Validation("La référence est requise.");
            }

            Reference = reference;
        }
Example #30
0
        public void SetSiret(string siret)
        {
            if (siret.IsNotNullAndIsEmptyOrWhiteSpace())
            {
                throw SheaftException.Validation("Le numéro de SIRET est requis.");
            }

            Siret = siret.Trim();
        }