All files / src/entities/guest-bag/model guestBag.ts

82.99% Statements 122/147
77.77% Branches 91/117
93.1% Functions 27/29
82.73% Lines 115/139

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                                      12x 12x 12x 12x 12x 12x                   2x 2x         19x       21x 4x   17x       18x     18x 18x 18x                             1x   17x                       1x     1x 1x             1x                   23x     23x 23x 23x       23x 23x 5x 5x 1x   4x 4x 1x 1x         3x 3x     23x 23x               23x     23x 23x 23x                   22x 22x   1x                 1x 1x 1x 1x 1x 1x                           8x     12x 23x 23x 23x 3x     23x 2x         20x 20x         12x 12x     12x 2x 12x 2x     2x         10x     10x   12x       2x 2x     2x 2x       2x 2x     2x 2x 2x       1x 1x     1x   1x 1x     1x 1x         20x 4x 2x   2x   16x 8x   8x     8x           8x 8x 8x   8x       3x 3x     3x 3x 3x     3x 3x 2x   1x     3x 3x 3x 3x   3x     23x                          
import { computed, ref } from "vue";
import { defineStore } from "pinia";
 
import {
  secureRandomUUID,
  type BusinessId,
  type GuestBagMergeItem,
} from "@plain-journal/foundation";
 
export interface GuestBagItem {
  productId: BusinessId;
  skuId: BusinessId;
  productTitle: string;
  skuName: string;
  unitPrice: string;
  quantity: number;
  coverUrl: string | null;
}
 
const STORAGE_KEY = "plain-journal:guest-bag:v1";
const PENDING_MERGE_KEY = "plain-journal:guest-bag-merge:v1";
const MAX_GUEST_QUANTITY = 999;
const MAX_GUEST_ITEMS = 100;
const BUSINESS_ID_PATTERN = /^\d+$/u;
const MERGE_KEY_PATTERN = /^[A-Za-z0-9._:-]{8,64}$/u;
 
export interface PendingGuestBagMerge {
  key: string;
  userId: BusinessId;
  items: GuestBagMergeItem[];
}
 
export class GuestBagMergeOwnershipError extends Error {
  constructor() {
    super("这个设备上有一笔属于另一账户且结果尚未确认的购物袋合并。");
    this.name = "GuestBagMergeOwnershipError";
  }
}
 
function isRecord(value: unknown): value is Record<string, unknown> {
  return Boolean(value && typeof value === "object");
}
 
function normalizeQuantity(value: unknown, fallback: number | null = null): number | null {
  if (typeof value !== "number" || !Number.isFinite(value)) {
    return fallback;
  }
  return Math.max(1, Math.min(MAX_GUEST_QUANTITY, Math.trunc(value)));
}
 
function normalizeItem(value: unknown): GuestBagItem | null {
  Iif (!isRecord(value)) {
    return null;
  }
  const quantity = normalizeQuantity(value.quantity);
  const numericPrice = Number(value.unitPrice);
  if (
    typeof value.productId !== "string"
    || !BUSINESS_ID_PATTERN.test(value.productId)
    || typeof value.skuId !== "string"
    || !BUSINESS_ID_PATTERN.test(value.skuId)
    || typeof value.productTitle !== "string"
    || value.productTitle.trim().length === 0
    || typeof value.skuName !== "string"
    || value.skuName.trim().length === 0
    || typeof value.unitPrice !== "string"
    || !Number.isFinite(numericPrice)
    || numericPrice < 0
    || quantity === null
    || !(value.coverUrl === null || typeof value.coverUrl === "string")
  ) {
    return null;
  }
  return {
    productId: value.productId,
    skuId: value.skuId,
    productTitle: value.productTitle,
    skuName: value.skuName,
    unitPrice: value.unitPrice,
    quantity,
    coverUrl: value.coverUrl,
  };
}
 
function normalizeMergeItem(value: unknown): GuestBagMergeItem | null {
  Iif (!isRecord(value)) {
    return null;
  }
  const quantity = normalizeQuantity(value.quantity);
  Eif (
    typeof value.productId !== "string"
    || !BUSINESS_ID_PATTERN.test(value.productId)
    || typeof value.skuId !== "string"
    || !BUSINESS_ID_PATTERN.test(value.skuId)
    || quantity === null
  ) {
    return null;
  }
  return {
    productId: value.productId,
    skuId: value.skuId,
    quantity,
  };
}
 
function loadItems(): GuestBagItem[] {
  Iif (typeof localStorage === "undefined") {
    return [];
  }
  try {
    const value: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]");
    Iif (!Array.isArray(value)) {
      localStorage.removeItem(STORAGE_KEY);
      return [];
    }
    const normalized: GuestBagItem[] = [];
    for (const candidate of value) {
      const item = normalizeItem(candidate);
      if (!item) {
        continue;
      }
      const existing = normalized.find((current) => current.skuId === item.skuId);
      if (existing) {
        Eif (existing.productId === item.productId) {
          existing.quantity = Math.min(
            MAX_GUEST_QUANTITY,
            existing.quantity + item.quantity,
          );
        }
      } else Eif (normalized.length < MAX_GUEST_ITEMS) {
        normalized.push(item);
      }
    }
    localStorage.setItem(STORAGE_KEY, JSON.stringify(normalized));
    return normalized;
  } catch {
    localStorage.removeItem(STORAGE_KEY);
    return [];
  }
}
 
function loadPendingMerge(): PendingGuestBagMerge | null {
  Iif (typeof localStorage === "undefined") {
    return null;
  }
  try {
    const value: unknown = JSON.parse(localStorage.getItem(PENDING_MERGE_KEY) ?? "null");
    if (
      !value
      || typeof value !== "object"
      || !("key" in value)
      || !("userId" in value)
      || !("items" in value)
      || typeof value.key !== "string"
      || typeof value.userId !== "string"
      || !Array.isArray(value.items)
    ) {
      localStorage.removeItem(PENDING_MERGE_KEY);
      return null;
    }
    Iif (
      !MERGE_KEY_PATTERN.test(value.key)
      || !BUSINESS_ID_PATTERN.test(value.userId)
      || value.items.length === 0
      || value.items.length > MAX_GUEST_ITEMS
    ) {
      localStorage.removeItem(PENDING_MERGE_KEY);
      return null;
    }
    const items = value.items.map(normalizeMergeItem);
    const validItems = items.filter((item): item is GuestBagMergeItem => item !== null);
    const uniqueSkuIds = new Set(validItems.map((item) => item.skuId));
    Eif (validItems.length !== value.items.length || uniqueSkuIds.size !== validItems.length) {
      localStorage.removeItem(PENDING_MERGE_KEY);
      return null;
    }
    return {
      key: value.key,
      userId: value.userId,
      items: validItems,
    };
  } catch {
    localStorage.removeItem(PENDING_MERGE_KEY);
    return null;
  }
}
 
function newMergeKey(): string {
  return `guest-merge:${secureRandomUUID()}`;
}
 
export const useBagStore = defineStore("guest-bag", () => {
  const items = ref<GuestBagItem[]>(loadItems());
  const pendingMerge = ref<PendingGuestBagMerge | null>(loadPendingMerge());
  const itemCount = computed(() => items.value.reduce(
    (total, item) => total + item.quantity,
    0,
  ));
  const subtotal = computed(() => items.value.reduce(
    (total, item) => total + Number(item.unitPrice) * item.quantity,
    0,
  ));
 
  function persist() {
    Eif (typeof localStorage !== "undefined") {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(items.value));
    }
  }
 
  function addItem(item: GuestBagItem) {
    const normalized = normalizeItem(item);
    Iif (!normalized) {
      throw new Error("商品信息不完整,无法写入当前设备购物袋。");
    }
    const existing = items.value.find((candidate) =>
      candidate.skuId === normalized.skuId);
    if (existing) {
      Iif (existing.productId !== normalized.productId) {
        throw new Error("同一 SKU 对应了不同商品,当前设备购物袋未修改。");
      }
      existing.quantity = Math.min(
        MAX_GUEST_QUANTITY,
        existing.quantity + normalized.quantity,
      );
    } else {
      Iif (items.value.length >= MAX_GUEST_ITEMS) {
        throw new Error("当前设备购物袋最多保留 100 种商品。");
      }
      items.value.push(normalized);
    }
    persist();
  }
 
  function updateQuantity(skuId: BusinessId, quantity: number) {
    const item = items.value.find((candidate) => candidate.skuId === skuId);
    Iif (!item) {
      return;
    }
    item.quantity = normalizeQuantity(quantity, item.quantity) ?? item.quantity;
    persist();
  }
 
  function removeItem(skuId: BusinessId): GuestBagItem | null {
    const index = items.value.findIndex((candidate) => candidate.skuId === skuId);
    Iif (index < 0) {
      return null;
    }
    const [removed] = items.value.splice(index, 1);
    persist();
    return removed ?? null;
  }
 
  function restoreItem(item: GuestBagItem) {
    const normalized = normalizeItem(item);
    Iif (!normalized) {
      return;
    }
    const existing = items.value.some((candidate) =>
      candidate.skuId === normalized.skuId);
    Eif (!existing) {
      Iif (items.value.length >= MAX_GUEST_ITEMS) {
        return;
      }
      items.value.push(normalized);
      persist();
    }
  }
 
  function prepareMerge(userId: BusinessId): PendingGuestBagMerge | null {
    if (pendingMerge.value) {
      if (pendingMerge.value.userId !== userId) {
        throw new GuestBagMergeOwnershipError();
      }
      return pendingMerge.value;
    }
    if (items.value.length === 0) {
      return null;
    }
    const prepared: PendingGuestBagMerge = {
      key: newMergeKey(),
      userId,
      items: items.value.map((item) => ({
        productId: item.productId,
        skuId: item.skuId,
        quantity: item.quantity,
      })),
    };
    pendingMerge.value = prepared;
    Eif (typeof localStorage !== "undefined") {
      localStorage.setItem(PENDING_MERGE_KEY, JSON.stringify(prepared));
    }
    return prepared;
  }
 
  function completeMerge(key: string): boolean {
    const prepared = pendingMerge.value;
    Iif (!prepared || prepared.key !== key) {
      return false;
    }
    for (const submitted of prepared.items) {
      const index = items.value.findIndex((item) => item.skuId === submitted.skuId);
      Iif (index < 0) {
        continue;
      }
      const current = items.value[index];
      if (!current || current.quantity <= submitted.quantity) {
        items.value.splice(index, 1);
      } else {
        current.quantity -= submitted.quantity;
      }
    }
    pendingMerge.value = null;
    persist();
    Eif (typeof localStorage !== "undefined") {
      localStorage.removeItem(PENDING_MERGE_KEY);
    }
    return true;
  }
 
  return {
    items,
    pendingMerge,
    itemCount,
    subtotal,
    addItem,
    updateQuantity,
    removeItem,
    restoreItem,
    prepareMerge,
    completeMerge,
  };
});