official-site-job-tab-mock.ts 18.8 KB
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
import { getAgentTagSource } from './agent-tag-mock';
import { getPositionDerivedInfo, getPositionsWithChannelCode, getChannelCodeSource } from './channel-code-mock';

export interface OfficialSiteJobTabMockItem extends Record<string, unknown> {
  tab_id: number;
  position_tag_id: number;
  position_code: string;
  position_name: string;
  qrcode_id: number;
  qrcode_name: string;
  channel_code: string;
  employee_name: string;
  employee_role_text: string;
  tab_order: number;
  display_status: 'enable' | 'disable';
  main_title: string;
  sub_title: string;
  agent_count: number;
  created_at: string;
  updated_at: string;
  operations: ('edit' | 'enable' | 'disable' | 'delete' | 'configureAgent')[];
}

export interface PositionTagCandidate {
  tag_id: number;
  name: string;
  code: string;
  has_channel_code: boolean;
  qrcode_id?: number;
  qrcode_name?: string;
}

export interface PositionQRCodeDerivedInfo {
  channel_code: string;
  employee_name: string;
  employee_role_text: string;
}

export interface OfficialSiteJobTabListPageQuery {
  keyword?: string;
  displayStatus?: 'enable' | 'disable' | '';
  page: number;
  pageSize: number;
  source?: OfficialSiteJobTabMockItem[];
}

export interface OfficialSiteJobTabListPageResult {
  items: OfficialSiteJobTabMockItem[];
  page: number;
  pageSize: number;
  total: number;
}

export interface SaveOfficialSiteJobTabPayload {
  tabId?: number;
  position_code?: string;
  qrcode_id?: number;
  tab_order: number;
  display_status: 'enable' | 'disable';
  main_title?: string;
  sub_title?: string;
}

export interface SaveOfficialSiteJobTabResult {
  tab_id: number;
  position_code: string;
  position_name: string;
  qrcode_id: number;
  qrcode_name: string;
  channel_code: string;
  employee_name: string;
  employee_role_text: string;
  tab_order: number;
  display_status: 'enable' | 'disable';
  main_title: string;
  sub_title: string;
  agent_count: number;
  created_at: string;
  updated_at: string;
  operations: ('edit' | 'enable' | 'disable' | 'delete' | 'configureAgent')[];
  blocked?: boolean;
  message?: string;
}

export interface UpdateOfficialSiteJobTabStatusResult {
  tab_id: number;
  display_status: 'enable' | 'disable';
  updated_at: string;
  blocked?: boolean;
  message?: string;
}

export interface DeleteOfficialSiteJobTabResult {
  tab_id: number;
  success: boolean;
  message: string;
}

export interface OfficialSiteJobTabMockFixture {
  items: OfficialSiteJobTabMockItem[];
  loadError?: boolean;
  saveError?: boolean;
  statusBlockError?: boolean;
  positionDuplicate?: boolean;
  positionNoQRCode?: boolean;
}

const savedStorageKey = 'agent-admin-saved-official-site-job-tabs';
const deletedStorageKey = 'agent-admin-deleted-official-site-job-tabs';
const statusStorageKey = 'agent-admin-official-site-job-tab-status';

const now = () => new Date().toISOString().replace('T', ' ').slice(0, 19);

const baseOfficialSiteJobTabs: OfficialSiteJobTabMockItem[] = [
  {
    tab_id: 1,
    position_tag_id: 1,
    position_code: 'store_sales',
    position_name: '店销顾问',
    qrcode_id: 1,
    qrcode_name: '店销顾问渠道活码',
    channel_code: 'DSC-QR-001',
    employee_name: '张小萌',
    employee_role_text: '店销主管',
    tab_order: 10,
    display_status: 'enable',
    main_title: 'AI 智能助手提升店销效率',
    sub_title: '通过 AI 智能问答、客户画像分析和销售话术推荐,帮助店销顾问快速响应客户需求,提升销售转化率。',
    agent_count: 3,
    created_at: '2026-05-10 09:00:00',
    updated_at: '2026-05-15 10:30:00',
    operations: ['edit', 'disable', 'delete', 'configureAgent'],
  },
  {
    tab_id: 2,
    position_tag_id: 2,
    position_code: 'after_sales_service',
    position_name: '售后客服',
    qrcode_id: 2,
    qrcode_name: '售后客服渠道活码',
    channel_code: 'ASC-QR-002',
    employee_name: '李小燕',
    employee_role_text: '客服专员',
    tab_order: 20,
    display_status: 'enable',
    main_title: 'AI 客服机器人赋能售后服务',
    sub_title: 'AI 客服机器人自动解答常见问题,智能分流复杂工单,缩短客户等待时间,提升服务满意度。',
    agent_count: 2,
    created_at: '2026-05-11 10:15:00',
    updated_at: '2026-05-16 11:45:00',
    operations: ['edit', 'disable', 'delete', 'configureAgent'],
  },
  {
    tab_id: 3,
    position_tag_id: 5,
    position_code: 'crm_growth',
    position_name: '私域增长',
    qrcode_id: 5,
    qrcode_name: '私域增长渠道活码',
    channel_code: 'CRM-QR-005',
    employee_name: '陈欣欣',
    employee_role_text: '私域运营主管',
    tab_order: 30,
    display_status: 'disable',
    main_title: 'AI 助力私域精细化运营',
    sub_title: 'AI 自动分析客户行为数据,智能推荐运营策略,帮助私域运营人员实现精准触达和高效转化。',
    agent_count: 0,
    created_at: '2026-05-12 11:30:00',
    updated_at: '2026-05-17 14:20:00',
    operations: ['edit', 'enable', 'delete', 'configureAgent'],
  },
  {
    tab_id: 4,
    position_tag_id: 6,
    position_code: 'training_teacher',
    position_name: '培训讲师',
    qrcode_id: 6,
    qrcode_name: '培训讲师渠道活码',
    channel_code: 'TT-QR-006',
    employee_name: '周小明',
    employee_role_text: '培训专员',
    tab_order: 40,
    display_status: 'disable',
    main_title: '',
    sub_title: '',
    agent_count: 0,
    created_at: '2026-05-13 12:00:00',
    updated_at: '2026-05-18 15:00:00',
    operations: ['edit', 'enable', 'delete', 'configureAgent'],
  },
  {
    tab_id: 5,
    position_tag_id: 7,
    position_code: 'online_consultant',
    position_name: '在线顾问',
    qrcode_id: 7,
    qrcode_name: '在线顾问渠道活码',
    channel_code: 'OC-QR-007',
    employee_name: '吴小花',
    employee_role_text: '在线顾问专员',
    tab_order: 50,
    display_status: 'disable',
    main_title: '这是一段超过三十个字的岗位标题测试用例用于验证前端校验逻辑正确',
    sub_title: '',
    agent_count: 0,
    created_at: '2026-05-14 13:00:00',
    updated_at: '2026-05-19 16:00:00',
    operations: ['edit', 'enable', 'delete', 'configureAgent'],
  },
  {
    tab_id: 6,
    position_tag_id: 8,
    position_code: 'technical_support',
    position_name: '技术支持',
    qrcode_id: 8,
    qrcode_name: '技术支持渠道活码',
    channel_code: 'TS-QR-008',
    employee_name: '赵小刚',
    employee_role_text: '技术支持工程师',
    tab_order: 60,
    display_status: 'disable',
    main_title: 'AI 技术助手',
    sub_title: '这是一段超过二百个字的岗位说明测试用例用于验证前端校验逻辑,通过模拟超长文本输入来测试表单校验机制是否能够正确拦截并提示用户,确保数据完整性,防止用户输入过长的内容导致界面显示问题或后端存储异常,同时也能够帮助开发者更好地理解用户体验设计中的边界条件处理方式,从而提升整体产品质量和用户满意度,让系统更加稳定可靠运行,最终实现业务目标达成和客户价值创造,为企业数字化转型提供强有力的技术支撑和服务保障。',
    agent_count: 0,
    created_at: '2026-05-15 14:00:00',
    updated_at: '2026-05-20 17:00:00',
    operations: ['edit', 'enable', 'delete', 'configureAgent'],
  },
];

function canUseStorage() {
  return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}

function readStoredItems(): OfficialSiteJobTabMockItem[] {
  if (!canUseStorage()) return [];
  try {
    const raw = window.localStorage.getItem(savedStorageKey);
    return raw ? JSON.parse(raw) : [];
  } catch {
    return [];
  }
}

function readDeletedIds(): number[] {
  if (!canUseStorage()) return [];
  try {
    const raw = window.localStorage.getItem(deletedStorageKey);
    return raw ? JSON.parse(raw) : [];
  } catch {
    return [];
  }
}

function readStatusOverrides(): Record<number, 'enable' | 'disable'> {
  if (!canUseStorage()) return {};
  try {
    const raw = window.localStorage.getItem(statusStorageKey);
    return raw ? JSON.parse(raw) : {};
  } catch {
    return {};
  }
}

function writeStoredItems(items: OfficialSiteJobTabMockItem[]) {
  if (!canUseStorage()) return;
  window.localStorage.setItem(savedStorageKey, JSON.stringify(items));
}

function writeDeletedIds(ids: number[]) {
  if (!canUseStorage()) return;
  window.localStorage.setItem(deletedStorageKey, JSON.stringify(ids));
}

function writeStatusOverrides(overrides: Record<number, 'enable' | 'disable'>) {
  if (!canUseStorage()) return;
  window.localStorage.setItem(statusStorageKey, JSON.stringify(overrides));
}

export function resetOfficialSiteJobTabMockState() {
  if (!canUseStorage()) return;
  window.localStorage.removeItem(savedStorageKey);
  window.localStorage.removeItem(deletedStorageKey);
  window.localStorage.removeItem(statusStorageKey);
}

export function getOfficialSiteJobTabSource(): OfficialSiteJobTabMockItem[] {
  const deletedIds = new Set(readDeletedIds());
  const storedItems = readStoredItems();
  const storedById = new Map(storedItems.map((item) => [item.tab_id, item]));
  const statusOverrides = readStatusOverrides();

  const preservedBase = baseOfficialSiteJobTabs
    .filter((item) => !deletedIds.has(item.tab_id))
    .map((item) => {
      const stored = storedById.get(item.tab_id);
      if (stored) return stored;
      const overrideStatus = statusOverrides[item.tab_id];
      if (overrideStatus) {
        const operations: OfficialSiteJobTabMockItem['operations'] = overrideStatus === 'enable'
          ? ['edit', 'disable', 'delete', 'configureAgent']
          : ['edit', 'enable', 'delete', 'configureAgent'];
        return { ...item, display_status: overrideStatus, operations };
      }
      return item;
    });

  const createdItems = storedItems
    .filter((item) => !baseOfficialSiteJobTabs.some((base) => base.tab_id === item.tab_id))
    .filter((item) => !deletedIds.has(item.tab_id));

  return [...preservedBase, ...createdItems].sort((a, b) => a.tab_id - b.tab_id);
}

export const officialSiteJobTabMockFixtures: Record<string, OfficialSiteJobTabMockFixture> = {
  normal: { items: baseOfficialSiteJobTabs },
  empty: { items: [] },
  filteredEmpty: { items: [] },
  loadError: { items: [], loadError: true },
  saveError: { items: baseOfficialSiteJobTabs, saveError: true },
  statusBlockError: { items: baseOfficialSiteJobTabs, statusBlockError: true },
  positionDuplicate: { items: baseOfficialSiteJobTabs, positionDuplicate: true },
  positionNoQRCode: { items: baseOfficialSiteJobTabs, positionNoQRCode: true },
};

export function getOfficialSiteJobTabRecord(tabId?: string, source = getOfficialSiteJobTabSource()): OfficialSiteJobTabMockItem | undefined {
  if (!tabId) return undefined;
  return source.find((item) => String(item.tab_id) === tabId);
}

export function getPositionTagCandidates(): PositionTagCandidate[] {
  const agentTags = getAgentTagSource();
  const positionsWithCodes = getPositionsWithChannelCode();
  const channelCodes = getChannelCodeSource();
  const existingTabPositions = getOfficialSiteJobTabSource().map((tab) => tab.position_code);

  return agentTags.map((tag) => {
    const hasChannelCode = positionsWithCodes.includes(tag.code);
    const channelCode = channelCodes.find((code) => code.position_code === tag.code);

    return {
      tag_id: tag.tag_id,
      name: tag.name,
      code: tag.code,
      has_channel_code: hasChannelCode,
      qrcode_id: channelCode?.code_id,
      qrcode_name: channelCode?.code_name,
    };
  });
}

export function getPositionQRCodeDerivedInfo(positionCode: string): PositionQRCodeDerivedInfo | undefined {
  const derivedInfo = getPositionDerivedInfo(positionCode);
  if (!derivedInfo) return undefined;

  return {
    channel_code: derivedInfo.channel_code,
    employee_name: derivedInfo.employee_name,
    employee_role_text: derivedInfo.employee_role_text,
  };
}

export function isPositionDuplicate(positionCode: string, currentTabId?: number): boolean {
  const source = getOfficialSiteJobTabSource();
  return source.some((tab) => tab.position_code === positionCode && tab.tab_id !== currentTabId);
}

export function getOfficialSiteJobTabListPage({
  keyword = '',
  displayStatus = '',
  page,
  pageSize,
  source = getOfficialSiteJobTabSource(),
}: OfficialSiteJobTabListPageQuery): OfficialSiteJobTabListPageResult {
  const normalizedKeyword = keyword.trim().toLowerCase();
  const filtered = source.filter((item) => {
    if (normalizedKeyword) {
      const matchPosition = item.position_name.toLowerCase().includes(normalizedKeyword);
      const matchQRCode = item.qrcode_name.toLowerCase().includes(normalizedKeyword);
      if (!matchPosition && !matchQRCode) return false;
    }
    if (displayStatus && item.display_status !== displayStatus) return false;
    return true;
  });

  const start = (page - 1) * pageSize;
  return {
    items: filtered.slice(start, start + pageSize),
    page,
    pageSize,
    total: filtered.length,
  };
}

export function saveOfficialSiteJobTabRecord(payload: SaveOfficialSiteJobTabPayload, scenario = 'normal'): SaveOfficialSiteJobTabResult {
  const source = getOfficialSiteJobTabSource();
  const current = payload.tabId ? source.find((item) => item.tab_id === payload.tabId) : undefined;

  // Handle save error fixture
  if (scenario === 'saveError' && !payload.tabId) {
    return {
      tab_id: 0,
      position_code: payload.position_code ?? '',
      position_name: '',
      qrcode_id: 0,
      qrcode_name: '',
      channel_code: '',
      employee_name: '',
      employee_role_text: '',
      tab_order: payload.tab_order,
      display_status: payload.display_status,
      main_title: payload.main_title ?? '',
      sub_title: payload.sub_title ?? '',
      agent_count: 0,
      created_at: now(),
      updated_at: now(),
      operations: [],
      blocked: true,
      message: '保存失败,请重试',
    };
  }

  // Create mode validations
  if (!payload.tabId) {
    // Check for duplicate position
    if (isPositionDuplicate(payload.position_code ?? '')) {
      return {
        tab_id: 0,
        position_code: payload.position_code ?? '',
        position_name: '',
        qrcode_id: 0,
        qrcode_name: '',
        channel_code: '',
        employee_name: '',
        employee_role_text: '',
        tab_order: payload.tab_order,
        display_status: payload.display_status,
        main_title: payload.main_title ?? '',
        sub_title: payload.sub_title ?? '',
        agent_count: 0,
        created_at: now(),
        updated_at: now(),
        operations: [],
        blocked: true,
        message: '该岗位已存在官网岗位展示,请编辑原配置',
      };
    }

    // Check for position without channel code
    const derivedInfo = getPositionQRCodeDerivedInfo(payload.position_code ?? '');
    if (!derivedInfo) {
      return {
        tab_id: 0,
        position_code: payload.position_code ?? '',
        position_name: '',
        qrcode_id: 0,
        qrcode_name: '',
        channel_code: '',
        employee_name: '',
        employee_role_text: '',
        tab_order: payload.tab_order,
        display_status: payload.display_status,
        main_title: payload.main_title ?? '',
        sub_title: payload.sub_title ?? '',
        agent_count: 0,
        created_at: now(),
        updated_at: now(),
        operations: [],
        blocked: true,
        message: '该岗位暂未配置渠道活码',
      };
    }
  }

  const nextId = current?.tab_id ?? Math.max(0, ...source.map((item) => item.tab_id)) + 1;
  const agentTag = getAgentTagSource().find((tag) => tag.code === (current?.position_code ?? payload.position_code));
  const channelCode = getChannelCodeSource().find((code) => code.code_id === (current?.qrcode_id ?? payload.qrcode_id));
  const derivedInfo = payload.position_code ? getPositionQRCodeDerivedInfo(payload.position_code) : undefined;

  const operations: OfficialSiteJobTabMockItem['operations'] = payload.display_status === 'enable'
    ? ['edit', 'disable', 'delete', 'configureAgent']
    : ['edit', 'enable', 'delete', 'configureAgent'];

  const nextRecord: SaveOfficialSiteJobTabResult = {
    tab_id: nextId,
    position_code: current?.position_code ?? payload.position_code ?? '',
    position_name: current?.position_name ?? agentTag?.name ?? '',
    qrcode_id: current?.qrcode_id ?? payload.qrcode_id ?? 0,
    qrcode_name: current?.qrcode_name ?? channelCode?.code_name ?? '',
    channel_code: current?.channel_code ?? derivedInfo?.channel_code ?? '',
    employee_name: current?.employee_name ?? derivedInfo?.employee_name ?? '',
    employee_role_text: current?.employee_role_text ?? derivedInfo?.employee_role_text ?? '',
    tab_order: payload.tab_order,
    display_status: payload.display_status,
    main_title: payload.main_title ?? current?.main_title ?? '',
    sub_title: payload.sub_title ?? current?.sub_title ?? '',
    agent_count: current?.agent_count ?? 0,
    created_at: current?.created_at ?? now(),
    updated_at: now(),
    operations,
  };

  const storedItems = readStoredItems();
  writeStoredItems([...storedItems.filter((item) => item.tab_id !== nextRecord.tab_id), nextRecord as OfficialSiteJobTabMockItem]);
  writeDeletedIds(readDeletedIds().filter((id) => id !== nextRecord.tab_id));

  return nextRecord;
}

export function updateOfficialSiteJobTabStatus(
  tabId: number,
  targetStatus: 'enable' | 'disable',
  scenario: 'normal' | 'statusBlockError' = 'normal',
): UpdateOfficialSiteJobTabStatusResult {
  const source = getOfficialSiteJobTabSource();
  const current = source.find((item) => item.tab_id === tabId);

  if (!current) {
    return {
      tab_id: tabId,
      display_status: targetStatus,
      updated_at: now(),
    };
  }

  // Business blocking: cannot disable if tab has agents configured
  if (scenario === 'statusBlockError' && targetStatus === 'disable' && current.display_status === 'enable') {
    return {
      tab_id: tabId,
      display_status: 'enable',
      updated_at: current.updated_at,
      blocked: true,
      message: '该岗位展示配置下存在 Agent 配置,请先移除后再下架',
    };
  }

  const newTime = now();
  const overrides = readStatusOverrides();
  overrides[tabId] = targetStatus;
  writeStatusOverrides(overrides);

  return {
    tab_id: tabId,
    display_status: targetStatus,
    updated_at: newTime,
  };
}

export function deleteOfficialSiteJobTabRecord(tabId: number): DeleteOfficialSiteJobTabResult {
  const current = getOfficialSiteJobTabRecord(String(tabId));

  if (!current) {
    return {
      tab_id: tabId,
      success: false,
      message: '岗位展示配置不存在',
    };
  }

  writeDeletedIds([...new Set([...readDeletedIds(), tabId])]);
  writeStoredItems(readStoredItems().filter((item) => item.tab_id !== tabId));

  return {
    tab_id: tabId,
    success: true,
    message: '已清理该岗位展示配置下的 Agent 展示配置,不影响 Agent 原始数据或渠道活码信息',
  };
}