| | | 1 | | using Microsoft.AspNetCore.Mvc; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | using OzonDomains.Models.Authorization; |
| | | 4 | | using OzonOrdersWeb.Areas.Admin.Models; |
| | | 5 | | using OzonOrdersWeb.Areas.Admin.Services; |
| | | 6 | | using OzonRepositories.Context; |
| | | 7 | | using Services.ApiServices._1CApi; |
| | | 8 | | using Services.Authorization.Services; |
| | | 9 | | using System.Globalization; |
| | | 10 | | using System.Linq.Dynamic.Core; |
| | | 11 | | using Services.ApiServices; |
| | | 12 | | |
| | | 13 | | namespace OzonOrdersWeb.Areas.Admin.Controllers; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// CRUD наборов данных (RLS, row-level security) с валидацией Dynamic LINQ выражений. |
| | | 17 | | /// </summary> |
| | | 18 | | public class DataScopesController : AdminAreaControllerBase |
| | | 19 | | { |
| | | 20 | | private readonly ApplicationDbContext _db; |
| | | 21 | | private readonly IPermissionService _permissions; |
| | | 22 | | private readonly DataScopeFilterSummaryService _filterSummary; |
| | | 23 | | private readonly OneCDataManager _oneCDataManager; |
| | | 24 | | |
| | 0 | 25 | | public DataScopesController( |
| | 0 | 26 | | ApplicationDbContext db, |
| | 0 | 27 | | IPermissionService permissions, |
| | 0 | 28 | | DataScopeFilterSummaryService filterSummary, |
| | 0 | 29 | | OneCDataManager oneCDataManager) |
| | | 30 | | { |
| | 0 | 31 | | _db = db; |
| | 0 | 32 | | _permissions = permissions; |
| | 0 | 33 | | _filterSummary = filterSummary; |
| | 0 | 34 | | _oneCDataManager = oneCDataManager; |
| | 0 | 35 | | } |
| | | 36 | | |
| | | 37 | | public async Task<IActionResult> Index(CancellationToken ct) |
| | | 38 | | { |
| | 0 | 39 | | ViewData["Title"] = "Наборы данных"; |
| | 0 | 40 | | ViewData["Breadcrumb"] = new List<(string, string?)> { ("Админка", Url.Action("Index", "Home")), ("Наборы данных |
| | 0 | 41 | | var list = await _db.DataScopes |
| | 0 | 42 | | .OrderBy(s => s.EntityName).ThenBy(s => s.Code) |
| | 0 | 43 | | .Select(s => new DataScopeListItemVm |
| | 0 | 44 | | { |
| | 0 | 45 | | Id = s.Id, Code = s.Code, DisplayName = s.DisplayName, |
| | 0 | 46 | | EntityName = s.EntityName, FilterExpression = s.FilterExpression, IsActive = s.IsActive, |
| | 0 | 47 | | }) |
| | 0 | 48 | | .ToListAsync(ct); |
| | 0 | 49 | | await _filterSummary.PopulateFilterSummariesAsync(list, ct); |
| | 0 | 50 | | return View(list); |
| | 0 | 51 | | } |
| | | 52 | | |
| | | 53 | | [HttpGet] |
| | | 54 | | public IActionResult Create() |
| | | 55 | | { |
| | 0 | 56 | | ViewData["Title"] = "Новый набор данных"; |
| | 0 | 57 | | return View("Edit", new DataScopeEditVm { IsActive = true }); |
| | | 58 | | } |
| | | 59 | | |
| | | 60 | | [HttpPost] |
| | | 61 | | [ValidateAntiForgeryToken] |
| | | 62 | | public async Task<IActionResult> Create(DataScopeEditVm model, CancellationToken ct) |
| | | 63 | | { |
| | 0 | 64 | | if (await _db.DataScopes.AnyAsync(s => s.Code == model.Code, ct)) |
| | 0 | 65 | | ModelState.AddModelError(nameof(model.Code), "Набор с таким кодом уже существует"); |
| | 0 | 66 | | ValidateExpression(model.FilterExpression); |
| | 0 | 67 | | if (!ModelState.IsValid) return View("Edit", model); |
| | | 68 | | |
| | 0 | 69 | | _db.DataScopes.Add(Apply(new DataScope(), model)); |
| | 0 | 70 | | await _db.SaveChangesAsync(ct); |
| | 0 | 71 | | _permissions.InvalidateAll(); |
| | 0 | 72 | | TempData["SuccessMessage"] = "Набор данных создан"; |
| | 0 | 73 | | return RedirectToAction(nameof(Index)); |
| | 0 | 74 | | } |
| | | 75 | | |
| | | 76 | | [HttpGet] |
| | | 77 | | public async Task<IActionResult> Edit(int id, CancellationToken ct) |
| | | 78 | | { |
| | 0 | 79 | | var s = await _db.DataScopes.FirstOrDefaultAsync(x => x.Id == id, ct); |
| | 0 | 80 | | if (s == null) return NotFound(); |
| | 0 | 81 | | ViewData["Title"] = $"Набор: {s.DisplayName}"; |
| | 0 | 82 | | return View(new DataScopeEditVm |
| | 0 | 83 | | { |
| | 0 | 84 | | Id = s.Id, Code = s.Code, DisplayName = s.DisplayName, EntityName = s.EntityName, |
| | 0 | 85 | | FilterExpression = s.FilterExpression, Description = s.Description, IsActive = s.IsActive, |
| | 0 | 86 | | }); |
| | 0 | 87 | | } |
| | | 88 | | |
| | | 89 | | [HttpPost] |
| | | 90 | | [ValidateAntiForgeryToken] |
| | | 91 | | public async Task<IActionResult> Edit(int id, DataScopeEditVm model, CancellationToken ct) |
| | | 92 | | { |
| | 0 | 93 | | var s = await _db.DataScopes.FirstOrDefaultAsync(x => x.Id == id, ct); |
| | 0 | 94 | | if (s == null) return NotFound(); |
| | 0 | 95 | | ValidateExpression(model.FilterExpression); |
| | 0 | 96 | | if (!ModelState.IsValid) return View(model); |
| | 0 | 97 | | Apply(s, model); |
| | 0 | 98 | | s.UpdatedAt = DateTime.UtcNow; |
| | 0 | 99 | | await _db.SaveChangesAsync(ct); |
| | 0 | 100 | | _permissions.InvalidateAll(); |
| | 0 | 101 | | TempData["SuccessMessage"] = "Сохранено"; |
| | 0 | 102 | | return RedirectToAction(nameof(Index)); |
| | 0 | 103 | | } |
| | | 104 | | |
| | | 105 | | [HttpPost] |
| | | 106 | | [ValidateAntiForgeryToken] |
| | | 107 | | public async Task<IActionResult> Delete(int id, CancellationToken ct) |
| | | 108 | | { |
| | 0 | 109 | | var s = await _db.DataScopes.FirstOrDefaultAsync(x => x.Id == id, ct); |
| | 0 | 110 | | if (s == null) return NotFound(); |
| | 0 | 111 | | _db.DataScopes.Remove(s); |
| | 0 | 112 | | await _db.SaveChangesAsync(ct); |
| | 0 | 113 | | _permissions.InvalidateAll(); |
| | 0 | 114 | | TempData["SuccessMessage"] = "Удалено"; |
| | 0 | 115 | | return RedirectToAction(nameof(Index)); |
| | 0 | 116 | | } |
| | | 117 | | |
| | | 118 | | // ===== Создание DataScope из готовых шаблонов ===== |
| | | 119 | | |
| | | 120 | | [HttpGet] |
| | | 121 | | public IActionResult Templates() |
| | | 122 | | { |
| | 0 | 123 | | ViewData["Title"] = "Новый набор из шаблона"; |
| | 0 | 124 | | ViewData["Breadcrumb"] = new List<(string, string?)> |
| | 0 | 125 | | { |
| | 0 | 126 | | ("Админка", Url.Action("Index", "Home")), |
| | 0 | 127 | | ("Наборы данных", Url.Action(nameof(Index))), |
| | 0 | 128 | | ("Из шаблона", null) |
| | 0 | 129 | | }; |
| | 0 | 130 | | return View(DataScopeTemplateRegistry.All); |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | [HttpGet] |
| | | 134 | | public async Task<IActionResult> FromTemplate(string key, CancellationToken ct) |
| | | 135 | | { |
| | 0 | 136 | | var tpl = DataScopeTemplateRegistry.GetByKey(key); |
| | 0 | 137 | | if (tpl is null) return NotFound(); |
| | | 138 | | |
| | 0 | 139 | | var items = await LoadTemplateItemsAsync(tpl, ct); |
| | 0 | 140 | | ViewData["Title"] = tpl.DisplayName; |
| | 0 | 141 | | ViewData["Breadcrumb"] = new List<(string, string?)> |
| | 0 | 142 | | { |
| | 0 | 143 | | ("Админка", Url.Action("Index", "Home")), |
| | 0 | 144 | | ("Наборы данных", Url.Action(nameof(Index))), |
| | 0 | 145 | | ("Из шаблона", Url.Action(nameof(Templates))), |
| | 0 | 146 | | (tpl.DisplayName, null) |
| | 0 | 147 | | }; |
| | | 148 | | |
| | 0 | 149 | | var vm = new DataScopeFromTemplateVm |
| | 0 | 150 | | { |
| | 0 | 151 | | TemplateKey = tpl.Key, |
| | 0 | 152 | | EntityName = tpl.EntityName, |
| | 0 | 153 | | FkField = tpl.FkField, |
| | 0 | 154 | | TemplateDisplayName = tpl.DisplayName, |
| | 0 | 155 | | TemplateIcon = tpl.Icon, |
| | 0 | 156 | | TemplateDescription = tpl.Description, |
| | 0 | 157 | | Items = items, |
| | 0 | 158 | | IsRangeTemplate = tpl.Kind == DataScopeTemplateKind.Range, |
| | 0 | 159 | | RangeIsDecimal = tpl.RangeIsDecimal, |
| | 0 | 160 | | Code = SuggestCode(tpl.Key), |
| | 0 | 161 | | DisplayName = tpl.DisplayName, |
| | 0 | 162 | | IsActive = true, |
| | 0 | 163 | | }; |
| | 0 | 164 | | return View(vm); |
| | 0 | 165 | | } |
| | | 166 | | |
| | | 167 | | [HttpPost] |
| | | 168 | | [ValidateAntiForgeryToken] |
| | | 169 | | public async Task<IActionResult> FromTemplate(DataScopeFromTemplateVm model, CancellationToken ct) |
| | | 170 | | { |
| | 0 | 171 | | var tpl = DataScopeTemplateRegistry.GetByKey(model.TemplateKey); |
| | 0 | 172 | | if (tpl is null) return NotFound(); |
| | | 173 | | |
| | 0 | 174 | | model.Items = await LoadTemplateItemsAsync(tpl, ct); |
| | 0 | 175 | | model.EntityName = tpl.EntityName; |
| | 0 | 176 | | model.FkField = tpl.FkField; |
| | 0 | 177 | | model.TemplateDisplayName = tpl.DisplayName; |
| | 0 | 178 | | model.TemplateIcon = tpl.Icon; |
| | 0 | 179 | | model.TemplateDescription = tpl.Description; |
| | 0 | 180 | | model.IsRangeTemplate = tpl.Kind == DataScopeTemplateKind.Range; |
| | 0 | 181 | | model.RangeIsDecimal = tpl.RangeIsDecimal; |
| | | 182 | | |
| | 0 | 183 | | if (string.IsNullOrWhiteSpace(model.Code)) |
| | 0 | 184 | | ModelState.AddModelError(nameof(model.Code), "Укажите код набора"); |
| | 0 | 185 | | if (string.IsNullOrWhiteSpace(model.DisplayName)) |
| | 0 | 186 | | ModelState.AddModelError(nameof(model.DisplayName), "Укажите название набора"); |
| | 0 | 187 | | if (await _db.DataScopes.AnyAsync(s => s.Code == model.Code, ct)) |
| | 0 | 188 | | ModelState.AddModelError(nameof(model.Code), "Набор с таким кодом уже существует"); |
| | | 189 | | |
| | | 190 | | string expression; |
| | 0 | 191 | | if (tpl.Kind == DataScopeTemplateKind.Range) |
| | | 192 | | { |
| | 0 | 193 | | if (!model.MinValue.HasValue && !model.MaxValue.HasValue) |
| | | 194 | | { |
| | 0 | 195 | | ModelState.AddModelError(nameof(model.MinValue), "Укажите минимум и/или максимум"); |
| | | 196 | | } |
| | 0 | 197 | | else if (model.MinValue.HasValue && model.MaxValue.HasValue && model.MinValue.Value > model.MaxValue.Value) |
| | | 198 | | { |
| | 0 | 199 | | ModelState.AddModelError(nameof(model.MaxValue), "Минимум не может быть больше максимума"); |
| | | 200 | | } |
| | 0 | 201 | | if (!tpl.RangeIsDecimal) |
| | | 202 | | { |
| | 0 | 203 | | if (model.MinValue.HasValue && model.MinValue.Value != Math.Truncate(model.MinValue.Value)) |
| | 0 | 204 | | ModelState.AddModelError(nameof(model.MinValue), "Для количества укажите целое число"); |
| | 0 | 205 | | if (model.MaxValue.HasValue && model.MaxValue.Value != Math.Truncate(model.MaxValue.Value)) |
| | 0 | 206 | | ModelState.AddModelError(nameof(model.MaxValue), "Для количества укажите целое число"); |
| | | 207 | | } |
| | 0 | 208 | | if (!ModelState.IsValid) return View(model); |
| | 0 | 209 | | expression = BuildRangeExpression(tpl.FkField, tpl.RangeIsDecimal, model.MinValue, model.MaxValue); |
| | | 210 | | } |
| | | 211 | | else |
| | | 212 | | { |
| | 0 | 213 | | if (model.SelectedIds is null || model.SelectedIds.Length == 0) |
| | 0 | 214 | | ModelState.AddModelError(nameof(model.SelectedIds), "Выберите хотя бы одно значение"); |
| | 0 | 215 | | if (!ModelState.IsValid) return View(model); |
| | 0 | 216 | | expression = BuildInExpression(tpl.FkField, model.SelectedIds!); |
| | | 217 | | } |
| | | 218 | | |
| | 0 | 219 | | _db.DataScopes.Add(new DataScope |
| | 0 | 220 | | { |
| | 0 | 221 | | Code = model.Code.Trim(), |
| | 0 | 222 | | DisplayName = model.DisplayName.Trim(), |
| | 0 | 223 | | EntityName = tpl.EntityName, |
| | 0 | 224 | | FilterExpression = expression, |
| | 0 | 225 | | Description = string.IsNullOrWhiteSpace(model.Description) |
| | 0 | 226 | | ? BuildTemplateDescription(tpl, model) |
| | 0 | 227 | | : model.Description, |
| | 0 | 228 | | IsActive = model.IsActive, |
| | 0 | 229 | | }); |
| | 0 | 230 | | await _db.SaveChangesAsync(ct); |
| | 0 | 231 | | _permissions.InvalidateAll(); |
| | 0 | 232 | | TempData["SuccessMessage"] = "Набор данных создан из шаблона"; |
| | 0 | 233 | | return RedirectToAction(nameof(Index)); |
| | 0 | 234 | | } |
| | | 235 | | |
| | | 236 | | private static string BuildRangeExpression(string field, bool isDecimal, decimal? min, decimal? max) |
| | | 237 | | { |
| | 0 | 238 | | if (!min.HasValue && !max.HasValue) return "false"; |
| | 0 | 239 | | if (min.HasValue && max.HasValue && min.Value > max.Value) return "false"; |
| | | 240 | | |
| | 0 | 241 | | var inv = CultureInfo.InvariantCulture; |
| | 0 | 242 | | var parts = new List<string> { $"{field} != null" }; |
| | 0 | 243 | | if (isDecimal) |
| | | 244 | | { |
| | 0 | 245 | | if (min.HasValue) parts.Add($"{field} >= {min.Value.ToString(inv)}"); |
| | 0 | 246 | | if (max.HasValue) parts.Add($"{field} <= {max.Value.ToString(inv)}"); |
| | | 247 | | } |
| | | 248 | | else |
| | | 249 | | { |
| | 0 | 250 | | if (min.HasValue) parts.Add($"{field} >= {(long)Math.Truncate(min.Value)}"); |
| | 0 | 251 | | if (max.HasValue) parts.Add($"{field} <= {(long)Math.Truncate(max.Value)}"); |
| | | 252 | | } |
| | | 253 | | |
| | 0 | 254 | | return "(" + string.Join(" && ", parts) + ")"; |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | private async Task<List<DataScopeLookupItem>> LoadTemplateItemsAsync(DataScopeTemplate tpl, CancellationToken ct) |
| | | 258 | | { |
| | 0 | 259 | | if (string.Equals(tpl.Key, "bitrix-warehouse", StringComparison.OrdinalIgnoreCase)) |
| | | 260 | | { |
| | 0 | 261 | | var bitrixWarehouses = await _oneCDataManager.GetWarehouseListAsync(); |
| | 0 | 262 | | return bitrixWarehouses |
| | 0 | 263 | | .Select(x => x.Name?.Trim()) |
| | 0 | 264 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 0 | 265 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 266 | | .OrderBy(x => x) |
| | 0 | 267 | | .Select(x => new DataScopeLookupItem(x!, x!)) |
| | 0 | 268 | | .ToList(); |
| | | 269 | | } |
| | | 270 | | |
| | 0 | 271 | | return await tpl.LoadItems(_db, ct); |
| | 0 | 272 | | } |
| | | 273 | | |
| | | 274 | | private static string BuildTemplateDescription(DataScopeTemplate tpl, DataScopeFromTemplateVm model) |
| | | 275 | | { |
| | 0 | 276 | | if (tpl.Kind == DataScopeTemplateKind.Range) |
| | | 277 | | { |
| | 0 | 278 | | var inv = CultureInfo.InvariantCulture; |
| | 0 | 279 | | var bits = new List<string>(); |
| | 0 | 280 | | if (model.MinValue.HasValue) bits.Add($"от {model.MinValue.Value.ToString(inv)}"); |
| | 0 | 281 | | if (model.MaxValue.HasValue) bits.Add($"до {model.MaxValue.Value.ToString(inv)}"); |
| | 0 | 282 | | return $"Шаблон: {tpl.DisplayName}. {tpl.FkField}: {string.Join(", ", bits)}."; |
| | | 283 | | } |
| | | 284 | | |
| | 0 | 285 | | return $"Шаблон: {tpl.DisplayName}. Значений: {model.SelectedIds?.Length ?? 0}."; |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | private static string BuildInExpression(string fkField, IEnumerable<string> ids) |
| | | 289 | | { |
| | 0 | 290 | | var sanitized = ids |
| | 0 | 291 | | .Where(s => !string.IsNullOrWhiteSpace(s)) |
| | 0 | 292 | | .Select(s => s.Trim()) |
| | 0 | 293 | | .Distinct() |
| | 0 | 294 | | .ToList(); |
| | | 295 | | |
| | 0 | 296 | | if (sanitized.Count == 0) return "false"; |
| | | 297 | | |
| | 0 | 298 | | var allNumeric = sanitized.All(s => long.TryParse(s, out _)); |
| | 0 | 299 | | var parts = sanitized.Select(v => allNumeric |
| | 0 | 300 | | ? $"{fkField} == {v}" |
| | 0 | 301 | | : $"{fkField} == \"{v.Replace("\"", "\\\"")}\""); |
| | 0 | 302 | | return "(" + string.Join(" || ", parts) + ")"; |
| | | 303 | | } |
| | | 304 | | |
| | | 305 | | private string SuggestCode(string templateKey) |
| | | 306 | | { |
| | 0 | 307 | | var baseCode = templateKey.ToLowerInvariant(); |
| | 0 | 308 | | var code = baseCode; |
| | 0 | 309 | | var i = 2; |
| | 0 | 310 | | while (_db.DataScopes.Any(s => s.Code == code)) |
| | 0 | 311 | | code = $"{baseCode}-{i++}"; |
| | 0 | 312 | | return code; |
| | | 313 | | } |
| | | 314 | | |
| | | 315 | | /// <summary>AJAX-тестирование Dynamic LINQ выражения (синтаксическая проверка без выполнения).</summary> |
| | | 316 | | [HttpPost] |
| | | 317 | | [ValidateAntiForgeryToken] |
| | | 318 | | public IActionResult TestExpression([FromForm] string expression) |
| | | 319 | | { |
| | | 320 | | try |
| | | 321 | | { |
| | 0 | 322 | | var data = new List<object>().AsQueryable(); |
| | 0 | 323 | | var userId = "test-user"; |
| | 0 | 324 | | var userName = "test"; |
| | 0 | 325 | | var tokens = ReplaceTokens(expression, userId, userName); |
| | | 326 | | _ = tokens; |
| | 0 | 327 | | return Json(new { ok = true, message = "Выражение синтаксически корректно. Параметры: @userId, @userName." } |
| | | 328 | | } |
| | 0 | 329 | | catch (Exception ex) |
| | | 330 | | { |
| | 0 | 331 | | return Json(new { ok = false, message = ex.Message }); |
| | | 332 | | } |
| | 0 | 333 | | } |
| | | 334 | | |
| | | 335 | | private static string ReplaceTokens(string expr, string userId, string userName) |
| | | 336 | | { |
| | 0 | 337 | | return expr |
| | 0 | 338 | | .Replace("@userId", $"\"{userId}\"") |
| | 0 | 339 | | .Replace("@userName", $"\"{userName}\""); |
| | | 340 | | } |
| | | 341 | | |
| | | 342 | | private void ValidateExpression(string expr) |
| | | 343 | | { |
| | 0 | 344 | | if (string.IsNullOrWhiteSpace(expr)) { ModelState.AddModelError(nameof(DataScopeEditVm.FilterExpression), "Выраж |
| | 0 | 345 | | } |
| | | 346 | | |
| | | 347 | | private static DataScope Apply(DataScope target, DataScopeEditVm vm) |
| | | 348 | | { |
| | 0 | 349 | | target.Code = vm.Code.Trim(); |
| | 0 | 350 | | target.DisplayName = vm.DisplayName.Trim(); |
| | 0 | 351 | | target.EntityName = vm.EntityName.Trim(); |
| | 0 | 352 | | target.FilterExpression = vm.FilterExpression.Trim(); |
| | 0 | 353 | | target.Description = vm.Description; |
| | 0 | 354 | | target.IsActive = vm.IsActive; |
| | 0 | 355 | | return target; |
| | | 356 | | } |
| | | 357 | | } |