All files / src/entities/admin-catalog/model adminCatalogStore.ts

56.25% Statements 252/448
52.95% Branches 224/423
73.23% Functions 52/71
57.56% Lines 236/410

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078                                                  3x                                                           1x 1x           1x 1x         164x                   102x             34x       3x       1x     1x     1x             20x                                     20x                             22x           17x       12x                                                     5x                                                                                           5x                                         5x       3x         3x           3x         3x                   13x                           11x   1x       12x       13x                                                       8x     8x 8x 8x 8x                                 5x     5x 3x   2x         2x             2x             2x 2x                                                                                                       3x 7x 7x 7x 7x 7x             7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x 7x     7x     12x           34x 34x                 51x           23x       34x 34x 34x 34x 34x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x             8x       4x 4x       4x       3x 3x       3x 3x 3x 3x 3x 3x 3x           3x 3x           3x 3x       3x 3x 3x 3x 3x 3x 3x           3x 3x           14x 14x       14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x           13x 13x 10x 10x 10x     3x 2x     14x 12x                 3x 3x       3x 3x 3x 3x 3x 3x 3x 2x 2x   1x             3x 2x           3x       2x 2x 2x                       1x       1x 1x                     2x 2x 2x 2x 2x             3x 3x 3x 3x 3x     2x 2x 2x         2x 2x         2x   1x 1x 1x 1x                 1x               3x 3x 3x 3x 3x 3x 3x   3x 3x             2x 2x 2x         2x                   1x 1x 1x 1x 1x 1x 1x 1x                           1x 1x 1x       1x             1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                       7x                                                                                      
import { computed, reactive, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createCatalogApi,
  secureRandomUUID,
  type AdminProductQuery,
  type AdminProductStatus,
  type AdminProductSummary,
  type Brand,
  type BusinessId,
  type CatalogApi,
  type Category,
  type CreateProductInput,
  type PageResponse,
  type ProductDetail,
  type ProductMedia,
  type ProductSku,
  type UpdateProductInput,
  type UpdateProductSkuInput,
} from "@plain-journal/foundation";
import { createAuthenticatedApiClient } from "../../../shared/api";
 
const PENDING_CREATE_PREFIX =
  "plain-journal:admin-catalog:pending-create:v1:";
 
export type CatalogCommandPhase =
  | "idle"
  | "processing"
  | "unknown"
  | "accepted"
  | "rejected";
 
export interface AdminCatalogAccessContext {
  authorized: boolean;
  operatorId: BusinessId | null;
  accessToken: string | null;
}
 
interface ActiveAccess {
  operatorId: BusinessId;
  accessToken: string;
  revision: number;
  api: CatalogApi;
}
 
export interface PendingProductCreate {
  commandId: string;
  input: CreateProductInput;
  createdAt: string;
}
 
export class CatalogAccessChangedError extends Error {
  constructor() {
    super("员工账户或会话已切换,旧的商品经营结果不会写入当前页面。");
    this.name = "CatalogAccessChangedError";
  }
}
 
export class CatalogProjectionContractError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "CatalogProjectionContractError";
  }
}
 
function isBusinessId(value: unknown): value is BusinessId {
  return typeof value === "string" && /^[0-9]+$/u.test(value);
}
 
function isActiveContext(
  context: AdminCatalogAccessContext,
): context is {
  authorized: true;
  operatorId: BusinessId;
  accessToken: string;
} {
  return context.authorized
    && isBusinessId(context.operatorId)
    && typeof context.accessToken === "string"
    && context.accessToken.length > 0;
}
 
function createApi(accessToken: string): CatalogApi {
  return createCatalogApi(createAuthenticatedApiClient(accessToken, 10000));
}
 
function errorMessage(cause: unknown, fallback: string): string {
  return cause instanceof Error ? cause.message : fallback;
}
 
function resultMayBeUnknown(cause: unknown): boolean {
  Iif (cause instanceof CatalogProjectionContractError) {
    return true;
  }
  Iif (!(cause instanceof ApiError)) {
    return true;
  }
  return cause.kind === "network"
    || cause.kind === "timeout"
    || cause.kind === "invalid-response"
    || (cause.kind === "http" && (cause.status ?? 500) >= 500);
}
 
function validCategory(value: unknown): value is Category {
  return Boolean(
    value
    && typeof value === "object"
    && "id" in value
    && isBusinessId(value.id)
    && "parentId" in value
    && (value.parentId === null || isBusinessId(value.parentId))
    && "name" in value
    && typeof value.name === "string"
    && value.name.length > 0
    && "slug" in value
    && typeof value.slug === "string"
    && value.slug.length > 0
    && "sortOrder" in value
    && Number.isInteger(value.sortOrder),
  );
}
 
function validBrand(value: unknown): value is Brand {
  return Boolean(
    value
    && typeof value === "object"
    && "id" in value
    && isBusinessId(value.id)
    && "name" in value
    && typeof value.name === "string"
    && value.name.length > 0
    && "slug" in value
    && typeof value.slug === "string"
    && value.slug.length > 0,
  );
}
 
function validMoney(value: unknown, nullable = false): boolean {
  return (nullable && value === null)
    || (typeof value === "string" && /^\d+(?:\.\d{1,2})?$/u.test(value))
    || (typeof value === "number" && Number.isFinite(value) && value >= 0);
}
 
function validAdminStatus(value: unknown): value is AdminProductStatus {
  return value === "DRAFT" || value === "ACTIVE" || value === "INACTIVE";
}
 
function validAdminProduct(value: unknown): value is AdminProductSummary {
  return Boolean(
    value
    && typeof value === "object"
    && "id" in value
    && isBusinessId(value.id)
    && "title" in value
    && typeof value.title === "string"
    && value.title.length > 0
    && "subtitle" in value
    && (value.subtitle === null || typeof value.subtitle === "string")
    && "status" in value
    && validAdminStatus(value.status)
    && "version" in value
    && Number.isInteger(value.version)
    && Number(value.version) >= 0
    && "category" in value
    && validCategory(value.category)
    && "brand" in value
    && validBrand(value.brand)
    && "minimumPrice" in value
    && validMoney(value.minimumPrice, true)
    && "coverUrl" in value
    && (value.coverUrl === null || typeof value.coverUrl === "string"),
  );
}
 
function validSku(value: unknown): value is ProductSku {
  return Boolean(
    value
    && typeof value === "object"
    && "id" in value
    && isBusinessId(value.id)
    && "skuCode" in value
    && typeof value.skuCode === "string"
    && value.skuCode.length > 0
    && "name" in value
    && typeof value.name === "string"
    && "specJson" in value
    && typeof value.specJson === "string"
    && "salePrice" in value
    && validMoney(value.salePrice)
    && "marketPrice" in value
    && validMoney(value.marketPrice, true)
    && "status" in value
    && (value.status === "ACTIVE" || value.status === "INACTIVE")
    && "version" in value
    && Number.isInteger(value.version),
  );
}
 
function validMedia(value: unknown): value is ProductMedia {
  return Boolean(
    value
    && typeof value === "object"
    && "id" in value
    && isBusinessId(value.id)
    && "skuId" in value
    && (value.skuId === null || isBusinessId(value.skuId))
    && "objectKey" in value
    && typeof value.objectKey === "string"
    && value.objectKey.length > 0
    && "mimeType" in value
    && typeof value.mimeType === "string"
    && "sizeBytes" in value
    && Number.isInteger(value.sizeBytes)
    && "sortOrder" in value
    && Number.isInteger(value.sortOrder)
    && "url" in value
    && (value.url === null || typeof value.url === "string"),
  );
}
 
function validateProductDetail(value: ProductDetail): ProductDetail {
  Iif (
    !value
    || typeof value !== "object"
    || !isBusinessId(value.id)
    || typeof value.title !== "string"
    || value.title.length === 0
    || !(value.subtitle === null || typeof value.subtitle === "string")
    || !(value.description === null || typeof value.description === "string")
    || !validAdminStatus(value.status)
    || !Number.isInteger(value.version)
    || !validCategory(value.category)
    || !validBrand(value.brand)
    || !Array.isArray(value.skus)
    || !value.skus.every(validSku)
    || !Array.isArray(value.media)
    || !value.media.every(validMedia)
  ) {
    throw new CatalogProjectionContractError(
      "Catalog 商品详情缺少稳定身份、版本或经营字段。",
    );
  }
  return value;
}
 
function validateCategories(value: Category[]): Category[] {
  Iif (!Array.isArray(value) || !value.every(validCategory)) {
    throw new CatalogProjectionContractError(
      "Catalog 分类投影缺少稳定字符串 ID 或必要字段。",
    );
  }
  return [...new Map(value.map((item) => [item.id, item])).values()]
    .sort((left, right) => left.sortOrder - right.sortOrder
      || left.name.localeCompare(right.name));
}
 
function validateBrands(value: Brand[]): Brand[] {
  Iif (!Array.isArray(value) || !value.every(validBrand)) {
    throw new CatalogProjectionContractError(
      "Catalog 品牌投影缺少稳定字符串 ID 或必要字段。",
    );
  }
  return [...new Map(value.map((item) => [item.id, item])).values()]
    .sort((left, right) => left.name.localeCompare(right.name));
}
 
function validateProductsPage(
  value: PageResponse<AdminProductSummary>,
  expectedPage: number,
  expectedSize: number,
  expectedStatus: AdminProductStatus | "",
): PageResponse<AdminProductSummary> {
  if (
    !value
    || typeof value !== "object"
    || !Array.isArray(value.items)
    || !value.items.every(validAdminProduct)
    || (expectedStatus !== ""
      && value.items.some((item) => item.status !== expectedStatus))
    || !Number.isInteger(value.page)
    || value.page !== expectedPage
    || !Number.isInteger(value.size)
    || value.size !== expectedSize
    || !Number.isInteger(value.total)
    || value.total < value.items.length
    || value.items.length > expectedSize
    || new Set(value.items.map((item) => item.id)).size !== value.items.length
  ) {
    throw new CatalogProjectionContractError(
      "Catalog 管理商品分页与当前查询、状态或字符串身份契约不一致。",
    );
  }
  return value;
}
 
function storageKey(operatorId: BusinessId): string {
  return `${PENDING_CREATE_PREFIX}${operatorId}`;
}
 
function validCreateInput(value: unknown): value is CreateProductInput {
  if (!value || typeof value !== "object") {
    return false;
  }
  const input = value as Partial<CreateProductInput>;
  return isBusinessId(input.categoryId)
    && isBusinessId(input.brandId)
    && typeof input.title === "string"
    && input.title.length > 0
    && input.title.length <= 160
    && Array.isArray(input.skus)
    && input.skus.length > 0
    && input.skus.every((sku) => Boolean(
      sku
      && typeof sku.skuCode === "string"
      && sku.skuCode.length > 0
      && typeof sku.name === "string"
      && sku.name.length > 0
      && typeof sku.specJson === "string"
      && typeof sku.salePrice === "string"
      && sku.salePrice.length > 0,
    ));
}
 
function loadPending(operatorId: BusinessId): PendingProductCreate | null {
  Iif (typeof localStorage === "undefined") {
    return null;
  }
  try {
    const raw = localStorage.getItem(storageKey(operatorId));
    Eif (!raw) {
      return null;
    }
    const value = JSON.parse(raw) as Partial<PendingProductCreate>;
    return typeof value.commandId === "string"
      && value.commandId.length > 0
      && value.commandId.length <= 64
      && validCreateInput(value.input)
      && typeof value.createdAt === "string"
      && Number.isFinite(Date.parse(value.createdAt))
      ? value as PendingProductCreate
      : null;
  } catch {
    return null;
  }
}
 
function savePending(operatorId: BusinessId, command: PendingProductCreate | null) {
  Iif (typeof localStorage === "undefined") {
    return;
  }
  if (command) {
    localStorage.setItem(storageKey(operatorId), JSON.stringify(command));
  } else {
    localStorage.removeItem(storageKey(operatorId));
  }
}
 
function sameMoney(left: string | number, right: string): boolean {
  return Number(left) === Number(right);
}
 
function createResultMatches(
  product: ProductDetail,
  input: CreateProductInput,
): boolean {
  return product.category.id === input.categoryId
    && product.brand.id === input.brandId
    && product.title === input.title
    && (product.subtitle ?? null) === (input.subtitle ?? null)
    && (product.description ?? null) === (input.description ?? null)
    && product.skus.length === input.skus.length
    && input.skus.every((expected, index) => {
      const actual = product.skus[index];
      return actual?.skuCode === expected.skuCode
        && actual.name === expected.name
        && actual.specJson === expected.specJson
        && sameMoney(actual.salePrice, expected.salePrice)
        && (actual.marketPrice === null && expected.marketPrice == null
          || actual.marketPrice !== null
            && expected.marketPrice != null
            && sameMoney(actual.marketPrice, expected.marketPrice));
    });
}
 
async function uploadObject(intentUrl: string, file: File): Promise<void> {
  const controller = new AbortController();
  const timeout = globalThis.setTimeout(() => controller.abort(), 15000);
  try {
    const response = await fetch(intentUrl, {
      method: "PUT",
      headers: { "Content-Type": file.type },
      body: file,
      signal: controller.signal,
    });
    if (!response.ok) {
      throw new ApiError(
        "http",
        `HTTP_${response.status}`,
        "对象存储明确拒绝了商品图片上传。",
        response.status,
      );
    }
  } catch (cause) {
    if (cause instanceof ApiError) throw cause;
    if (cause instanceof DOMException && cause.name === "AbortError") {
      throw new ApiError(
        "timeout",
        "UPLOAD_TIMEOUT",
        "图片上传响应未能确认。",
        undefined,
        { cause },
      );
    }
    throw new ApiError(
      "network",
      "UPLOAD_NETWORK_UNAVAILABLE",
      "暂时无法连接对象存储。",
      undefined,
      { cause },
    );
  } finally {
    globalThis.clearTimeout(timeout);
  }
}
 
export const useAdminCatalogStore = defineStore("admin-catalog", () => {
  const categories = ref<Category[]>([]);
  const brands = ref<Brand[]>([]);
  const products = ref<AdminProductSummary[]>([]);
  const selectedProduct = ref<ProductDetail | null>(null);
  const query = reactive({
    keyword: "",
    categoryId: "" as BusinessId | "",
    status: "" as AdminProductStatus | "",
    page: 1,
    size: 20,
  });
  const total = ref(0);
  const loadingCategories = ref(false);
  const loadingBrands = ref(false);
  const loadingProducts = ref(false);
  const loadingDetail = ref(false);
  const categoriesError = ref<string | null>(null);
  const brandsError = ref<string | null>(null);
  const productsError = ref<string | null>(null);
  const detailError = ref<string | null>(null);
  const refreshedAt = ref<string | null>(null);
  const activeOperatorId = ref<BusinessId | null>(null);
  const commandPhase = ref<CatalogCommandPhase>("idle");
  const commandMessage = ref<string | null>(null);
  const pendingCreate = ref<PendingProductCreate | null>(null);
  let activeAccessToken: string | null = null;
  let accessRevision = 0;
  let categoriesRevision = 0;
  let brandsRevision = 0;
  let productsRevision = 0;
  let detailRevision = 0;
  let commandRevision = 0;
  let activeCreatePromise: Promise<ProductDetail | null> | null = null;
 
  const pageCount = computed(() => Math.max(1, Math.ceil(total.value / query.size)));
  const hasPreviousPage = computed(() => query.page > 1);
  const hasNextPage = computed(() => query.page < pageCount.value);
  const visibleStart = computed(() => products.value.length === 0
    ? 0
    : ((query.page - 1) * query.size) + 1);
  const visibleEnd = computed(() => products.value.length === 0
    ? 0
    : visibleStart.value + products.value.length - 1);
  const refreshing = computed(() => loadingCategories.value
    || loadingBrands.value
    || loadingProducts.value
    || loadingDetail.value);
 
  function activeAccess(context: AdminCatalogAccessContext): ActiveAccess | null {
    Iif (!isActiveContext(context)) return null;
    return {
      operatorId: context.operatorId,
      accessToken: context.accessToken,
      revision: accessRevision,
      api: createApi(context.accessToken),
    };
  }
 
  function accessIsCurrent(access: ActiveAccess): boolean {
    return access.revision === accessRevision
      && access.operatorId === activeOperatorId.value
      && access.accessToken === activeAccessToken;
  }
 
  function requireCurrent(access: ActiveAccess) {
    if (!accessIsCurrent(access)) throw new CatalogAccessChangedError();
  }
 
  function synchronizeAccess(context: AdminCatalogAccessContext) {
    const nextOperatorId = isActiveContext(context) ? context.operatorId : null;
    const nextAccessToken = isActiveContext(context) ? context.accessToken : null;
    const operatorChanged = activeOperatorId.value !== nextOperatorId;
    const accessChanged = operatorChanged || activeAccessToken !== nextAccessToken;
    if (!accessChanged) return activeAccess(context);
 
    activeOperatorId.value = nextOperatorId;
    activeAccessToken = nextAccessToken;
    accessRevision += 1;
    categoriesRevision += 1;
    brandsRevision += 1;
    productsRevision += 1;
    detailRevision += 1;
    commandRevision += 1;
    activeCreatePromise = null;
    loadingCategories.value = false;
    loadingBrands.value = false;
    loadingProducts.value = false;
    loadingDetail.value = false;
 
    if (operatorChanged) {
      categories.value = [];
      brands.value = [];
      products.value = [];
      selectedProduct.value = null;
      query.keyword = "";
      query.categoryId = "";
      query.status = "";
      query.page = 1;
      total.value = 0;
      categoriesError.value = null;
      brandsError.value = null;
      productsError.value = null;
      detailError.value = null;
      refreshedAt.value = null;
      pendingCreate.value = nextOperatorId ? loadPending(nextOperatorId) : null;
      commandPhase.value = pendingCreate.value ? "unknown" : "idle";
      commandMessage.value = pendingCreate.value
        ? "发现一条结果未知的商品创建命令;原命令 ID 与完整载荷已恢复,只能先查询或原样重放。"
        : null;
    } else Eif (pendingCreate.value) {
      commandPhase.value = "unknown";
      commandMessage.value = "员工会话凭据已更新,商品创建命令仍保持结果未知。";
    }
    return activeAccess(context);
  }
 
  function requireAccess(context: AdminCatalogAccessContext, message: string): ActiveAccess | null {
    const access = synchronizeAccess(context);
    Iif (!access) {
      commandPhase.value = "rejected";
      commandMessage.value = message;
    }
    return access;
  }
 
  async function loadCategories(context: AdminCatalogAccessContext) {
    const access = synchronizeAccess(context);
    Iif (!access) {
      categoriesError.value = "当前会话无权读取商品经营工作区。";
      return;
    }
    const revision = ++categoriesRevision;
    loadingCategories.value = true;
    categoriesError.value = null;
    try {
      const value = validateCategories(await access.api.listCategories());
      requireCurrent(access);
      Eif (revision === categoriesRevision) categories.value = value;
    } catch (cause) {
      if (accessIsCurrent(access) && revision === categoriesRevision) {
        categoriesError.value = errorMessage(cause, "Catalog 分类暂时无法读取。");
      }
    } finally {
      Eif (accessIsCurrent(access) && revision === categoriesRevision) {
        loadingCategories.value = false;
      }
    }
  }
 
  async function loadBrands(context: AdminCatalogAccessContext) {
    const access = synchronizeAccess(context);
    Iif (!access) {
      brandsError.value = "当前会话无权读取商品经营工作区。";
      return;
    }
    const revision = ++brandsRevision;
    loadingBrands.value = true;
    brandsError.value = null;
    try {
      const value = validateBrands(await access.api.listBrands());
      requireCurrent(access);
      Eif (revision === brandsRevision) brands.value = value;
    } catch (cause) {
      if (accessIsCurrent(access) && revision === brandsRevision) {
        brandsError.value = errorMessage(cause, "Catalog 品牌暂时无法读取。");
      }
    } finally {
      Eif (accessIsCurrent(access) && revision === brandsRevision) {
        loadingBrands.value = false;
      }
    }
  }
 
  async function loadProducts(context: AdminCatalogAccessContext) {
    const access = synchronizeAccess(context);
    Iif (!access) {
      productsError.value = "当前会话无权读取商品经营工作区。";
      return;
    }
    const expectedPage = query.page;
    const expectedSize = query.size;
    const expectedStatus = query.status;
    const request: AdminProductQuery = { page: expectedPage, size: expectedSize };
    if (expectedStatus) request.status = expectedStatus;
    if (query.categoryId) request.categoryId = query.categoryId;
    if (query.keyword.trim()) request.keyword = query.keyword.trim();
    const revision = ++productsRevision;
    loadingProducts.value = true;
    productsError.value = null;
    try {
      const value = validateProductsPage(
        await access.api.listAdminProducts(request),
        expectedPage,
        expectedSize,
        expectedStatus,
      );
      requireCurrent(access);
      if (revision === productsRevision) {
        products.value = value.items;
        total.value = value.total;
        refreshedAt.value = new Date().toISOString();
      }
    } catch (cause) {
      if (accessIsCurrent(access) && revision === productsRevision) {
        productsError.value = errorMessage(cause, "Catalog 管理商品暂时无法读取。");
      }
    } finally {
      if (accessIsCurrent(access) && revision === productsRevision) {
        loadingProducts.value = false;
      }
    }
  }
 
  async function loadProduct(
    context: AdminCatalogAccessContext,
    productId: BusinessId,
  ): Promise<ProductDetail | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      detailError.value = "当前会话无权读取商品详情。";
      return null;
    }
    const revision = ++detailRevision;
    loadingDetail.value = true;
    detailError.value = null;
    try {
      const product = validateProductDetail(await access.api.getAdminProduct(productId));
      requireCurrent(access);
      if (revision === detailRevision) {
        selectedProduct.value = product;
        return product;
      }
      return null;
    } catch (cause) {
      if (accessIsCurrent(access) && revision === detailRevision) {
        detailError.value = errorMessage(cause, "Catalog 商品详情暂时无法读取。");
      }
      return null;
    } finally {
      if (accessIsCurrent(access) && revision === detailRevision) {
        loadingDetail.value = false;
      }
    }
  }
 
  async function loadWorkspace(context: AdminCatalogAccessContext) {
    await Promise.all([loadCategories(context), loadBrands(context), loadProducts(context)]);
  }
 
  async function applyFilters(context: AdminCatalogAccessContext) {
    query.keyword = query.keyword.trim();
    query.page = 1;
    await loadProducts(context);
  }
 
  async function clearFilters(context: AdminCatalogAccessContext) {
    query.keyword = "";
    query.categoryId = "";
    query.status = "";
    query.page = 1;
    await loadProducts(context);
  }
 
  async function goToPage(context: AdminCatalogAccessContext, page: number) {
    Iif (!Number.isInteger(page)
      || page < 1
      || page > pageCount.value
      || page === query.page) return;
    query.page = page;
    await loadProducts(context);
  }
 
  async function refreshProductFacts(
    context: AdminCatalogAccessContext,
    productId: BusinessId,
  ) {
    await Promise.all([loadProducts(context), loadProduct(context, productId)]);
  }
 
  function settleCreateAccepted(access: ActiveAccess, product: ProductDetail) {
    pendingCreate.value = null;
    savePending(access.operatorId, null);
    selectedProduct.value = product;
    commandPhase.value = "accepted";
    commandMessage.value = `Catalog 已确认商品 ${product.id} 的创建事实。`;
  }
 
  async function executeCreate(
    access: ActiveAccess,
    command: PendingProductCreate,
  ): Promise<ProductDetail | null> {
    const revision = ++commandRevision;
    commandPhase.value = "processing";
    commandMessage.value = "商品创建命令正在等待 Catalog 确认。";
    try {
      const product = validateProductDetail(
        await access.api.createProduct(command.input, command.commandId),
      );
      requireCurrent(access);
      Iif (revision !== commandRevision) return null;
      Iif (!createResultMatches(product, command.input)) {
        throw new CatalogProjectionContractError(
          "Catalog 已响应,但创建结果与冻结的商品载荷不一致。",
        );
      }
      settleCreateAccepted(access, product);
      await loadProducts({
        authorized: true,
        operatorId: access.operatorId,
        accessToken: access.accessToken,
      });
      return product;
    } catch (cause) {
      Iif (!accessIsCurrent(access) || revision !== commandRevision) return null;
      if (resultMayBeUnknown(cause)) {
        commandPhase.value = "unknown";
        commandMessage.value =
          `${errorMessage(cause, "商品创建响应未能确认。")} `
          + "原命令 ID 与完整载荷已冻结;请先查询服务端事实,再决定是否原样重放。";
      } else E{
        pendingCreate.value = null;
        savePending(access.operatorId, null);
        commandPhase.value = "rejected";
        commandMessage.value = errorMessage(cause, "Catalog 明确拒绝了商品创建命令。");
      }
      return null;
    }
  }
 
  function runCreate(
    access: ActiveAccess,
    command: PendingProductCreate,
  ): Promise<ProductDetail | null> {
    Iif (activeCreatePromise) return activeCreatePromise;
    pendingCreate.value = command;
    savePending(access.operatorId, command);
    const request = executeCreate(access, command);
    activeCreatePromise = request;
    const clear = () => {
      Eif (activeCreatePromise === request) activeCreatePromise = null;
    };
    void request.then(clear, clear);
    return request;
  }
 
  function createProduct(
    context: AdminCatalogAccessContext,
    input: CreateProductInput,
  ): Promise<ProductDetail | null> {
    const access = requireAccess(context, "当前会话无权创建商品。");
    Iif (!access) return Promise.resolve(null);
    Iif (pendingCreate.value) {
      commandPhase.value = "unknown";
      commandMessage.value = "已有一条结果未知的创建命令;必须先查询或原样重放,不能覆盖它。";
      return Promise.resolve(null);
    }
    return runCreate(access, {
      commandId: `catalog:create:${secureRandomUUID()}`,
      input: structuredClone(input),
      createdAt: new Date().toISOString(),
    });
  }
 
  async function resolvePendingCreate(
    context: AdminCatalogAccessContext,
  ): Promise<ProductDetail | null> {
    const access = requireAccess(context, "当前会话无权查询创建命令。");
    const command = pendingCreate.value;
    Iif (!access || !command) return null;
    const revision = ++commandRevision;
    commandPhase.value = "processing";
    commandMessage.value = "正在按原命令 ID 查询 Catalog 事实。";
    try {
      const product = validateProductDetail(
        await access.api.findCreatedProduct(command.commandId),
      );
      requireCurrent(access);
      if (revision !== commandRevision) return null;
      if (!createResultMatches(product, command.input)) {
        throw new CatalogProjectionContractError(
          "Catalog 返回的创建事实与冻结载荷不一致。",
        );
      }
      settleCreateAccepted(access, product);
      await loadProducts(context);
      return product;
    } catch (cause) {
      Iif (!accessIsCurrent(access) || revision !== commandRevision) return null;
      commandPhase.value = "unknown";
      commandMessage.value = cause instanceof ApiError
        && cause.code === "RESOURCE_NOT_FOUND"
        ? "Catalog 尚未观察到该命令的创建事实;原载荷仍被保留,可原样重放。"
        : `${errorMessage(cause, "创建事实查询未完成。")} 不能据此判断原命令失败。`;
      return null;
    }
  }
 
  function retryPendingCreate(
    context: AdminCatalogAccessContext,
  ): Promise<ProductDetail | null> {
    const access = requireAccess(context, "当前会话无权重放创建命令。");
    const command = pendingCreate.value;
    return access && command ? runCreate(access, command) : Promise.resolve(null);
  }
 
  async function executeProductCommand(
    context: AdminCatalogAccessContext,
    productId: BusinessId,
    action: (api: CatalogApi) => Promise<ProductDetail>,
    recovered: (product: ProductDetail) => boolean,
    acceptedMessage: string,
  ): Promise<ProductDetail | null> {
    const access = requireAccess(context, "当前会话无权修改商品。");
    if (!access) return null;
    const revision = ++commandRevision;
    commandPhase.value = "processing";
    commandMessage.value = "商品命令正在等待 Catalog 确认。";
    try {
      const product = validateProductDetail(await action(access.api));
      requireCurrent(access);
      if (revision !== commandRevision) return null;
      selectedProduct.value = product;
      commandPhase.value = "accepted";
      commandMessage.value = acceptedMessage;
      await loadProducts(context);
      return product;
    } catch (cause) {
      if (!accessIsCurrent(access) || revision !== commandRevision) return null;
      if (!resultMayBeUnknown(cause)) {
        commandPhase.value = "rejected";
        commandMessage.value = errorMessage(cause, "Catalog 明确拒绝了商品命令。");
        return null;
      }
      commandPhase.value = "unknown";
      commandMessage.value =
        `${errorMessage(cause, "商品命令响应未能确认。")} 正在读取当前 owner 事实。`;
      try {
        const current = validateProductDetail(await access.api.getAdminProduct(productId));
        requireCurrent(access);
        if (revision !== commandRevision) return null;
        selectedProduct.value = current;
        if (recovered(current)) {
          commandPhase.value = "accepted";
          commandMessage.value = `${acceptedMessage}(通过 owner 详情恢复确认)`;
          await loadProducts(context);
          return current;
        }
        commandMessage.value =
          "当前 owner 事实尚不能证明原命令成功或失败;页面不会自动重放写请求。";
      } catch (readCause) {
        if (accessIsCurrent(access) && revision === commandRevision) {
          commandMessage.value =
            `${errorMessage(readCause, "当前 owner 事实读取失败。")} 原命令仍保持结果未知。`;
        }
      }
      return null;
    }
  }
 
  function updateProduct(
    context: AdminCatalogAccessContext,
    productId: BusinessId,
    input: UpdateProductInput,
  ) {
    return executeProductCommand(
      context,
      productId,
      (api) => api.updateProduct(productId, input),
      (current) => current.id === productId
        && current.version === input.expectedVersion + 1
        && current.category.id === input.categoryId
        && current.brand.id === input.brandId
        && current.title === input.title
        && (current.subtitle ?? null) === (input.subtitle ?? null)
        && (current.description ?? null) === (input.description ?? null),
      `Catalog 已确认商品 ${productId} 的基本信息更新。`,
    );
  }
 
  function setPublished(
    context: AdminCatalogAccessContext,
    productId: BusinessId,
    expectedVersion: number,
    publish: boolean,
  ) {
    const target: AdminProductStatus = publish ? "ACTIVE" : "INACTIVE";
    return executeProductCommand(
      context,
      productId,
      (api) => publish
        ? api.publishProduct(productId, expectedVersion)
        : api.unpublishProduct(productId, expectedVersion),
      (current) => current.id === productId
        && current.version === expectedVersion + 1
        && current.status === target,
      `Catalog 已确认商品 ${productId} 迁移为 ${target}。`,
    );
  }
 
  async function updateSku(
    context: AdminCatalogAccessContext,
    productId: BusinessId,
    skuId: BusinessId,
    input: UpdateProductSkuInput,
  ): Promise<ProductSku | null> {
    const access = requireAccess(context, "当前会话无权修改 SKU。");
    if (!access) return null;
    const revision = ++commandRevision;
    commandPhase.value = "processing";
    commandMessage.value = "SKU 命令正在等待 Catalog 确认。";
    try {
      const sku = await access.api.updateProductSku(productId, skuId, input);
      if (!validSku(sku)
        || sku.id !== skuId
        || sku.version !== input.expectedVersion + 1) {
        throw new CatalogProjectionContractError(
          "Catalog 已响应,但 SKU 结果与冻结命令不一致。",
        );
      }
      requireCurrent(access);
      if (revision !== commandRevision) return null;
      commandPhase.value = "accepted";
      commandMessage.value = `Catalog 已确认 SKU ${skuId} 的更新。`;
      await refreshProductFacts(context, productId);
      return sku;
    } catch (cause) {
      if (!accessIsCurrent(access) || revision !== commandRevision) return null;
      if (!resultMayBeUnknown(cause)) {
        commandPhase.value = "rejected";
        commandMessage.value = errorMessage(cause, "Catalog 明确拒绝了 SKU 命令。");
        return null;
      }
      commandPhase.value = "unknown";
      commandMessage.value =
        `${errorMessage(cause, "SKU 命令响应未能确认。")} 页面不会自动重放写请求。`;
      return null;
    }
  }
 
  async function uploadMedia(
    context: AdminCatalogAccessContext,
    productId: BusinessId,
    file: File,
    skuId: BusinessId | null,
    sortOrder: number,
  ): Promise<ProductMedia | null> {
    const access = requireAccess(context, "当前会话无权上传商品图片。");
    if (!access) return null;
    const revision = ++commandRevision;
    commandPhase.value = "processing";
    commandMessage.value = "正在申请上传凭据并写入对象存储。";
    let objectKey: string | null = null;
    try {
      const intent = await access.api.createProductUploadIntent(
        productId,
        file.type,
        file.size,
      );
      objectKey = intent.objectKey;
      await uploadObject(intent.uploadUrl, file);
      const media = await access.api.confirmProductMedia(productId, {
        skuId,
        objectKey,
        sortOrder,
      });
      if (!validMedia(media) || media.objectKey !== objectKey) {
        throw new CatalogProjectionContractError(
          "Catalog 已响应,但媒体事实与上传对象不一致。",
        );
      }
      requireCurrent(access);
      if (revision !== commandRevision) return null;
      commandPhase.value = "accepted";
      commandMessage.value = `Catalog 已确认媒体 ${media.id}。`;
      await refreshProductFacts(context, productId);
      return media;
    } catch (cause) {
      if (!accessIsCurrent(access) || revision !== commandRevision) return null;
      if (!objectKey || !resultMayBeUnknown(cause)) {
        commandPhase.value = "rejected";
        commandMessage.value = errorMessage(cause, "媒体上传被明确拒绝。");
        return null;
      }
      try {
        const current = validateProductDetail(await access.api.getAdminProduct(productId));
        requireCurrent(access);
        if (revision !== commandRevision) return null;
        const media = current.media.find((item) => item.objectKey === objectKey);
        selectedProduct.value = current;
        if (media) {
          commandPhase.value = "accepted";
          commandMessage.value =
            `Catalog owner 详情已确认媒体 ${media.id},响应丢失没有制造第二条记录。`;
          await loadProducts(context);
          return media;
        }
      } catch {
        // The original result remains unknown; the message below is authoritative.
      }
      commandPhase.value = "unknown";
      commandMessage.value =
        `对象 ${objectKey} 的确认结果未知;当前详情不能证明它已登记,页面不会换 object key 猜测重试。`;
      return null;
    }
  }
 
  return {
    categories,
    brands,
    products,
    selectedProduct,
    query,
    total,
    loadingCategories,
    loadingBrands,
    loadingProducts,
    loadingDetail,
    categoriesError,
    brandsError,
    productsError,
    detailError,
    refreshedAt,
    commandPhase,
    commandMessage,
    pendingCreate,
    pageCount,
    hasPreviousPage,
    hasNextPage,
    visibleStart,
    visibleEnd,
    refreshing,
    synchronizeAccess,
    loadCategories,
    loadBrands,
    loadProducts,
    loadProduct,
    loadWorkspace,
    applyFilters,
    clearFilters,
    goToPage,
    createProduct,
    resolvePendingCreate,
    retryPendingCreate,
    updateProduct,
    setPublished,
    updateSku,
    uploadMedia,
  };
});