using System.ComponentModel.DataAnnotations; using Connected.Annotations; using Connected.Common.Documents; using Connected.Contacts.Types; using Connected.Data; using Connected.Logistics.Types.Warehouses; using Connected.Security.Identity; using Connected.Validation; namespace Connected.Logistics.Documents.Receive; [Priority(0)] internal sealed class InsertReceiveDocumentValidator : InsertDocumentValidator { public InsertReceiveDocumentValidator(IUserService users, IBusinessPartnerService businessPartners, IWarehouseService warehouses) : base(users) { BusinessPartners = businessPartners; Warehouses = warehouses; } private IBusinessPartnerService BusinessPartners { get; } private IWarehouseService Warehouses { get; } protected override async Task OnValidating() { await ValidateSupplier(); await ValidateWarehouse(); } private async Task ValidateSupplier() { /* * If supplier is not set there is no need for a validation. */ if (Arguments.Supplier is null) return; /* * Check is business partner exists. */ if (await BusinessPartners.Select((int)Arguments.Supplier) is not IBusinessPartner supplier) throw ValidationExceptions.NotFound(nameof(Arguments.Supplier), Arguments.Supplier); /* * Check if business partner has Supplier role which means it's actually a supplier. */ if (!supplier.Roles.HasFlag(CustomerRoles.Supplier)) throw new ValidationException($"{SR.ValPartnerNotSupplier} ({Arguments.Supplier})"); } private async Task ValidateWarehouse() { if (Arguments.Warehouse is null) return; /* * Check is warehouse exists. */ if (await Warehouses.Select(Arguments.Warehouse) is not IWarehouse warehouse) throw ValidationExceptions.NotFound(nameof(Arguments.Warehouse), Arguments.Warehouse); /* * Only Enabled warehouses can be used. */ if (warehouse.Status == Status.Disabled) throw ValidationExceptions.Disabled(nameof(Arguments.Warehouse)); } }