All files / demo adapter.js

62.04% Statements 340/548
61.29% Branches 304/496
70.64% Functions 77/109
65.45% Lines 324/495

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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037                    20x       50x 50x 50x       9x 9x 9x       29x 29x             13x 13x       50x 27x 27x 27x             11x 11x 11x 11x       50x                 46x       3x       50x                     50x         50x       50x 2x   50x       50x 50x 50x 185x         73x       11x 11x       5x 60x   5x     5x     5x     5x       42x       21x 21x   100x       21x 11x                     3x 10x 3x 10x   10x 3x   3x 3x   3x   17x 2x   3x 3x 10x 10x   10x 3x     36x           21x       21x 69x   21x     21x 21x     21x   21x         21x   42x   3x 3x 3x 3x 3x 20x     5x 15x 15x 15x   20x 20x   3x 11x 9x     18x                       3x 18x   3x 3x                       1x 1x 2x           1x 2x   1x             1x                                                                 1x 1x 1x 1x 1x   1x       1x   1x 1x                           1x 1x                                                           1x 1x       1x         1x 2x           1x 1x   1x 1x   1x     1x   1x       1x 1x                                 5x 5x   5x   5x     5x 5x     5x 5x               5x 5x 5x 5x 5x 5x 5x 5x   5x 2x 1x 1x 1x 1x   1x     5x 5x                 8x 1x   12x 12x   1x 1x     7x 1x                       6x 1x                   5x 1x   12x 7x             4x 1x       3x 1x 5x     60x 12x       2x       50x 50x 50x 50x 50x 50x 50x     50x   50x                                   50x 6x 44x                 44x 4x   4x     4x   28x       4x 1x   3x 3x 3x 3x 3x     40x   40x   40x   40x   40x   40x 5x 35x 3x     32x           32x 1x 1x 1x         31x 1x 1x 1x 30x 2x 2x 2x     2x 2x 2x   28x                 28x                 28x 1x 7x 12x 1x 2x   27x 1x 26x 1x 25x 1x 1x   1x   1x 1x 1x 1x 1x 1x   24x                         24x   24x   24x                     24x 1x 4x   4x 4x                 1x 23x             23x       1x 1x 3x   1x 1x 1x 1x 1x   1x   1x     1x 1x 22x   22x                                             22x                           22x                                 22x                                         22x   22x                 22x   22x   22x                               22x   22x     22x 1x 1x         1x     1x 21x                                                             21x                       21x                                               21x 1x 20x 5x 15x 3x     3x         3x 12x 2x 2x 2x           1x     2x 2x 10x                                 10x   10x 1x 1x 2x 2x   9x 1x           8x 8x 6x 2x   2x         1x 1x             1x       50x       9x 9x          
import { createDemoState } from "@/demo/data.js";
import {
  activateDemoIdentity,
  DEMO_STATE_KEY,
  findDemoIdentity,
  getActiveDemoIdentity,
  toDemoUser,
} from "@/demo/runtime.js";
 
function clone(value) {
  return JSON.parse(JSON.stringify(value));
}
 
function readState() {
  try {
    const stored = sessionStorage.getItem(DEMO_STATE_KEY);
    if (stored) return JSON.parse(stored);
  } catch {
    // Fall through to a fresh in-memory state.
  }
  const state = createDemoState();
  writeState(state);
  return state;
}
 
function writeState(state) {
  try {
    sessionStorage.setItem(DEMO_STATE_KEY, JSON.stringify(state));
  } catch {
    // The current response remains valid even if persistence is unavailable.
  }
}
 
function nextId(state) {
  state.sequence += 1;
  return state.sequence;
}
 
function parsePayload(config) {
  if (!config.data) return {};
  Iif (typeof config.data === "object") return config.data;
  try {
    return JSON.parse(config.data);
  } catch {
    return {};
  }
}
 
function page(items, payload = {}) {
  const current = Math.max(1, Number(payload.current || 1));
  const size = Math.max(1, Number(payload.size || items.length || 10));
  const start = (current - 1) * size;
  return { items: items.slice(start, start + size), total: items.length };
}
 
function body(code, data, msg, total) {
  return {
    code,
    msg,
    data,
    ...(total === undefined ? {} : { total }),
  };
}
 
function ok(data = null, msg = "操作成功", total) {
  return body(200, data, msg, total);
}
 
function rejected(msg) {
  return body(409, null, msg);
}
 
function response(config, data) {
  return Promise.resolve({
    data,
    status: 200,
    statusText: "OK",
    headers: { "content-type": "application/json;charset=UTF-8" },
    config,
    request: null,
  });
}
 
function pathOf(config) {
  return new URL(config.url || "/", "https://demo.darkroomlibrary.local")
    .pathname;
}
 
function queryParams(config) {
  const url = new URL(
    config.url || "/",
    "https://demo.darkroomlibrary.local"
  );
  Object.entries(config.params || {}).forEach(([key, value]) => {
    Eif (value !== null && value !== undefined) url.searchParams.set(key, value);
  });
  return url.searchParams;
}
 
function activeUser(state) {
  const identity = getActiveDemoIdentity();
  Iif (!identity) return null;
  return (
    state.users.find((user) => user.id === identity.id) || toDemoUser(identity)
  );
}
 
function findBook(state, id) {
  return state.books.find((book) => book.id === Number(id));
}
 
function paginateResponse(items, payload) {
  const result = page(items, payload);
  return ok(clone(result.items), "查询成功", result.total);
}
 
function queryBooks(state, payload) {
  let books = state.books.filter(
    (book) => Boolean(book.deleted) === Boolean(payload.deleted)
  );
  Iif (payload.name) {
    books = books.filter((book) => book.name.includes(String(payload.name)));
  }
  Iif (payload.author) {
    books = books.filter((book) => book.author.includes(String(payload.author)));
  }
  Iif (payload.category) {
    books = books.filter((book) => book.category === payload.category);
  }
  return paginateResponse(books, payload);
}
 
function recommendationItemId(userId, bookId) {
  return 800000 + Number(userId) * 100 + Number(bookId);
}
 
function recordRecommendationEvent(state, userId, itemId, eventType) {
  state.recommendationEvents ||= [];
  const exists = state.recommendationEvents.some(
    (event) =>
      event.userId === Number(userId) &&
      event.itemId === Number(itemId) &&
      event.eventType === eventType
  );
  if (!exists) {
    state.recommendationEvents.push({
      id: nextId(state),
      userId: Number(userId),
      itemId: Number(itemId),
      eventType,
      createdAt: "2026-08-01 12:00:00",
    });
  }
}
 
function recommendationFeed(state, user, requestedSize) {
  const size = Math.max(1, Math.min(Number(requestedSize || 6), 8));
  const favorites = state.favorites.filter((item) => item.userId === user.id);
  const favoriteBooks = favorites
    .map((item) => findBook(state, item.bookId))
    .filter(Boolean);
  const favoriteIds = new Set(favoriteBooks.map((book) => book.id));
  const activeBorrowIds = new Set(
    state.borrowRecords
      .filter((item) => item.userId === user.id && !item.status)
      .map((item) => item.bookId)
  );
  const dismissedItemIds = new Set(
    (state.recommendationEvents || [])
      .filter((event) => event.userId === user.id && event.eventType === "DISMISS")
      .map((event) => event.itemId)
  );
  const personalized = state.recommendationEnabled !== false && favoriteBooks.length >= 3;
  const categoryCounts = favoriteBooks.reduce((counts, book) => {
    counts[book.category] = Number(counts[book.category] || 0) + 1;
    return counts;
  }, {});
  const authorSet = new Set(favoriteBooks.map((book) => book.author));
  const scored = state.books
    .filter(
      (book) =>
        !book.deleted &&
        !favoriteIds.has(book.id) &&
        !activeBorrowIds.has(book.id) &&
        !dismissedItemIds.has(recommendationItemId(user.id, book.id))
    )
    .map((book) => {
      const content = personalized
        ? Number(categoryCounts[book.category] || 0) * 3 +
          (authorSet.has(book.author) ? 2 : 0)
        : 0;
      const popularity = state.favorites.filter(
        (favorite) => favorite.bookId === book.id
      ).length;
      const availability = book.totalCount
        ? book.availableCount / book.totalCount
        : 0;
      const exploration = ((user.id * 31 + book.id * 17) % 100) / 100;
      const total = personalized
        ? content * 0.7 + popularity * 0.2 + exploration * 0.1
        : popularity * 0.55 + availability * 0.25 + exploration * 0.2;
      const sourceType = personalized && content > 0 ? "CONTENT" : "PUBLIC";
      const reason =
        sourceType === "CONTENT"
          ? `沿着你收藏的「${book.category}」书签,灯下又出现了它。`
          : popularity > 0
            ? "最近有人收藏或谈起这本书。"
            : "它与已有书签稍远,留作一次偶然相遇。";
      return { book, total, sourceType, reason };
    })
    .sort((left, right) => right.total - left.total || left.book.id - right.book.id);
 
  const selected = [];
  const selectedIds = new Set();
  const categoryLimits = {};
  const authorLimits = {};
  for (const candidate of scored) {
    if (
      Number(categoryLimits[candidate.book.category] || 0) >= 2 ||
      Number(authorLimits[candidate.book.author] || 0) >= 1
    ) continue;
    selected.push(candidate);
    selectedIds.add(candidate.book.id);
    categoryLimits[candidate.book.category] =
      Number(categoryLimits[candidate.book.category] || 0) + 1;
    authorLimits[candidate.book.author] = 1;
    if (selected.length === size) break;
  }
  for (const candidate of scored) {
    if (selected.length === size) break;
    if (!selectedIds.has(candidate.book.id)) selected.push(candidate);
  }
 
  const items = selected.map(({ book, sourceType, reason }) => ({
    itemId: recommendationItemId(user.id, book.id),
    bookId: book.id,
    name: book.name,
    author: book.author,
    category: book.category,
    cover: book.cover,
    description: book.description,
    availableCount: book.availableCount,
    sourceType,
    reason,
  }));
  items.forEach((item) =>
    recordRecommendationEvent(state, user.id, item.itemId, "EXPOSE")
  );
  writeState(state);
  return ok({
    mode: personalized ? "CONTENT" : "PUBLIC",
    personalized,
    enabled: state.recommendationEnabled !== false,
    signalCount: favoriteBooks.length,
    generatedAt: "2026-08-01 12:00:00",
    privacyNotice: "只使用你主动留下的收藏、借阅与评分,不记录无关浏览行为。",
    items,
  });
}
 
function queryBorrowRecords(state, payload, user) {
  let records = state.borrowRecords;
  if (user?.userRole === 2) {
    records = records.filter((record) => record.userId === user.id);
  } else Eif (payload.userId) {
    records = records.filter(
      (record) => record.userId === Number(payload.userId)
    );
  }
  Eif (typeof payload.status === "boolean") {
    records = records.filter((record) => record.status === payload.status);
  }
  Iif (typeof payload.overdue === "boolean") {
    const now = Date.now();
    records = records.filter((record) => {
      const overdue = !record.status && new Date(record.dueDate).getTime() < now;
      return overdue === payload.overdue;
    });
  }
  return paginateResponse(records, payload);
}
 
function queryReservations(state, payload, user) {
  let reservations = state.reservations;
  if (user?.userRole === 2) {
    reservations = reservations.filter((item) => item.userId === user.id);
  } else if (payload.userId) {
    reservations = reservations.filter(
      (item) => item.userId === Number(payload.userId)
    );
  }
  return paginateResponse(reservations, payload);
}
 
function queryReviews(state, payload) {
  let reviews = state.reviews.filter((review) => review.status !== 1);
  if (payload.bookId) {
    reviews = reviews.filter(
      (review) => review.bookId === Number(payload.bookId)
    );
  }
  if (payload.sortBy === "hot") {
    reviews = [...reviews].sort((a, b) => b.likeCount - a.likeCount);
  } else {
    reviews = [...reviews].sort((a, b) =>
      String(b.createTime).localeCompare(String(a.createTime))
    );
  }
  return paginateResponse(reviews, payload);
}
 
function borrowBook(state, bookId, user) {
  Iif (user?.userRole !== 2) return rejected("只有读者身份可以借阅图书。");
  const book = findBook(state, bookId);
  Iif (!book) return rejected("未找到图书。");
  Iif (book.availableCount <= 0) return rejected("当前无可借库存,请先预约。");
  const active = state.borrowRecords.some(
    (record) =>
      record.userId === user.id &&
      record.bookId === book.id &&
      record.status === false
  );
  Iif (active) return rejected("你已经借阅了这本书。");
 
  book.availableCount -= 1;
  state.borrowRecords.unshift({
    id: nextId(state),
    userId: user.id,
    userName: user.userName,
    bookId: book.id,
    bookName: book.name,
    bookAuthor: book.author,
    borrowTime: "2026-07-27 20:30:00",
    dueDate: "2026-08-26 20:30:00",
    returnTime: null,
    status: false,
    renewCount: 0,
    fine: 0,
  });
  writeState(state);
  return ok(null, "借阅成功,库存已同步扣减。");
}
 
function reserveBook(state, bookId, user) {
  if (user?.userRole !== 2) return rejected("只有读者身份可以预约图书。");
  const book = findBook(state, bookId);
  if (!book) return rejected("未找到图书。");
  const active = state.reservations.some(
    (item) =>
      item.userId === user.id &&
      item.bookId === book.id &&
      [0, 3].includes(item.status)
  );
  if (active) return rejected("你已经在这本书的预约队列中。");
  state.reservations.unshift({
    id: nextId(state),
    userId: user.id,
    userName: user.userName,
    bookId: book.id,
    bookName: book.name,
    status: 0,
    createTime: "2026-07-27 20:32:00",
    expireTime: "2026-08-06 20:32:00",
    queuePosition: 1,
  });
  writeState(state);
  return ok(null, "预约成功,已加入候书队列。");
}
 
function filterOrdersForIdentity(orders, identity) {
  Iif (!identity || identity.role === 0) return orders;
  Iif (identity.role === 1) {
    if (identity.isCoordinatorAdmin) return orders;
    return orders.filter((order) => order.requesterId === identity.id);
  }
  Iif (identity.role === 3) {
    return orders.filter(
      (order) => !order.purchaserId || order.purchaserId === identity.id
    );
  }
  Eif (identity.role === 4) {
    return orders.filter((order) => order.logisticsId === identity.id);
  }
  return [];
}
 
function updateProcurementStatus(state, payload, identity) {
  const order = state.procurementOrders.find(
    (item) => item.id === Number(payload.id)
  );
  Iif (!order) return rejected("未找到采购单。");
  const targetStatus = Number(payload.status);
  const canManage =
    [0, 1].includes(identity?.role) ||
    (identity?.role === 3 &&
      (!order.purchaserId || order.purchaserId === identity.id));
  Iif (!canManage) return rejected("当前身份不能推进该采购单。");
  const allowed =
    targetStatus === order.status ||
    (targetStatus === 7 && order.status < 5) ||
    (targetStatus === 6 && order.status === 5) ||
    (targetStatus === order.status + 1 && targetStatus <= 2);
  Eif (!allowed) {
    return rejected(
      targetStatus === 3 || targetStatus === 4
        ? "发货和到货状态必须通过物流进度更新。"
        : "采购状态流转不合法。"
    );
  }
  if (identity?.role === 3 && !order.purchaserId) {
    order.purchaserId = identity.id;
    order.purchaserName = identity.name;
  }
  order.status = targetStatus;
  order.updateTime = "2026-07-27 20:40:00";
  writeState(state);
  return ok(null, "采购状态已更新。");
}
 
function updateLogistics(state, payload, identity) {
  const order = state.procurementOrders.find(
    (item) => item.id === Number(payload.orderId)
  );
  Iif (!order) return rejected("未找到采购单。");
  const canManage =
    identity?.role === 0 ||
    (identity?.role === 3 && order.purchaserId === identity.id) ||
    (identity?.role === 4 && order.logisticsId === identity.id);
  Iif (!canManage) return rejected("当前身份不能更新该物流任务。");
  Iif (order.status < 2 || [6, 7].includes(order.status)) {
    return rejected("当前采购状态不能更新物流进度。");
  }
  const status = Number(payload.status);
  Iif (
    status < 0 ||
    status > 3 ||
    (status !== order.logisticsStatus &&
      status !== order.logisticsStatus + 1)
  ) {
    return rejected("物流状态流转不合法。");
  }
  order.logisticsStatus = status;
  order.carrier = payload.carrier || order.carrier;
  order.trackingNo = payload.trackingNo || order.trackingNo;
  order.logisticsRemark = payload.remark || "";
  order.updateTime = "2026-07-27 20:42:00";
  const mappedOrderStatus = { 1: 3, 2: 4, 3: 5 }[status];
  Eif (mappedOrderStatus) {
    order.status = Math.max(order.status, mappedOrderStatus);
  }
  if (status === 3) {
    if (!order.stockApplied) {
      const book = findBook(state, order.bookId);
      Eif (book) {
        book.totalCount += order.requestCount;
        book.availableCount += order.requestCount;
      }
      order.stockApplied = true;
    }
  }
  writeState(state);
  return ok(
    null,
    status === 3
      ? "入库完成,采购数量已幂等写入库存。"
      : "物流状态已更新。"
  );
}
 
function statistics(path, state) {
  if (path === "/statistics/overview") {
    return ok({
      totalBooks: state.books
        .filter((book) => !book.deleted)
        .reduce((sum, book) => sum + book.totalCount, 0),
      totalUsers: state.users.length,
      activeBorrows: state.borrowRecords.filter((item) => !item.status).length,
      returnedBorrows: 764 + state.borrowRecords.filter((item) => item.status).length,
    });
  }
  if (path.startsWith("/statistics/monthlyBorrow/")) {
    return ok([
      { day: 1, count: 3 },
      { day: 4, count: 6 },
      { day: 7, count: 5 },
      { day: 10, count: 8 },
      { day: 13, count: 7 },
      { day: 16, count: 10 },
      { day: 19, count: 12 },
      { day: 22, count: 9 },
      { day: 25, count: 14 },
    ]);
  }
  if (path === "/statistics/hotBooks") {
    return ok({
      books: [
        { bookName: "暗室藏书", borrowCount: 37 },
        { bookName: "归架之前", borrowCount: 31 },
        { bookName: "雾灯索引", borrowCount: 28 },
        { bookName: "星阑采书札", borrowCount: 22 },
        { bookName: "青梧守卷录", borrowCount: 17 },
      ],
    });
  }
  if (path === "/statistics/lowStock") {
    return ok({
      books: state.books
        .filter((book) => !book.deleted && book.availableCount < 3)
        .map(({ name, author, availableCount }) => ({
          name,
          author,
          availableCount,
        })),
    });
  }
  if (path === "/statistics/overdueUsers") {
    return ok([
      { userName: "纸月听澜", overdueCount: 1, totalFine: 2 },
    ]);
  }
  if (path === "/statistics/collectionAnalysis") {
    return ok({
      categories: state.categories.map((category) => ({
        category: category.name,
        totalCount: state.books
          .filter((book) => !book.deleted && book.category === category.name)
          .reduce((sum, book) => sum + book.totalCount, 0),
      })),
    });
  }
  return null;
}
 
export async function demoAdapter(config) {
  const state = readState();
  const path = pathOf(config);
  const method = String(config.method || "get").toLowerCase();
  const payload = parsePayload(config);
  const params = queryParams(config);
  const identity = getActiveDemoIdentity();
  const user = activeUser(state);
  let result;
 
  Iif (path === "/captcha/generate") {
    result = ok({ captchaId: "browser-demo", expression: "7 + 5 = ?" });
  } else Iif (path === "/user/login" && method === "post") {
    const loginIdentity = findDemoIdentity(payload.userAccount);
    if (
      !loginIdentity ||
      payload.userPwd !== "DarkRoom@20606" ||
      Number(payload.captchaAnswer) !== 12
    ) {
      result = rejected("演示账号、密码或验证题答案不正确。");
    } else {
      activateDemoIdentity(loginIdentity.key);
      result = ok(
        {
          token: sessionStorage.getItem("token"),
          role: loginIdentity.role,
        },
        "登录成功"
      );
    }
  } else if (path === "/user/auth") {
    result = user ? ok(clone(user)) : body(401, null, "请先选择演示身份。");
  } else Iif (
    [
      "/user/sendVerifyCode",
      "/user/sendEmailChangeCode",
      "/user/register",
      "/user/resetPwd",
    ].includes(path)
  ) {
    result = rejected("在线演示不发送邮件或创建真实账号。");
  } else if (path === "/user/update" && method === "put") {
    Iif (!user) result = body(401, null, "请先选择演示身份。");
    else {
      const requestedEmail = String(payload.userEmail || user.userEmail)
        .trim()
        .toLowerCase();
      const linkedAccounts = state.users.filter(
        (candidate) =>
          candidate.id !== user.id &&
          String(candidate.userEmail || "").trim().toLowerCase() ===
            requestedEmail
      ).length;
      if (requestedEmail && linkedAccounts >= 3) {
        result = body(400, null, "同一邮箱最多关联 3 个账号,请更换邮箱");
      } else {
        user.userName = payload.userName || user.userName;
        user.userEmail = requestedEmail || user.userEmail;
        user.userAvatar = payload.userAvatar || user.userAvatar;
        writeState(state);
        result = ok(clone(user), "个人资料已在当前演示会话中更新。");
      }
    }
  } else Iif (path === "/user/cancelAccount") {
    result = rejected("在线演示不执行账号注销。");
  } else Iif (path === "/category/queryAll") {
    result = ok(clone(state.categories));
  } else Iif (path === "/bookshelf/queryAll") {
    result = ok(clone(state.bookshelves));
  } else Iif (path === "/category/query") {
    result = paginateResponse(state.categories, payload);
  } else Iif (path === "/bookshelf/query") {
    result = paginateResponse(state.bookshelves, payload);
  } else if (path === "/book/query") {
    result = queryBooks(state, payload);
  } else if (path === "/recommendation/feed") {
    result = user?.userRole === 2
      ? recommendationFeed(state, user, params.get("size"))
      : rejected("当前身份不能读取读者推荐。");
  } else Iif (path === "/recommendation/setting" && method === "get") {
    result = ok({
      enabled: state.recommendationEnabled !== false,
      dataScope: "只使用你主动留下的收藏、借阅与评分,不记录无关浏览行为。",
      clearEffect: "清除曝光、点击与计算结果,不删除收藏、借阅或书评。",
    });
  } else if (path === "/recommendation/setting" && method === "put") {
    state.recommendationEnabled = Boolean(payload.enabled);
    writeState(state);
    result = ok({
      enabled: state.recommendationEnabled,
      dataScope: "只使用你主动留下的收藏、借阅与评分,不记录无关浏览行为。",
      clearEffect: "清除曝光、点击与计算结果,不删除收藏、借阅或书评。",
    }, state.recommendationEnabled ? "个性化推荐已开启" : "已改为公共荐书");
  } else if (path === "/recommendation/history" && method === "delete") {
    state.recommendationEvents = [];
    writeState(state);
    result = ok(null, "推荐记录已清除,收藏、借阅和书评保持不变");
  } else if (/^\/recommendation\/items\/\d+\/events$/.test(path)) {
    const itemId = Number(path.split("/")[3]);
    Iif (!user || user.userRole !== 2) result = rejected("当前身份不能记录读者推荐事件。");
    else Iif (!["CLICK", "DISMISS"].includes(payload.eventType)) {
      result = rejected("推荐事件无效");
    } else {
      recordRecommendationEvent(state, user.id, itemId, payload.eventType);
      writeState(state);
      result = ok(null, payload.eventType === "DISMISS" ? "已减少此类推荐" : "操作成功");
    }
  } else Iif (path.startsWith("/book/queryByDays/")) {
    result = ok([
      { name: "07-20", count: 1 },
      { name: "07-21", count: 2 },
      { name: "07-22", count: 4 },
      { name: "07-23", count: 3 },
      { name: "07-24", count: 5 },
      { name: "07-25", count: 6 },
    ]);
  } else Iif (path.startsWith("/user/queryByDays/")) {
    result = ok([
      { name: "07-20", count: 2 },
      { name: "07-21", count: 3 },
      { name: "07-22", count: 3 },
      { name: "07-23", count: 5 },
      { name: "07-24", count: 6 },
      { name: "07-25", count: 8 },
    ]);
  } else if (path === "/views/staticControls") {
    result = ok([
      { name: "注册读者", count: state.users.filter((item) => item.userRole === 2).length },
      { name: "在馆图书", count: state.books.reduce((sum, book) => sum + book.totalCount, 0) },
      { name: "借阅中", count: state.borrowRecords.filter((item) => !item.status).length },
      { name: "采购流转", count: state.procurementOrders.filter((item) => item.status < 6).length },
    ]);
  } else if (path === "/borrowRecord/query") {
    result = queryBorrowRecords(state, payload, user);
  } else if (path.startsWith("/borrowRecord/borrow/")) {
    result = borrowBook(state, path.split("/").pop(), user);
  } else if (path.startsWith("/borrowRecord/return/")) {
    const record = state.borrowRecords.find(
      (item) => item.id === Number(path.split("/").pop())
    );
    Iif (!record || record.status) result = rejected("借阅记录不可归还。");
    else {
      record.status = true;
      record.returnTime = "2026-07-27 20:35:00";
      const book = findBook(state, record.bookId);
      Eif (book) book.availableCount += 1;
      writeState(state);
      result = ok(null, "归还成功,库存已同步恢复。");
    }
  } else Iif (path.startsWith("/borrowRecord/renew/")) {
    const record = state.borrowRecords.find(
      (item) => item.id === Number(path.split("/").pop())
    );
    if (!record || record.status) result = rejected("借阅记录不可续借。");
    else {
      const due = new Date(record.dueDate);
      due.setDate(due.getDate() + 14);
      record.dueDate = due.toISOString().replace("T", " ").slice(0, 19);
      record.renewCount = Number(record.renewCount || 0) + 1;
      writeState(state);
      result = ok(null, "续借成功,到期时间已延长 14 天。");
    }
  } else Iif (path === "/bookReservation/query") {
    result = queryReservations(state, payload, user);
  } else Iif (path.startsWith("/bookReservation/reserve/")) {
    result = reserveBook(state, path.split("/").pop(), user);
  } else Iif (path.startsWith("/bookReservation/cancel/")) {
    const reservation = state.reservations.find(
      (item) => item.id === Number(path.split("/").pop())
    );
    if (!reservation || ![0, 3].includes(reservation.status)) {
      result = rejected("预约记录不可取消。");
    } else {
      reservation.status = 2;
      writeState(state);
      result = ok(null, "预约已取消。");
    }
  } else if (path === "/bookFavorite/query") {
    const favorites = state.favorites
      .filter((item) => item.userId === user?.id)
      .map((favorite) => {
        const book = findBook(state, favorite.bookId);
        return {
          ...favorite,
          bookId: book.id,
          bookName: book.name,
          bookAuthor: book.author,
          cover: book.cover,
          availableCount: book.availableCount,
        };
      });
    result = paginateResponse(favorites, payload);
  } else Iif (path.startsWith("/bookFavorite/isFavorited/")) {
    const bookId = Number(path.split("/").pop());
    result = ok(
      state.favorites.some(
        (item) => item.userId === user?.id && item.bookId === bookId
      )
    );
  } else if (
    path.startsWith("/bookFavorite/add/") ||
    path.startsWith("/bookFavorite/remove/")
  ) {
    const bookId = Number(path.split("/").pop());
    const index = state.favorites.findIndex(
      (item) => item.userId === user?.id && item.bookId === bookId
    );
    Eif (path.includes("/add/") && index < 0) {
      state.favorites.push({ id: nextId(state), userId: user.id, bookId });
      const itemId = recommendationItemId(user.id, bookId);
      const exposed = (state.recommendationEvents || []).some(
        (event) => event.itemId === itemId && event.eventType === "EXPOSE"
      );
      Eif (exposed) recordRecommendationEvent(state, user.id, itemId, "FAVORITE");
    }
    Iif (path.includes("/remove/") && index >= 0) {
      state.favorites.splice(index, 1);
    }
    writeState(state);
    result = ok(null, path.includes("/add/") ? "收藏成功。" : "已取消收藏。");
  } else Iif (path === "/bookReview/query") {
    result = queryReviews(state, payload);
  } else Iif (path === "/bookReview/save") {
    const book = findBook(state, payload.bookId);
    if (!book || user?.userRole !== 2) result = rejected("当前身份不能提交书评。");
    else {
      state.reviews.unshift({
        id: nextId(state),
        userId: user.id,
        userName: user.userName,
        bookId: book.id,
        bookName: book.name,
        rating: Number(payload.rating),
        content: payload.content,
        createTime: "2026-07-27 20:36:00",
        likeCount: 0,
        liked: false,
        reported: false,
        reportCount: 0,
        status: 0,
        replies: [],
      });
      writeState(state);
      result = ok(null, "书评已保存在当前演示会话。");
    }
  } else Iif (path.startsWith("/bookReview/like/")) {
    const review = state.reviews.find(
      (item) => item.id === Number(path.split("/").pop())
    );
    if (!review) result = rejected("未找到书评。");
    else {
      review.liked = !review.liked;
      review.likeCount = Math.max(
        0,
        review.likeCount + (review.liked ? 1 : -1)
      );
      writeState(state);
      result = ok(review.liked, review.liked ? "已点赞。" : "已取消点赞。");
    }
  } else Iif (path.startsWith("/bookReview/reply/")) {
    const review = state.reviews.find(
      (item) => item.id === Number(path.split("/").pop())
    );
    if (!review || !user) result = rejected("未找到可回复的书评。");
    else {
      review.replies.push({
        id: nextId(state),
        userId: user.id,
        userName: user.userName,
        replyToUserName: review.userName,
        content: payload.content,
        createTime: "2026-07-27 20:37:00",
      });
      writeState(state);
      result = ok(null, "回复已保存。");
    }
  } else Iif (path.startsWith("/bookReview/report/")) {
    const review = state.reviews.find(
      (item) => item.id === Number(path.split("/").pop())
    );
    if (!review || !user) result = rejected("未找到可举报的书评。");
    else {
      review.reported = true;
      review.reportCount = Number(review.reportCount || 0) + 1;
      state.reviewReports.unshift({
        id: nextId(state),
        reviewId: review.id,
        bookName: review.bookName,
        reviewerName: review.userName,
        reporterName: user.userName,
        reason: payload.reason,
        status: 0,
        createTime: "2026-07-27 20:38:00",
      });
      writeState(state);
      result = ok(null, "举报已进入演示审核队列。");
    }
  } else Iif (path === "/bookReviewReport/query") {
    result = paginateResponse(state.reviewReports, payload);
  } else Iif (path.startsWith("/bookReviewReport/")) {
    const reportId = Number(path.split("/").pop());
    const report = state.reviewReports.find((item) => item.id === reportId);
    if (!report) result = rejected("未找到举报记录。");
    else {
      report.status = 1;
      writeState(state);
      result = ok(null, "举报审核状态已更新。");
    }
  } else Iif (path === "/notice/query") {
    result = paginateResponse(state.notices, payload);
  } else Iif (path === "/messageBoard/query") {
    result = paginateResponse(state.messageBoard, payload);
  } else Iif (path === "/messageBoard/save") {
    if (!user) result = body(401, null, "请先选择演示身份。");
    else {
      state.messageBoard.unshift({
        id: nextId(state),
        userId: user.id,
        userName: user.userName,
        content: payload.content,
        replyContent: "",
        createTime: "2026-07-27 20:39:00",
        attachmentUrl: "",
        attachmentName: "",
      });
      writeState(state);
      result = ok(null, "留言已保存在当前演示会话。");
    }
  } else Iif (path === "/user/query") {
    result = paginateResponse(state.users, payload);
  } else Iif (path === "/user/collaborationUsers") {
    const role = Number(params.get("role"));
    result = ok(clone(state.users.filter((item) => item.userRole === role)));
  } else if (path === "/procurement/query") {
    let orders = filterOrdersForIdentity(state.procurementOrders, identity);
    Iif (payload.bookName) {
      orders = orders.filter((order) =>
        order.bookName.includes(String(payload.bookName))
      );
    }
    Iif (payload.status !== null && payload.status !== undefined) {
      orders = orders.filter((order) => order.status === Number(payload.status));
    }
    result = paginateResponse(orders, payload);
  } else Iif (path === "/procurement/save") {
    const book = findBook(state, payload.bookId);
    if (!book || !identity || ![0, 1].includes(identity.role)) {
      result = rejected("当前身份不能创建采购单。");
    } else {
      const purchaser = state.users.find(
        (item) => item.id === Number(payload.purchaserId)
      );
      state.procurementOrders.unshift({
        id: nextId(state),
        bookId: book.id,
        bookName: book.name,
        requestCount: Number(payload.requestCount),
        status: 0,
        requesterId: identity.id,
        requesterName: identity.name,
        purchaserId: purchaser?.id || null,
        purchaserName: purchaser?.userName || "",
        logisticsId: null,
        logisticsName: "",
        logisticsStatus: 0,
        carrier: "",
        trackingNo: "",
        logisticsRemark: "",
        updateTime: "2026-07-27 20:40:00",
        unreadCount: 0,
        stockApplied: false,
      });
      writeState(state);
      result = ok(null, "采购单已创建。");
    }
  } else Iif (path.startsWith("/procurement/claim/")) {
    const order = state.procurementOrders.find(
      (item) => item.id === Number(path.split("/").pop())
    );
    if (!order || identity?.role !== 3 || order.purchaserId) {
      result = rejected("当前采购单不可认领。");
    } else {
      order.purchaserId = identity.id;
      order.purchaserName = identity.name;
      writeState(state);
      result = ok(null, "采购单认领成功。");
    }
  } else Iif (
    ["/procurement/assignPurchaser", "/procurement/assignLogistics"].includes(
      path
    )
  ) {
    const order = state.procurementOrders.find(
      (item) => item.id === Number(payload.orderId)
    );
    const assigned = state.users.find(
      (item) => item.id === Number(payload.userId)
    );
    if (!order || !assigned) result = rejected("采购单或人员不存在。");
    else {
      if (path.endsWith("assignPurchaser")) {
        order.purchaserId = assigned.id;
        order.purchaserName = assigned.userName;
      } else {
        order.logisticsId = assigned.id;
        order.logisticsName = assigned.userName;
        order.logisticsStatus = 0;
      }
      writeState(state);
      result = ok(null, "协作人员已更新。");
    }
  } else if (path === "/procurement/updateStatus") {
    result = updateProcurementStatus(state, payload, identity);
  } else if (path === "/procurement/updateLogistics") {
    result = updateLogistics(state, payload, identity);
  } else if (path === "/procurement/message/query") {
    const messages = state.procurementMessages
      .filter(
        (item) =>
          item.orderId === Number(payload.orderId) &&
          item.channelType === Number(payload.channelType) &&
          (!payload.beforeId || item.id < Number(payload.beforeId))
      )
      .sort((left, right) => right.id - left.id);
    result = paginateResponse(messages, payload);
  } else if (path === "/procurement/message/read") {
    const messageIds = new Set((payload.messageIds || []).map(Number));
    state.procurementMessages.forEach((message) => {
      if (
        messageIds.has(message.id) &&
        message.orderId === Number(payload.orderId) &&
        message.channelType === Number(payload.channelType) &&
        message.receiverId === identity?.id
      ) {
        message.readStatus = true;
      }
    });
    writeState(state);
    result = ok(null, "消息已读。");
  } else Iif (path === "/procurement/message/send") {
    if (!identity) result = body(401, null, "请先选择演示身份。");
    else {
      state.procurementMessages.push({
        id: nextId(state),
        orderId: Number(payload.orderId),
        channelType: Number(payload.channelType),
        senderId: identity.id,
        senderName: identity.name,
        receiverId: Number(payload.receiverId),
        content: payload.content,
        readStatus: false,
        createTime: "2026-07-27 20:43:00",
      });
      writeState(state);
      result = ok(null, "协作消息已发送。");
    }
  } else Iif (path === "/operationLog/query") {
    result = paginateResponse(state.operationLogs, payload);
  } else if (path === "/adminWorkflow/auditStatus") {
    result = ok({
      pendingReviewReports: state.reviewReports.filter((item) => item.status === 0).length,
      activeProcurements: state.procurementOrders.filter((item) => item.status < 6).length,
      unreadMessages: state.procurementOrders.reduce((sum, item) => sum + Number(item.unreadCount || 0), 0),
    });
  } else if (path === "/adminWorkflow/backendFlow") {
    result = ok([
      { name: "认证与权限", status: "NORMAL", detail: "JWT 与角色边界" },
      { name: "借阅与库存", status: "NORMAL", detail: "会话内一致性" },
      { name: "采购与物流", status: "NORMAL", detail: "幂等入库演示" },
    ]);
  } else {
    const stats = statistics(path, state);
    if (stats) {
      result = stats;
    } else Iif (path === "/file/query") {
      result = ok([], "在线演示不保存真实文件。", 0);
    } else if (
      path.startsWith("/file/") ||
      path.includes("/export") ||
      config.responseType === "blob"
    ) {
      result = rejected("在线演示不上传、下载或导出真实文件。");
    } else Iif (
      method === "get" ||
      path.endsWith("/query") ||
      path.endsWith("/queryAll")
    ) {
      result = ok([], "当前页面没有更多演示数据。", 0);
    } else {
      result = rejected("此写操作未纳入浏览器演示,不会伪造成功结果。");
    }
  }
 
  return response(config, result);
}
 
export function resetDemoStateForTest() {
  try {
    sessionStorage.removeItem(DEMO_STATE_KEY);
  } catch {
    // No-op in storage-restricted test environments.
  }
}