aboutsummaryrefslogtreecommitdiff
path: root/RhSolutions.SkuParser.Api/Controllers/ParseController.cs
blob: ca1d0d48bda872b192ea953caa8fe04e35675a37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using Microsoft.AspNetCore.Mvc;
using RhSolutions.SkuParser.Models;
using RhSolutions.SkuParser.Abstractions;

namespace RhSolutions.SkuParser.Controllers;

[ApiController]
[Route("/api/[controller]")]
public class ParseController : ControllerBase
{
	private IServiceProvider _provider;
	private Dictionary<Product, double> _result;
	public ParseController(IServiceProvider provider)
	{
		_provider = provider;
		_result = new();
	}

	[HttpPost]
	public IActionResult PostFiles([FromQuery] bool bs = false)
	{
		IFormFileCollection files = Request.Form.Files;
		try
		{
			foreach (var file in files)
			{
				ISkuParser parser = bs ? _provider.GetRequiredKeyedService<ISkuParser>("BS")
					: _provider.GetRequiredKeyedService<ISkuParser>(file.ContentType);
				var dict = parser.ParseProducts(file);

				foreach (var kvp in dict)
				{
					if (_result.ContainsKey(kvp.Key))
					{
						_result[kvp.Key] += kvp.Value;
					}
					else
					{
						_result.Add(kvp.Key, kvp.Value);
					}
				}
			}
		}
		catch (Exception ex)
		{
			return BadRequest(error: $"{ex.Message}\n\n{ex.Source}\n{ex.StackTrace}");
		}
		return new JsonResult(_result.Select(x => new
		{
			x.Key.Sku,
			x.Key.ProductLine,
			x.Key.Name,
			x.Key.Price,
			quantity = x.Value
		}));
	}
}