All files / src/features/order-fulfillment/model receiptConfirmationStore.ts

84.07% Statements 95/113
76.62% Branches 59/77
100% Functions 14/14
84.07% Lines 95/113

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                                      2x 2x                         45x               6x     6x         3x                 2x     7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x         15x 15x 15x 15x 15x   15x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x     15x     15x               25x           15x 1x               3x 3x     3x             2x 2x                 2x 2x 2x             2x 2x 2x             8x 8x       8x         1x     7x 7x 7x 7x 7x 7x       6x 6x 6x     7x 7x               7x 7x               7x       7x 1x 1x 1x     6x 6x 6x 6x   3x 3x     2x   4x 1x   3x     3x 3x 3x 3x 1x 1x 1x   2x       2x           4x   6x       5x         7x                      
import { ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createApiClient,
  createFulfillmentApi,
  type BusinessId,
  type Fulfillment,
  type FulfillmentApi,
} from "@plain-journal/foundation";
 
import {
  FulfillmentAccessChangedError,
  FulfillmentResponseMismatchError,
  useFulfillmentsStore,
  type FulfillmentAccessContext,
} from "../../../entities/fulfillment";
 
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
const CONFIRMABLE_STATUSES = new Set(["SHIPPED", "IN_TRANSIT", "DELIVERING"]);
 
interface ActiveReceiptAccess {
  ownerId: BusinessId;
  accessToken: string;
  revision: number;
}
 
function isActiveContext(context: FulfillmentAccessContext): 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 fulfillmentApi(accessToken: string): FulfillmentApi {
  return createFulfillmentApi(createApiClient({
    baseUrl: apiBaseUrl,
    timeoutMs: 8000,
    tokenProvider: () => accessToken,
  }));
}
 
function isUncertainConfirmationFailure(cause: unknown): boolean {
  return cause instanceof FulfillmentResponseMismatchError
    || (cause instanceof ApiError && (
      cause.kind === "network"
      || cause.kind === "timeout"
      || cause.kind === "invalid-response"
      || (cause.kind === "http" && (cause.status ?? 500) >= 500)
    ));
}
 
export const useReceiptConfirmationStore = defineStore(
  "customer-receipt-confirmation",
  () => {
    const confirmingOrderNo = ref<string | null>(null);
    const unknownOrderNo = ref<string | null>(null);
    const confirmationError = ref<string | null>(null);
    const activeOwnerId = ref<BusinessId | null>(null);
    const fulfillments = useFulfillmentsStore();
    let activeAccessToken: string | null = null;
    let accessRevision = 0;
    let confirmationRevision = 0;
    let activeConfirmationPromise: Promise<Fulfillment | null> | null = null;
    let activeConfirmationOrderNo: string | null = null;
    let activeConfirmationAccessRevision = -1;
 
    function synchronizeAccess(
      context: FulfillmentAccessContext,
    ): ActiveReceiptAccess | null {
      fulfillments.synchronizeAccess(context);
      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;
        confirmationRevision += 1;
        activeConfirmationPromise = null;
        activeConfirmationOrderNo = null;
        activeConfirmationAccessRevision = -1;
        confirmingOrderNo.value = null;
        unknownOrderNo.value = null;
        confirmationError.value = null;
      }
 
      Iif (!isActiveContext(context)) {
        return null;
      }
      return {
        ownerId: context.ownerId,
        accessToken: context.accessToken,
        revision: accessRevision,
      };
    }
 
    function accessIsCurrent(access: ActiveReceiptAccess): boolean {
      return access.revision === accessRevision
        && access.ownerId === activeOwnerId.value
        && access.accessToken === activeAccessToken;
    }
 
    function requireCurrent(access: ActiveReceiptAccess) {
      if (!accessIsCurrent(access)) {
        throw new FulfillmentAccessChangedError();
      }
    }
 
    function resolveFromFact(
      context: FulfillmentAccessContext,
      value: Fulfillment | null,
    ) {
      const access = synchronizeAccess(context);
      Iif (!access || !value || value.userId !== access.ownerId) {
        return;
      }
      Iif (value.status === "SIGNED" && unknownOrderNo.value === value.orderNo) {
        unknownOrderNo.value = null;
        confirmationError.value = null;
      }
    }
 
    function markUnknown(orderNo: string, message: string) {
      unknownOrderNo.value = orderNo;
      confirmationError.value = message;
    }
 
    function completeConfirmation(
      context: FulfillmentAccessContext,
      access: ActiveReceiptAccess,
      orderNo: string,
      value: Fulfillment,
    ): Fulfillment {
      requireCurrent(access);
      fulfillments.recordAuthoritativeFulfillment(context, orderNo, value);
      Iif (value.status !== "SIGNED") {
        markUnknown(
          orderNo,
          "确认接口已响应,但 Fulfillment 尚未返回 SIGNED。",
        );
        return value;
      }
      unknownOrderNo.value = null;
      confirmationError.value = null;
      return value;
    }
 
    function confirmReceipt(
      context: FulfillmentAccessContext,
      orderNo: string,
    ): Promise<Fulfillment | null> {
      const access = synchronizeAccess(context);
      Iif (!access) {
        confirmationError.value = "当前会话没有可用于确认收货的用户事实。";
        return Promise.resolve(null);
      }
      if (
        activeConfirmationPromise
        && activeConfirmationOrderNo === orderNo
        && activeConfirmationAccessRevision === access.revision
      ) {
        return activeConfirmationPromise;
      }
 
      const request = confirmReceiptWithAccess(context, access, orderNo);
      activeConfirmationPromise = request;
      activeConfirmationOrderNo = orderNo;
      activeConfirmationAccessRevision = access.revision;
      const clearActiveConfirmation = () => {
        if (
          activeConfirmationPromise === request
          && activeConfirmationAccessRevision === access.revision
        ) {
          activeConfirmationPromise = null;
          activeConfirmationOrderNo = null;
          activeConfirmationAccessRevision = -1;
        }
      };
      void request.then(clearActiveConfirmation, clearActiveConfirmation);
      return request;
    }
 
    async function confirmReceiptWithAccess(
      context: FulfillmentAccessContext,
      access: ActiveReceiptAccess,
      orderNo: string,
    ): Promise<Fulfillment | null> {
      confirmationError.value = null;
      const current = fulfillments.fulfillmentForOrder(orderNo)
        ?? await fulfillments.loadForOrder(context, orderNo, false);
      requireCurrent(access);
      if (!current) {
        confirmationError.value = fulfillments.error
          ?? "当前订单没有可确认的履约事实。";
        return null;
      }
      Iif (current.status === "SIGNED") {
        unknownOrderNo.value = null;
        return current;
      }
      if (!CONFIRMABLE_STATUSES.has(current.status)) {
        unknownOrderNo.value = null;
        confirmationError.value = `履约当前为 ${current.status},不能确认收货。`;
        return current;
      }
 
      const requestRevision = ++confirmationRevision;
      confirmingOrderNo.value = orderNo;
      try {
        const value = await fulfillmentApi(access.accessToken)
          .confirmReceipt(orderNo);
        requireCurrent(access);
        Iif (requestRevision !== confirmationRevision) {
          return null;
        }
        return completeConfirmation(context, access, orderNo, value);
      } catch (cause) {
        if (!accessIsCurrent(access)) {
          throw new FulfillmentAccessChangedError();
        }
        Iif (requestRevision !== confirmationRevision) {
          return null;
        }
        Eif (isUncertainConfirmationFailure(cause)) {
          const recovered = await fulfillments.loadForOrder(context, orderNo, false);
          requireCurrent(access);
          if (recovered?.status === "SIGNED") {
            unknownOrderNo.value = null;
            confirmationError.value = null;
            return recovered;
          }
          markUnknown(
            orderNo,
            "确认收货结果尚未确认。请先查询履约事实,仍未确认时可安全重试同一路径。",
          );
          return recovered;
        }
        unknownOrderNo.value = null;
        confirmationError.value = cause instanceof Error
          ? cause.message
          : "确认收货未完成。";
        return null;
      } finally {
        if (
          accessIsCurrent(access)
          && requestRevision === confirmationRevision
        ) {
          confirmingOrderNo.value = null;
        }
      }
    }
 
    return {
      confirmingOrderNo,
      unknownOrderNo,
      confirmationError,
      activeOwnerId,
      synchronizeAccess,
      resolveFromFact,
      confirmReceipt,
    };
  },
);