EndpointExtensions.cs 44.2 KB
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using RobotProductionSystem.Api.Contracts;
using RobotProductionSystem.Api.Domain;
using RobotProductionSystem.Api.Infrastructure;
using RobotProductionSystem.Api.Services;

namespace RobotProductionSystem.Api.Endpoints;

public static class EndpointExtensions
{
    public static void MapRobotApi(this WebApplication app)
    {
        app.MapModule("");
        app.MapModule("/api");
    }

    private static void MapModule(this WebApplication app, string prefix)
    {
        MapAuth(app, prefix);
        MapBaseInfo(app, prefix);
        MapWorkOrders(app, prefix);
        MapSn(app, prefix);
        MapOperations(app, prefix);
        MapDashboard(app, prefix);
        MapSettings(app, prefix);
        MapShell(app, prefix);
    }

    private static string? Text(string? value)
    {
        var trimmed = value?.Trim();
        return string.IsNullOrWhiteSpace(trimmed) ? null : trimmed;
    }

    private static string NewId(string prefix) => $"{prefix}-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}-{Guid.NewGuid():N}"[..Math.Min(prefix.Length + 1 + 13 + 1 + 12, prefix.Length + 27)];
    private static DateTimeOffset Now() => DateTimeOffset.UtcNow;
    private static bool ContainsCi(string source, string? value) => Text(value) is not { } text || source.ToLower().Contains(text.ToLower());
    private static object Fail(string code, string message) => new { Success = false, ErrorCode = code, Message = message };
    private static object OkMutation(string message, object? extra = null) => extra is null ? new { Success = true, ErrorCode = (string?)null, Message = message } : extra;
    private static string BuildSnOperationReason(string action, OperationActionPayload payload)
    {
        var remark = Text(payload.Remark);
        if (action == "submit_test" && payload.TestPassed is not null)
        {
            var testResult = payload.TestPassed.Value ? "通过" : "失败";
            return remark is null
                ? $"工序执行:{action}(测试{testResult})"
                : $"工序执行:{action}(测试{testResult});备注:{remark}";
        }

        return remark is null
            ? $"工序执行:{action}"
            : $"工序执行:{action};备注:{remark}";
    }

    private static bool TryResolveOperationStep(OperationActionPayload payload, out ProcessStep step, out string? error)
    {
        error = null;
        step = ProcessStep.Unknown;

        if (Text(payload.StepName) is { } stepText)
        {
            if (!ProcessStepMapper.TryParse(stepText, out step))
            {
                error = "工序参数不正确。";
                return false;
            }

            return true;
        }

        if (Text(payload.Workstation) is not { } workstation)
        {
            return true;
        }

        if (!TryInferStepFromWorkstation(workstation, out step))
        {
            error = "工位编码无法识别对应工序。";
            return false;
        }

        return true;
    }

    private static bool TryInferStepFromWorkstation(string workstation, out ProcessStep step)
    {
        step = ProcessStep.Unknown;
        var key = workstation.Trim().ToUpperInvariant();
        if (key.Length == 0)
        {
            return false;
        }

        step = key[0] switch
        {
            'A' => ProcessStep.Assembly,
            'D' => ProcessStep.Debug,
            'T' => ProcessStep.Testing,
            'Q' => ProcessStep.FinalInspection,
            'R' => ProcessStep.Rework,
            'W' => ProcessStep.Warehousing,
            _ => ProcessStep.Unknown
        };
        return step != ProcessStep.Unknown;
    }

    private static ProcessStep ResolveStepFromAction(string action, ProcessStep currentStep, bool? testPassed)
    {
        if (action == "complete_assembly")
        {
            return ProcessStep.Testing;
        }

        if (action == "complete_rework")
        {
            return ProcessStep.Testing;
        }

        if (action == "submit_test")
        {
            return testPassed == true ? ProcessStep.FinalInspection : ProcessStep.Rework;
        }

        return currentStep;
    }

    private static void MapAuth(WebApplication app, string prefix)
    {
        app.MapPost($"{prefix}/auth/login", async (LoginRequest request, AppDbContext db, JwtTokenService jwt) =>
        {
            var username = Text(request.Username);
            var password = Text(request.Password);
            if (username is null || password is null)
            {
                return Results.Ok(new LoginResponse(false, "failed", "retry", "VALIDATION_ERROR", "用户名和密码不能为空。"));
            }

            var user = await db.Users.Include(x => x.Roles).FirstOrDefaultAsync(x => x.Username == username);
            if (user is null || !PasswordHasher.Verify(password, user.PasswordHash))
            {
                return Results.Ok(new LoginResponse(false, "failed", "retry", "INVALID_CREDENTIALS", "用户名或密码错误。"));
            }

            var issued = jwt.Issue(user);
            return Results.Ok(new LoginResponse(true, "authenticated", "enter_dashboard", null, "登录成功。", issued.Token, issued.ExpiresAt.ToString("O"), ApiMapper.ToAuthUser(user)));
        });

        app.MapGet($"{prefix}/auth/me", async (HttpContext http, AppDbContext db, IOptions<JwtOptions> options) =>
        {
            var authorization = http.Request.Headers.Authorization.ToString();
            var parts = authorization.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length != 2 || !string.Equals(parts[0], "Bearer", StringComparison.OrdinalIgnoreCase))
            {
                return Results.Ok(new MeResponse(false, "failed", "relogin", "TOKEN_MISSING", "未提供有效 token。"));
            }

            try
            {
                var jwtOptions = options.Value;
                var principal = new JwtSecurityTokenHandler().ValidateToken(parts[1], new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtOptions.Issuer,
                    ValidAudience = jwtOptions.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Secret)),
                    ClockSkew = TimeSpan.FromSeconds(30)
                }, out var validatedToken);

                var username = principal.FindFirstValue("username");
                var user = await db.Users.Include(x => x.Roles).FirstOrDefaultAsync(x => x.Username == username);
                return user is null
                    ? Results.Ok(new MeResponse(false, "failed", "relogin", "TOKEN_INVALID", "token 无效。"))
                    : Results.Ok(new MeResponse(true, "authenticated", "continue", null, "token 校验通过。", ApiMapper.ToAuthUser(user), ((JwtSecurityToken)validatedToken).ValidTo.ToString("O")));
            }
            catch (SecurityTokenExpiredException)
            {
                return Results.Ok(new MeResponse(false, "failed", "relogin", "TOKEN_EXPIRED", "token 已过期。"));
            }
            catch
            {
                return Results.Ok(new MeResponse(false, "failed", "relogin", "TOKEN_INVALID", "token 无效。"));
            }
        });
    }

    private static void MapBaseInfo(WebApplication app, string prefix)
    {
        app.MapGet($"{prefix}/base-info/device-types", async (AppDbContext db) =>
            await db.DeviceTypes.OrderByDescending(x => x.UpdatedAt).Select(x => ApiMapper.ToDeviceType(x)).ToListAsync());

        app.MapPost($"{prefix}/base-info/device-types", async (DeviceTypePayload payload, AppDbContext db) =>
        {
            var validation = ValidateDeviceType(payload);
            if (validation is not null) return Results.Ok(validation);
            var name = Text(payload.Name)!;
            var model = Text(payload.Model)!;
            if (await db.DeviceTypes.AnyAsync(x => x.Name.ToLower() == name.ToLower() && x.Model.ToLower() == model.ToLower()))
            {
                return Results.Ok(Fail("DEVICE_TYPE_EXISTS", "设备名称与型号组合已存在。"));
            }

            var item = new DeviceType { Id = await NextId(db.DeviceTypes), Name = name, Model = model, Category = payload.Category!, LengthMm = payload.LengthMm, WidthMm = payload.WidthMm, HeightMm = payload.HeightMm, WeightKg = payload.WeightKg, HasBattery = payload.HasBattery, BatterySpec = payload.HasBattery ? Text(payload.BatterySpec) : null, Description = Text(payload.Description), UpdatedAt = Now() };
            db.DeviceTypes.Add(item);
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "设备类型已创建。", Item = ApiMapper.ToDeviceType(item) });
        });

        app.MapPut($"{prefix}/base-info/device-types/{{id:int}}", async (int id, DeviceTypePayload payload, AppDbContext db) =>
        {
            var validation = ValidateDeviceType(payload);
            if (validation is not null) return Results.Ok(validation);
            var item = await db.DeviceTypes.FindAsync(id);
            if (item is null) return Results.Ok(Fail("DEVICE_TYPE_NOT_FOUND", "设备类型不存在。"));
            var name = Text(payload.Name)!;
            var model = Text(payload.Model)!;
            if (await db.DeviceTypes.AnyAsync(x => x.Id != id && x.Name.ToLower() == name.ToLower() && x.Model.ToLower() == model.ToLower()))
            {
                return Results.Ok(Fail("DEVICE_TYPE_EXISTS", "设备名称与型号组合已存在。"));
            }

            item.Name = name; item.Model = model; item.Category = payload.Category!; item.LengthMm = payload.LengthMm; item.WidthMm = payload.WidthMm; item.HeightMm = payload.HeightMm; item.WeightKg = payload.WeightKg; item.HasBattery = payload.HasBattery; item.BatterySpec = payload.HasBattery ? Text(payload.BatterySpec) : null; item.Description = Text(payload.Description); item.UpdatedAt = Now();
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "设备类型已更新。", Item = ApiMapper.ToDeviceType(item) });
        });

        app.MapDelete($"{prefix}/base-info/device-types/{{id:int}}", async (int id, AppDbContext db) =>
        {
            var item = await db.DeviceTypes.FindAsync(id);
            if (item is null) return Results.Ok(Fail("DEVICE_TYPE_NOT_FOUND", "设备类型不存在。"));
            db.DeviceTypes.Remove(item);
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "设备类型已删除。", Item = ApiMapper.ToDeviceType(item) });
        });
    }

    private static object? ValidateDeviceType(DeviceTypePayload payload)
    {
        if (Text(payload.Name) is null || Text(payload.Model) is null || Text(payload.Category) is null || !Rules.DeviceTypeCategories.Contains(payload.Category))
        {
            return Fail("VALIDATION_ERROR", "设备类型参数不正确。");
        }

        if (payload.LengthMm <= 0 || payload.WidthMm <= 0 || payload.HeightMm <= 0 || payload.WeightKg <= 0)
        {
            return Fail("VALIDATION_ERROR", "尺寸和重量必须为正数。");
        }

        return payload.HasBattery && Text(payload.BatterySpec) is null
            ? Fail("VALIDATION_ERROR", "电池设备必须填写电池规格。")
            : null;
    }

    private static void MapWorkOrders(WebApplication app, string prefix)
    {
        app.MapGet($"{prefix}/work-orders", async (HttpRequest request, AppDbContext db) =>
        {
            var q = request.Query;
            var items = await db.WorkOrders.Include(x => x.Events).ToListAsync();
            var filtered = items.Where(x =>
                ContainsCi(x.OrderNo, q["orderNo"]) &&
                ContainsCi(x.DeviceCode, q["deviceCode"]) &&
                ContainsCi(x.BatchNo, q["batchNo"]) &&
                (Text(q["ownerUsername"]) is not { } owner || x.OwnerUsername.Equals(owner, StringComparison.OrdinalIgnoreCase)) &&
                (Text(q["status"]) is not { } status || x.Status == status) &&
                (!DateOnly.TryParse(q["plannedStart"], out var start) || x.PlannedDate >= start) &&
                (!DateOnly.TryParse(q["plannedEnd"], out var end) || x.PlannedDate <= end));
            return filtered.OrderByDescending(x => x.UpdatedAt).Select(ApiMapper.ToWorkOrder);
        });

        app.MapPost($"{prefix}/work-orders", async (WorkOrderPayload payload, AppDbContext db) =>
        {
            var error = ValidateWorkOrderPayload(payload);
            if (error is not null) return Results.Ok(error);
            var orderNo = Text(payload.OrderNo)!;
            if (await db.WorkOrders.AnyAsync(x => x.OrderNo.ToLower() == orderNo.ToLower())) return Results.Ok(Fail("WORK_ORDER_EXISTS", "工单号已存在。"));
            var ownerName = await db.Members.Where(x => x.Username == Text(payload.OwnerUsername)).Select(x => x.Name).FirstOrDefaultAsync();
            if (ownerName is null) return Results.Ok(Fail("WORK_ORDER_OWNER_NOT_FOUND", "责任人不存在,请选择有效成员。"));
            var at = Now();
            var item = new WorkOrder { Id = await NextId(db.WorkOrders), OrderNo = orderNo, DeviceCode = Text(payload.DeviceCode)!, BatchNo = Text(payload.BatchNo)!, Line = Text(payload.Line)!, OwnerUsername = Text(payload.OwnerUsername)!, OwnerName = ownerName, PlannedDate = DateOnly.Parse(payload.PlannedDate!), Status = "draft", CompletedSn = 0, TotalSn = payload.TotalSn, CreatedBy = Text(payload.Operator)!, CreatedAt = at, UpdatedBy = Text(payload.Operator)!, UpdatedAt = at, LastAction = "create", LastActionAt = at, LastActionBy = Text(payload.Operator)!, Events = [new WorkOrderEvent { EventId = NewId("evt"), Action = "create", ToStatus = "draft", Operator = Text(payload.Operator)!, At = at, Remark = "新建工单" }] };
            db.WorkOrders.Add(item);
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "工单草稿已创建。", Item = ApiMapper.ToWorkOrder(item) });
        });

        app.MapPut($"{prefix}/work-orders/{{id:int}}", async (int id, WorkOrderPayload payload, AppDbContext db) =>
        {
            var item = await db.WorkOrders.Include(x => x.Events).FirstOrDefaultAsync(x => x.Id == id);
            if (item is null) return Results.Ok(Fail("WORK_ORDER_NOT_FOUND", "工单不存在。"));
            if (item.Status != "draft") return Results.Ok(Fail("WORK_ORDER_NOT_DRAFT", "仅草稿状态允许编辑。"));
            var error = ValidateWorkOrderPayload(payload);
            if (error is not null) return Results.Ok(error);
            var orderNo = Text(payload.OrderNo)!;
            if (await db.WorkOrders.AnyAsync(x => x.Id != id && x.OrderNo.ToLower() == orderNo.ToLower())) return Results.Ok(Fail("WORK_ORDER_EXISTS", "工单号已存在。"));
            var ownerName = await db.Members.Where(x => x.Username == Text(payload.OwnerUsername)).Select(x => x.Name).FirstOrDefaultAsync();
            if (ownerName is null) return Results.Ok(Fail("WORK_ORDER_OWNER_NOT_FOUND", "责任人不存在,请选择有效成员。"));
            var at = Now();
            item.OrderNo = orderNo; item.DeviceCode = Text(payload.DeviceCode)!; item.BatchNo = Text(payload.BatchNo)!; item.Line = Text(payload.Line)!; item.OwnerUsername = Text(payload.OwnerUsername)!; item.OwnerName = ownerName; item.PlannedDate = DateOnly.Parse(payload.PlannedDate!); item.TotalSn = payload.TotalSn; item.CompletedSn = Math.Min(item.CompletedSn, payload.TotalSn); item.UpdatedBy = Text(payload.Operator)!; item.UpdatedAt = at; item.LastAction = "edit_draft"; item.LastActionAt = at; item.LastActionBy = Text(payload.Operator)!;
            item.Events.Add(new WorkOrderEvent { EventId = NewId("evt"), Action = "edit_draft", FromStatus = "draft", ToStatus = "draft", Operator = Text(payload.Operator)!, At = at, Remark = "编辑草稿" });
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "工单草稿已更新。", Item = ApiMapper.ToWorkOrder(item) });
        });

        app.MapPost($"{prefix}/work-orders/{{id:int}}/actions/{{action}}", async (int id, string action, TransitionPayload payload, AppDbContext db) =>
        {
            var item = await db.WorkOrders.Include(x => x.Events).FirstOrDefaultAsync(x => x.Id == id);
            if (item is null) return Results.Ok(Fail("WORK_ORDER_NOT_FOUND", "工单不存在。"));
            if (!Rules.WorkOrderActionToStatus.ContainsKey(action) || !Rules.WorkOrderAllowedTransitions[item.Status].Contains(action)) return Results.Ok(Fail("INVALID_STATUS_TRANSITION", "当前状态不允许执行该操作。"));
            var at = Now();
            var from = item.Status;
            var to = Rules.WorkOrderActionToStatus[action];
            var op = Text(payload.Operator) ?? "";
            item.Status = to; item.UpdatedBy = op; item.UpdatedAt = at; item.LastAction = action; item.LastActionAt = at; item.LastActionBy = op;
            item.Events.Add(new WorkOrderEvent { EventId = NewId("evt"), Action = action, FromStatus = from, ToStatus = to, Operator = op, At = at, Remark = Text(payload.Remark) });
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "工单状态已更新。", Item = ApiMapper.ToWorkOrder(item) });
        });
    }

    private static object? ValidateWorkOrderPayload(WorkOrderPayload payload)
    {
        if (Text(payload.OrderNo) is null || Text(payload.DeviceCode) is null || Text(payload.BatchNo) is null || Text(payload.Line) is null || Text(payload.OwnerUsername) is null || Text(payload.Operator) is null || payload.TotalSn <= 0 || !DateOnly.TryParse(payload.PlannedDate, out _))
        {
            return Fail("VALIDATION_ERROR", "工单参数不正确。");
        }
        return null;
    }

    private static void MapSn(WebApplication app, string prefix)
    {
        app.MapGet($"{prefix}/sn", async (HttpRequest request, AppDbContext db) =>
        {
            var q = request.Query;
            var items = await db.SnItems.Include(x => x.Events).ToListAsync();
            return items.Where(x => ContainsCi(x.Sn, q["sn"]) && ContainsCi(x.WorkOrderNo, q["workOrderNo"]) && ProcessStepMapper.MatchesFilter(x.CurrentStep, q["currentStep"]) && (Text(q["status"]) is not { } status || x.Status == status) && (Text(q["exceptionStatus"]) is not { } ex || x.ExceptionStatus == ex)).OrderByDescending(x => x.UpdatedAt).Select(ApiMapper.ToSnItem);
        });

        app.MapPost($"{prefix}/sn/import", async (SnImportPayload payload, AppDbContext db) =>
        {
            if (Text(payload.WorkOrderNo) is null || Text(payload.CurrentStep) is null || Text(payload.Operator) is null || payload.SnList is null || payload.SnList.Length == 0)
            {
                return Results.Ok(new { Success = false, ErrorCode = "VALIDATION_ERROR", Message = "SN 导入参数不正确。", ImportedCount = 0, SkippedCount = 0, DuplicateSnList = Array.Empty<string>() });
            }
            if (!ProcessStepMapper.TryParse(payload.CurrentStep, out var currentStep))
            {
                return Results.Ok(new { Success = false, ErrorCode = "VALIDATION_ERROR", Message = "工序参数不正确。", ImportedCount = 0, SkippedCount = 0, DuplicateSnList = Array.Empty<string>() });
            }

            var workOrderNo = Text(payload.WorkOrderNo)!;
            var workOrder = await db.WorkOrders.FirstOrDefaultAsync(x => x.OrderNo.ToLower() == workOrderNo.ToLower());
            if (workOrder is null)
            {
                return Results.Ok(new { Success = false, ErrorCode = "WORK_ORDER_NOT_FOUND", Message = "工单不存在,不允许导入 SN。", ImportedCount = 0, SkippedCount = 0, DuplicateSnList = Array.Empty<string>() });
            }
            if (workOrder.Status != "pending_dispatch")
            {
                return Results.Ok(new { Success = false, ErrorCode = "WORK_ORDER_STATUS_INVALID", Message = "仅已下发工单允许导入 SN。", ImportedCount = 0, SkippedCount = 0, DuplicateSnList = Array.Empty<string>() });
            }

            var candidates = payload.SnList.Select(x => x.Trim().ToUpperInvariant()).Where(x => x.Length > 0).ToList();
            if (candidates.Count == 0) return Results.Ok(new { Success = false, ErrorCode = "VALIDATION_ERROR", Message = "未提供可导入的 SN。", ImportedCount = 0, SkippedCount = 0, DuplicateSnList = Array.Empty<string>() });

            var batchDuplicates = candidates.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).OrderBy(x => x).ToArray();
            if (batchDuplicates.Length > 0)
            {
                return Results.Ok(new
                {
                    Success = false,
                    ErrorCode = "SN_DUPLICATED_IN_BATCH",
                    Message = "导入失败,导入批次存在重复 SN。",
                    ImportedCount = 0,
                    SkippedCount = batchDuplicates.Length,
                    DuplicateSnList = batchDuplicates
                });
            }

            var importedCount = await db.SnItems.CountAsync(x => x.WorkOrderNo.ToLower() == workOrderNo.ToLower());
            var remainingCount = Math.Max(0, workOrder.TotalSn - importedCount);
            if (candidates.Count > remainingCount)
            {
                return Results.Ok(new
                {
                    Success = false,
                    ErrorCode = "SN_IMPORT_EXCEEDS_REMAINING",
                    Message = $"导入失败,本次导入数量 {candidates.Count} 大于未导入数量 {remainingCount}。",
                    ImportedCount = 0,
                    SkippedCount = candidates.Count,
                    DuplicateSnList = Array.Empty<string>()
                });
            }

            // 历史 SN 去重:导入集合内不允许重复,也不允许与历史任意 SN 重复。
            var historicalSnSet = (await db.SnItems.Select(x => x.Sn).ToListAsync())
                .Select(x => x.Trim().ToUpperInvariant())
                .ToHashSet();
            var currentBatchSet = new HashSet<string>();
            var unique = new List<string>();
            var duplicates = new HashSet<string>();
            foreach (var sn in candidates)
            {
                if (currentBatchSet.Contains(sn) || historicalSnSet.Contains(sn))
                {
                    duplicates.Add(sn);
                    continue;
                }

                currentBatchSet.Add(sn);
                unique.Add(sn);
            }

            var at = Now();
            var operatorName = Text(payload.Operator)!;
            var nextId = await NextId(db.SnItems);
            var nextTaskId = await NextId(db.OperationTasks);
            var pendingNextAction = Rules.OperationNextAction["pending"];
            foreach (var sn in unique)
            {
                var item = new SnItem
                {
                    Id = nextId++,
                    Sn = sn,
                    WorkOrderNo = workOrderNo,
                    Status = "pending",
                    ExceptionStatus = "none",
                    CreatedBy = operatorName,
                    CreatedAt = at,
                    UpdatedBy = operatorName,
                    UpdatedAt = at,
                    LastAction = "import",
                    LastActionAt = at,
                    LastActionBy = operatorName
                };
                if (!item.TryInitializeCurrentStep(currentStep, out var stepError))
                {
                    return Results.Ok(new { Success = false, ErrorCode = "STEP_TRANSITION_INVALID", Message = stepError ?? "工序状态流转不合法。", ImportedCount = 0, SkippedCount = 0, DuplicateSnList = Array.Empty<string>() });
                }

                var importEvent = new SnEvent
                {
                    EventId = NewId("sn-evt"),
                    Action = "import",
                    ToStatus = "pending",
                    Operator = operatorName,
                    At = at,
                    Reason = "批量导入",
                    ExceptionStatus = "none"
                };
                importEvent.CaptureCurrentStep(item.CurrentStep);
                item.Events = [importEvent];

                db.SnItems.Add(item);

                var operationTask = new OperationTask
                {
                    Id = nextTaskId++,
                    WorkOrderNo = workOrderNo,
                    Sn = sn,
                    StepName = ProcessStep.Assembly,
                    Workstation = "UNASSIGNED",
                    Device = "UNASSIGNED",
                    Operator = operatorName,
                    StartedAt = null,
                    EndedAt = null,
                    Result = "pending",
                    Status = "pending",
                    NextAction = pendingNextAction,
                    AuditEvents =
                    [
                        new OperationTaskEvent
                        {
                            EventId = NewId("op-evt"),
                            Action = "create",
                            FromStatus = null,
                            ToStatus = "pending",
                            Operator = operatorName,
                            At = at,
                            Remark = "SN导入自动创建首工序任务",
                            NextAction = pendingNextAction
                        }
                    ]
                };
                db.OperationTasks.Add(operationTask);
            }

            await db.SaveChangesAsync();
            var success = unique.Count > 0;
            return Results.Ok(new { Success = success, ErrorCode = success ? null : "SN_DUPLICATED", Message = success ? $"SN 导入完成,成功 {unique.Count} 条,跳过 {duplicates.Count} 条重复记录。" : "导入失败,SN 全部重复。", ImportedCount = unique.Count, SkippedCount = duplicates.Count, DuplicateSnList = duplicates.ToArray() });
        });

        app.MapPost($"{prefix}/sn/{{id:int}}/actions/{{action}}", async (int id, string action, SnActionPayload payload, AppDbContext db) =>
        {
            var item = await db.SnItems.Include(x => x.Events).FirstOrDefaultAsync(x => x.Id == id);
            if (item is null) return Results.Ok(Fail("SN_NOT_FOUND", "SN 不存在。"));
            if (!Rules.SnAllowedActions[item.Status].Contains(action)) return Results.Ok(new { Success = false, ErrorCode = "SN_ACTION_NOT_ALLOWED", Message = "当前 SN 状态不支持该操作。", Item = ApiMapper.ToSnItem(item) });
            var op = Text(payload.Operator) ?? "";
            var reason = Text(payload.Reason) ?? "";
            var from = item.Status;
            var to = action switch { "freeze" => "frozen", "unfreeze" => item.ExceptionStatus == "none" ? "in_process" : "pending", "scrap" => "scrapped", _ => item.Status };
            var at = Now();
            if (action == "freeze") item.FreezeReason = reason;
            if (action == "unfreeze") item.FreezeReason = null;
            if (action == "scrap") item.ScrapReason = reason;
            item.Status = to; item.UpdatedAt = at; item.UpdatedBy = op; item.LastAction = action; item.LastActionAt = at; item.LastActionBy = op;
            var actionEvent = new SnEvent
            {
                EventId = NewId("sn-evt"),
                Action = action,
                FromStatus = from,
                ToStatus = to,
                Operator = op,
                At = at,
                Reason = reason,
                ExceptionStatus = item.ExceptionStatus
            };
            actionEvent.CaptureCurrentStep(item.CurrentStep);
            item.Events.Add(actionEvent);
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = action == "freeze" ? "SN 已冻结。" : action == "unfreeze" ? "SN 已解冻。" : "SN 已报废。", Item = ApiMapper.ToSnItem(item) });
        });
    }

    private static void MapOperations(WebApplication app, string prefix)
    {
        app.MapGet($"{prefix}/operations", async (HttpRequest request, AppDbContext db) =>
        {
            var q = request.Query;
            var items = await db.OperationTasks.Include(x => x.AuditEvents).ToListAsync();
            return items.Where(x => ContainsCi(x.Workstation, q["workstation"]) && ProcessStepMapper.MatchesFilter(x.StepName, q["stepName"]) && ContainsCi(x.Operator, q["operator"]) && ContainsCi(x.Sn, q["sn"]) && (Text(q["status"]) is not { } status || x.Status == status)).OrderByDescending(x => x.AuditEvents.OrderByDescending(e => e.At).FirstOrDefault()?.At).Select(ApiMapper.ToOperationTask);
        });

        app.MapPost($"{prefix}/operations/{{id:int}}/actions/{{action}}", async (int id, string action, OperationActionPayload payload, HttpContext http, AppDbContext db) =>
        {
            var item = await db.OperationTasks.Include(x => x.AuditEvents).FirstOrDefaultAsync(x => x.Id == id);
            if (item is null) return Results.Ok(Fail("TASK_NOT_FOUND", "工序任务不存在。"));
            if (!Rules.OperationAllowedActions[item.Status].Contains(action)) return Results.Ok(new { Success = false, ErrorCode = "ACTION_NOT_ALLOWED", Message = "当前任务状态不允许执行该操作。", State = item.Status, item.NextAction });
            if (action == "skip" && Text(payload.Remark) is null) return Results.Ok(new { Success = false, ErrorCode = "SKIP_REASON_REQUIRED", Message = "跳过工序必须填写原因。", State = item.Status, item.NextAction });
            if (action == "skip" && !(http.User?.IsInRole("admin") ?? false)) return Results.Ok(new { Success = false, ErrorCode = "FORBIDDEN", Message = "仅管理员允许跳过工序。", State = item.Status, item.NextAction });
            if (action == "submit_test" && payload.TestPassed is null) return Results.Ok(new { Success = false, ErrorCode = "TEST_RESULT_REQUIRED", Message = "提交测试结果时必须明确通过或失败。", State = item.Status, item.NextAction });
            if (!TryResolveOperationStep(payload, out var targetStep, out var stepError))
            {
                return Results.Ok(new { Success = false, ErrorCode = "VALIDATION_ERROR", Message = stepError ?? "工序参数不正确。", State = item.Status, item.NextAction });
            }

            var workstation = Text(payload.Workstation);
            if (workstation is not null)
            {
                item.Workstation = workstation;
            }

            if (action == "complete_rework")
            {
                item.StepName = ProcessStep.Testing;
            }
            else if (targetStep != ProcessStep.Unknown)
            {
                item.StepName = targetStep;
            }
            else
            {
                item.StepName = ResolveStepFromAction(action, item.StepName, payload.TestPassed);
            }

            var from = item.Status;
            var at = Now();
            if (action == "start") { item.Status = "in_progress"; item.StartedAt ??= at; item.Result = "pending"; }
            if (action == "complete_assembly") { item.Status = "pending_test"; item.Result = "pending"; }
            if (action == "complete_rework") { item.Status = "pending_test"; item.Result = "pending"; item.EndedAt = null; }
            if (action == "submit_test") { item.Status = payload.TestPassed == true ? "completed" : "failed"; item.Result = payload.TestPassed == true ? "pass" : "fail"; item.EndedAt = at; }
            if (action == "skip") { item.Status = "skipped"; item.Result = "pending"; item.EndedAt = at; }
            item.Operator = Text(payload.Operator) ?? "";
            item.NextAction = Rules.OperationNextAction[item.Status];
            item.AuditEvents.Add(new OperationTaskEvent { EventId = NewId("op-evt"), Action = action, FromStatus = from, ToStatus = item.Status, Operator = item.Operator, At = at, Remark = Text(payload.Remark), NextAction = item.NextAction });

            var snItem = await db.SnItems.Include(x => x.Events).FirstOrDefaultAsync(x => x.Sn == item.Sn);
            if (snItem is null) return Results.Ok(Fail("SN_NOT_FOUND", "工序任务关联的 SN 不存在。"));
            var snStatus = snItem.Status;
            snItem.UpdatedAt = at;
            snItem.UpdatedBy = item.Operator;
            snItem.LastAction = $"operation_{action}";
            snItem.LastActionAt = at;
            snItem.LastActionBy = item.Operator;
            snItem.OverrideCurrentStep(item.StepName);
            var snEvent = new SnEvent
            {
                EventId = NewId("sn-evt"),
                Action = $"operation_{action}",
                FromStatus = snStatus,
                ToStatus = snItem.Status,
                Operator = item.Operator,
                At = at,
                Reason = BuildSnOperationReason(action, payload),
                ExceptionStatus = snItem.ExceptionStatus
            };
            snEvent.CaptureCurrentStep(item.StepName);
            snItem.Events.Add(snEvent);

            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "工序任务状态已更新。", State = item.Status, item.NextAction });
        });
    }

    private static void MapDashboard(WebApplication app, string prefix)
    {
        app.MapGet($"{prefix}/dashboard/overview", async (HttpRequest request, AppDbContext db) =>
            BuildDashboard(await FilterDashboard(request, db).ToListAsync(), request));

        app.MapGet($"{prefix}/dashboard/overview/export", async (HttpRequest request, AppDbContext db) =>
        {
            var overview = BuildDashboard(await FilterDashboard(request, db).ToListAsync(), request);
            var latest = (IEnumerable<object>)overview.GetType().GetProperty("LatestWorkOrders")!.GetValue(overview)!;
            var rows = latest.Select(x =>
            {
                var t = x.GetType();
                return string.Join(",", t.GetProperty("OrderNo")!.GetValue(x), t.GetProperty("Line")!.GetValue(x), t.GetProperty("Status")!.GetValue(x), t.GetProperty("PlannedDate")!.GetValue(x), t.GetProperty("CompletedSn")!.GetValue(x), t.GetProperty("TotalSn")!.GetValue(x));
            });
            var content = string.Join("\n", new[] { "orderNo,line,status,plannedDate,completedSn,totalSn" }.Concat(rows));
            return new { Success = true, ErrorCode = (string?)null, Message = "汇总导出已生成。", FileName = $"dashboard-overview-{DateTime.UtcNow:yyyy-MM-dd}.csv", ContentType = "text/csv;charset=utf-8", Content = content };
        });
    }

    private static IQueryable<DashboardWorkOrderSnapshot> FilterDashboard(HttpRequest request, AppDbContext db)
    {
        var q = request.Query;
        var query = db.DashboardWorkOrderSnapshots.AsQueryable();
        if (DateOnly.TryParse(q["start"], out var start)) query = query.Where(x => x.PlannedDate >= start);
        if (DateOnly.TryParse(q["end"], out var end)) query = query.Where(x => x.PlannedDate <= end);
        if (Text(q["line"]) is { } line) query = query.Where(x => x.Line == line);
        if (Text(q["workOrderStatus"]) is { } status && Rules.DashboardStatuses.Contains(status)) query = query.Where(x => x.Status == status);
        return query;
    }

    private static object BuildDashboard(List<DashboardWorkOrderSnapshot> list, HttpRequest request)
    {
        static decimal Percent(int numerator, int denominator) => denominator <= 0 ? 0 : Math.Round((decimal)numerator / denominator * 100, 2);
        var latest = list.OrderByDescending(x => x.PlannedDate).Take(8).Select(x => new { x.OrderNo, x.Line, x.Status, PlannedDate = x.PlannedDate.ToString("yyyy-MM-dd"), x.CompletedSn, x.TotalSn }).ToList();
        return new
        {
            Query = new { Start = Text(request.Query["start"]), End = Text(request.Query["end"]), Line = Text(request.Query["line"]), WorkOrderStatus = Text(request.Query["workOrderStatus"]) },
            Filters = new { Lines = new[] { "L1-装配线", "L2-测试线", "L3-总装线" }, WorkOrderStatuses = Rules.DashboardStatuses },
            WorkOrders = new { Total = list.Count, Running = list.Count(x => x.Status == "running"), PendingQc = list.Count(x => x.Status == "pending_qc"), InException = list.Count(x => x.Status == "in_exception") },
            Sn = new { Completed = list.Sum(x => x.CompletedSn), InProcess = list.Sum(x => x.InProcessSn), Frozen = list.Sum(x => x.FrozenSn) },
            Quality = new { FirstPassRate = Percent(list.Sum(x => x.FirstTestPassed), list.Sum(x => x.FirstTestTotal)), RetestPassRate = Percent(list.Sum(x => x.RetestPassed), list.Sum(x => x.RetestTotal)), ExceptionRate = Percent(list.Sum(x => x.ExceptionCount), list.Sum(x => x.TotalSn)) },
            LatestWorkOrders = latest
        };
    }

    private static void MapSettings(WebApplication app, string prefix)
    {
        app.MapGet($"{prefix}/settings/profile", async (AppDbContext db) => ApiMapper.ToProfile((await db.SettingsProfiles.FirstAsync())));
        app.MapPut($"{prefix}/settings/profile", async (SettingsProfilePayload payload, AppDbContext db) =>
        {
            if (Text(payload.Name) is null || Text(payload.Email) is null || Text(payload.Username) is null) return Results.Ok(Fail("VALIDATION_ERROR", "提交的个人资料格式不正确。"));
            var profile = await db.SettingsProfiles.FirstAsync();
            profile.Name = Text(payload.Name)!; profile.Email = Text(payload.Email)!; profile.Username = Text(payload.Username)!; profile.Avatar = Text(payload.Avatar); profile.Bio = Text(payload.Bio);
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "个人资料已保存。", Profile = ApiMapper.ToProfile(profile) });
        });

        app.MapGet($"{prefix}/settings/notifications", async (AppDbContext db) => ApiMapper.ToNotifications(await db.SettingsNotifications.FirstAsync()));
        app.MapPut($"{prefix}/settings/notifications", async (SettingsNotificationsDto payload, AppDbContext db) =>
        {
            var item = await db.SettingsNotifications.FirstAsync();
            item.Email = payload.Email; item.Desktop = payload.Desktop; item.ProductUpdates = payload.ProductUpdates; item.WeeklyDigest = payload.WeeklyDigest; item.ImportantUpdates = payload.ImportantUpdates;
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "通知设置已保存。", Notifications = ApiMapper.ToNotifications(item) });
        });

        app.MapPost($"{prefix}/settings/security/password", async (PasswordPayload payload, AppDbContext db) =>
        {
            if (Text(payload.CurrentPassword) is null || Text(payload.NewPassword) is null) return Results.Ok(Fail("VALIDATION_ERROR", "密码参数不正确。"));
            var account = await db.SecurityAccounts.FirstAsync();
            if (!PasswordHasher.Verify(Text(payload.CurrentPassword)!, account.PasswordHash)) return Results.Ok(Fail("CURRENT_PASSWORD_INCORRECT", "当前密码不正确。"));
            account.PasswordHash = PasswordHasher.Hash(Text(payload.NewPassword)!);
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "密码已更新。" });
        });

        app.MapDelete($"{prefix}/settings/security/account", async (AppDbContext db) =>
        {
            var account = await db.SecurityAccounts.FirstAsync();
            account.AccountDeleted = true;
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, Message = "账号已标记删除(Mock)。" });
        });

        app.MapGet($"{prefix}/settings/members", async (AppDbContext db) => (await db.Members.OrderBy(x => x.Id).ToListAsync()).Select(ApiMapper.ToMember));
        app.MapPost($"{prefix}/settings/members", async (MemberPayload payload, AppDbContext db) => await UpsertMember(null, payload, db, create: true));
        app.MapPatch($"{prefix}/settings/members/{{username}}", async (string username, MemberPayload payload, AppDbContext db) =>
        {
            var member = await db.Members.FirstOrDefaultAsync(x => x.Username == username);
            if (member is null) return Results.Ok(Fail("MEMBER_NOT_FOUND", "成员不存在。"));
            if (Text(payload.Role) is null || !Rules.MemberRoles.Contains(payload.Role!)) return Results.Ok(Fail("VALIDATION_ERROR", "成员信息格式不正确。"));
            member.Role = payload.Role!;
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "成员角色已更新。", Member = ApiMapper.ToMember(member) });
        });
        app.MapPut($"{prefix}/settings/members/{{username}}/profile", async (string username, MemberPayload payload, AppDbContext db) => await UpsertMember(username, payload, db, create: false));
        app.MapDelete($"{prefix}/settings/members/{{username}}", async (string username, AppDbContext db) =>
        {
            var member = await db.Members.FirstOrDefaultAsync(x => x.Username == username);
            if (member is null) return Results.Ok(Fail("MEMBER_NOT_FOUND", "成员不存在。"));
            db.Members.Remove(member);
            await db.SaveChangesAsync();
            return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = "成员已移除。", Member = ApiMapper.ToMember(member) });
        });
    }

    private static async Task<IResult> UpsertMember(string? username, MemberPayload payload, AppDbContext db, bool create)
    {
        if (Text(payload.Name) is null || Text(payload.Email) is null || Text(payload.Username) is null || Text(payload.Role) is null || !Rules.MemberRoles.Contains(payload.Role!))
        {
            return Results.Ok(Fail("VALIDATION_ERROR", "成员信息格式不正确。"));
        }

        Member? member = null;
        if (!create)
        {
            member = await db.Members.FirstOrDefaultAsync(x => x.Username == username);
            if (member is null) return Results.Ok(Fail("MEMBER_NOT_FOUND", "成员不存在。"));
        }

        var newUsername = Text(payload.Username)!;
        var email = Text(payload.Email)!;
        if (await db.Members.AnyAsync(x => x.Username == newUsername && (create || x.Username != username))) return Results.Ok(Fail("USERNAME_EXISTS", "用户名已存在。"));
        if (await db.Members.AnyAsync(x => x.Email == email && (create || x.Username != username))) return Results.Ok(Fail("EMAIL_EXISTS", "邮箱已存在。"));

        member ??= new Member { Id = await NextId(db.Members) };
        member.Name = Text(payload.Name)!; member.Email = email; member.Username = newUsername; member.Role = Text(payload.Role)!; member.Bio = Text(payload.Bio); member.AvatarSrc = Text(payload.Avatar) ?? $"https://i.pravatar.cc/128?u={Uri.EscapeDataString(member.Name)}"; member.AvatarAlt = member.Name;
        if (create) db.Members.Add(member);
        await db.SaveChangesAsync();
        return Results.Ok(new { Success = true, ErrorCode = (string?)null, Message = create ? "成员邀请已发送。" : "成员资料已更新。", Member = ApiMapper.ToMember(member) });
    }

    private static void MapShell(WebApplication app, string prefix)
    {
        app.MapGet($"{prefix}/customers", async (AppDbContext db) => Results.Json(JsonSerializer.Deserialize<JsonElement>((await db.ShellJsonItems.SingleAsync(x => x.Kind == "customers")).PayloadJson)));
        app.MapGet($"{prefix}/mails", async (AppDbContext db) => Results.Json(JsonSerializer.Deserialize<JsonElement>((await db.ShellJsonItems.SingleAsync(x => x.Kind == "mails")).PayloadJson)));
        app.MapGet($"{prefix}/notifications", async (AppDbContext db) => Results.Json(JsonSerializer.Deserialize<JsonElement>((await db.ShellJsonItems.SingleAsync(x => x.Kind == "notifications")).PayloadJson)));
    }

    private static async Task<int> NextId<T>(DbSet<T> set) where T : class
    {
        var ids = await set.Select(x => EF.Property<int>(x, "Id")).ToListAsync();
        return ids.Count == 0 ? 1 : ids.Max() + 1;
    }
}