| | | 1 | | using System.Data.Common; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using OzonRepositories.Context; |
| | | 6 | | using Services.ApiServices.TelegramBotApi; |
| | | 7 | | |
| | | 8 | | namespace Services.BitrixStockServices; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Собирает итог наката остатков (по складам 1С) и активные остатки складов из выгрузки 1С |
| | | 12 | | /// и отправляет сводку в Telegram. Ошибки не пробрасывает: уведомление не должно ронять пайплайн. |
| | | 13 | | /// </summary> |
| | 2 | 14 | | public sealed class BitrixStockRolloutTelegramReporter( |
| | 2 | 15 | | IDbContextFactory<ApplicationDbContext> dbFactory, |
| | 2 | 16 | | ITelegramNotifier telegram, |
| | 2 | 17 | | TelegramBotConfig config, |
| | 2 | 18 | | ILogger<BitrixStockRolloutTelegramReporter>? logger = null) |
| | | 19 | | { |
| | | 20 | | /// <summary>Склады 1С, по которым в выгрузке есть колонка остатка (имя колонки — <c>{склад}Qty</c>).</summary> |
| | 0 | 21 | | private static readonly string[] KnownStores = ["B1", "B2", "M1", "M2", "M3"]; |
| | | 22 | | |
| | | 23 | | public async Task NotifyAsync(BitrixStockSyncReportRunDto run, CancellationToken ct = default) |
| | | 24 | | { |
| | 0 | 25 | | if (!telegram.IsConfigured || string.IsNullOrWhiteSpace(run.ReportId)) return; |
| | 0 | 26 | | if (!HasActivity(run)) return; |
| | | 27 | | |
| | | 28 | | try |
| | | 29 | | { |
| | 0 | 30 | | var summary = await BuildSummaryAsync(run, ct); |
| | 0 | 31 | | await telegram.SendAsync(TelegramMessageFactory.StockRollout(summary, config.SiteBaseUrl), ct); |
| | 0 | 32 | | } |
| | 0 | 33 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 34 | | { |
| | 0 | 35 | | throw; |
| | | 36 | | } |
| | 0 | 37 | | catch (Exception ex) |
| | | 38 | | { |
| | 0 | 39 | | logger?.LogWarning(ex, "Не удалось отправить итог наката остатков {ReportId} в Telegram", run.ReportId); |
| | 0 | 40 | | } |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <summary>Пайплайн прерван: этап, текст ошибки и частичные результаты (если отчёт уже есть). Не бросает исключени |
| | | 44 | | public async Task NotifyFailedAsync(string reportId, BitrixStockSyncReportRunDto? run, int failedStage, string error |
| | | 45 | | CancellationToken ct = default) |
| | | 46 | | { |
| | 2 | 47 | | if (!telegram.IsConfigured || string.IsNullOrWhiteSpace(reportId)) return; |
| | | 48 | | |
| | | 49 | | try |
| | | 50 | | { |
| | 2 | 51 | | TelegramRolloutSummary? partial = null; |
| | 2 | 52 | | if (run != null) |
| | | 53 | | { |
| | | 54 | | try |
| | | 55 | | { |
| | 0 | 56 | | partial = await BuildSummaryAsync(run, ct); |
| | 0 | 57 | | } |
| | 0 | 58 | | catch (Exception ex) when (ex is not OperationCanceledException) |
| | | 59 | | { |
| | 0 | 60 | | logger?.LogWarning(ex, "Не удалось собрать частичные результаты прерванного наката {ReportId}", repo |
| | 0 | 61 | | } |
| | | 62 | | } |
| | | 63 | | |
| | 2 | 64 | | await telegram.SendAsync(TelegramMessageFactory.StockRolloutFailed(reportId, partial, failedStage, error, co |
| | 2 | 65 | | } |
| | 0 | 66 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 67 | | { |
| | 0 | 68 | | throw; |
| | | 69 | | } |
| | 0 | 70 | | catch (Exception ex) |
| | | 71 | | { |
| | 0 | 72 | | logger?.LogWarning(ex, "Не удалось отправить сообщение о прерванном накате {ReportId} в Telegram", reportId) |
| | 0 | 73 | | } |
| | 2 | 74 | | } |
| | | 75 | | |
| | | 76 | | /// <summary>Прогон без наката, очистки, цен и сирот — нечего сообщать (почасовые «холостые» прогоны).</summary> |
| | | 77 | | public static bool HasActivity(BitrixStockSyncReportRunDto run) => |
| | 3 | 78 | | run.OzonAppliedSuccessCount + run.OzonApplyFailedCount + run.OzonCleanupSuccessCount + run.OzonCleanupFailedCoun |
| | 3 | 79 | | + run.PricePushCount + run.PricePushErrorCount + run.OrphansFound > 0; |
| | | 80 | | |
| | | 81 | | public async Task<TelegramRolloutSummary> BuildSummaryAsync(BitrixStockSyncReportRunDto run, CancellationToken ct = |
| | | 82 | | { |
| | 0 | 83 | | await using var db = await dbFactory.CreateDbContextAsync(ct); |
| | 0 | 84 | | await db.Database.OpenConnectionAsync(ct); |
| | | 85 | | try |
| | | 86 | | { |
| | 0 | 87 | | var conn = db.Database.GetDbConnection(); |
| | 0 | 88 | | var stores = await LoadStoreRowsAsync(conn, run.ReportId!, ct); |
| | 0 | 89 | | var participating = await LoadParticipatingStoresAsync(conn, run, stores, ct); |
| | 0 | 90 | | var (stock, asOf) = await LoadActiveStockAsync(conn, participating, ct); |
| | 0 | 91 | | var ozonStock = await OzonWarehouseStockQuery.LoadAsync(conn, run.ReportId!, ct); |
| | | 92 | | |
| | 0 | 93 | | var client = run.MultiClientNames is { Count: > 0 } |
| | 0 | 94 | | ? string.Join(", ", run.MultiClientNames) |
| | 0 | 95 | | : run.OzonClientName ?? $"ID {run.OzonClientId}"; |
| | | 96 | | |
| | 0 | 97 | | return new TelegramRolloutSummary( |
| | 0 | 98 | | run.ReportId!, client, run.CompletedAtUtc ?? run.GeneratedAtUtc, run.ProductsInReport, stores, |
| | 0 | 99 | | run.OzonCleanupSuccessCount, run.OzonCleanupFailedCount, |
| | 0 | 100 | | run.PricePushCount, run.PricePushUnchangedCount, run.PricePushErrorCount, |
| | 0 | 101 | | run.OrphansFound, run.OrphansZeroed, stock, asOf, ozonStock); |
| | | 102 | | } |
| | | 103 | | finally |
| | | 104 | | { |
| | 0 | 105 | | await db.Database.CloseConnectionAsync(); |
| | | 106 | | } |
| | 0 | 107 | | } |
| | | 108 | | |
| | | 109 | | /// <summary>Применённое в Ozon по складам 1С: Push — добавлено, Decrease — убавлено, Clear — обнулено.</summary> |
| | | 110 | | private static async Task<List<TelegramRolloutStoreRow>> LoadStoreRowsAsync(DbConnection conn, string reportId, Canc |
| | | 111 | | { |
| | 0 | 112 | | await using var cmd = conn.CreateCommand(); |
| | 0 | 113 | | cmd.CommandText = @"SELECT OneCStore, Action, OzonApplyStatus, COUNT(*) |
| | 0 | 114 | | FROM BitrixStockSyncReportLines |
| | 0 | 115 | | WHERE ReportId = @rid AND Action IN ('Push','Decrease','Clear','ClearDisabledLink') AND OzonApplyStatus IS NOT NULL |
| | 0 | 116 | | GROUP BY OneCStore, Action, OzonApplyStatus"; |
| | 0 | 117 | | AddParam(cmd, "@rid", reportId); |
| | | 118 | | |
| | 0 | 119 | | var map = new SortedDictionary<string, int[]>(StringComparer.OrdinalIgnoreCase); // added, decreased, cleared, f |
| | 0 | 120 | | await using var reader = await cmd.ExecuteReaderAsync(ct); |
| | 0 | 121 | | while (await reader.ReadAsync(ct)) |
| | | 122 | | { |
| | 0 | 123 | | var store = reader.GetString(0); |
| | 0 | 124 | | var action = reader.GetString(1); |
| | 0 | 125 | | var status = reader.GetString(2); |
| | 0 | 126 | | var count = Convert.ToInt32(reader.GetValue(3)); |
| | 0 | 127 | | if (!map.TryGetValue(store, out var row)) map[store] = row = new int[4]; |
| | | 128 | | |
| | 0 | 129 | | if (status == BitrixStockSyncReportApplyStatuses.Failed) row[3] += count; |
| | 0 | 130 | | else if (status == BitrixStockSyncReportApplyStatuses.Success) |
| | | 131 | | { |
| | 0 | 132 | | if (action == BitrixStockSyncReportActions.Push) row[0] += count; |
| | 0 | 133 | | else if (action == BitrixStockSyncReportActions.Decrease) row[1] += count; |
| | 0 | 134 | | else row[2] += count; |
| | | 135 | | } |
| | | 136 | | } |
| | | 137 | | |
| | 0 | 138 | | return map.Select(x => new TelegramRolloutStoreRow(x.Key, x.Value[0], x.Value[1], x.Value[2], x.Value[3])).ToLis |
| | 0 | 139 | | } |
| | | 140 | | |
| | | 141 | | /// <summary>Склады, участвующие в обработке: из настроек пресетов, склады самого отчёта и склады из его строк.</sum |
| | | 142 | | private static async Task<List<string>> LoadParticipatingStoresAsync(DbConnection conn, BitrixStockSyncReportRunDto |
| | | 143 | | IReadOnlyList<TelegramRolloutStoreRow> rolled, CancellationToken ct) |
| | | 144 | | { |
| | 0 | 145 | | var stores = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | | 146 | | void AddJson(string? json) |
| | | 147 | | { |
| | 0 | 148 | | if (string.IsNullOrWhiteSpace(json)) return; |
| | | 149 | | try |
| | | 150 | | { |
| | 0 | 151 | | foreach (var s in JsonSerializer.Deserialize<List<string>>(json) ?? []) stores.Add(s.Trim()); |
| | 0 | 152 | | } |
| | 0 | 153 | | catch (JsonException) |
| | | 154 | | { |
| | | 155 | | // Некорректный JSON в настройках не должен ломать сводку. |
| | 0 | 156 | | } |
| | 0 | 157 | | } |
| | | 158 | | |
| | 0 | 159 | | AddJson(run.SelectedStores); |
| | 0 | 160 | | foreach (var r in rolled) stores.Add(r.Store); |
| | | 161 | | |
| | 0 | 162 | | await using var cmd = conn.CreateCommand(); |
| | 0 | 163 | | cmd.CommandText = "SELECT SelectedStoresJson FROM BitrixStockSyncPresets"; |
| | 0 | 164 | | await using var reader = await cmd.ExecuteReaderAsync(ct); |
| | 0 | 165 | | while (await reader.ReadAsync(ct)) AddJson(reader.IsDBNull(0) ? null : reader.GetString(0)); |
| | | 166 | | |
| | 0 | 167 | | return KnownStores.Where(stores.Contains).ToList(); |
| | 0 | 168 | | } |
| | | 169 | | |
| | | 170 | | /// <summary>Активные остатки по складам из последней выгрузки 1С: позиции листа склада с остатком > 0.</summary> |
| | | 171 | | private static async Task<(List<TelegramStoreStockRow> Rows, DateTime? AsOfUtc)> LoadActiveStockAsync( |
| | | 172 | | DbConnection conn, IReadOnlyList<string> stores, CancellationToken ct) |
| | | 173 | | { |
| | 0 | 174 | | var rows = new List<TelegramStoreStockRow>(); |
| | 0 | 175 | | DateTime? asOf = null; |
| | 0 | 176 | | foreach (var store in stores) |
| | | 177 | | { |
| | | 178 | | // Имя колонки берётся только из белого списка KnownStores — подстановка безопасна. |
| | 0 | 179 | | await using var cmd = conn.CreateCommand(); |
| | 0 | 180 | | cmd.CommandText = $@"SELECT COUNT(*), COALESCE(SUM({store}Qty), 0), MAX(SyncedAtUtc) |
| | 0 | 181 | | FROM WarehouseStockSnapshot |
| | 0 | 182 | | WHERE SyncRunId = (SELECT MAX(SyncRunId) FROM WarehouseStockSnapshot) AND Warehouse = @store AND {store}Qty > 0"; |
| | 0 | 183 | | AddParam(cmd, "@store", store); |
| | | 184 | | |
| | 0 | 185 | | await using var reader = await cmd.ExecuteReaderAsync(ct); |
| | 0 | 186 | | if (!await reader.ReadAsync(ct)) continue; |
| | 0 | 187 | | rows.Add(new TelegramStoreStockRow(store, Convert.ToInt32(reader.GetValue(0)), Convert.ToDecimal(reader.GetV |
| | 0 | 188 | | if (!reader.IsDBNull(2)) |
| | | 189 | | { |
| | 0 | 190 | | var synced = reader.GetDateTime(2); |
| | 0 | 191 | | if (asOf == null || synced > asOf) asOf = synced; |
| | | 192 | | } |
| | 0 | 193 | | } |
| | | 194 | | |
| | 0 | 195 | | return (rows, asOf); |
| | 0 | 196 | | } |
| | | 197 | | |
| | | 198 | | private static void AddParam(DbCommand command, string name, object? value) |
| | | 199 | | { |
| | 0 | 200 | | var parameter = command.CreateParameter(); |
| | 0 | 201 | | parameter.ParameterName = name; |
| | 0 | 202 | | parameter.Value = value ?? DBNull.Value; |
| | 0 | 203 | | command.Parameters.Add(parameter); |
| | 0 | 204 | | } |
| | | 205 | | } |