/// <summary> /// Создает класс ответа без строк (orders), /// копируя из запроса в ответ те поля, которые должны вернуться неизменными, /// и устанавливая поля ErrorCode, Message и Description в указанные значения. /// </summary> /// <param name="request">Запрос.</param> /// <param name="errorCode">Значение для поля <see cref="ResponseBase.ErrorCode"/>.</param> /// <param name="message">Значение для поля <see cref="ResponseBase.Message"/>.</param> /// <param name="description">Значение для поля <see cref="GetDiscountResponse.Description"/>.</param> /// <returns>Ответ, заполненный данными из запроса (без копирования блока Orders).</returns> /// <remarks>Аналогичен методу <see cref="CreateEmptyResponse(GetDiscountRequest, int, string)"/>, но дополнительно заполняет поле <see cref="GetDiscountResponse.Description"/>.</remarks> public static GetDiscountResponse CreateResponseWithoutOrders( this GetDiscountRequest request, int errorCode, string message, string?description = null) { var resp = CreateEmptyResponse(request, errorCode, message); resp.Description = description; return(resp); }
/// <summary> /// Создает класс ответа со строками (orders). /// Вначале вызывает метод <see cref="CreateResponseWithoutOrders(GetDiscountRequest, int, string, string?)"/> чтобы создать корневой объект. /// После этого копирует строки (orders), выставляя им статус Empty или NotFound в зависимости от заполненности поля <see cref="GetDiscountRequest.Order.Barcode"/>. /// Никакие скидки не рассчитываются, сохраняются исходные цены. /// </summary> /// <param name="request">Запрос.</param> /// <param name="orderMessageWhenEmptyBarcode">Сообщение для строк с пустым ШК.</param> /// <param name="orderMessageWhenUnknownBarcode">Сообщения для строк с непустым ШК.</param> /// <param name="errorCode">Значение для поля <see cref="ResponseBase.ErrorCode"/>.</param> /// <param name="message">Значение для поля <see cref="ResponseBase.Message"/>.</param> /// <param name="description">Значение для поля <see cref="GetDiscountResponse.Description"/>.</param> /// <returns>Ответ, заполненный данными из запроса (без скидок).</returns> public static GetDiscountResponse CreateResponseWithOrders( this GetDiscountRequest request, string orderMessageWhenEmptyBarcode, string orderMessageWhenUnknownBarcode, int errorCode, string message, string?description = null) { request = request ?? throw new ArgumentNullException(nameof(request)); var resp = CreateResponseWithoutOrders(request, errorCode, message, description); if (string.IsNullOrEmpty(orderMessageWhenEmptyBarcode)) { throw new ArgumentNullException(nameof(orderMessageWhenEmptyBarcode)); } if (string.IsNullOrEmpty(orderMessageWhenUnknownBarcode)) { throw new ArgumentNullException(nameof(orderMessageWhenUnknownBarcode)); } resp.Orders = request.Orders .Select(x => new GetDiscountResponse.Order { Barcode = x.Barcode, Count = x.Count, Price = x.Price, AnyData = x.AnyData, ErrorCode = string.IsNullOrEmpty(x.Barcode) ? GetDiscountOrderErrorCodes.EmptyBarcode : GetDiscountOrderErrorCodes.UnknownBarcode, Message = string.IsNullOrEmpty(x.Barcode) ? orderMessageWhenEmptyBarcode : orderMessageWhenUnknownBarcode, Discount = 0, ValuePerItem = x.Price, Value = x.Price * x.Count, }) .ToList(); return(resp); }
/// <summary> /// Выполняет валидацию объекта с учётом вложенных коллекций (Orders, Products, ...), используя <see cref="ProtocolSettings">параметры протокола</see>, заданные в конструкторе. /// </summary> /// <param name="instance">Экземпляр объекта для проверки.</param> /// <param name="results">Список, который необходимо заполнить ошибками (если они будут найдены).</param> /// <returns>Результат валидации: <b>true</b> в случае успешной валидации или <b>false</b> если были обнаружены ошибки.</returns> public bool TryValidateObject(object instance, out List <ValidationResult> results) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } var psp = new ProtocolSettingsServiceProvider(protocolSettings); var vc = new ValidationContext(instance, psp, null); results = new List <ValidationResult>(); var isValid = Validator.TryValidateObject(instance, vc, results, true); IEnumerable <object>?children = instance switch { GetDiscountRequest gdr => gdr.Orders, GetDiscountResponse gdr => gdr.Orders, ConfirmPurchaseRequest cpr => cpr.Skus, GetProgramsResponse gpr => gpr.Programs, GetProductsResponse gpr => gpr.Products, UpdatePharmaciesRequest upr => upr.Pharmacies, _ => null, }; if (children != null) { foreach (var child in children) { if (child != null) { var childvc = new ValidationContext(child, psp, null); isValid &= Validator.TryValidateObject(child, childvc, results, true); } } } return(isValid); }
public GetDiscountRequestValidationTests() { this.protocolSettings = ProtocolSettings.CreateEmpty(); this.validator = new LikePharmaValidator(protocolSettings); validValue = new GetDiscountRequest { PosId = PosIdAttributeTests.ValidPosIdValue, CardNumber = "12345", AnyData = "Hello, World!", Orders = new List <GetDiscountRequest.Order> { new GetDiscountRequest.Order { Barcode = "1234567890123", Count = 11, Price = 123.45M, AnyData = "AnyData1", }, }, }; }
/// <summary> /// Создает пустой класс ответа, /// копируя из запроса в ответ те поля, которые должны вернуться неизменными, /// и устанавливая поля ErrorCode и Message в указанные значения. /// </summary> /// <param name="request">Запрос.</param> /// <param name="errorCode">Значение для поля <see cref="ResponseBase.ErrorCode"/>.</param> /// <param name="message">Значение для поля <see cref="ResponseBase.Message"/>.</param> /// <returns>Ответ с установленными полями <see cref="ResponseBase.Status"/>, <see cref="ResponseBase.ErrorCode"/>, <see cref="ResponseBase.Message"/>.</returns> /// <remarks>Если передать значение 0 для <paramref name="errorCode"/>, то будет создан "успешный" ответ, иначе "ошибочный".</remarks> public static GetDiscountResponse CreateEmptyResponse( this GetDiscountRequest request, int errorCode, string message) { request = request ?? throw new ArgumentNullException(nameof(request)); if (string.IsNullOrEmpty(message)) { throw new ArgumentNullException(nameof(message)); } return(new GetDiscountResponse { Status = errorCode == 0 ? Globals.StatusSuccess : Globals.StatusError, ErrorCode = errorCode, Message = message, PosId = request.PosId, PharmacyId = request.PharmacyId, CardNumber = request.CardNumber, PhoneNumber = request.PhoneNumber, AnyData = request.AnyData, }); }
/// <inheritdoc /> public Task <GetDiscountResponse> GetDiscountAsync(GetDiscountRequest request) { return(MakeRequestAsync <GetDiscountRequest, GetDiscountResponse>("get_discount", request)); }