All files / src/features/order-payment/model paymentStore.ts

81.29% Statements 213/262
69.94% Branches 128/183
93.1% Functions 27/29
81.15% Lines 211/260

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                          2x 2x 2x                                               2x 2x                               117x               34x             36x 33x   3x 3x 3x                               3x             19x     19x 19x 19x 2x   17x       17x 1x 1x   17x       8x       32x     32x         4x                 2x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x   18x     39x 39x 39x 39x   39x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x   19x 19x 19x 19x 19x 19x             39x         39x               108x           58x 1x         24x       14x 14x 1x 14x 1x   13x               15x 15x 15x     15x 15x 8x   7x         14x 14x 14x 14x 1x   13x 7x   13x 13x               17x 17x     17x 17x 17x 17x 17x 8x 8x     7x     7x 7x   10x 1x   9x     9x 9x 9x     10x   17x 16x                 1x 1x     1x 1x 1x 1x 1x 1x 1x     1x     1x 1x                   1x 1x                 5x 5x     5x 5x 5x 5x   1x 1x     1x     1x 1x   4x     4x     4x 4x 4x     4x         4x   5x 5x                                 9x 9x 1x         1x   8x             8x 8x             10x 10x       10x         1x     9x 9x 9x 9x 9x 9x       9x 9x 9x     9x 9x             9x 9x                 9x 9x       9x 1x 1x 1x       9x 9x       9x 9x 9x 9x       5x 5x     5x     5x 5x   4x     4x     4x 4x 4x 4x 1x   3x 3x 3x         4x   9x         9x         18x                                        
import { computed, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createApiClient,
  createPaymentApi,
  secureRandomUUID,
  type BusinessId,
  type Payment,
  type PaymentApi,
} from "@plain-journal/foundation";
 
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
const LEGACY_PENDING_PAYMENT_KEY = "plain-journal:pending-payment:v1";
const PENDING_PAYMENT_KEY_PREFIX = "plain-journal:pending-payment:v2:";
 
export interface PaymentAccessContext {
  authenticated: boolean;
  ownerId: BusinessId | null;
  accessToken: string | null;
}
 
interface ActivePaymentAccess {
  ownerId: BusinessId;
  accessToken: string;
  revision: number;
}
 
export interface PendingPaymentSubmission {
  key: string;
  userId: BusinessId;
  orderNo: string;
  channel: "MOCK";
  createdAt: string;
}
 
export class PaymentAccessChangedError extends Error {
  constructor() {
    super("账户或会话已切换,旧的支付请求结果不会写入当前页面。");
    this.name = "PaymentAccessChangedError";
  }
}
 
class PaymentResponseMismatchError extends Error {
  constructor() {
    super("Payment 已响应,但返回的支付事实与本次请求不一致。");
    this.name = "PaymentResponseMismatchError";
  }
}
 
function isActiveContext(context: PaymentAccessContext): context is {
  authenticated: true;
  ownerId: BusinessId;
  accessToken: string;
} {
  return context.authenticated
    && typeof context.ownerId === "string"
    && context.ownerId.length > 0
    && typeof context.accessToken === "string"
    && context.accessToken.length > 0;
}
 
function pendingPaymentKey(ownerId: BusinessId): string {
  return `${PENDING_PAYMENT_KEY_PREFIX}${ownerId}`;
}
 
function parsePendingPayment(
  raw: string | null,
  ownerId: BusinessId,
): PendingPaymentSubmission | null {
  if (!raw) {
    return null;
  }
  try {
    const value: unknown = JSON.parse(raw);
    Iif (
      !value
      || typeof value !== "object"
      || !("key" in value)
      || !("userId" in value)
      || !("orderNo" in value)
      || !("channel" in value)
      || !("createdAt" in value)
      || typeof value.key !== "string"
      || value.userId !== ownerId
      || typeof value.orderNo !== "string"
      || value.channel !== "MOCK"
      || typeof value.createdAt !== "string"
    ) {
      return null;
    }
    return value as PendingPaymentSubmission;
  } catch {
    return null;
  }
}
 
function loadPendingPayment(ownerId: BusinessId): PendingPaymentSubmission | null {
  Iif (typeof localStorage === "undefined") {
    return null;
  }
  const scopedKey = pendingPaymentKey(ownerId);
  const scoped = parsePendingPayment(localStorage.getItem(scopedKey), ownerId);
  if (scoped) {
    return scoped;
  }
  const legacy = parsePendingPayment(
    localStorage.getItem(LEGACY_PENDING_PAYMENT_KEY),
    ownerId,
  );
  if (legacy) {
    localStorage.setItem(scopedKey, JSON.stringify(legacy));
    localStorage.removeItem(LEGACY_PENDING_PAYMENT_KEY);
  }
  return legacy;
}
 
function newPaymentKey(): string {
  return `payment:${secureRandomUUID()}`;
}
 
function paymentApi(accessToken: string): PaymentApi {
  return createPaymentApi(createApiClient({
    baseUrl: apiBaseUrl,
    timeoutMs: 8000,
    tokenProvider: () => accessToken,
  }));
}
 
function isUncertainPaymentFailure(cause: unknown): boolean {
  return cause instanceof PaymentResponseMismatchError
    || (cause instanceof ApiError && (
      cause.kind === "network"
      || cause.kind === "timeout"
      || cause.kind === "invalid-response"
      || (cause.kind === "http" && (cause.status ?? 500) >= 500)
    ));
}
 
export const usePaymentsStore = defineStore("customer-payments", () => {
  const payments = ref<Payment[]>([]);
  const loadingOrderNo = ref<string | null>(null);
  const creatingOrderNo = ref<string | null>(null);
  const refreshingPaymentNo = ref<string | null>(null);
  const resolvingSubmission = ref(false);
  const error = ref<string | null>(null);
  const submissionUnknown = ref(false);
  const submissionError = ref<string | null>(null);
  const pendingSubmission = ref<PendingPaymentSubmission | null>(null);
  const activeOwnerId = ref<BusinessId | null>(null);
  let activeAccessToken: string | null = null;
  let accessRevision = 0;
  let readRevision = 0;
  let createRevision = 0;
  let submissionRevision = 0;
  let activeCreatePromise: Promise<Payment | null> | null = null;
  let activeCreateOrderNo: string | null = null;
  let activeCreateAccessRevision = -1;
  const knownAbsentOrderNos = new Set<string>();
 
  const currentAccountPendingSubmission = computed(() => pendingSubmission.value);
 
  function synchronizeAccess(context: PaymentAccessContext): ActivePaymentAccess | null {
    const nextOwnerId = isActiveContext(context) ? context.ownerId : null;
    const nextAccessToken = isActiveContext(context) ? context.accessToken : null;
    const ownerChanged = activeOwnerId.value !== nextOwnerId;
    const tokenChanged = activeAccessToken !== nextAccessToken;
 
    if (ownerChanged || tokenChanged) {
      activeOwnerId.value = nextOwnerId;
      activeAccessToken = nextAccessToken;
      accessRevision += 1;
      readRevision += 1;
      createRevision += 1;
      submissionRevision += 1;
      activeCreatePromise = null;
      activeCreateOrderNo = null;
      activeCreateAccessRevision = -1;
      loadingOrderNo.value = null;
      creatingOrderNo.value = null;
      refreshingPaymentNo.value = null;
      resolvingSubmission.value = false;
      error.value = null;
 
      if (ownerChanged) {
        payments.value = [];
        knownAbsentOrderNos.clear();
        pendingSubmission.value = nextOwnerId ? loadPendingPayment(nextOwnerId) : null;
        submissionUnknown.value = Boolean(pendingSubmission.value);
        submissionError.value = null;
      } else Eif (pendingSubmission.value) {
        submissionUnknown.value = true;
        submissionError.value = "会话凭据更新时支付结果仍待确认,请重新查询 Payment 事实。";
      }
    }
 
    Iif (!isActiveContext(context)) {
      payments.value = [];
      pendingSubmission.value = null;
      return null;
    }
    return {
      ownerId: context.ownerId,
      accessToken: context.accessToken,
      revision: accessRevision,
    };
  }
 
  function accessIsCurrent(access: ActivePaymentAccess): boolean {
    return access.revision === accessRevision
      && access.ownerId === activeOwnerId.value
      && access.accessToken === activeAccessToken;
  }
 
  function requireCurrent(access: ActivePaymentAccess) {
    if (!accessIsCurrent(access)) {
      throw new PaymentAccessChangedError();
    }
  }
 
  function paymentForOrder(orderNo: string): Payment | null {
    return payments.value.find((payment) => payment.orderNo === orderNo) ?? null;
  }
 
  function upsertPayment(value: Payment) {
    knownAbsentOrderNos.delete(value.orderNo);
    const index = payments.value.findIndex((payment) =>
      payment.paymentNo === value.paymentNo || payment.orderNo === value.orderNo);
    if (index >= 0) {
      payments.value[index] = value;
    } else {
      payments.value.push(value);
    }
  }
 
  function persistPendingSubmission(
    access: ActivePaymentAccess,
    value: PendingPaymentSubmission | null,
  ) {
    requireCurrent(access);
    pendingSubmission.value = value;
    Iif (typeof localStorage === "undefined") {
      return;
    }
    const key = pendingPaymentKey(access.ownerId);
    if (value) {
      localStorage.setItem(key, JSON.stringify(value));
    } else {
      localStorage.removeItem(key);
    }
  }
 
  function completeSubmission(access: ActivePaymentAccess, value: Payment) {
    requireCurrent(access);
    upsertPayment(value);
    const pending = pendingSubmission.value;
    if (pending && pending.orderNo !== value.orderNo) {
      return;
    }
    if (pending) {
      persistPendingSubmission(access, null);
    }
    submissionUnknown.value = false;
    submissionError.value = null;
  }
 
  async function loadForOrder(
    context: PaymentAccessContext,
    orderNo: string,
    silentNotFound = true,
  ): Promise<Payment | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      return null;
    }
    const requestRevision = ++readRevision;
    loadingOrderNo.value = orderNo;
    error.value = null;
    try {
      const value = await paymentApi(access.accessToken).paymentByOrder(orderNo);
      requireCurrent(access);
      Iif (requestRevision !== readRevision) {
        return null;
      }
      Iif (value.orderNo !== orderNo) {
        throw new PaymentResponseMismatchError();
      }
      completeSubmission(access, value);
      return value;
    } catch (cause) {
      if (!accessIsCurrent(access)) {
        throw new PaymentAccessChangedError();
      }
      Iif (requestRevision !== readRevision) {
        return null;
      }
      Eif (silentNotFound && cause instanceof ApiError && cause.status === 404) {
        knownAbsentOrderNos.add(orderNo);
        return null;
      }
      error.value = cause instanceof Error ? cause.message : "支付事实暂时无法读取。";
      return null;
    } finally {
      if (accessIsCurrent(access) && requestRevision === readRevision) {
        loadingOrderNo.value = null;
      }
    }
  }
 
  async function refreshPayment(
    context: PaymentAccessContext,
    paymentNo: string,
  ): Promise<Payment | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      return null;
    }
    const requestRevision = ++readRevision;
    refreshingPaymentNo.value = paymentNo;
    error.value = null;
    try {
      const value = await paymentApi(access.accessToken).payment(paymentNo);
      requireCurrent(access);
      Iif (requestRevision !== readRevision) {
        return null;
      }
      Iif (value.paymentNo !== paymentNo) {
        throw new PaymentResponseMismatchError();
      }
      completeSubmission(access, value);
      return value;
    } catch (cause) {
      if (!accessIsCurrent(access)) {
        throw new PaymentAccessChangedError();
      }
      if (requestRevision === readRevision) {
        error.value = cause instanceof Error ? cause.message : "支付状态暂时无法刷新。";
      }
      return null;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === readRevision) {
        refreshingPaymentNo.value = null;
      }
    }
  }
 
  async function recoverPendingSubmissionForAccess(
    access: ActivePaymentAccess,
    silent = false,
  ): Promise<Payment | null> {
    const pending = pendingSubmission.value;
    Iif (!pending) {
      return null;
    }
    const requestRevision = ++submissionRevision;
    resolvingSubmission.value = true;
    try {
      const value = await paymentApi(access.accessToken)
        .paymentByIdempotencyKey(pending.key);
      requireCurrent(access);
      Iif (requestRevision !== submissionRevision) {
        return null;
      }
      Iif (value.orderNo !== pending.orderNo) {
        throw new PaymentResponseMismatchError();
      }
      completeSubmission(access, value);
      return value;
    } catch (cause) {
      Iif (!accessIsCurrent(access)) {
        throw new PaymentAccessChangedError();
      }
      Iif (requestRevision !== submissionRevision) {
        return null;
      }
      submissionUnknown.value = true;
      Eif (cause instanceof ApiError && cause.status === 404) {
        Iif (!silent) {
          submissionError.value = "暂未查询到支付单。可以使用原支付键安全重试,不能换键创建第二笔支付。";
        }
        return null;
      }
      submissionError.value = cause instanceof Error
        ? `支付结果查询未完成:${cause.message}`
        : "支付结果查询未完成。";
      return null;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === submissionRevision) {
        resolvingSubmission.value = false;
      }
    }
  }
 
  async function recoverPendingSubmission(
    context: PaymentAccessContext,
    silent = false,
  ): Promise<Payment | null> {
    const access = synchronizeAccess(context);
    return access ? recoverPendingSubmissionForAccess(access, silent) : null;
  }
 
  function prepareSubmission(
    access: ActivePaymentAccess,
    orderNo: string,
  ): PendingPaymentSubmission | null {
    const existing = pendingSubmission.value;
    if (existing) {
      Iif (existing.orderNo !== orderNo) {
        submissionUnknown.value = true;
        submissionError.value = "已有另一笔支付结果尚未确认,请先处理原订单。";
        return null;
      }
      return existing;
    }
    const pending: PendingPaymentSubmission = {
      key: newPaymentKey(),
      userId: access.ownerId,
      orderNo,
      channel: "MOCK",
      createdAt: new Date().toISOString(),
    };
    persistPendingSubmission(access, pending);
    return pending;
  }
 
  function createForOrder(
    context: PaymentAccessContext,
    orderNo: string,
  ): Promise<Payment | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      submissionError.value = "当前会话没有可用于创建支付单的用户事实。";
      return Promise.resolve(null);
    }
    if (
      activeCreatePromise
      && activeCreateOrderNo === orderNo
      && activeCreateAccessRevision === access.revision
    ) {
      return activeCreatePromise;
    }
 
    const request = createForOrderWithAccess(access, orderNo);
    activeCreatePromise = request;
    activeCreateOrderNo = orderNo;
    activeCreateAccessRevision = access.revision;
    const clearActiveCreate = () => {
      Eif (
        activeCreatePromise === request
        && activeCreateAccessRevision === access.revision
      ) {
        activeCreatePromise = null;
        activeCreateOrderNo = null;
        activeCreateAccessRevision = -1;
      }
    };
    void request.then(clearActiveCreate, clearActiveCreate);
    return request;
  }
 
  async function createForOrderWithAccess(
    access: ActivePaymentAccess,
    orderNo: string,
  ): Promise<Payment | null> {
    submissionError.value = null;
    const known = paymentForOrder(orderNo) ?? (
      knownAbsentOrderNos.has(orderNo)
        ? null
        : await loadForOrder({
          authenticated: true,
          ownerId: access.ownerId,
          accessToken: access.accessToken,
        }, orderNo, true)
    );
    requireCurrent(access);
    Iif (known) {
      return known;
    }
 
    if (pendingSubmission.value) {
      const recovered = await recoverPendingSubmissionForAccess(access, true);
      requireCurrent(access);
      Iif (recovered) {
        return recovered;
      }
    }
    const pending = prepareSubmission(access, orderNo);
    Iif (!pending) {
      return null;
    }
 
    const requestRevision = ++createRevision;
    creatingOrderNo.value = orderNo;
    try {
      const value = await paymentApi(access.accessToken).createPayment({
        orderNo: pending.orderNo,
        channel: pending.channel,
      }, pending.key);
      requireCurrent(access);
      Iif (requestRevision !== createRevision) {
        return null;
      }
      Iif (value.orderNo !== orderNo) {
        throw new PaymentResponseMismatchError();
      }
      completeSubmission(access, value);
      return value;
    } catch (cause) {
      Iif (!accessIsCurrent(access)) {
        throw new PaymentAccessChangedError();
      }
      Iif (requestRevision !== createRevision) {
        return null;
      }
      Eif (isUncertainPaymentFailure(cause)) {
        const recovered = await recoverPendingSubmissionForAccess(access, true);
        requireCurrent(access);
        if (recovered) {
          return recovered;
        }
        submissionUnknown.value = true;
        submissionError.value = "支付创建结果尚未确认。原支付键已保留,请查询或使用原键安全重试。";
        return null;
      }
      persistPendingSubmission(access, null);
      submissionUnknown.value = false;
      submissionError.value = cause instanceof Error ? cause.message : "支付单创建未完成。";
      return null;
    } finally {
      Eif (
        accessIsCurrent(access)
        && requestRevision === createRevision
        && creatingOrderNo.value === orderNo
      ) {
        creatingOrderNo.value = null;
      }
    }
  }
 
  return {
    payments,
    loadingOrderNo,
    creatingOrderNo,
    refreshingPaymentNo,
    resolvingSubmission,
    error,
    submissionUnknown,
    submissionError,
    pendingSubmission,
    currentAccountPendingSubmission,
    activeOwnerId,
    synchronizeAccess,
    paymentForOrder,
    loadForOrder,
    refreshPayment,
    recoverPendingSubmission,
    createForOrder,
  };
});