All files / src/entities/fulfillment/model fulfillmentStore.ts

87.21% Statements 116/133
80.45% Branches 70/87
92.3% Functions 24/26
88.28% Lines 113/128

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                          3x                               6x 6x           2x 2x                 129x               17x     17x       3x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x         43x 43x 43x 43x   43x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 16x 16x       43x         43x               47x           24x 2x         24x       5x       1x 1x               17x 1x         5x 5x             1x         16x 6x   16x 6x   10x         4x 1x 4x 1x   3x                 9x 9x     9x 9x 9x 9x               11x 11x     11x 11x 11x 11x 11x   10x 10x     8x 8x 8x   4x 2x   2x     2x 1x 1x 1x         1x     4x   11x 9x                   6x 6x     6x 6x 6x 6x 6x   5x 5x     5x 5x 5x   2x     2x     2x 1x 1x 1x         1x     2x   6x 6x         14x                                
import { ref } from "vue";
import { defineStore } from "pinia";
 
import {
  ApiError,
  createApiClient,
  createFulfillmentApi,
  type BusinessId,
  type Fulfillment,
  type FulfillmentApi,
  type ShipmentPosition,
} from "@plain-journal/foundation";
 
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
 
export interface FulfillmentAccessContext {
  authenticated: boolean;
  ownerId: BusinessId | null;
  accessToken: string | null;
}
 
interface ActiveFulfillmentAccess {
  ownerId: BusinessId;
  accessToken: string;
  revision: number;
}
 
export class FulfillmentAccessChangedError extends Error {
  constructor() {
    super("账户或会话已切换,旧的履约请求结果不会写入当前页面。");
    this.name = "FulfillmentAccessChangedError";
  }
}
 
export class FulfillmentResponseMismatchError extends Error {
  constructor() {
    super("Fulfillment 已响应,但返回的履约事实与本次订单或账户不一致。");
    this.name = "FulfillmentResponseMismatchError";
  }
}
 
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,
  }));
}
 
export const useFulfillmentsStore = defineStore("customer-fulfillments", () => {
  const fulfillments = ref<Fulfillment[]>([]);
  const positions = ref<ShipmentPosition[]>([]);
  const loadingOrderNo = ref<string | null>(null);
  const loadingPositionOrderNo = ref<string | null>(null);
  const error = ref<string | null>(null);
  const positionError = ref<string | null>(null);
  const activeOwnerId = ref<BusinessId | null>(null);
  let activeAccessToken: string | null = null;
  let accessRevision = 0;
  let fulfillmentReadRevision = 0;
  let positionReadRevision = 0;
 
  function synchronizeAccess(
    context: FulfillmentAccessContext,
  ): ActiveFulfillmentAccess | 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;
      fulfillmentReadRevision += 1;
      positionReadRevision += 1;
      loadingOrderNo.value = null;
      loadingPositionOrderNo.value = null;
      error.value = null;
      positionError.value = null;
      if (ownerChanged) {
        fulfillments.value = [];
        positions.value = [];
      }
    }
 
    Iif (!isActiveContext(context)) {
      fulfillments.value = [];
      positions.value = [];
      return null;
    }
    return {
      ownerId: context.ownerId,
      accessToken: context.accessToken,
      revision: accessRevision,
    };
  }
 
  function accessIsCurrent(access: ActiveFulfillmentAccess): boolean {
    return access.revision === accessRevision
      && access.ownerId === activeOwnerId.value
      && access.accessToken === activeAccessToken;
  }
 
  function requireCurrent(access: ActiveFulfillmentAccess) {
    if (!accessIsCurrent(access)) {
      throw new FulfillmentAccessChangedError();
    }
  }
 
  function fulfillmentForOrder(orderNo: string): Fulfillment | null {
    return fulfillments.value.find((value) => value.orderNo === orderNo) ?? null;
  }
 
  function positionForOrder(orderNo: string): ShipmentPosition | null {
    return positions.value.find((value) => value.orderNo === orderNo) ?? null;
  }
 
  function removeOrderFacts(orderNo: string) {
    fulfillments.value = fulfillments.value.filter((value) => value.orderNo !== orderNo);
    positions.value = positions.value.filter((value) => value.orderNo !== orderNo);
  }
 
  function assertFulfillmentIdentity(
    value: Fulfillment,
    access: ActiveFulfillmentAccess,
    orderNo: string,
  ) {
    if (value.orderNo !== orderNo || value.userId !== access.ownerId) {
      throw new FulfillmentResponseMismatchError();
    }
  }
 
  function assertPositionIdentity(value: ShipmentPosition, orderNo: string) {
    const knownFulfillment = fulfillmentForOrder(orderNo);
    if (
      value.orderNo !== orderNo
      || (
        knownFulfillment
        && value.fulfillmentNo !== knownFulfillment.fulfillmentNo
      )
    ) {
      throw new FulfillmentResponseMismatchError();
    }
  }
 
  function upsertFulfillment(value: Fulfillment) {
    const index = fulfillments.value.findIndex((candidate) =>
      candidate.fulfillmentNo === value.fulfillmentNo
      || candidate.orderNo === value.orderNo);
    if (index >= 0) {
      fulfillments.value[index] = value;
    } else {
      fulfillments.value.push(value);
    }
  }
 
  function upsertPosition(value: ShipmentPosition) {
    const index = positions.value.findIndex((candidate) =>
      candidate.orderNo === value.orderNo);
    if (index >= 0) {
      positions.value[index] = value;
    } else {
      positions.value.push(value);
    }
  }
 
  function recordAuthoritativeFulfillment(
    context: FulfillmentAccessContext,
    orderNo: string,
    value: Fulfillment,
  ): Fulfillment {
    const access = synchronizeAccess(context);
    Iif (!access) {
      throw new FulfillmentAccessChangedError();
    }
    requireCurrent(access);
    assertFulfillmentIdentity(value, access, orderNo);
    upsertFulfillment(value);
    return value;
  }
 
  async function loadForOrder(
    context: FulfillmentAccessContext,
    orderNo: string,
    silentNotFound = true,
  ): Promise<Fulfillment | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      return null;
    }
    const requestRevision = ++fulfillmentReadRevision;
    loadingOrderNo.value = orderNo;
    error.value = null;
    try {
      const value = await fulfillmentApi(access.accessToken)
        .fulfillmentByOrder(orderNo);
      requireCurrent(access);
      Iif (requestRevision !== fulfillmentReadRevision) {
        return null;
      }
      assertFulfillmentIdentity(value, access, orderNo);
      upsertFulfillment(value);
      return value;
    } catch (cause) {
      if (!accessIsCurrent(access)) {
        throw new FulfillmentAccessChangedError();
      }
      Iif (requestRevision !== fulfillmentReadRevision) {
        return null;
      }
      if (cause instanceof ApiError && cause.status === 404) {
        removeOrderFacts(orderNo);
        Eif (silentNotFound) {
          return null;
        }
        error.value = "履约事实不存在,或不属于当前账户。";
        return null;
      }
      error.value = cause instanceof Error
        ? cause.message
        : "履约事实暂时无法读取。";
      return null;
    } finally {
      if (accessIsCurrent(access) && requestRevision === fulfillmentReadRevision) {
        loadingOrderNo.value = null;
      }
    }
  }
 
  async function loadPosition(
    context: FulfillmentAccessContext,
    orderNo: string,
    silentNotFound = true,
  ): Promise<ShipmentPosition | null> {
    const access = synchronizeAccess(context);
    Iif (!access) {
      return null;
    }
    const requestRevision = ++positionReadRevision;
    loadingPositionOrderNo.value = orderNo;
    positionError.value = null;
    try {
      const value = await fulfillmentApi(access.accessToken)
        .shipmentPosition(orderNo);
      requireCurrent(access);
      Iif (requestRevision !== positionReadRevision) {
        return null;
      }
      assertPositionIdentity(value, orderNo);
      upsertPosition(value);
      return value;
    } catch (cause) {
      Iif (!accessIsCurrent(access)) {
        throw new FulfillmentAccessChangedError();
      }
      Iif (requestRevision !== positionReadRevision) {
        return null;
      }
      if (cause instanceof ApiError && cause.status === 404) {
        positions.value = positions.value.filter((value) => value.orderNo !== orderNo);
        Eif (silentNotFound) {
          return null;
        }
        positionError.value = "该订单暂时没有可读取的物流位置。";
        return null;
      }
      positionError.value = cause instanceof Error
        ? cause.message
        : "最新物流位置暂时无法读取。";
      return null;
    } finally {
      Eif (accessIsCurrent(access) && requestRevision === positionReadRevision) {
        loadingPositionOrderNo.value = null;
      }
    }
  }
 
  return {
    fulfillments,
    positions,
    loadingOrderNo,
    loadingPositionOrderNo,
    error,
    positionError,
    activeOwnerId,
    synchronizeAccess,
    fulfillmentForOrder,
    positionForOrder,
    recordAuthoritativeFulfillment,
    loadForOrder,
    loadPosition,
  };
});