All files / src/entities/admin-inventory/model adminInventoryStore.ts

69.04% Statements 232/336
57.76% Branches 119/206
83.33% Functions 40/48
69.16% Lines 231/334

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                              2x   2x                                                                     1x 1x                                   42x               14x     8x         14x       11x             27x 27x             8x       13x       7x 6x   1x 1x 1x                                       1x             7x     7x             6x     6x 4x   2x         4x     4x     4x             4x     2x 6x 6x 6x 6x 6x             6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 4x 1x   3x 3x       6x   6x 4x           14x     14x                 17x           4x 1x         7x 6x   1x         1x 1x 1x 1x 1x       14x 14x 14x 14x 14x 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       7x                                 1x 1x       1x 1x 1x 1x 1x 1x 1x         1x       1x                     1x 1x         1x                                                                                 4x 4x 4x 4x       2x 2x 2x 2x                         7x                         5x 1x         4x             1x                       1x 1x                             1x         1x 1x 1x 1x 1x 1x 1x 1x               5x 5x 5x 5x 5x 5x 1x 1x     1x 1x     1x 1x           5x   4x     4x 4x 4x     4x               5x 5x                 4x     4x 4x 4x 4x 4x 4x     4x 4x           1x       1x     1x           1x 1x 1x                       3x       3x     3x           3x 3x                                 1x       1x             1x           1x     1x 1x 1x 1x 1x 1x     1x 1x           2x       2x 2x             2x 2x 2x 2x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x       1x           1x     1x 1x 1x 1x     1x 1x 1x 1x 1x     1x                   2x 2x                         6x                                                      
import { computed, reactive, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createApiClient,
  createInventoryApi,
  secureRandomUUID,
  type AdjustStockInput,
  type BusinessId,
  type InventoryApi,
  type StockPosition,
  type Warehouse,
} from "@plain-journal/foundation";
 
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
const PENDING_STORAGE_PREFIX =
  "plain-journal:admin-inventory:pending-command:v1:";
 
type NumericInput = string | number;
type InventoryCommandKind = "warehouse" | "adjustment";
 
export type InventoryCommandPhase =
  | "idle"
  | "processing"
  | "unknown"
  | "accepted"
  | "rejected";
 
export interface AdminInventoryAccessContext {
  authorized: boolean;
  operatorId: BusinessId | null;
  accessToken: string | null;
}
 
interface ActiveAccess {
  operatorId: BusinessId;
  accessToken: string;
  revision: number;
  api: InventoryApi;
}
 
interface PendingInventoryCommand {
  kind: InventoryCommandKind;
  referenceNo: string;
  commandKey: string;
  payload: Record<string, unknown>;
  createdAt: string;
}
 
export class InventoryAccessChangedError extends Error {
  constructor() {
    super("员工账户或会话已切换,旧的库存请求结果不会写入当前页面。");
    this.name = "InventoryAccessChangedError";
  }
}
 
export class InventoryContractError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "InventoryContractError";
  }
}
 
function isActiveContext(
  context: AdminInventoryAccessContext,
): context is {
  authorized: true;
  operatorId: BusinessId;
  accessToken: string;
} {
  return context.authorized
    && typeof context.operatorId === "string"
    && context.operatorId.length > 0
    && typeof context.accessToken === "string"
    && context.accessToken.length > 0;
}
 
function createApi(accessToken: string): InventoryApi {
  return createInventoryApi(createApiClient({
    baseUrl: apiBaseUrl,
    timeoutMs: 10000,
    tokenProvider: () => accessToken,
  }));
}
 
function newMovementNo(): string {
  return `admin-stock:${secureRandomUUID()}`;
}
 
function normalizedInput(value: unknown): string {
  return String(value ?? "").trim();
}
 
function stringPayload(
  payload: Record<string, unknown>,
  key: string,
): string {
  const value = payload[key];
  return typeof value === "string" ? value : "";
}
 
function numberPayload(
  payload: Record<string, unknown>,
  key: string,
): number {
  return Number(payload[key]);
}
 
function storageKey(operatorId: BusinessId): string {
  return `${PENDING_STORAGE_PREFIX}${operatorId}`;
}
 
function parsePending(raw: string | null): PendingInventoryCommand | null {
  if (!raw) {
    return null;
  }
  try {
    const value: unknown = JSON.parse(raw);
    Iif (
      !value
      || typeof value !== "object"
      || !("kind" in value)
      || !["warehouse", "adjustment"].includes(String(value.kind))
      || !("referenceNo" in value)
      || typeof value.referenceNo !== "string"
      || value.referenceNo.length === 0
      || !("commandKey" in value)
      || typeof value.commandKey !== "string"
      || value.commandKey.length === 0
      || !("payload" in value)
      || !value.payload
      || typeof value.payload !== "object"
      || Array.isArray(value.payload)
      || !("createdAt" in value)
      || typeof value.createdAt !== "string"
    ) {
      return null;
    }
    return value as PendingInventoryCommand;
  } catch {
    return null;
  }
}
 
function loadPending(operatorId: BusinessId): PendingInventoryCommand | null {
  Iif (typeof localStorage === "undefined") {
    return null;
  }
  return parsePending(localStorage.getItem(storageKey(operatorId)));
}
 
function savePending(
  operatorId: BusinessId,
  value: PendingInventoryCommand | null,
) {
  Iif (typeof localStorage === "undefined") {
    return;
  }
  if (value) {
    localStorage.setItem(storageKey(operatorId), JSON.stringify(value));
  } else {
    localStorage.removeItem(storageKey(operatorId));
  }
}
 
function resultMayBeUnknown(cause: unknown): boolean {
  Iif (cause instanceof InventoryContractError) {
    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 errorMessage(cause: unknown, fallback: string): string {
  return cause instanceof Error ? cause.message : fallback;
}
 
export const useAdminInventoryStore = defineStore("admin-inventory", () => {
  const warehouses = ref<Warehouse[]>([]);
  const stock = ref<StockPosition | null>(null);
  const warehouseForm = reactive({ code: "", name: "" });
  const lookup = reactive({ warehouseId: "", skuId: "" });
  const adjustment = reactive({
    movementNo: newMovementNo(),
    warehouseId: "",
    skuId: "",
    quantityDelta: 0 as NumericInput,
    reason: "",
  });
  const loadingWarehouses = ref(false);
  const stockBusy = ref(false);
  const loadError = ref<string | null>(null);
  const stockError = ref<string | null>(null);
  const commandPhase = ref<InventoryCommandPhase>("idle");
  const commandMessage = ref<string | null>(null);
  const pendingCommand = ref<PendingInventoryCommand | null>(null);
  const submitting = ref(false);
  const activeOperatorId = ref<BusinessId | null>(null);
  let activeAccessToken: string | null = null;
  let accessRevision = 0;
  let warehouseRevision = 0;
  let stockRevision = 0;
  let commandRevision = 0;
  let activeCommandPromise: Promise<Warehouse | StockPosition | null> | null = null;
 
  const pendingCommandLabel = computed(() => {
    if (pendingCommand.value?.kind === "warehouse") {
      return "创建仓库";
    }
    Eif (pendingCommand.value?.kind === "adjustment") {
      return "调整库存";
    }
    return null;
  });
  const pendingReferenceNo = computed(() =>
    pendingCommand.value?.referenceNo ?? null);
  const commandBlocked = computed(() =>
    submitting.value
    || (commandPhase.value === "unknown" && Boolean(pendingCommand.value)));
 
  function activeAccess(
    context: AdminInventoryAccessContext,
  ): 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 InventoryAccessChangedError();
    }
  }
 
  function hydratePending(command: PendingInventoryCommand | null) {
    if (!command) {
      return;
    }
    Iif (command.kind === "warehouse") {
      warehouseForm.code = stringPayload(command.payload, "code");
      warehouseForm.name = stringPayload(command.payload, "name");
      return;
    }
    adjustment.movementNo = command.commandKey;
    adjustment.warehouseId = stringPayload(command.payload, "warehouseId");
    adjustment.skuId = stringPayload(command.payload, "skuId");
    adjustment.quantityDelta = numberPayload(command.payload, "quantityDelta");
    adjustment.reason = stringPayload(command.payload, "reason");
  }
 
  function synchronizeAccess(context: AdminInventoryAccessContext) {
    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;
    warehouseRevision += 1;
    stockRevision += 1;
    commandRevision += 1;
    loadingWarehouses.value = false;
    stockBusy.value = false;
    submitting.value = false;
    activeCommandPromise = null;
 
    if (operatorChanged) {
      warehouses.value = [];
      stock.value = null;
      loadError.value = null;
      stockError.value = null;
      warehouseForm.code = "";
      warehouseForm.name = "";
      lookup.warehouseId = "";
      lookup.skuId = "";
      adjustment.movementNo = newMovementNo();
      adjustment.warehouseId = "";
      adjustment.skuId = "";
      adjustment.quantityDelta = 0;
      adjustment.reason = "";
      pendingCommand.value = nextOperatorId
        ? loadPending(nextOperatorId)
        : null;
      hydratePending(pendingCommand.value);
      commandPhase.value = pendingCommand.value ? "unknown" : "idle";
      commandMessage.value = pendingCommand.value
        ? "发现一条尚未确认的库存命令。业务号和原始载荷已恢复;请读取权威事实或沿用原流水重试。"
        : null;
    } else Eif (pendingCommand.value) {
      commandPhase.value = "unknown";
      commandMessage.value =
        "员工会话凭据已更新,原库存命令继续保持结果未知。";
    }
    return activeAccess(context);
  }
 
  function requireAccess(
    context: AdminInventoryAccessContext,
    message: string,
  ): ActiveAccess | null {
    const access = synchronizeAccess(context);
    Iif (!access) {
      commandPhase.value = "rejected";
      commandMessage.value = message;
    }
    return access;
  }
 
  function upsertWarehouse(value: Warehouse) {
    const index = warehouses.value.findIndex((warehouse) =>
      warehouse.id === value.id || warehouse.code === value.code);
    if (index >= 0) {
      warehouses.value[index] = value;
    } else {
      warehouses.value.push(value);
      warehouses.value.sort((left, right) => left.code.localeCompare(right.code));
    }
  }
 
  async function loadWarehouses(
    context: AdminInventoryAccessContext,
  ): Promise<void> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      loadError.value = "当前会话无权读取仓库事实。";
      return;
    }
    const requestRevision = ++warehouseRevision;
    loadingWarehouses.value = true;
    loadError.value = null;
    try {
      const values = await access.api.warehouses();
      requireCurrent(access);
      Iif (requestRevision !== warehouseRevision) {
        return;
      }
      warehouses.value = values;
    } catch (cause) {
      Iif (accessIsCurrent(access) && requestRevision === warehouseRevision) {
        loadError.value = errorMessage(cause, "仓库事实暂时无法读取。");
      }
    } finally {
      Iif (accessIsCurrent(access) && requestRevision === warehouseRevision) {
        loadingWarehouses.value = false;
      }
    }
  }
 
  async function readStock(
    access: ActiveAccess,
    warehouseId: string,
    skuId: string,
  ): Promise<StockPosition> {
    const value = await access.api.stockPosition(warehouseId, skuId);
    Iif (value.warehouseId !== warehouseId || value.skuId !== skuId) {
      throw new InventoryContractError(
        "Inventory 已响应,但返回库存与当前仓库或 SKU 不一致。",
      );
    }
    return value;
  }
 
  async function lookupStock(
    context: AdminInventoryAccessContext,
  ): Promise<StockPosition | null> {
    const access = synchronizeAccess(context);
    if (!access) {
      stockError.value = "当前会话无权读取库存事实。";
      return null;
    }
    const warehouseId = normalizedInput(lookup.warehouseId);
    const skuId = normalizedInput(lookup.skuId);
    const requestRevision = ++stockRevision;
    stockBusy.value = true;
    stockError.value = null;
    try {
      const value = await readStock(access, warehouseId, skuId);
      requireCurrent(access);
      if (requestRevision !== stockRevision) {
        return null;
      }
      stock.value = value;
      return value;
    } catch (cause) {
      if (accessIsCurrent(access) && requestRevision === stockRevision) {
        stock.value = null;
        stockError.value = errorMessage(cause, "库存事实暂时无法读取。");
      }
      return null;
    } finally {
      if (accessIsCurrent(access) && requestRevision === stockRevision) {
        stockBusy.value = false;
      }
    }
  }
 
  function beginPending(
    access: ActiveAccess,
    command: PendingInventoryCommand,
  ) {
    pendingCommand.value = command;
    savePending(access.operatorId, command);
    commandPhase.value = "processing";
    commandMessage.value = `${pendingCommandLabel.value}命令正在等待 Inventory 确认。`;
  }
 
  function settleAccepted(access: ActiveAccess, message: string) {
    pendingCommand.value = null;
    savePending(access.operatorId, null);
    commandPhase.value = "accepted";
    commandMessage.value = message;
  }
 
  function settleRejected(access: ActiveAccess, message: string) {
    pendingCommand.value = null;
    savePending(access.operatorId, null);
    commandPhase.value = "rejected";
    commandMessage.value = message;
  }
 
  function adjustmentInput(
    command: PendingInventoryCommand,
  ): AdjustStockInput {
    return {
      movementNo: command.commandKey,
      warehouseId: stringPayload(command.payload, "warehouseId"),
      skuId: stringPayload(command.payload, "skuId"),
      quantityDelta: numberPayload(command.payload, "quantityDelta"),
      reason: stringPayload(command.payload, "reason"),
    };
  }
 
  async function callCommand(
    api: InventoryApi,
    command: PendingInventoryCommand,
  ): Promise<Warehouse | StockPosition> {
    if (command.kind === "warehouse") {
      return api.createWarehouse(
        stringPayload(command.payload, "code"),
        stringPayload(command.payload, "name"),
      );
    }
    return api.adjustStock(adjustmentInput(command));
  }
 
  function validateResult(
    command: PendingInventoryCommand,
    value: Warehouse | StockPosition,
  ) {
    Iif (command.kind === "warehouse") {
      if (
        !("code" in value)
        || value.code !== stringPayload(command.payload, "code")
        || value.name !== stringPayload(command.payload, "name")
      ) {
        throw new InventoryContractError(
          "Inventory 已响应,但返回仓库与当前创建命令不一致。",
        );
      }
      return;
    }
    const input = adjustmentInput(command);
    Iif (
      !("warehouseId" in value)
      || value.warehouseId !== input.warehouseId
      || value.skuId !== input.skuId
    ) {
      throw new InventoryContractError(
        "Inventory 已响应,但返回库存与当前调整命令不一致。",
      );
    }
  }
 
  function resetAcceptedForm(
    command: PendingInventoryCommand,
    value: Warehouse | StockPosition,
  ) {
    Iif (command.kind === "warehouse") {
      warehouseForm.code = "";
      warehouseForm.name = "";
      return;
    }
    const input = adjustmentInput(command);
    lookup.warehouseId = input.warehouseId;
    lookup.skuId = input.skuId;
    adjustment.movementNo = newMovementNo();
    adjustment.quantityDelta = 0;
    adjustment.reason = "";
    Eif ("warehouseId" in value) {
      stock.value = value;
    }
  }
 
  async function executePending(
    access: ActiveAccess,
    command: PendingInventoryCommand,
  ): Promise<Warehouse | StockPosition | null> {
    const requestRevision = ++commandRevision;
    submitting.value = true;
    commandPhase.value = "processing";
    commandMessage.value = `${pendingCommandLabel.value}命令正在等待 Inventory 确认。`;
    try {
      const value = await callCommand(access.api, command);
      requireCurrent(access);
      Iif (requestRevision !== commandRevision) {
        return null;
      }
      validateResult(command, value);
      Iif ("code" in value) {
        upsertWarehouse(value);
      }
      resetAcceptedForm(command, value);
      settleAccepted(
        access,
        "code" in value
          ? `Inventory 已确认仓库 ${value.code} 已创建。`
          : `Inventory 已确认库存流水 ${command.commandKey} 已应用。`,
      );
      return value;
    } catch (cause) {
      Iif (!accessIsCurrent(access) || requestRevision !== commandRevision) {
        return null;
      }
      Eif (resultMayBeUnknown(cause)) {
        commandPhase.value = "unknown";
        commandMessage.value =
          `${errorMessage(cause, "库存命令响应未能确认。")} `
          + "页面没有显示成功;业务号、命令身份和原始载荷均已保留。";
        return null;
      }
      settleRejected(
        access,
        errorMessage(cause, "Inventory 已明确拒绝当前命令。"),
      );
      return null;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === commandRevision) {
        submitting.value = false;
      }
    }
  }
 
  function runPending(
    access: ActiveAccess,
    command: PendingInventoryCommand,
  ): Promise<Warehouse | StockPosition | null> {
    Iif (activeCommandPromise) {
      return activeCommandPromise;
    }
    beginPending(access, command);
    const request = executePending(access, command);
    activeCommandPromise = request;
    const clear = () => {
      Eif (activeCommandPromise === request) {
        activeCommandPromise = null;
      }
    };
    void request.then(clear, clear);
    return request;
  }
 
  function createWarehouse(
    context: AdminInventoryAccessContext,
  ): Promise<Warehouse | StockPosition | null> {
    const access = requireAccess(
      context,
      "当前会话无权创建仓库。",
    );
    Iif (!access) {
      return Promise.resolve(null);
    }
    Iif (commandBlocked.value) {
      commandPhase.value = "unknown";
      commandMessage.value =
        "上一条库存命令尚未确认,不能创建第二条命令。";
      return Promise.resolve(null);
    }
    const code = normalizedInput(warehouseForm.code).toUpperCase();
    const name = normalizedInput(warehouseForm.name);
    return runPending(access, {
      kind: "warehouse",
      referenceNo: code,
      commandKey: code,
      payload: { code, name },
      createdAt: new Date().toISOString(),
    });
  }
 
  function adjustStock(
    context: AdminInventoryAccessContext,
  ): Promise<Warehouse | StockPosition | null> {
    const access = requireAccess(
      context,
      "当前会话无权调整库存。",
    );
    Iif (!access) {
      return Promise.resolve(null);
    }
    Iif (commandBlocked.value) {
      commandPhase.value = "unknown";
      commandMessage.value =
        "上一条库存命令尚未确认,不能生成第二条库存流水。";
      return Promise.resolve(null);
    }
    const quantityDelta = Number(adjustment.quantityDelta);
    return runPending(access, {
      kind: "adjustment",
      referenceNo: adjustment.movementNo,
      commandKey: adjustment.movementNo,
      payload: {
        warehouseId: normalizedInput(adjustment.warehouseId),
        skuId: normalizedInput(adjustment.skuId),
        quantityDelta,
        reason: normalizedInput(adjustment.reason),
      },
      createdAt: new Date().toISOString(),
    });
  }
 
  function retryPending(
    context: AdminInventoryAccessContext,
  ): Promise<Warehouse | StockPosition | null> {
    const access = requireAccess(
      context,
      "当前会话无权重试库存命令。",
    );
    Iif (!access || !pendingCommand.value) {
      if (!pendingCommand.value) {
        commandPhase.value = "rejected";
        commandMessage.value = "当前没有可重试的结果未知命令。";
      }
      return Promise.resolve(null);
    }
    Iif (pendingCommand.value.kind === "warehouse") {
      commandPhase.value = "unknown";
      commandMessage.value =
        "仓库创建接口没有稳定幂等命令键,不能盲目重复 POST;请继续读取仓库列表核对唯一代码与名称。";
      return Promise.resolve(null);
    }
    Iif (activeCommandPromise) {
      return activeCommandPromise;
    }
    const command = pendingCommand.value;
    const request = executePending(access, command);
    activeCommandPromise = request;
    const clear = () => {
      Eif (activeCommandPromise === request) {
        activeCommandPromise = null;
      }
    };
    void request.then(clear, clear);
    return request;
  }
 
  async function readPendingAuthority(
    context: AdminInventoryAccessContext,
  ): Promise<Warehouse | StockPosition | null> {
    const access = requireAccess(
      context,
      "当前会话无权读取 Inventory 权威事实。",
    );
    const command = pendingCommand.value;
    Iif (!access || !command) {
      if (!command) {
        commandPhase.value = "rejected";
        commandMessage.value = "当前没有待核对的结果未知命令。";
      }
      return null;
    }
    const requestRevision = ++commandRevision;
    submitting.value = true;
    try {
      if (command.kind === "warehouse") {
        const values = await access.api.warehouses();
        requireCurrent(access);
        Iif (requestRevision !== commandRevision) {
          return null;
        }
        warehouses.value = values;
        const expectedName = stringPayload(command.payload, "name");
        const matched = values.find((value) => value.code === command.referenceNo);
        Eif (matched?.name === expectedName) {
          warehouseForm.code = "";
          warehouseForm.name = "";
          settleAccepted(
            access,
            `Inventory 仓库列表已确认 ${matched.code} / ${matched.name}。`,
          );
          return matched;
        }
        commandPhase.value = "unknown";
        commandMessage.value = matched
          ? "相同仓库代码已存在,但名称与原命令不一致,当前事实不能证明原创建命令成功。"
          : "仓库列表尚未出现原代码;原创建命令继续保持结果未知,不能开始第二条命令。";
        return matched ?? null;
      }
 
      const input = adjustmentInput(command);
      const value = await readStock(access, input.warehouseId, input.skuId);
      requireCurrent(access);
      Iif (requestRevision !== commandRevision) {
        return null;
      }
      stock.value = value;
      lookup.warehouseId = input.warehouseId;
      lookup.skuId = input.skuId;
      commandPhase.value = "unknown";
      commandMessage.value =
        `Inventory 当前库存为在手 ${value.onHand}、预占 ${value.reserved}、版本 ${value.version},`
        + "但库存 DTO 不公开 movementNo,不能把当前数量归因于原调整;必须沿用原流水重试确认。";
      return value;
    } catch (cause) {
      if (accessIsCurrent(access) && requestRevision === commandRevision) {
        commandPhase.value = "unknown";
        commandMessage.value =
          `${errorMessage(cause, "Inventory 权威事实暂时无法读取。")} `
          + "原命令继续保持结果未知。";
      }
      return null;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === commandRevision) {
        submitting.value = false;
      }
    }
  }
 
  function resetCommandNotice() {
    if (pendingCommand.value) {
      return;
    }
    commandPhase.value = "idle";
    commandMessage.value = null;
  }
 
  return {
    warehouses,
    stock,
    warehouseForm,
    lookup,
    adjustment,
    loadingWarehouses,
    stockBusy,
    loadError,
    stockError,
    commandPhase,
    commandMessage,
    pendingCommand,
    pendingCommandLabel,
    pendingReferenceNo,
    submitting,
    commandBlocked,
    synchronizeAccess,
    loadWarehouses,
    lookupStock,
    createWarehouse,
    adjustStock,
    retryPending,
    readPendingAuthority,
    resetCommandNotice,
  };
});