All files / src/entities/admin-fulfillment/model adminFulfillmentStore.ts

60.74% Statements 260/428
50.34% Branches 145/288
74.28% Functions 52/70
60.74% Lines 260/428

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 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263                                2x   2x                                                                                                                                                                                       1x 1x                                   63x               21x     12x         10x       21x       9x 8x   1x 1x 1x                                                         1x 1x                         9x     9x 9x 9x 1x   9x               5x                                   4x     4x                           2x     2x       6x 6x         5x     5x     5x             5x             46x 46x       26x           5x                     2x     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 6x 6x                             21x     21x                 23x           6x 1x         9x 8x   1x 1x         1x 1x                                                     21x 21x 21x 21x 21x 12x     9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x 9x 9x             45x       9x     9x 9x 9x                   9x             12x 12x       12x       5x   5x     5x                                 1x 1x       1x 1x 1x 1x 1x       1x 1x           1x 1x                 1x                       11x               11x                 2x       2x           6x 6x 6x             4x 4x                       2x 2x             5x 5x 5x 5x             1x 1x 1x 1x             5x     5x                     8x 8x   1x                 5x             2x                               5x 4x               1x   1x 1x                         8x 8x 8x 8x 8x 8x 3x 3x     3x 3x 3x       3x 3x       3x   5x     5x     5x 4x 4x     4x   1x       1x   8x 8x               7x       7x     7x 1x 1x   1x   6x     6x             6x 6x 6x 6x 6x     6x 6x             2x 2x     2x 2x             5x 5x 1x   4x 4x               1x                         1x                                                                           5x 5x 5x 5x         5x         5x 5x                                                                             1x 1x 1x         1x                                                                         3x       3x             3x       1x 1x   1x   2x     2x 2x 2x 2x 2x 2x     2x 2x                                         2x 2x 2x                   2x 2x                                                                         2x       2x 2x             2x 2x 2x 2x     2x 2x     2x 2x 2x       2x 2x 2x                   2x                         2x 2x                                                                                                                                                                                       8x                                                                                    
import { computed, reactive, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createApiClient,
  createFulfillmentApi,
  secureRandomUUID,
  type AddLogisticsTraceInput,
  type BusinessId,
  type Fulfillment,
  type FulfillmentApi,
  type NearbyShipmentPosition,
  type ReturnReceipt,
} from "@plain-journal/foundation";
 
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
const PENDING_STORAGE_PREFIX =
  "plain-journal:admin-fulfillment:pending-command:v1:";
 
export type FulfillmentCommandPhase =
  | "idle"
  | "processing"
  | "unknown"
  | "accepted"
  | "rejected";
 
type FulfillmentCommandKind =
  | "picking"
  | "packed"
  | "ship"
  | "trace"
  | "exception"
  | "resolve"
  | "receive"
  | "inspect";
 
type NonTraceFulfillmentCommandKind = Exclude<
  FulfillmentCommandKind,
  "trace"
>;
 
export interface AdminFulfillmentAccessContext {
  authorized: boolean;
  operatorId: BusinessId | null;
  accessToken: string | null;
}
 
interface ActiveAccess {
  operatorId: BusinessId;
  accessToken: string;
  revision: number;
  api: FulfillmentApi;
}
 
type FulfillmentCommandResult = Promise<
  Fulfillment | ReturnReceipt | null
>;
 
type SubmissionDecision =
  | { access: ActiveAccess }
  | { result: FulfillmentCommandResult };
 
interface PendingFulfillmentCommandBase {
  referenceNo: string;
  commandKey: string;
  payload: Record<string, unknown>;
  createdAt: string;
}
 
interface PendingTraceCommand extends PendingFulfillmentCommandBase {
  kind: "trace";
  requiresAuthorityRead?: boolean;
}
 
interface PendingNonTraceCommand extends PendingFulfillmentCommandBase {
  kind: NonTraceFulfillmentCommandKind;
  requiresAuthorityRead?: never;
}
 
type PendingFulfillmentCommand =
  | PendingTraceCommand
  | PendingNonTraceCommand;
 
interface ShipForm {
  carrier: string;
  trackingNo: string;
}
 
type NumericInput = string | number;
 
interface TraceForm {
  externalEventId: string;
  nodeType: "TRANSIT" | "DELIVERING" | "SIGNED" | "EXCEPTION";
  description: string;
  locationName: string;
  longitude: NumericInput;
  latitude: NumericInput;
}
 
interface ReasonForm {
  reason: string;
}
 
interface ResolutionForm extends ReasonForm {
  commandId: string;
}
 
export class FulfillmentAccessChangedError extends Error {
  constructor() {
    super("员工账户或会话已切换,旧的履约请求结果不会写入当前页面。");
    this.name = "FulfillmentAccessChangedError";
  }
}
 
export class FulfillmentContractError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "FulfillmentContractError";
  }
}
 
function isActiveContext(
  context: AdminFulfillmentAccessContext,
): 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): FulfillmentApi {
  return createFulfillmentApi(createApiClient({
    baseUrl: apiBaseUrl,
    timeoutMs: 10000,
    tokenProvider: () => accessToken,
  }));
}
 
function newIdentity(prefix: string): string {
  return `${prefix}:${secureRandomUUID()}`;
}
 
function storageKey(operatorId: BusinessId): string {
  return `${PENDING_STORAGE_PREFIX}${operatorId}`;
}
 
function parsePending(raw: string | null): PendingFulfillmentCommand | null {
  if (!raw) {
    return null;
  }
  try {
    const value: unknown = JSON.parse(raw);
    Iif (
      !value
      || typeof value !== "object"
      || !("kind" in value)
      || !("referenceNo" in value)
      || !("commandKey" in value)
      || !("payload" in value)
      || !("createdAt" in value)
      || ![
        "picking",
        "packed",
        "ship",
        "trace",
        "exception",
        "resolve",
        "receive",
        "inspect",
      ].includes(String(value.kind))
      || typeof value.referenceNo !== "string"
      || value.referenceNo.length === 0
      || typeof value.commandKey !== "string"
      || value.commandKey.length === 0
      || !value.payload
      || typeof value.payload !== "object"
      || Array.isArray(value.payload)
      || typeof value.createdAt !== "string"
    ) {
      return null;
    }
    const command = value as PendingFulfillmentCommand;
    return command.kind === "trace"
      ? traceAuthorityRecovery(
          command.referenceNo,
          command.commandKey,
          command.createdAt,
        )
      : command;
  } catch {
    return null;
  }
}
 
function loadPending(operatorId: BusinessId): PendingFulfillmentCommand | null {
  Iif (typeof localStorage === "undefined") {
    return null;
  }
  const key = storageKey(operatorId);
  const command = parsePending(localStorage.getItem(key));
  if (command?.kind === "trace") {
    localStorage.setItem(key, JSON.stringify(command));
  }
  return command;
}
 
function traceAuthorityRecovery(
  referenceNo: string,
  externalEventId: string,
  createdAt: string,
): PendingTraceCommand {
  return {
    kind: "trace",
    referenceNo,
    commandKey: externalEventId,
    payload: {
      externalEventId,
    },
    createdAt,
    requiresAuthorityRead: true,
  };
}
 
function saveTraceAuthorityRecovery(
  operatorId: BusinessId,
  referenceNo: string,
  externalEventId: string,
  createdAt: string,
) {
  Iif (typeof localStorage === "undefined") {
    return;
  }
  localStorage.setItem(
    storageKey(operatorId),
    JSON.stringify(traceAuthorityRecovery(
      referenceNo,
      externalEventId,
      createdAt,
    )),
  );
}
 
function saveRetryablePending(
  operatorId: BusinessId,
  command: PendingNonTraceCommand,
) {
  Iif (typeof localStorage === "undefined") {
    return;
  }
  localStorage.setItem(storageKey(operatorId), JSON.stringify(command));
}
 
function clearPending(operatorId: BusinessId) {
  Eif (typeof localStorage !== "undefined") {
    localStorage.removeItem(storageKey(operatorId));
  }
}
 
function resultMayBeUnknown(cause: unknown): boolean {
  Iif (cause instanceof FulfillmentContractError) {
    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;
}
 
function stringPayload(
  payload: Record<string, unknown>,
  key: string,
): string {
  const value = payload[key];
  return typeof value === "string" ? value : "";
}
 
function normalizedInput(value: unknown): string {
  return String(value ?? "").trim();
}
 
function tracePayload(
  payload: Record<string, unknown>,
): AddLogisticsTraceInput {
  return {
    externalEventId: stringPayload(payload, "externalEventId"),
    nodeType: stringPayload(payload, "nodeType") as AddLogisticsTraceInput["nodeType"],
    description: stringPayload(payload, "description"),
    locationName: stringPayload(payload, "locationName") || null,
    longitude: stringPayload(payload, "longitude") || null,
    latitude: stringPayload(payload, "latitude") || null,
    occurredAt: stringPayload(payload, "occurredAt"),
  };
}
 
export const useAdminFulfillmentStore = defineStore(
  "admin-fulfillment",
  () => {
    const fulfillments = ref<Fulfillment[]>([]);
    const returns = ref<ReturnReceipt[]>([]);
    const fulfillmentStatus = ref("");
    const returnStatus = ref("");
    const loading = ref(false);
    const loadError = ref<string | null>(null);
    const nearbyPositions = ref<NearbyShipmentPosition[]>([]);
    const geoQuery = reactive({
      longitude: "120.155100" as NumericInput,
      latitude: "30.274100" as NumericInput,
      radiusMeters: "50000" as NumericInput,
      limit: "20" as NumericInput,
    });
    const geoBusy = ref(false);
    const geoMessage = ref<string | null>(null);
    const geoError = ref<string | null>(null);
    const shipForms = reactive<Record<string, ShipForm>>({});
    const traceForms = reactive<Record<string, TraceForm>>({});
    const exceptionForms = reactive<Record<string, ReasonForm>>({});
    const resolutionForms = reactive<Record<string, ResolutionForm>>({});
    const inspectRemarks = reactive<Record<string, string>>({});
    const commandPhase = ref<FulfillmentCommandPhase>("idle");
    const commandMessage = ref<string | null>(null);
    const pendingCommand = ref<PendingFulfillmentCommand | null>(null);
    const submitting = ref(false);
    const activeOperatorId = ref<BusinessId | null>(null);
    let activeAccessToken: string | null = null;
    let accessRevision = 0;
    let factsRevision = 0;
    let geoRevision = 0;
    let commandRevision = 0;
    let activeCommandPromise: Promise<Fulfillment | ReturnReceipt | null> | null = null;
 
    const commandBlocked = computed(() =>
      submitting.value
      || (commandPhase.value === "unknown" && Boolean(pendingCommand.value)));
    const pendingReferenceNo = computed(() =>
      pendingCommand.value?.referenceNo ?? null);
    const pendingCommandLabel = computed(() => {
      const kind = pendingCommand.value?.kind;
      return kind ? {
        picking: "开始拣货",
        packed: "确认打包",
        ship: "确认发货",
        trace: "追加物流轨迹",
        exception: "标记履约异常",
        resolve: "恢复履约异常",
        receive: "确认退货收货",
        inspect: "确认退货验收",
      }[kind] : null;
    });
 
    function activeAccess(
      context: AdminFulfillmentAccessContext,
    ): 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 FulfillmentAccessChangedError();
      }
    }
 
    function hydratePending(command: PendingFulfillmentCommand | null) {
      if (!command) {
        return;
      }
      const { referenceNo, payload } = command;
      Iif (command.kind === "ship") {
        shipForms[referenceNo] = {
          carrier: stringPayload(payload, "carrier"),
          trackingNo: stringPayload(payload, "trackingNo"),
        };
      } else if (command.kind === "trace") {
        traceForms[referenceNo] = {
          externalEventId: stringPayload(payload, "externalEventId"),
          nodeType: stringPayload(payload, "nodeType") as TraceForm["nodeType"],
          description: stringPayload(payload, "description"),
          locationName: stringPayload(payload, "locationName"),
          longitude: command.requiresAuthorityRead
            ? ""
            : stringPayload(payload, "longitude"),
          latitude: command.requiresAuthorityRead
            ? ""
            : stringPayload(payload, "latitude"),
        };
      } else Eif (command.kind === "exception") {
        exceptionForms[referenceNo] = {
          reason: stringPayload(payload, "reason"),
        };
      } else if (command.kind === "resolve") {
        resolutionForms[referenceNo] = {
          commandId: command.commandKey,
          reason: stringPayload(payload, "reason"),
        };
      } else if (command.kind === "inspect") {
        inspectRemarks[referenceNo] = stringPayload(payload, "remark");
      }
    }
 
    function synchronizeAccess(context: AdminFulfillmentAccessContext) {
      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;
      factsRevision += 1;
      geoRevision += 1;
      commandRevision += 1;
      loading.value = false;
      geoBusy.value = false;
      submitting.value = false;
      activeCommandPromise = null;
 
      if (operatorChanged) {
        fulfillments.value = [];
        returns.value = [];
        nearbyPositions.value = [];
        loadError.value = null;
        geoMessage.value = null;
        geoError.value = null;
        for (const forms of [
          shipForms,
          traceForms,
          exceptionForms,
          resolutionForms,
          inspectRemarks,
        ]) {
          for (const key of Object.keys(forms)) {
            delete forms[key];
          }
        }
        pendingCommand.value = nextOperatorId
          ? loadPending(nextOperatorId)
          : null;
        hydratePending(pendingCommand.value);
        commandPhase.value = pendingCommand.value ? "unknown" : "idle";
        commandMessage.value = pendingCommand.value
          ? pendingCommand.value.requiresAuthorityRead
            ? "发现一条尚未确认的物流轨迹。坐标未本地持久化,请先读取权威事实确认外部事件 ID,不能在刷新后直接重放。"
            : "发现一条尚未确认的履约命令。业务号、命令身份和原始载荷已恢复;请读取权威事实或原样重试。"
          : null;
      } else Eif (pendingCommand.value) {
        commandPhase.value = "unknown";
        commandMessage.value =
          "员工会话凭据已更新,原履约命令继续保持结果未知。";
      }
      return activeAccess(context);
    }
 
    function requireAccess(
      context: AdminFulfillmentAccessContext,
      message: string,
    ): ActiveAccess | null {
      const access = synchronizeAccess(context);
      Iif (!access) {
        commandPhase.value = "rejected";
        commandMessage.value = message;
      }
      return access;
    }
 
    function upsertFulfillment(value: Fulfillment) {
      const index = fulfillments.value.findIndex((item) =>
        item.fulfillmentNo === value.fulfillmentNo);
      Iif (index >= 0) {
        fulfillments.value[index] = value;
      } else {
        fulfillments.value.unshift(value);
      }
    }
 
    function upsertReturn(value: ReturnReceipt) {
      const index = returns.value.findIndex((item) =>
        item.returnReceiptNo === value.returnReceiptNo);
      if (index >= 0) {
        returns.value[index] = value;
      } else {
        returns.value.unshift(value);
      }
    }
 
    async function loadFacts(
      context: AdminFulfillmentAccessContext,
    ): Promise<void> {
      const access = synchronizeAccess(context);
      Iif (!access) {
        loadError.value = "当前会话无权读取履约工作区。";
        return;
      }
      const requestRevision = ++factsRevision;
      loading.value = true;
      loadError.value = null;
      try {
        const [orders, returnReceipts] = await Promise.all([
          access.api.adminFulfillments(fulfillmentStatus.value || undefined),
          access.api.adminReturns(returnStatus.value || undefined),
        ]);
        requireCurrent(access);
        Iif (requestRevision !== factsRevision) {
          return;
        }
        fulfillments.value = orders;
        returns.value = returnReceipts;
      } catch (cause) {
        Eif (!accessIsCurrent(access)) {
          return;
        }
        if (requestRevision === factsRevision) {
          loadError.value = errorMessage(
            cause,
            "履约与退货事实暂时无法读取。",
          );
        }
      } finally {
        Iif (accessIsCurrent(access) && requestRevision === factsRevision) {
          loading.value = false;
        }
      }
    }
 
    function shipForm(referenceNo: string): ShipForm {
      shipForms[referenceNo] ??= { carrier: "", trackingNo: "" };
      return shipForms[referenceNo];
    }
 
    function traceForm(referenceNo: string): TraceForm {
      traceForms[referenceNo] ??= {
        externalEventId: newIdentity("trace"),
        nodeType: "TRANSIT",
        description: "",
        locationName: "",
        longitude: "",
        latitude: "",
      };
      return traceForms[referenceNo];
    }
 
    function exceptionForm(referenceNo: string): ReasonForm {
      exceptionForms[referenceNo] ??= { reason: "" };
      return exceptionForms[referenceNo];
    }
 
    function resolutionForm(referenceNo: string): ResolutionForm {
      resolutionForms[referenceNo] ??= {
        commandId: newIdentity("fulfillment-exception"),
        reason: "",
      };
      return resolutionForms[referenceNo];
    }
 
    function markPending(
      command: PendingFulfillmentCommand,
    ) {
      pendingCommand.value = command;
      commandPhase.value = "processing";
      commandMessage.value = `${pendingCommandLabel.value}命令正在等待 Fulfillment 确认。`;
    }
 
    function beginTracePending(
      access: ActiveAccess,
      command: PendingTraceCommand,
    ) {
      markPending(command);
      saveTraceAuthorityRecovery(
        access.operatorId,
        command.referenceNo,
        command.commandKey,
        command.createdAt,
      );
    }
 
    function beginRetryablePending(
      access: ActiveAccess,
      command: PendingNonTraceCommand,
    ) {
      markPending(command);
      saveRetryablePending(access.operatorId, command);
    }
 
    function settleAccepted(
      access: ActiveAccess,
      message: string,
    ) {
      pendingCommand.value = null;
      clearPending(access.operatorId);
      commandPhase.value = "accepted";
      commandMessage.value = message;
    }
 
    function settleRejected(
      access: ActiveAccess,
      message: string,
    ) {
      pendingCommand.value = null;
      clearPending(access.operatorId);
      commandPhase.value = "rejected";
      commandMessage.value = message;
    }
 
    function validateResult(
      command: PendingFulfillmentCommand,
      value: Fulfillment | ReturnReceipt,
    ) {
      const actual = "fulfillmentNo" in value
        ? value.fulfillmentNo
        : value.returnReceiptNo;
      Iif (actual !== command.referenceNo) {
        throw new FulfillmentContractError(
          "Fulfillment 已响应,但返回事实与当前命令业务号不一致。",
        );
      }
    }
 
    async function callCommand(
      api: FulfillmentApi,
      command: PendingFulfillmentCommand,
    ): Promise<Fulfillment | ReturnReceipt> {
      const { kind, referenceNo, payload } = command;
      switch (kind) {
        case "picking":
          return api.startPicking(referenceNo);
        case "packed":
          return api.markPacked(referenceNo);
        case "ship":
          return api.shipFulfillment(referenceNo, {
            carrier: stringPayload(payload, "carrier"),
            trackingNo: stringPayload(payload, "trackingNo"),
          });
        case "trace":
          return api.addLogisticsTrace(referenceNo, tracePayload(payload));
        case "exception":
          return api.markFulfillmentException(
            referenceNo,
            stringPayload(payload, "reason"),
          );
        case "resolve":
          return api.resolveFulfillmentException(
            referenceNo,
            command.commandKey,
            stringPayload(payload, "reason"),
          );
        case "receive":
          return api.receiveReturn(referenceNo);
        case "inspect":
          return api.inspectReturn(
            referenceNo,
            stringPayload(payload, "remark"),
          );
      }
    }
 
    function resetAcceptedForm(command: PendingFulfillmentCommand) {
      if (command.kind === "trace") {
        traceForms[command.referenceNo] = {
          externalEventId: newIdentity("trace"),
          nodeType: "TRANSIT",
          description: "",
          locationName: "",
          longitude: "",
          latitude: "",
        };
      } else Iif (command.kind === "exception") {
        exceptionForms[command.referenceNo] = { reason: "" };
      } else if (command.kind === "resolve") {
        resolutionForms[command.referenceNo] = {
          commandId: newIdentity("fulfillment-exception"),
          reason: "",
        };
      } else Eif (command.kind === "inspect") {
        inspectRemarks[command.referenceNo] = "";
      }
    }
 
    async function executePending(
      access: ActiveAccess,
      command: PendingFulfillmentCommand,
    ): Promise<Fulfillment | ReturnReceipt | null> {
      const requestRevision = ++commandRevision;
      submitting.value = true;
      commandPhase.value = "processing";
      commandMessage.value = `${pendingCommandLabel.value}命令正在等待 Fulfillment 确认。`;
      try {
        const value = await callCommand(access.api, command);
        requireCurrent(access);
        Iif (requestRevision !== commandRevision) {
          return null;
        }
        validateResult(command, value);
        if ("fulfillmentNo" in value) {
          upsertFulfillment(value);
        } else E{
          upsertReturn(value);
        }
        resetAcceptedForm(command);
        settleAccepted(
          access,
          `Fulfillment 已确认 ${command.referenceNo} 当前状态为 ${value.status}。`,
        );
        return value;
      } catch (cause) {
        Iif (!accessIsCurrent(access)) {
          return null;
        }
        Iif (requestRevision !== commandRevision) {
          return null;
        }
        if (resultMayBeUnknown(cause)) {
          commandPhase.value = "unknown";
          commandMessage.value =
            `${errorMessage(cause, "履约命令响应未能确认。")} `
            + "页面没有把命令显示为成功;业务号、命令身份和原始载荷已保留。";
          return null;
        }
        settleRejected(
          access,
          errorMessage(cause, "Fulfillment 已明确拒绝当前命令。"),
        );
        return null;
      } finally {
        Eif (accessIsCurrent(access) && requestRevision === commandRevision) {
          submitting.value = false;
        }
      }
    }
 
    function decideSubmission(
      context: AdminFulfillmentAccessContext,
    ): SubmissionDecision {
      const access = requireAccess(
        context,
        "当前会话无权提交 Fulfillment 命令。",
      );
      Iif (!access) {
        return { result: Promise.resolve(null) };
      }
      if (pendingCommand.value) {
        commandPhase.value = "unknown";
        commandMessage.value =
          "已有一条结果未知命令,不能生成或提交第二条命令;请先读取权威事实或原样重试。";
        return { result: Promise.resolve(null) };
      }
      Iif (activeCommandPromise) {
        return { result: activeCommandPromise };
      }
      return { access };
    }
 
    function trackSubmission(
      access: ActiveAccess,
      command: PendingFulfillmentCommand,
    ): Promise<Fulfillment | ReturnReceipt | null> {
      const request = executePending(access, command);
      activeCommandPromise = request;
      const clear = () => {
        Eif (activeCommandPromise === request) {
          activeCommandPromise = null;
        }
      };
      void request.then(clear, clear);
      return request;
    }
 
    function submitRetryable(
      context: AdminFulfillmentAccessContext,
      command: PendingNonTraceCommand,
    ): FulfillmentCommandResult {
      const decision = decideSubmission(context);
      Iif ("result" in decision) {
        return decision.result;
      }
      beginRetryablePending(decision.access, command);
      return trackSubmission(decision.access, command);
    }
 
    function submitTrace(
      context: AdminFulfillmentAccessContext,
      command: PendingTraceCommand,
    ): FulfillmentCommandResult {
      const decision = decideSubmission(context);
      if ("result" in decision) {
        return decision.result;
      }
      beginTracePending(decision.access, command);
      return trackSubmission(decision.access, command);
    }
 
    function naturalCommand(
      kind: NonTraceFulfillmentCommandKind,
      referenceNo: string,
      payload: Record<string, unknown> = {},
    ): PendingNonTraceCommand {
      return {
        kind,
        referenceNo,
        commandKey: `${kind}:${referenceNo}`,
        payload,
        createdAt: new Date().toISOString(),
      };
    }
 
    function startPicking(
      context: AdminFulfillmentAccessContext,
      fulfillmentNo: string,
    ) {
      return submitRetryable(
        context,
        naturalCommand("picking", fulfillmentNo),
      );
    }
 
    function markPacked(
      context: AdminFulfillmentAccessContext,
      fulfillmentNo: string,
    ) {
      return submitRetryable(
        context,
        naturalCommand("packed", fulfillmentNo),
      );
    }
 
    function ship(
      context: AdminFulfillmentAccessContext,
      fulfillmentNo: string,
    ) {
      const form = shipForm(fulfillmentNo);
      const carrier = normalizedInput(form.carrier).toUpperCase();
      const trackingNo = normalizedInput(form.trackingNo);
      if (!carrier || !trackingNo) {
        commandPhase.value = "rejected";
        commandMessage.value = "承运商和运单号不能为空。";
        return Promise.resolve(null);
      }
      return submitRetryable(context, naturalCommand("ship", fulfillmentNo, {
        carrier,
        trackingNo,
      }));
    }
 
    function addTrace(
      context: AdminFulfillmentAccessContext,
      fulfillmentNo: string,
    ) {
      const form = traceForm(fulfillmentNo);
      const longitude = normalizedInput(form.longitude);
      const latitude = normalizedInput(form.latitude);
      Iif (Boolean(longitude) !== Boolean(latitude)) {
        commandPhase.value = "rejected";
        commandMessage.value = "经度与纬度必须同时填写,不能只提交一个坐标。";
        return Promise.resolve(null);
      }
      Iif (!normalizedInput(form.description)) {
        commandPhase.value = "rejected";
        commandMessage.value = "物流轨迹说明不能为空。";
        return Promise.resolve(null);
      }
      const occurredAt = new Date().toISOString();
      return submitTrace(context, {
        kind: "trace",
        referenceNo: fulfillmentNo,
        commandKey: form.externalEventId,
        payload: {
          externalEventId: form.externalEventId,
          nodeType: form.nodeType,
          description: normalizedInput(form.description),
          locationName: normalizedInput(form.locationName),
          longitude,
          latitude,
          occurredAt,
        },
        createdAt: occurredAt,
      });
    }
 
    function markException(
      context: AdminFulfillmentAccessContext,
      fulfillmentNo: string,
    ) {
      const reason = normalizedInput(exceptionForm(fulfillmentNo).reason);
      if (!reason) {
        commandPhase.value = "rejected";
        commandMessage.value = "履约异常原因不能为空。";
        return Promise.resolve(null);
      }
      return submitRetryable(
        context,
        naturalCommand("exception", fulfillmentNo, {
        reason,
        }),
      );
    }
 
    function resolveException(
      context: AdminFulfillmentAccessContext,
      fulfillmentNo: string,
    ) {
      const form = resolutionForm(fulfillmentNo);
      const reason = normalizedInput(form.reason);
      Iif (!reason) {
        commandPhase.value = "rejected";
        commandMessage.value = "异常恢复原因不能为空。";
        return Promise.resolve(null);
      }
      return submitRetryable(context, {
        kind: "resolve",
        referenceNo: fulfillmentNo,
        commandKey: form.commandId,
        payload: { reason },
        createdAt: new Date().toISOString(),
      });
    }
 
    function receiveReturn(
      context: AdminFulfillmentAccessContext,
      returnReceiptNo: string,
    ) {
      return submitRetryable(
        context,
        naturalCommand("receive", returnReceiptNo),
      );
    }
 
    function inspectReturn(
      context: AdminFulfillmentAccessContext,
      returnReceiptNo: string,
    ) {
      const remark = normalizedInput(inspectRemarks[returnReceiptNo]);
      if (!remark) {
        commandPhase.value = "rejected";
        commandMessage.value = "退货验收说明不能为空。";
        return Promise.resolve(null);
      }
      return submitRetryable(context, naturalCommand("inspect", returnReceiptNo, {
        remark,
      }));
    }
 
    function retryPending(
      context: AdminFulfillmentAccessContext,
    ): Promise<Fulfillment | ReturnReceipt | null> {
      const access = requireAccess(
        context,
        "当前会话无权重试 Fulfillment 命令。",
      );
      Iif (!access || !pendingCommand.value) {
        if (!pendingCommand.value) {
          commandPhase.value = "rejected";
          commandMessage.value = "当前没有可重试的结果未知命令。";
        }
        return Promise.resolve(null);
      }
      if (
        pendingCommand.value.kind === "trace"
        && pendingCommand.value.requiresAuthorityRead
      ) {
        commandPhase.value = "unknown";
        commandMessage.value =
          "物流坐标未写入本地存储,刷新后不能安全原样重试;请读取 Fulfillment 权威事实确认外部事件 ID。";
        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;
    }
 
    function historyMatches(
      value: Fulfillment,
      expectedCommand: string,
      expectedReason?: string,
    ): boolean {
      return value.history.some((history) =>
        history.command === expectedCommand
        && history.operatorId === activeOperatorId.value
        && (
          expectedReason === undefined
          || history.reason === expectedReason
        ));
    }
 
    function authorityConfirms(
      command: PendingFulfillmentCommand,
      value: Fulfillment | ReturnReceipt,
    ): boolean {
      const payload = command.payload;
      Eif ("fulfillmentNo" in value) {
        switch (command.kind) {
          case "picking":
            return historyMatches(value, "START_PICKING");
          case "packed":
            return historyMatches(value, "MARK_PACKED");
          case "ship":
            return value.carrier === stringPayload(payload, "carrier")
              && value.trackingNo === stringPayload(payload, "trackingNo")
              && historyMatches(value, "SHIP");
          case "trace":
            return value.traces.some((trace) =>
              trace.externalEventId === command.commandKey
              && (
                command.requiresAuthorityRead
                || (
                  trace.nodeType === stringPayload(payload, "nodeType")
                  && trace.description === stringPayload(payload, "description")
                  && (trace.locationName ?? "") === stringPayload(payload, "locationName")
                  && String(trace.longitude ?? "") === stringPayload(payload, "longitude")
                  && String(trace.latitude ?? "") === stringPayload(payload, "latitude")
                )
              ));
          case "exception":
            return value.status === "EXCEPTION"
              && historyMatches(
                value,
                "MARK_EXCEPTION",
                stringPayload(payload, "reason"),
              );
          case "resolve":
            return false;
          default:
            return false;
        }
      }
      if (command.kind === "receive") {
        return ["RECEIVED", "INSPECTED"].includes(value.status);
      }
      if (command.kind === "inspect") {
        return value.status === "INSPECTED"
          && value.inspectionRemark === stringPayload(payload, "remark");
      }
      return false;
    }
 
    async function readPendingAuthority(
      context: AdminFulfillmentAccessContext,
    ): Promise<Fulfillment | ReturnReceipt | null> {
      const access = requireAccess(
        context,
        "当前会话无权读取 Fulfillment 权威事实。",
      );
      const command = pendingCommand.value;
      Iif (!access || !command) {
        if (!command) {
          commandPhase.value = "rejected";
          commandMessage.value = "当前没有待核对的结果未知命令。";
        }
        return null;
      }
      const requestRevision = ++commandRevision;
      submitting.value = true;
      try {
        const value = ["receive", "inspect"].includes(command.kind)
          ? await access.api.adminReturn(command.referenceNo)
          : await access.api.adminFulfillment(command.referenceNo);
        requireCurrent(access);
        Iif (requestRevision !== commandRevision) {
          return null;
        }
        validateResult(command, value);
        if ("fulfillmentNo" in value) {
          upsertFulfillment(value);
        } else E{
          upsertReturn(value);
        }
        if (authorityConfirms(command, value)) {
          resetAcceptedForm(command);
          settleAccepted(
            access,
            `Fulfillment 权威事实已确认原命令,${command.referenceNo} 当前为 ${value.status}。`,
          );
        } else E{
          commandPhase.value = "unknown";
          commandMessage.value = command.kind === "resolve"
            ? "履约事实可以显示当前状态,但响应模型不公开异常恢复命令 ID;无法把当前状态归因于原命令,必须沿用原 ID 重试确认。"
            : `当前权威事实尚未证明原命令已生效,${command.referenceNo} 仍为 ${value.status};不能生成第二条命令。`;
        }
        return value;
      } catch (cause) {
        if (!accessIsCurrent(access)) {
          return null;
        }
        if (requestRevision === commandRevision) {
          commandPhase.value = "unknown";
          commandMessage.value =
            `${errorMessage(cause, "Fulfillment 权威事实暂时无法读取。")} `
            + "原命令继续保持结果未知。";
        }
        return null;
      } finally {
        Eif (accessIsCurrent(access) && requestRevision === commandRevision) {
          submitting.value = false;
        }
      }
    }
 
    async function searchNearby(
      context: AdminFulfillmentAccessContext,
    ): Promise<void> {
      const access = synchronizeAccess(context);
      if (!access) {
        geoError.value = "当前会话无权读取附近物流位置。";
        return;
      }
      const requestRevision = ++geoRevision;
      geoBusy.value = true;
      geoError.value = null;
      geoMessage.value = null;
      try {
        const values = await access.api.nearbyShipmentPositions({
          longitude: normalizedInput(geoQuery.longitude),
          latitude: normalizedInput(geoQuery.latitude),
          radiusMeters: Number(geoQuery.radiusMeters),
          limit: Number(geoQuery.limit),
        });
        requireCurrent(access);
        if (requestRevision !== geoRevision) {
          return;
        }
        nearbyPositions.value = values;
        geoMessage.value =
          `Fulfillment 返回 ${values.length} 个范围内最新位置。`;
      } catch (cause) {
        if (!accessIsCurrent(access)) {
          return;
        }
        if (requestRevision === geoRevision) {
          geoError.value = errorMessage(
            cause,
            "附近物流位置查询未完成。",
          );
        }
      } finally {
        if (accessIsCurrent(access) && requestRevision === geoRevision) {
          geoBusy.value = false;
        }
      }
    }
 
    async function rebuildGeoCache(
      context: AdminFulfillmentAccessContext,
    ): Promise<void> {
      const access = synchronizeAccess(context);
      if (!access) {
        geoError.value = "当前会话无权重建物流位置缓存。";
        return;
      }
      const requestRevision = ++geoRevision;
      geoBusy.value = true;
      geoError.value = null;
      geoMessage.value = null;
      try {
        const result = await access.api.rebuildShipmentGeoCache();
        requireCurrent(access);
        if (requestRevision !== geoRevision) {
          return;
        }
        geoMessage.value =
          `Redis GEO 已从 MySQL 投影重建 ${result.cached}/${result.scanned} 条位置。`;
      } catch (cause) {
        if (!accessIsCurrent(access)) {
          return;
        }
        if (requestRevision === geoRevision) {
          geoError.value =
            `${errorMessage(cause, "Redis GEO 重建未完成。")} `
            + "MySQL 物流轨迹未被修改。";
        }
      } finally {
        if (accessIsCurrent(access) && requestRevision === geoRevision) {
          geoBusy.value = false;
        }
      }
    }
 
    function resetCommandNotice() {
      if (pendingCommand.value) {
        return;
      }
      commandPhase.value = "idle";
      commandMessage.value = null;
    }
 
    return {
      fulfillments,
      returns,
      fulfillmentStatus,
      returnStatus,
      loading,
      loadError,
      nearbyPositions,
      geoQuery,
      geoBusy,
      geoMessage,
      geoError,
      inspectRemarks,
      commandPhase,
      commandMessage,
      pendingCommand,
      pendingReferenceNo,
      pendingCommandLabel,
      submitting,
      commandBlocked,
      synchronizeAccess,
      loadFacts,
      shipForm,
      traceForm,
      exceptionForm,
      resolutionForm,
      startPicking,
      markPacked,
      ship,
      addTrace,
      markException,
      resolveException,
      receiveReturn,
      inspectReturn,
      retryPending,
      readPendingAuthority,
      searchNearby,
      rebuildGeoCache,
      resetCommandNotice,
    };
  },
);