model.ts 12.8 KB
/**
 * 创建商户二级页的数据模型。
 *
 * 事实来源:temp/account/html/merchant/add.html
 *   - merchantForm 初始对象 L645-664
 *   - 提交参数组装 L880-1045(fieldToFormNameList / checkClassNameList / merchantBrandListJson)
 *   - 权限树组装 L2186-2253(getAuthList)
 * 字段名、取值口径、提示文案逐字保留;这里不引入源系统没有的字段。
 */

export interface BrandNode {
  id?: string | number;
  label?: string;
  children?: BrandNode[];
  [key: string]: unknown;
}

export interface PermNode {
  id?: string | number;
  label?: string;
  logo?: string;
  parentId?: string | number;
  superParentId?: string | number;
  children?: PermNode[];
  [key: string]: unknown;
}

export interface ProductPerm {
  productId: string | number;
  productName?: string;
  treeData?: PermNode[];
  children?: PermNode[];
  merchantProTreeResponses?: PermNode[];
  [key: string]: unknown;
}

export interface AccountPerm {
  accounttypeId: string | number;
  accounttypeName?: string;
  products?: ProductPerm[];
  [key: string]: unknown;
}

export interface MerchantFile {
  fileUrl: string;
  fileName: string;
}

/** 表单值:只列源页面真实提交或真实参与联动的字段。 */
export interface CreateFormValues {
  channelId?: string | number;
  merchantModel?: string | number;
  merchantName?: string;
  merchantAbbreviation?: string;
  merchantLegalPerson?: string;
  merchantLegalPersonPhone?: string;
  isloginName?: number;
  mesVerifyFlag?: number;
  sapCode?: string;
  merchantAddress?: string;
  lat?: string;
  lng?: string;
  provinceName?: string;
  provinceCode?: string;
  cityName?: string;
  cityCode?: string;
  residentContact?: string;
  residentPhone?: string;
  bussinessBegintime?: string;
  bussinessEndtime?: string;
  businessType?: Array<string | number>;
  merchantBrandChecked?: Array<string | number>;
  merchantFiles?: MerchantFile[];
  merchantLoginAccount?: string;
  merchantLoginPassword?: string;
  merchantAccountLevel?: string | number;
  accounttypeId?: Array<string | number>;
  /** edit/sub 门店草稿的有效期区间(源 effectiveShowEl)。 */
  effectiveStarttime?: string;
  expireDate?: string;
  /** 源页面已注释的字段(merchantType / merchantOrgcode / effectiveTime)不进表单。 */
  [key: string]: unknown;
}

/** 源 js/validator.js:2 PHONEREG;lay-verify="phone" 的同一口径。 */
export const PHONE_REGEX = /^(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9]|14[0-9])[0-9]{8}$/;
/** 源 js/validator.js:7 PHONETWO;驻店电话可手机可固话。 */
export const RESIDENT_PHONE_REGEX = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/;
/** 源 add.html:829 密码规则(未在 validator.js,直接写在页面里)。 */
export const PASSWORD_REGEX = /^(?=.*\d)(?=.*[a-zA-Z])[\s\S]{6,20}$/;

export function asArray<T>(value: unknown): T[] {
  return Array.isArray(value) ? (value as T[]) : [];
}

export function nodeList(product: ProductPerm): PermNode[] {
  return asArray<PermNode>(
    product.merchantProTreeResponses ?? product.treeData ?? product.children,
  );
}

/** 源 add.html:994-1019:勾选的叶子按父节点(cars)归组,生成 merchantBrandListJson。 */
export function buildBrandList(
  tree: BrandNode[],
  checked: Array<string | number> | undefined,
): Array<{ cars: string | number; merchantBrandId: Array<string | number> }> {
  const keys = new Set((checked ?? []).map(String));
  const result: Array<{ cars: string | number; merchantBrandId: Array<string | number> }> = [];
  tree.forEach((car) => {
    if (!car.children?.length || car.id === undefined || car.id === null) return;
    const merchantBrandId = car.children
      .filter((child) => child.id !== undefined && child.id !== null && keys.has(String(child.id)))
      .map((child) => child.id as string | number);
    if (merchantBrandId.length) result.push({ cars: car.id, merchantBrandId });
  });
  return result;
}

/** 源 add.html:880-1045 的 saveMerchant 参数;createdSource 由 nextStepRequest L1070 再补。
 *  edit/sub 复用同一组装(edit.html L1216-1388 与 add 逐字同构,仅差 id/parentId/status/effectiveTime)。 */
export function buildCreatePayload(
  values: CreateFormValues,
  brandTree: BrandNode[],
  opts: {
    /** edit.html L1369-1374:更新时带 id;子商户带 parentId。 */
    id?: string | number;
    parentId?: string | number;
    /** edit.html L1384-1388:status 沿用商户当前状态,缺省 1(草稿)。 */
    status?: string | number;
    /** edit.html L1271-1273:merchantId 存在时 effectiveTime 原样回传。 */
    effectiveTime?: unknown;
  } = {},
): Record<string, unknown> {
  const params: Record<string, unknown> = {
    isloginName: values.isloginName === 1 ? 1 : 0,
    mesVerifyFlag: values.mesVerifyFlag === 1 ? 1 : 0,
  };

  params['bussinessBegintime'] = values['bussinessBegintime'] || '';
  params['bussinessEndtime'] = values['bussinessEndtime'] || '';
  if (values.lat) {
    params.lat = values.lat;
    params.lng = values.lng;
    params.merchantAddress = values.merchantAddress;
  }
  if (values.provinceName) {
    params.provinceName = values.provinceName;
    params.provinceCode = values.provinceCode;
    params.cityName = values.cityName;
    params.cityCode = values.cityCode;
  }

  // fieldToFormNameList L890-904:注释掉的字段仍以空串入参,保持老协议形状。
  const fieldToFormNameList = [
    'merchantName',
    'merchantAbbreviation',
    'merchantType',
    'merchantOrgcode',
    'merchantLegalPerson',
    'merchantLegalPersonPhone',
    'residentContact',
    'residentPhone',
    'merchantLoginAccount',
    'merchantLoginPassword',
    'merchantAccountLevel',
    'effectiveTime',
    'merchantModel',
  ] as const;
  fieldToFormNameList.forEach((name) => {
    params[name] = values[name] || '';
  });

  params.channelId = values.channelId;
  if (String(values.channelId) === '2') params.sapCode = values.sapCode;

  // checkClassNameList L950-974:多选取勾选值,逗号拼接;空数组回空串。
  params.businessType = (values.businessType ?? []).join(',');
  params.accounttypeId = (values.accounttypeId ?? []).join(',');

  if (values.merchantBrandChecked?.length) {
    params.merchantBrandListJson = JSON.stringify(
      buildBrandList(brandTree, values.merchantBrandChecked),
    );
  }
  if (values.merchantFiles?.length) {
    params.merchantFiles = JSON.stringify(values.merchantFiles);
  }

  // edit.html L1269-1273:门店草稿的有效期日期与原有 effectiveTime。
  if (values.effectiveStarttime) params.effectiveStarttime = values.effectiveStarttime;
  if (values.expireDate) params.expireDate = values.expireDate;
  if (opts.id !== undefined && opts.id !== null) params.id = opts.id;
  if (opts.parentId !== undefined && opts.parentId !== null) params.parentId = opts.parentId;
  if (opts.effectiveTime !== undefined) params.effectiveTime = opts.effectiveTime;

  // L1029-1041:editLevel == 1 → saveMerchant;保存状态 1.草稿 / 2.发布。
  params.method = 'merchants.api.merchant.saveMerchant';
  params.status = opts.status ?? 1;
  return params;
}

/**
 * 详情 → 表单值(edit.html getMerchantInfo L1942-2052 + getCarBrandTree L2112-2117
 * + recoveryFile L2233-2249 的回显口径)。
 */
export function detailToFormValues(detail: Record<string, unknown>): CreateFormValues {
  const splitIds = (value: unknown): Array<string | number> =>
    String(value ?? '')
      .split(',')
      .filter(Boolean);
  // 源 merchantBrandMain 是分号分隔串且尾项为空(checkedList.pop())。
  const brandIds = String(detail.merchantBrandMain ?? '')
    .replaceAll(';', ',')
    .split(',')
    .filter(Boolean)
    .map((item) => parseInt(item, 10))
    .filter((item) => !Number.isNaN(item));
  return {
    channelId: detail.channelId as string | number | undefined,
    merchantModel: detail.merchantModel as string | number | undefined,
    merchantName: detail.merchantName as string | undefined,
    merchantAbbreviation: detail.merchantAbbreviation as string | undefined,
    merchantLegalPerson: detail.merchantLegalPerson as string | undefined,
    merchantLegalPersonPhone: detail.merchantLegalPersonPhone as string | undefined,
    isloginName: Number(detail.isloginName ?? 0),
    mesVerifyFlag: Number(detail.mesVerifyFlag ?? 0),
    sapCode: detail.sapCode as string | undefined,
    merchantAddress: detail.merchantAddress as string | undefined,
    lat: detail.lat as string | undefined,
    lng: detail.lng as string | undefined,
    provinceName: detail.provinceName as string | undefined,
    provinceCode: detail.provinceCode as string | undefined,
    cityName: detail.cityName as string | undefined,
    cityCode: detail.cityCode as string | undefined,
    residentContact: detail.residentContact as string | undefined,
    residentPhone: detail.residentPhone as string | undefined,
    bussinessBegintime: detail.bussinessBegintime as string | undefined,
    bussinessEndtime: detail.bussinessEndtime as string | undefined,
    businessType: splitIds(detail.businessType),
    merchantBrandChecked: brandIds,
    merchantFiles: asArray<{ fileUrl?: string; fileName?: string }>(
      detail.merchantFileResponses,
    ).map((item) => ({ fileUrl: item.fileUrl ?? '', fileName: item.fileName ?? '' })),
    merchantLoginAccount: detail.merchantLoginAccount as string | undefined,
    merchantLoginPassword: (detail.merchantLoginPassword as string | undefined) ?? '',
    merchantAccountLevel: detail.merchantAccountLevel as string | number | undefined,
    accounttypeId: splitIds(detail.accountType),
  };
}

/**
 * 源 add.html:2186-2253 getAuthList 的逐字口径。
 * treeData 的 key 是账户类型,value 里只放「用户勾选了产品」的产品。
 */
export function buildPermissionRequestList(
  accounts: AccountPerm[],
  productChecked: Record<string, Array<string | number>>,
  nodeChecked: Record<string, Array<string | number>>,
  nodeIndex: Map<string, PermNode>,
): Array<Record<string, unknown>> {
  const result: Array<Record<string, unknown>> = [];
  accounts.forEach((account) => {
    const accountId = String(account.accounttypeId);
    const selectedProducts = productChecked[accountId] ?? [];
    if (!selectedProducts.length) return;
    const products = (account.products ?? [])
      .filter((product) => selectedProducts.some((id) => String(id) === String(product.productId)))
      .map((product) => {
        const key = `${accountId}:${String(product.productId)}`;
        const checked = nodeChecked[key] ?? [];
        if (!nodeList(product).length) {
          return { productId: product.productId, functionIdList: [], menuIdList: [] };
        }
        const functionIds: Array<Record<string, unknown>> = [];
        const menuIds: Array<string | number> = [];
        checked.forEach((id) => {
          const node = nodeIndex.get(`${key}:${String(id)}`);
          if (!node) return;
          // 源 getCheckedNodes(true) 只取叶子节点;antd 的 checkedKeys 另含父节点。
          if (node.children?.length) return;
          if (node.logo === 'functionValue') {
            const value = `${String(id)}:${node.label ?? ''}`;
            const hit = functionIds.find(
              (item) => String(item.functionId) === String(node.parentId),
            );
            if (hit) hit.functionValue = `${String(hit.functionValue)};${value}`;
            else {
              functionIds.push({
                functionId: node.parentId,
                mendId: node.superParentId,
                functionValue: value,
              });
            }
          } else if (node.logo === 'function') {
            functionIds.push({ functionId: node.parentId, mendId: node.superParentId });
          } else if (node.logo !== 'neglect') {
            menuIds.push(id);
          }
        });
        return { productId: product.productId, functionIds, menuIds };
      });
    result.push({ accountTypeId: account.accounttypeId, products });
  });
  return result;
}

/** 源 L2058-2060:勾选产品后创建权限树,默认全选所有节点。 */
export function collectNodeIndex(accounts: AccountPerm[]): {
  nodeIndex: Map<string, PermNode>;
  allChecked: Record<string, Array<string | number>>;
} {
  const nodeIndex = new Map<string, PermNode>();
  const allChecked: Record<string, Array<string | number>> = {};
  accounts.forEach((account) => {
    const aid = String(account.accounttypeId);
    (account.products ?? []).forEach((product) => {
      const key = `${aid}:${String(product.productId)}`;
      const ids: Array<string | number> = [];
      const walk = (nodes: PermNode[]) =>
        nodes.forEach((node) => {
          if (node.id !== undefined && node.id !== null) {
            ids.push(node.id);
            nodeIndex.set(`${key}:${String(node.id)}`, node);
          }
          walk(node.children ?? []);
        });
      walk(nodeList(product));
      allChecked[key] = ids;
    });
  });
  return { nodeIndex, allChecked };
}