All files / src/entities/benefit/model benefitStore.ts

98.38% Statements 61/62
87.5% Branches 35/40
100% Functions 13/13
98.33% Lines 59/60

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                      2x                               2x 2x           2x 2x                 24x               7x     7x       2x 6x 6x 6x 6x 6x 6x 6x   6x 5x         8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x 8x       8x 1x 1x   7x               17x           7x 1x         8x 8x 1x     7x 7x 7x 7x 7x 7x 7x     9x 2x   4x 4x   3x 1x   2x 3x   7x 6x         6x                  
import { computed, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  createApiClient,
  createMarketingApi,
  type Benefit,
  type BusinessId,
  type MarketingApi,
} from "@plain-journal/foundation";
 
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
 
export interface BenefitAccessContext {
  authenticated: boolean;
  ownerId: BusinessId | null;
  accessToken: string | null;
}
 
interface ActiveBenefitAccess {
  ownerId: BusinessId;
  accessToken: string;
  revision: number;
}
 
export class BenefitAccessChangedError extends Error {
  constructor() {
    super("账户或会话已切换,旧的权益请求结果不会写入当前页面。");
    this.name = "BenefitAccessChangedError";
  }
}
 
export class BenefitOwnershipMismatchError extends Error {
  constructor() {
    super("权益响应包含不属于当前账户的事实,页面已拒绝展示。");
    this.name = "BenefitOwnershipMismatchError";
  }
}
 
function isActiveContext(context: BenefitAccessContext): 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 marketingApi(accessToken: string): MarketingApi {
  return createMarketingApi(createApiClient({
    baseUrl: apiBaseUrl,
    timeoutMs: 8000,
    tokenProvider: () => accessToken,
  }));
}
 
export const useBenefitsStore = defineStore("customer-benefits", () => {
  const benefits = ref<Benefit[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);
  const activeOwnerId = ref<BusinessId | null>(null);
  let activeAccessToken: string | null = null;
  let accessRevision = 0;
  let loadRevision = 0;
 
  const availableCount = computed(() =>
    benefits.value.filter((benefit) => benefit.status === "AVAILABLE").length);
 
  function synchronizeAccess(
    context: BenefitAccessContext,
  ): ActiveBenefitAccess | null {
    const nextOwnerId = isActiveContext(context) ? context.ownerId : null;
    const nextAccessToken = isActiveContext(context) ? context.accessToken : null;
    const ownerChanged = activeOwnerId.value !== nextOwnerId;
    const accessChanged = ownerChanged || activeAccessToken !== nextAccessToken;
 
    Eif (accessChanged) {
      activeOwnerId.value = nextOwnerId;
      activeAccessToken = nextAccessToken;
      accessRevision += 1;
      loadRevision += 1;
      loading.value = false;
      error.value = null;
      Eif (ownerChanged) {
        benefits.value = [];
      }
    }
 
    if (!isActiveContext(context)) {
      benefits.value = [];
      return null;
    }
    return {
      ownerId: context.ownerId,
      accessToken: context.accessToken,
      revision: accessRevision,
    };
  }
 
  function accessIsCurrent(access: ActiveBenefitAccess): boolean {
    return access.revision === accessRevision
      && access.ownerId === activeOwnerId.value
      && access.accessToken === activeAccessToken;
  }
 
  function requireCurrent(access: ActiveBenefitAccess) {
    if (!accessIsCurrent(access)) {
      throw new BenefitAccessChangedError();
    }
  }
 
  async function load(context: BenefitAccessContext): Promise<Benefit[]> {
    const access = synchronizeAccess(context);
    if (!access) {
      return [];
    }
 
    const requestRevision = ++loadRevision;
    loading.value = true;
    error.value = null;
    try {
      const result = await marketingApi(access.accessToken).benefits();
      requireCurrent(access);
      Iif (requestRevision !== loadRevision) {
        throw new BenefitAccessChangedError();
      }
      if (result.some((benefit) => benefit.userId !== access.ownerId)) {
        throw new BenefitOwnershipMismatchError();
      }
      benefits.value = result;
      return benefits.value;
    } catch (cause) {
      if (!accessIsCurrent(access) || requestRevision !== loadRevision) {
        throw new BenefitAccessChangedError();
      }
      error.value = cause instanceof Error ? cause.message : "权益事实暂时无法读取。";
      return benefits.value;
    } finally {
      if (accessIsCurrent(access) && requestRevision === loadRevision) {
        loading.value = false;
      }
    }
  }
 
  return {
    benefits,
    loading,
    error,
    activeOwnerId,
    availableCount,
    load,
  };
});