All files / src/entities/governance/model governanceStore.ts

66.48% Statements 238/358
55.88% Branches 114/204
78.04% Functions 32/41
66.48% Lines 238/358

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                                        2x   2x   2x   2x                                                                                                                 1x 1x                 57x               19x     11x   19x             32x       32x                             26x             16x 15x   1x 1x 1x                                 1x                     16x     16x                     10x     10x 10x 7x   3x                 16x 16x 15x   1x 1x 1x 1x 1x         8x 1x   7x     7x             9x             1x 1x                                         1x 1x                 1x 1x         2x 8x 8x           8x 8x 8x     8x     8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x                 19x 19x 19x 19x   19x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 32x   8x 8x             8x             8x 8x                                     19x     19x 19x                 23x           12x                                                                                                   6x 1x   5x 5x 5x         5x           5x 5x 5x 5x 5x           6x 6x         6x     6x 6x 6x 6x 6x     6x 6x           6x 6x     6x 6x 6x 6x 6x 6x         1x 1x     1x 1x 1x 1x   1x 1x 1x   6x 6x     6x 6x 5x 5x     5x   1x 1x       1x 1x 1x   6x 6x               1x 1x         1x 1x       1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x       1x 1x 1x     1x 1x                         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 2x 2x     2x                     2x 2x               2x 2x           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   2x 2x                                                               8x                                      
import { computed, reactive, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createApiClient,
  createGovernanceApi,
  createPaymentApi,
  secureRandomUUID,
  type BusinessId,
  type GovernanceApi,
  type PaymentApi,
  type PaymentExceptionRefundAudit,
  type ReconciliationDomain,
  type ReconciliationIssue,
  type ReconciliationStatus,
  type Refund,
  type RefundDispatchRetryAudit,
} from "@plain-journal/foundation";
 
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
const REFUND_RETRY_STORAGE_PREFIX =
  "plain-journal:admin-governance:refund-retry:v1:";
const PAYMENT_EXCEPTION_STORAGE_PREFIX =
  "plain-journal:admin-governance:payment-exception-refund:v1:";
 
export const GOVERNANCE_DOMAINS: ReconciliationDomain[] = [
  "trade",
  "payment",
  "inventory",
  "fulfillment",
];
 
export type CompensationPhase =
  | "idle"
  | "invalid"
  | "unknown"
  | "accepted"
  | "rejected";
 
export interface GovernanceAccessContext {
  authorized: boolean;
  operatorId: BusinessId | null;
  accessToken: string | null;
}
 
interface ActiveGovernanceAccess {
  operatorId: BusinessId;
  accessToken: string;
  revision: number;
  governanceApi: GovernanceApi;
  paymentApi: PaymentApi;
}
 
interface PendingCompensationCommand {
  referenceNo: string;
  commandId: string;
  reason: string;
  createdAt: string;
}
 
interface CompensationTrack<TAudit> {
  referenceNo: string;
  commandId: string;
  reason: string;
  phase: CompensationPhase;
  message: string | null;
  result: Refund | null;
  audits: TAudit[];
  auditError: string | null;
  submitting: boolean;
  loadingAudits: boolean;
}
 
export class GovernanceAccessChangedError extends Error {
  constructor() {
    super("管理员账户或会话已切换,旧的治理请求结果不会写入当前页面。");
    this.name = "GovernanceAccessChangedError";
  }
}
 
export class GovernanceContractError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "GovernanceContractError";
  }
}
 
function isActiveContext(context: GovernanceAccessContext): 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 createApis(accessToken: string) {
  const client = createApiClient({
    baseUrl: apiBaseUrl,
    timeoutMs: 10000,
    tokenProvider: () => accessToken,
  });
  return {
    governanceApi: createGovernanceApi(client),
    paymentApi: createPaymentApi(client),
  };
}
 
function newCommandId(prefix: string): string {
  return `${prefix}:${secureRandomUUID()}`;
}
 
function newTrack<TAudit>(prefix: string): CompensationTrack<TAudit> {
  return {
    referenceNo: "",
    commandId: newCommandId(prefix),
    reason: "",
    phase: "idle",
    message: null,
    result: null,
    audits: [],
    auditError: null,
    submitting: false,
    loadingAudits: false,
  };
}
 
function storageKey(prefix: string, operatorId: BusinessId): string {
  return `${prefix}${operatorId}`;
}
 
function parsePending(
  raw: string | null,
  commandPrefix: string,
): PendingCompensationCommand | null {
  if (!raw) {
    return null;
  }
  try {
    const value: unknown = JSON.parse(raw);
    Iif (
      !value
      || typeof value !== "object"
      || !("referenceNo" in value)
      || !("commandId" in value)
      || !("reason" in value)
      || !("createdAt" in value)
      || typeof value.referenceNo !== "string"
      || value.referenceNo.length === 0
      || typeof value.commandId !== "string"
      || !value.commandId.startsWith(`${commandPrefix}:`)
      || typeof value.reason !== "string"
      || value.reason.length === 0
      || typeof value.createdAt !== "string"
    ) {
      return null;
    }
    return value as PendingCompensationCommand;
  } catch {
    return null;
  }
}
 
function loadPending(
  prefix: string,
  operatorId: BusinessId,
  commandPrefix: string,
): PendingCompensationCommand | null {
  Iif (typeof localStorage === "undefined") {
    return null;
  }
  return parsePending(
    localStorage.getItem(storageKey(prefix, operatorId)),
    commandPrefix,
  );
}
 
function savePending(
  prefix: string,
  operatorId: BusinessId,
  value: PendingCompensationCommand | null,
) {
  Iif (typeof localStorage === "undefined") {
    return;
  }
  const key = storageKey(prefix, operatorId);
  if (value) {
    localStorage.setItem(key, JSON.stringify(value));
  } else {
    localStorage.removeItem(key);
  }
}
 
function restoreTrack<TAudit>(
  track: CompensationTrack<TAudit>,
  commandPrefix: string,
  pending: PendingCompensationCommand | null,
) {
  Object.assign(track, newTrack<TAudit>(commandPrefix));
  if (!pending) {
    return;
  }
  track.referenceNo = pending.referenceNo;
  track.commandId = pending.commandId;
  track.reason = pending.reason;
  track.phase = "unknown";
  track.message =
    "发现一条尚未确认的治理命令。原业务编号、命令 ID 与原因已恢复;请先读取权威审计。";
}
 
function resultMayBeUnknown(cause: unknown): boolean {
  if (cause instanceof GovernanceContractError) {
    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 validateRefundRetryResult(
  value: Refund,
  pending: PendingCompensationCommand,
) {
  Eif (value.refundNo !== pending.referenceNo) {
    throw new GovernanceContractError(
      "Payment 已响应,但退款事实与本次补偿命令不一致。",
    );
  }
}
 
function validatePaymentExceptionResult(
  value: Refund,
  pending: PendingCompensationCommand,
) {
  if (value.paymentNo !== pending.referenceNo) {
    throw new GovernanceContractError(
      "Payment 已响应,但异常支付退款事实与本次命令不一致。",
    );
  }
}
 
function matchingRefundAudit(
  audits: RefundDispatchRetryAudit[],
  pending: PendingCompensationCommand,
): RefundDispatchRetryAudit | null {
  return audits.find((audit) =>
    audit.commandId === pending.commandId
    && audit.refundNo === pending.referenceNo
    && audit.reason === pending.reason) ?? null;
}
 
function matchingExceptionAudit(
  audits: PaymentExceptionRefundAudit[],
  pending: PendingCompensationCommand,
): PaymentExceptionRefundAudit | null {
  return audits.find((audit) =>
    audit.commandId === pending.commandId
    && audit.paymentNo === pending.referenceNo
    && audit.reason === pending.reason) ?? null;
}
 
export const useGovernanceStore = defineStore("admin-governance", () => {
  const reconciliationStatus = ref<ReconciliationStatus>("OPEN");
  const issues = reactive<Record<ReconciliationDomain, ReconciliationIssue[]>>({
    trade: [],
    payment: [],
    inventory: [],
    fulfillment: [],
  });
  const loadingIssues = ref(false);
  const issuesError = ref<string | null>(null);
  const refundRetry = reactive(
    newTrack<RefundDispatchRetryAudit>("refund-retry"),
  );
  const paymentExceptionRefund = reactive(
    newTrack<PaymentExceptionRefundAudit>("payment-exception-refund"),
  );
  const activeOperatorId = ref<BusinessId | null>(null);
  let activeAccessToken: string | null = null;
  let accessRevision = 0;
  let issuesRevision = 0;
  let refundRevision = 0;
  let exceptionRevision = 0;
  let pendingRefundRetry: PendingCompensationCommand | null = null;
  let pendingPaymentException: PendingCompensationCommand | null = null;
  let activeRefundPromise: Promise<Refund | null> | null = null;
  let activeExceptionPromise: Promise<Refund | null> | null = null;
 
  const totalIssues = computed(() =>
    GOVERNANCE_DOMAINS.reduce(
      (total, domain) => total + issues[domain].length,
      0,
    ));
 
  function synchronizeAccess(
    context: GovernanceAccessContext,
  ): ActiveGovernanceAccess | null {
    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) {
      activeOperatorId.value = nextOperatorId;
      activeAccessToken = nextAccessToken;
      accessRevision += 1;
      issuesRevision += 1;
      refundRevision += 1;
      exceptionRevision += 1;
      loadingIssues.value = false;
      refundRetry.submitting = false;
      refundRetry.loadingAudits = false;
      paymentExceptionRefund.submitting = false;
      paymentExceptionRefund.loadingAudits = false;
      activeRefundPromise = null;
      activeExceptionPromise = null;
 
      if (operatorChanged) {
        for (const domain of GOVERNANCE_DOMAINS) {
          issues[domain] = [];
        }
        issuesError.value = null;
        pendingRefundRetry = nextOperatorId
          ? loadPending(
              REFUND_RETRY_STORAGE_PREFIX,
              nextOperatorId,
              "refund-retry",
            )
          : null;
        pendingPaymentException = nextOperatorId
          ? loadPending(
              PAYMENT_EXCEPTION_STORAGE_PREFIX,
              nextOperatorId,
              "payment-exception-refund",
            )
          : null;
        restoreTrack(refundRetry, "refund-retry", pendingRefundRetry);
        restoreTrack(
          paymentExceptionRefund,
          "payment-exception-refund",
          pendingPaymentException,
        );
      } else E{
        if (pendingRefundRetry) {
          refundRetry.phase = "unknown";
          refundRetry.message =
            "管理员会话凭据已更新,退款补偿结果继续保持待确认。";
        }
        if (pendingPaymentException) {
          paymentExceptionRefund.phase = "unknown";
          paymentExceptionRefund.message =
            "管理员会话凭据已更新,异常支付退款结果继续保持待确认。";
        }
      }
    }
 
    Iif (!isActiveContext(context)) {
      return null;
    }
    const apis = createApis(context.accessToken);
    return {
      operatorId: context.operatorId,
      accessToken: context.accessToken,
      revision: accessRevision,
      ...apis,
    };
  }
 
  function accessIsCurrent(access: ActiveGovernanceAccess): boolean {
    return access.revision === accessRevision
      && access.operatorId === activeOperatorId.value
      && access.accessToken === activeAccessToken;
  }
 
  function requireCurrent(access: ActiveGovernanceAccess) {
    Iif (!accessIsCurrent(access)) {
      throw new GovernanceAccessChangedError();
    }
  }
 
  async function loadIssues(
    context: GovernanceAccessContext,
  ): Promise<Record<ReconciliationDomain, ReconciliationIssue[]>> {
    const access = synchronizeAccess(context);
    if (!access) {
      issuesError.value = "当前会话无权读取所有者域对账事实。";
      return issues;
    }
    const requestRevision = ++issuesRevision;
    loadingIssues.value = true;
    issuesError.value = null;
    try {
      const values = await Promise.all(GOVERNANCE_DOMAINS.map((domain) =>
        access.governanceApi.reconciliationIssues(
          domain,
          reconciliationStatus.value,
          50,
        )));
      requireCurrent(access);
      if (requestRevision !== issuesRevision) {
        return issues;
      }
      GOVERNANCE_DOMAINS.forEach((domain, index) => {
        issues[domain] = values[index] ?? [];
      });
      return issues;
    } catch (cause) {
      requireCurrent(access);
      if (requestRevision === issuesRevision) {
        issuesError.value = errorMessage(
          cause,
          "四域对账事实暂时无法读取。",
        );
      }
      return issues;
    } finally {
      if (accessIsCurrent(access) && requestRevision === issuesRevision) {
        loadingIssues.value = false;
      }
    }
  }
 
  function prepareRefundRetry(
    access: ActiveGovernanceAccess,
  ): PendingCompensationCommand | null {
    if (pendingRefundRetry) {
      return pendingRefundRetry;
    }
    const referenceNo = refundRetry.referenceNo.trim();
    const reason = refundRetry.reason.trim();
    Iif (!referenceNo || !reason) {
      refundRetry.phase = "invalid";
      refundRetry.message = "退款号和补偿原因不能为空。";
      return null;
    }
    const pending: PendingCompensationCommand = {
      referenceNo,
      commandId: refundRetry.commandId,
      reason,
      createdAt: new Date().toISOString(),
    };
    pendingRefundRetry = pending;
    refundRetry.referenceNo = referenceNo;
    refundRetry.reason = reason;
    savePending(REFUND_RETRY_STORAGE_PREFIX, access.operatorId, pending);
    return pending;
  }
 
  function submitRefundRetry(
    context: GovernanceAccessContext,
  ): Promise<Refund | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      refundRetry.phase = "rejected";
      refundRetry.message = "当前会话无权提交 Payment 退款补偿命令。";
      return Promise.resolve(null);
    }
    Iif (activeRefundPromise) {
      return activeRefundPromise;
    }
    const request = submitRefundRetryForAccess(access);
    activeRefundPromise = request;
    const clear = () => {
      Eif (activeRefundPromise === request) {
        activeRefundPromise = null;
      }
    };
    void request.then(clear, clear);
    return request;
  }
 
  async function submitRefundRetryForAccess(
    access: ActiveGovernanceAccess,
  ): Promise<Refund | null> {
    const pending = prepareRefundRetry(access);
    Iif (!pending) {
      return null;
    }
    const requestRevision = ++refundRevision;
    refundRetry.submitting = true;
    refundRetry.auditError = null;
    refundRetry.message = null;
    try {
      const value = await access.paymentApi.retryRefundDispatch(
        pending.referenceNo,
        pending.commandId,
        pending.reason,
      );
      requireCurrent(access);
      Iif (requestRevision !== refundRevision) {
        return null;
      }
      validateRefundRetryResult(value, pending);
      refundRetry.result = value;
      refundRetry.phase = "accepted";
      refundRetry.message =
        `Payment 已接受命令;退款当前为 ${value.status} / ${value.requestStatus}。`;
      pendingRefundRetry = null;
      savePending(REFUND_RETRY_STORAGE_PREFIX, access.operatorId, null);
      return value;
    } catch (cause) {
      requireCurrent(access);
      Iif (requestRevision !== refundRevision) {
        return null;
      }
      refundRetry.result = null;
      if (resultMayBeUnknown(cause)) {
        refundRetry.phase = "unknown";
        refundRetry.message =
          `${errorMessage(cause, "退款补偿响应未能确认。")} `
          + "原命令 ID、退款号和原因已保留;请先读取权威审计,必要时再用原 ID 重试。";
        return null;
      }
      refundRetry.phase = "rejected";
      refundRetry.message = errorMessage(
        cause,
        "Payment 已明确拒绝退款补偿命令。",
      );
      pendingRefundRetry = null;
      savePending(REFUND_RETRY_STORAGE_PREFIX, access.operatorId, null);
      return null;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === refundRevision) {
        refundRetry.submitting = false;
      }
    }
  }
 
  async function loadRefundRetryAudits(
    context: GovernanceAccessContext,
  ): Promise<RefundDispatchRetryAudit[]> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      refundRetry.auditError = "当前会话无权读取退款补偿审计。";
      return refundRetry.audits;
    }
    const referenceNo =
      pendingRefundRetry?.referenceNo ?? refundRetry.referenceNo.trim();
    Iif (!referenceNo) {
      refundRetry.auditError = "请先填写退款号。";
      return refundRetry.audits;
    }
    const requestRevision = ++refundRevision;
    refundRetry.loadingAudits = true;
    refundRetry.auditError = null;
    try {
      const values = await access.paymentApi.refundRetryAudits(referenceNo);
      requireCurrent(access);
      Iif (requestRevision !== refundRevision) {
        return refundRetry.audits;
      }
      refundRetry.audits = values;
      Eif (pendingRefundRetry) {
        const audit = matchingRefundAudit(values, pendingRefundRetry);
        Iif (!audit) {
          refundRetry.phase = "unknown";
          refundRetry.message =
            "权威审计尚未记录当前命令,结果继续保持未知;不能生成新命令 ID。";
        } else if (audit.outcome === "ACCEPTED") {
          refundRetry.phase = "accepted";
          refundRetry.message =
            `权威审计已确认命令 ACCEPTED:`
            + `${audit.beforeRequestStatus} → ${audit.afterRequestStatus}。`;
          pendingRefundRetry = null;
          savePending(REFUND_RETRY_STORAGE_PREFIX, access.operatorId, null);
        } else Eif (audit.outcome === "REJECTED") {
          refundRetry.phase = "rejected";
          refundRetry.message =
            `权威审计已确认命令 REJECTED:${audit.errorCode ?? "未提供错误码"}。`;
          pendingRefundRetry = null;
          savePending(REFUND_RETRY_STORAGE_PREFIX, access.operatorId, null);
        } else {
          refundRetry.phase = "unknown";
          refundRetry.message =
            `审计返回未识别结果 ${audit.outcome},页面不会猜测命令已成功。`;
        }
      }
      return values;
    } catch (cause) {
      requireCurrent(access);
      if (requestRevision === refundRevision) {
        refundRetry.auditError = errorMessage(
          cause,
          "退款补偿审计暂时无法读取。",
        );
        if (pendingRefundRetry) {
          refundRetry.phase = "unknown";
          refundRetry.message =
            "权威审计当前不可用,原命令继续保持结果未知。";
        }
      }
      return refundRetry.audits;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === refundRevision) {
        refundRetry.loadingAudits = false;
      }
    }
  }
 
  function preparePaymentException(
    access: ActiveGovernanceAccess,
  ): PendingCompensationCommand | null {
    Iif (pendingPaymentException) {
      return pendingPaymentException;
    }
    const referenceNo = paymentExceptionRefund.referenceNo.trim();
    const reason = paymentExceptionRefund.reason.trim();
    Iif (!referenceNo || !reason) {
      paymentExceptionRefund.phase = "invalid";
      paymentExceptionRefund.message = "支付号和授权退款原因不能为空。";
      return null;
    }
    const pending: PendingCompensationCommand = {
      referenceNo,
      commandId: paymentExceptionRefund.commandId,
      reason,
      createdAt: new Date().toISOString(),
    };
    pendingPaymentException = pending;
    paymentExceptionRefund.referenceNo = referenceNo;
    paymentExceptionRefund.reason = reason;
    savePending(PAYMENT_EXCEPTION_STORAGE_PREFIX, access.operatorId, pending);
    return pending;
  }
 
  function submitPaymentExceptionRefund(
    context: GovernanceAccessContext,
  ): Promise<Refund | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      paymentExceptionRefund.phase = "rejected";
      paymentExceptionRefund.message =
        "当前会话无权提交异常支付退款命令。";
      return Promise.resolve(null);
    }
    Iif (activeExceptionPromise) {
      return activeExceptionPromise;
    }
    const request = submitPaymentExceptionRefundForAccess(access);
    activeExceptionPromise = request;
    const clear = () => {
      Eif (activeExceptionPromise === request) {
        activeExceptionPromise = null;
      }
    };
    void request.then(clear, clear);
    return request;
  }
 
  async function submitPaymentExceptionRefundForAccess(
    access: ActiveGovernanceAccess,
  ): Promise<Refund | null> {
    const pending = preparePaymentException(access);
    Iif (!pending) {
      return null;
    }
    const requestRevision = ++exceptionRevision;
    paymentExceptionRefund.submitting = true;
    paymentExceptionRefund.auditError = null;
    paymentExceptionRefund.message = null;
    try {
      const value = await access.paymentApi.createPaymentExceptionRefund(
        pending.referenceNo,
        pending.commandId,
        pending.reason,
      );
      requireCurrent(access);
      if (requestRevision !== exceptionRevision) {
        return null;
      }
      validatePaymentExceptionResult(value, pending);
      paymentExceptionRefund.result = value;
      paymentExceptionRefund.phase = "accepted";
      paymentExceptionRefund.message =
        `Payment 已创建退款 ${value.refundNo};`
        + `当前为 ${value.status} / ${value.requestStatus},并未伪造渠道成功。`;
      pendingPaymentException = null;
      savePending(PAYMENT_EXCEPTION_STORAGE_PREFIX, access.operatorId, null);
      return value;
    } catch (cause) {
      requireCurrent(access);
      Iif (requestRevision !== exceptionRevision) {
        return null;
      }
      paymentExceptionRefund.result = null;
      Eif (resultMayBeUnknown(cause)) {
        paymentExceptionRefund.phase = "unknown";
        paymentExceptionRefund.message =
          `${errorMessage(cause, "异常支付退款响应未能确认。")} `
          + "原命令 ID、支付号和原因已保留;请先读取权威审计,必要时再用原 ID 重试。";
        return null;
      }
      paymentExceptionRefund.phase = "rejected";
      paymentExceptionRefund.message = errorMessage(
        cause,
        "Payment 已明确拒绝异常支付退款命令。",
      );
      pendingPaymentException = null;
      savePending(PAYMENT_EXCEPTION_STORAGE_PREFIX, access.operatorId, null);
      return null;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === exceptionRevision) {
        paymentExceptionRefund.submitting = false;
      }
    }
  }
 
  async function loadPaymentExceptionAudits(
    context: GovernanceAccessContext,
  ): Promise<PaymentExceptionRefundAudit[]> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      paymentExceptionRefund.auditError =
        "当前会话无权读取异常支付退款审计。";
      return paymentExceptionRefund.audits;
    }
    const referenceNo =
      pendingPaymentException?.referenceNo
      ?? paymentExceptionRefund.referenceNo.trim();
    Iif (!referenceNo) {
      paymentExceptionRefund.auditError = "请先填写支付号。";
      return paymentExceptionRefund.audits;
    }
    const requestRevision = ++exceptionRevision;
    paymentExceptionRefund.loadingAudits = true;
    paymentExceptionRefund.auditError = null;
    try {
      const values = await access.paymentApi
        .paymentExceptionRefundAudits(referenceNo);
      requireCurrent(access);
      Iif (requestRevision !== exceptionRevision) {
        return paymentExceptionRefund.audits;
      }
      paymentExceptionRefund.audits = values;
      Eif (pendingPaymentException) {
        const audit = matchingExceptionAudit(values, pendingPaymentException);
        Iif (!audit) {
          paymentExceptionRefund.phase = "unknown";
          paymentExceptionRefund.message =
            "权威审计尚未记录当前命令,结果继续保持未知;不能生成新命令 ID。";
        } else Iif (audit.outcome === "ACCEPTED") {
          paymentExceptionRefund.phase = "accepted";
          paymentExceptionRefund.message =
            `权威审计已确认命令 ACCEPTED,退款号为 `
            + `${audit.refundNo ?? "审计未返回退款号"}。`;
          pendingPaymentException = null;
          savePending(
            PAYMENT_EXCEPTION_STORAGE_PREFIX,
            access.operatorId,
            null,
          );
        } else if (audit.outcome === "REJECTED") {
          paymentExceptionRefund.phase = "rejected";
          paymentExceptionRefund.message =
            `权威审计已确认命令 REJECTED:`
            + `${audit.errorCode ?? "未提供错误码"}。`;
          pendingPaymentException = null;
          savePending(
            PAYMENT_EXCEPTION_STORAGE_PREFIX,
            access.operatorId,
            null,
          );
        } else E{
          paymentExceptionRefund.phase = "unknown";
          paymentExceptionRefund.message =
            `审计返回未识别结果 ${audit.outcome},页面不会猜测命令已成功。`;
        }
      }
      return values;
    } catch (cause) {
      requireCurrent(access);
      Eif (requestRevision === exceptionRevision) {
        paymentExceptionRefund.auditError = errorMessage(
          cause,
          "异常支付退款审计暂时无法读取。",
        );
        Eif (pendingPaymentException) {
          paymentExceptionRefund.phase = "unknown";
          paymentExceptionRefund.message =
            "权威审计当前不可用,原命令继续保持结果未知。";
        }
      }
      return paymentExceptionRefund.audits;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === exceptionRevision) {
        paymentExceptionRefund.loadingAudits = false;
      }
    }
  }
 
  function resetRefundRetry(): boolean {
    if (pendingRefundRetry || refundRetry.phase === "unknown") {
      refundRetry.message =
        "当前命令尚未收敛,不能生成新命令 ID。请先读取权威审计。";
      return false;
    }
    restoreTrack(refundRetry, "refund-retry", null);
    return true;
  }
 
  function resetPaymentExceptionRefund(): boolean {
    if (
      pendingPaymentException
      || paymentExceptionRefund.phase === "unknown"
    ) {
      paymentExceptionRefund.message =
        "当前命令尚未收敛,不能生成新命令 ID。请先读取权威审计。";
      return false;
    }
    restoreTrack(
      paymentExceptionRefund,
      "payment-exception-refund",
      null,
    );
    return true;
  }
 
  return {
    reconciliationStatus,
    issues,
    loadingIssues,
    issuesError,
    totalIssues,
    refundRetry,
    paymentExceptionRefund,
    activeOperatorId,
    synchronizeAccess,
    loadIssues,
    submitRefundRetry,
    loadRefundRetryAudits,
    submitPaymentExceptionRefund,
    loadPaymentExceptionAudits,
    resetRefundRetry,
    resetPaymentExceptionRefund,
  };
});