| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using System.IO; |
| | | 3 | | using System.Threading; |
| | | 4 | | using System.Globalization; |
| | | 5 | | using System.IO.Compression; |
| | | 6 | | using SVETA.Api.Helpers.Authorize; |
| | | 7 | | using SVETA.Api.Services.Interfaces; |
| | | 8 | | using System; |
| | | 9 | | using System.Linq; |
| | | 10 | | using CrmVtbc; |
| | | 11 | | using System.Collections.Generic; |
| | | 12 | | using Microsoft.Extensions.Options; |
| | | 13 | | using SVETA.Api.Data.Domain; |
| | | 14 | | using WinSolutions.Sveta.Common; |
| | | 15 | | using System.Security.Claims; |
| | | 16 | | using System.Threading.Tasks; |
| | | 17 | | using WinSolutions.Sveta.Server.Data.DataModel.Contexts; |
| | | 18 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 19 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 20 | | using Microsoft.Extensions.Logging; |
| | | 21 | | using System.Xml.Linq; |
| | | 22 | | using System.Security.Policy; |
| | | 23 | | using Microsoft.AspNetCore.Mvc.Routing; |
| | | 24 | | using System.Net.Http; |
| | | 25 | | |
| | | 26 | | namespace SVETA.Api.Services.Implements |
| | | 27 | | { |
| | | 28 | | public class FeedsWorker : IFeedsWorker |
| | | 29 | | { |
| | | 30 | | private readonly SvetaDbContext _db; |
| | | 31 | | private readonly ILogger<FeedsWorker> _logger; |
| | | 32 | | private readonly UploadDownloadSettings _uploadSettings; |
| | | 33 | | private readonly ImagesSettings _imagesSettings; |
| | | 34 | | private readonly IDirectoriesService _dirService; |
| | | 35 | | private readonly ICategoryService _catService; |
| | | 36 | | private readonly IShowcaseWorker _showCaseWorker; |
| | | 37 | | private readonly CommonSettings _commonSettings; |
| | | 38 | | |
| | 0 | 39 | | public FeedsWorker(SvetaDbContext db, |
| | 0 | 40 | | ILogger<FeedsWorker> logger, |
| | 0 | 41 | | IOptions<UploadDownloadSettings> uploadSettings, |
| | 0 | 42 | | IOptions<CommonSettings> commonSettings, |
| | 0 | 43 | | IOptions<ImagesSettings> imagesSettings, |
| | 0 | 44 | | IDirectoriesService dirService, |
| | 0 | 45 | | ICategoryService catService, |
| | 0 | 46 | | IShowcaseWorker showCaseWorker) |
| | 0 | 47 | | { |
| | 0 | 48 | | _db = db; |
| | 0 | 49 | | _commonSettings = commonSettings.Value; |
| | 0 | 50 | | _imagesSettings = imagesSettings.Value; |
| | 0 | 51 | | _showCaseWorker = showCaseWorker; |
| | 0 | 52 | | _catService = catService; |
| | 0 | 53 | | _uploadSettings = uploadSettings.Value; |
| | 0 | 54 | | _dirService = dirService; |
| | 0 | 55 | | _logger = logger; |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// Генерирует фид для яндекса |
| | | 60 | | /// </summary> |
| | | 61 | | /// <param name="filename">название выходного файла</param> |
| | | 62 | | /// <returns>возвращает ссылку на файл</returns> |
| | | 63 | | public async Task<string> CreateFeedForYandex(string filename) |
| | 0 | 64 | | { |
| | 0 | 65 | | XDocument xdoc = new XDocument(); |
| | 0 | 66 | | XElement root = new XElement("yml_catalog"); |
| | 0 | 67 | | root.Add(new XAttribute("date", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm"))); |
| | 0 | 68 | | XElement shop = new XElement("shop"); |
| | 0 | 69 | | shop.Add(new XElement("name", "ЗАПОКУПКИ.РФ")); |
| | 0 | 70 | | shop.Add(new XElement("company", "ООО ВТБ БИЗНЕС КОННЕКТ")); |
| | 0 | 71 | | shop.Add(new XElement("url", "http://запокупки.рф")); |
| | 0 | 72 | | shop.Add(new XElement("platform", "na")); |
| | 0 | 73 | | shop.Add(new XElement("version", "1.0")); |
| | 0 | 74 | | XElement currencies = new XElement("currencies"); |
| | 0 | 75 | | foreach (var item in await _dirService.GetCurrencies()) |
| | 0 | 76 | | { |
| | 0 | 77 | | XElement currency = new XElement("currency", ""); |
| | 0 | 78 | | currency.Add(new XAttribute("rate", item.Rate)); |
| | 0 | 79 | | currency.Add(new XAttribute("id", item.STRCODE)); |
| | 0 | 80 | | currencies.Add(currency); |
| | 0 | 81 | | } |
| | 0 | 82 | | shop.Add(currencies); |
| | 0 | 83 | | XElement categories = new XElement("categories"); |
| | 0 | 84 | | foreach (var item in await _catService.GetCategories(0, int.MaxValue, null)) |
| | 0 | 85 | | { |
| | 0 | 86 | | if (item.ExcludeFromYandexFeed) |
| | 0 | 87 | | continue; |
| | 0 | 88 | | XElement category = new XElement("category", NormalizeStringValues(item.Name)); |
| | 0 | 89 | | category.Add(new XAttribute("id", item.Id)); |
| | 0 | 90 | | if (item.Parent != null) category.Add(new XAttribute("parentId", item.Parent.Id)); |
| | 0 | 91 | | categories.Add(category); |
| | 0 | 92 | | } |
| | 0 | 93 | | shop.Add(categories); |
| | 0 | 94 | | shop.Add(new XElement("enable_auto_discounts", "true")); |
| | 0 | 95 | | XElement delivery = new XElement("delivery-options"); |
| | 0 | 96 | | XElement option = new XElement("option"); |
| | 0 | 97 | | option.Add(new XAttribute("days", 1)); |
| | 0 | 98 | | option.Add(new XAttribute("cost", 0)); |
| | 0 | 99 | | delivery.Add(option); |
| | 0 | 100 | | shop.Add(delivery); |
| | 0 | 101 | | XElement offers = new XElement("offers"); |
| | 0 | 102 | | foreach (var item in _showCaseWorker.GetShowcaseGoods(null, -1, true, 0, int.MaxValue, null, "name", null, o |
| | 0 | 103 | | { |
| | 0 | 104 | | if (item.Category.ExcludeFromYandexFeed) |
| | 0 | 105 | | continue; |
| | 0 | 106 | | XElement offer = new XElement("offer"); |
| | 0 | 107 | | offer.Add(new XAttribute("id", item.Id)); |
| | 0 | 108 | | offer.Add(new XElement("name", NormalizeStringValues(item.Name))); |
| | 0 | 109 | | offer.Add(new XElement("description", NormalizeStringValues(item.Name))); |
| | 0 | 110 | | if (item.Brand?.Name != null) |
| | 0 | 111 | | offer.Add(new XElement("vendor", NormalizeStringValues(item.Brand.Name))); |
| | 0 | 112 | | if (item.VendorCode != null) |
| | 0 | 113 | | offer.Add(new XElement("vendorCode", NormalizeStringValues(item.VendorCode))); |
| | 0 | 114 | | offer.Add(new XElement("url", $"{_commonSettings.BaseFrontUrl}/showcase/catalog?product={item.Id}&depart |
| | 0 | 115 | | offer.Add(new XElement("price", item.Price)); |
| | 0 | 116 | | if (item.OldPrice != null) |
| | 0 | 117 | | offer.Add(new XElement("oldprice", item.OldPrice)); |
| | 0 | 118 | | offer.Add(new XElement("currencyId", currencies.Elements().FirstOrDefault().Attribute("id").Value)); |
| | 0 | 119 | | offer.Add(new XElement("categoryId", item.Category.Id)); |
| | 0 | 120 | | foreach (var photo in item.Photos) |
| | 0 | 121 | | offer.Add(new XElement("picture", photo.FullSizeUrl)); |
| | 0 | 122 | | offer.Add(new XElement("sales_notes", "Необходима предоплата.")); |
| | 0 | 123 | | if (item.Country?.Name != null) |
| | 0 | 124 | | offer.Add(new XElement("country_of_origin", NormalizeStringValues(item.Country.Name))); |
| | 0 | 125 | | if (item.MainBarcode?.Code != null) |
| | 0 | 126 | | offer.Add(new XElement("barcode", item.MainBarcode?.Code)); |
| | 0 | 127 | | foreach (var barcode in item.Barcodes) |
| | 0 | 128 | | offer.Add(new XElement("barcode", barcode.Code)); |
| | 0 | 129 | | if (item.GroupPackNesting != 0) |
| | 0 | 130 | | { |
| | 0 | 131 | | XElement param = new XElement("param", item.GroupPackNesting); |
| | 0 | 132 | | param.Add(new XAttribute("name", "Вложенность в групповую упаковку")); |
| | 0 | 133 | | offer.Add(param); |
| | 0 | 134 | | } |
| | 0 | 135 | | if (item.GroupPackWidth != 0) |
| | 0 | 136 | | { |
| | 0 | 137 | | XElement param = new XElement("param", item.GroupPackWidth); |
| | 0 | 138 | | param.Add(new XAttribute("name", "Ширина групповой упаковки")); |
| | 0 | 139 | | param.Add(new XAttribute("unit", "см")); |
| | 0 | 140 | | offer.Add(param); |
| | 0 | 141 | | } |
| | 0 | 142 | | if (item.GroupPackHeight != 0) |
| | 0 | 143 | | { |
| | 0 | 144 | | XElement param = new XElement("param", item.GroupPackHeight); |
| | 0 | 145 | | param.Add(new XAttribute("name", "Высота групповой упаковки")); |
| | 0 | 146 | | param.Add(new XAttribute("unit", "см")); |
| | 0 | 147 | | offer.Add(param); |
| | 0 | 148 | | } |
| | 0 | 149 | | if (item.GroupPackThickness != 0) |
| | 0 | 150 | | { |
| | 0 | 151 | | XElement param = new XElement("param", item.GroupPackThickness); |
| | 0 | 152 | | param.Add(new XAttribute("name", "Толщина групповой упаковки")); |
| | 0 | 153 | | param.Add(new XAttribute("unit", "см")); |
| | 0 | 154 | | offer.Add(param); |
| | 0 | 155 | | } |
| | 0 | 156 | | if (item.PalletNesting != 0) |
| | 0 | 157 | | { |
| | 0 | 158 | | XElement param = new XElement("param", item.PalletNesting); |
| | 0 | 159 | | param.Add(new XAttribute("name", "Вложенность в поддон")); |
| | 0 | 160 | | offer.Add(param); |
| | 0 | 161 | | } |
| | 0 | 162 | | if (item.ExpirationDays != 0) |
| | 0 | 163 | | offer.Add(new XElement("expiry", NormalizeExpireValues(item.ExpirationDays))); |
| | 0 | 164 | | if (item.Weight != 0) |
| | 0 | 165 | | offer.Add(new XElement("weight", item.Weight)); |
| | 0 | 166 | | if (item.Thickness != 0 && item.Width != 0 && item.Height != 0) |
| | 0 | 167 | | offer.Add(new XElement("dimensions", item.Thickness + "/" + item.Width + "/" + item.Height)); |
| | 0 | 168 | | offers.Add(offer); |
| | 0 | 169 | | } |
| | 0 | 170 | | shop.Add(offers); |
| | 0 | 171 | | root.Add(shop); |
| | 0 | 172 | | xdoc.Add(root); |
| | 0 | 173 | | xdoc.Save(Path.Combine(_uploadSettings.DownloadsSavePath, filename)); |
| | 0 | 174 | | return _uploadSettings.DownloadUrl + filename; |
| | 0 | 175 | | } |
| | | 176 | | |
| | | 177 | | /// <summary> |
| | | 178 | | /// Генерирует фид для гугла |
| | | 179 | | /// </summary> |
| | | 180 | | /// <param name="filename">название выходного файла</param> |
| | | 181 | | /// <returns>возвращает массив байт, представляющего файл</returns> |
| | | 182 | | public async Task<byte[]> CreateFeedForGoogle(string filename) |
| | 0 | 183 | | { |
| | 0 | 184 | | var rows = new List<string>(); |
| | 0 | 185 | | Dictionary<int, string> categoriesPath = new Dictionary<int, string>(); |
| | 0 | 186 | | var currency = (await _dirService.GetCurrencies()).FirstOrDefault(); |
| | 0 | 187 | | rows.Add("id\ttitle\tgtin\tdescription\tgoogle_product_category\tproduct_type\tlink\timage_link\tbrand\tMPN\ |
| | 0 | 188 | | foreach (var item in _showCaseWorker.GetShowcaseGoods(null, -1, true, 0, int.MaxValue, null, "name", null, o |
| | 0 | 189 | | { |
| | 0 | 190 | | if (item.Category.ExcludeFromGoogleFeed) |
| | 0 | 191 | | continue; |
| | 0 | 192 | | if (!categoriesPath.ContainsKey((int)item.Category.Id)) |
| | 0 | 193 | | categoriesPath.Add((int)item.Category.Id, await _catService.GetPathToCategoryForFeed(item.Category.I |
| | 0 | 194 | | rows.Add($"{item.Id}\t\"{item.Name}\"\t{item.MainBarcode?.Code}\t\"{item.Name}\"\t{item.Category.GoogleP |
| | 0 | 195 | | $"{item.Brand.Name}\t{item.VendorCode}\tin_stock\tnew\t{item.Price.ToString(CultureInfo.GetCultureIn |
| | 0 | 196 | | } |
| | 0 | 197 | | byte[] dataAsBytes = rows.SelectMany(s => |
| | 0 | 198 | | System.Text.Encoding.UTF8.GetBytes(s + Environment.NewLine)).ToArray(); |
| | | 199 | | |
| | 0 | 200 | | using (Stream stream = new MemoryStream(dataAsBytes)) |
| | 0 | 201 | | { |
| | 0 | 202 | | using FileStream compressedFileStream = File.Create(Path.Combine(_uploadSettings.DownloadsSavePath, file |
| | 0 | 203 | | using GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress); |
| | 0 | 204 | | await stream.CopyToAsync(compressionStream); |
| | 0 | 205 | | } |
| | 0 | 206 | | return await File.ReadAllBytesAsync(Path.Combine(_uploadSettings.DownloadsSavePath, filename) + ".gz"); |
| | 0 | 207 | | } |
| | | 208 | | |
| | | 209 | | /// <summary> |
| | | 210 | | /// нормализует значение согласно правилам яндекса |
| | | 211 | | /// </summary> |
| | | 212 | | /// <param name="value">значение</param> |
| | | 213 | | /// <returns>нормализованное значение</returns> |
| | | 214 | | private string NormalizeStringValues(string value) |
| | 0 | 215 | | { |
| | 0 | 216 | | value = value.Replace("\"", """) |
| | 0 | 217 | | .Replace("&", "&") |
| | 0 | 218 | | .Replace(">", ">") |
| | 0 | 219 | | .Replace("<", "<") |
| | 0 | 220 | | .Replace("'", "'"); |
| | 0 | 221 | | return value; |
| | 0 | 222 | | } |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// нормализует срок годности (кол-во дней) согласно правилам яндекса |
| | | 226 | | /// </summary> |
| | | 227 | | /// <param name="value">кол-во дней</param> |
| | | 228 | | /// <returns>нормализованное значение в формате iso8601</returns> |
| | | 229 | | private string NormalizeExpireValues(int value) |
| | 0 | 230 | | { |
| | | 231 | | //срок годности должен быть формате iso8601. Например, P1Y2M10DT2H30M - 1год 2 мес 10 дней 2 часа 30 мин |
| | 0 | 232 | | string expire = "P"; |
| | 0 | 233 | | var years = (int)(value / 365.2425); |
| | 0 | 234 | | var months = (int)((value - years * 365.2425) / 30); |
| | 0 | 235 | | var days = (int)(value - years * 365.2425 - months * 30); |
| | 0 | 236 | | expire += years + "Y" + months + "M" + days + "DT0H00M"; |
| | 0 | 237 | | return expire; |
| | 0 | 238 | | } |
| | | 239 | | } |
| | | 240 | | } |