Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Text.Json;
- using Task05.Models;
- namespace Task05.Services
- {
- public interface IDataMock
- {
- List<Product> GetProducts();
- List<Receipt> GetReceipts();
- }
- public class DataMock : IDataMock
- {
- private readonly IWebHostEnvironment _env;
- private readonly List<Product> _products = new List<Product>();
- private readonly List<Receipt> _receipts = new List<Receipt>();
- private readonly Random _random = new Random(142911);
- private string GenerateHexString(int length)
- => string.Concat(Enumerable.Range(0, length).Select(_ => _random.Next(16).ToString("X")));
- public DataMock(IWebHostEnvironment env) {
- _env = env;
- var productsJson = File.ReadAllText(Path.Combine(_env.WebRootPath, "products-mock.json"));
- var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
- _products = JsonSerializer.Deserialize<List<Product>>(productsJson, options) ?? new List<Product>();
- for (int i = 0; i < 100; i++)
- {
- var receipt = new Receipt {
- Id = i + 1,
- Code = GenerateHexString(20),
- Items = new List<ReceiptItem>(),
- };
- for (int j = 0; j < 3; j++)
- {
- var product = _products[_random.Next(_products.Count)];
- var quantity = _random.Next(10);
- var receiptItem = new ReceiptItem
- {
- ItemNo = j + 1,
- ProductName = product.Title,
- Price = product.Price,
- Quantity = quantity,
- Value = Math.Round(product.Price * quantity, 2),
- };
- receipt.Items.Add(receiptItem);
- }
- receipt.Total = receipt.Items.Sum(x => x.Value);
- _receipts.Add(receipt);
- }
- }
- public List<Product> GetProducts()
- {
- return _products;
- }
- public List<Receipt> GetReceipts()
- {
- return _receipts;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement