preflight.mjs 9.17 KB
export const PREFLIGHT_METHODS = {
  employees: 'dj.api.smartcarlife.employee.getByMerchantId',
  scenes: 'dj.api.smartcarlife.scene.config.getUserScene',
  merchantCoupons: 'dj.api.smartCarLife.merchant.coupon.list',
  subShops: 'dj.api.smartcarlife.diversionMerchant.getDiversionMerchantRef',
  goods: 'dj.api.smartcarlife.selectOrderGoods.list',
  technicians: 'dj.api.smartcarlife.roleTechnician.list.effective',
  serviceItems: 'dj.api.carboutique.construction.item.group.list',
  filmRolls: 'dj.api.smarcarlife.stock.filmroll.list'
}

const isSuccess = response => response?.code === 0 || response?.code === '0'

const listFrom = value => {
  if (Array.isArray(value)) return value
  if (!value || typeof value !== 'object') return []
  for (const key of ['list', 'records', 'rows', 'dataList', 'pageData']) {
    if (Array.isArray(value[key])) return value[key]
  }
  return []
}

const normalizeStaff = staff => {
  if (!staff) return null
  const id = staff.userId ?? staff.bussinessId ?? staff.id
  if (id === undefined || id === null || id === '') return null
  return {
    id,
    uuid: staff.uuid,
    name: staff.name ?? staff.employeeName ?? staff.staffName,
    merchantId: staff.merchantId
  }
}

const normalizeTechnician = technician => {
  if (!technician) return null
  const id = technician.userId ?? technician.technicianId ?? technician.id
  if (id === undefined || id === null || id === '') return null
  return {
    id,
    uuid:
      technician.uuid ??
      technician.technicianUuid ??
      technician.staffUuid ??
      technician.userId,
    name:
      technician.name ??
      technician.technicianName ??
      technician.employeeName ??
      technician.staffName,
    staffPhone: technician.staffPhone ?? technician.phone
  }
}

const normalizeServiceItem = groups => {
  for (const group of listFrom(groups)) {
    for (const item of listFrom(group.serviceItemList ?? group.detailList)) {
      if (item?.id !== undefined && item?.id !== null) {
        return {
          id: item.id,
          name:
            item.serviceItemsName ??
            item.serviceItemName ??
            item.itemName ??
            item.name,
          categoryId: item.categoryId,
          itemsConfigName: item.itemsConfigName,
          materialStandard: item.materialStandard,
          timeStandard: item.timeStandard,
          serviceCost: item.serviceCost,
          useNum: item.useNum ?? 1,
          categoryName: group.categoryName,
          groupName: group.itemName
        }
      }
    }
  }
  return null
}

const findImageUrl = value => {
  if (!value || typeof value !== 'object') return null
  for (const [key, item] of Object.entries(value)) {
    if (
      typeof item === 'string' &&
      /^https?:\/\//i.test(item) &&
      /image|picture|photo|url|logo|cover/i.test(key)
    ) {
      return item
    }
  }
  for (const item of Object.values(value)) {
    if (item && typeof item === 'object') {
      const found = findImageUrl(item)
      if (found) return found
    }
  }
  return null
}

const missingItem = (resource, method, neededField) => ({
  resource,
  method,
  neededField
})

export async function runPreflight(client, context, options = {}) {
  const diagnostics = []
  const missing = []

  const query = async (resource, method, payload) => {
    const response = await client.post(method, payload)
    if (!isSuccess(response)) {
      diagnostics.push({
        resource,
        method,
        ok: false,
        code: response?.code ?? 'missing'
      })
      return null
    }
    const data = response.data
    diagnostics.push({
      resource,
      method,
      ok: true,
      count: listFrom(data).length
    })
    return data
  }

  const common = { sessionId: context.sessionId }
  const employeeData = await query('employee', PREFLIGHT_METHODS.employees, {
    merchantId: context.store.id,
    sceneList: [context.sceneType],
    ...common
  })
  const employeeList = listFrom(employeeData)
  const selectedEmployee =
    employeeList.find(item => item.uuid && item.uuid === context.user?.uuid) ??
    employeeList[0]
  const employee = normalizeStaff(selectedEmployee)
  if (!employee) {
    missing.push(
      missingItem('employee', PREFLIGHT_METHODS.employees, 'sellerUserId/employee.id')
    )
  }

  const sceneList = listFrom(
    await query('baseScene', PREFLIGHT_METHODS.scenes, {
      phone: context.user?.phone,
      merchantId: context.store.id,
      sceneType: context.sceneType,
      ...common
    })
  )
  const activeScenes = sceneList
    .filter(item => item?.baseSceneCode && Number(item?.status ?? 1) === 1)
    .sort((left, right) =>
      String(left.baseSceneCode).localeCompare(String(right.baseSceneCode))
    )
  const baseScene = options.baseSceneCode
    ? activeScenes.find(item => item.baseSceneCode === options.baseSceneCode) ?? null
    : activeScenes[0] ?? null
  if (!baseScene) {
    missing.push(
      missingItem('baseScene', PREFLIGHT_METHODS.scenes, 'baseSceneCode')
    )
  }

  const couponList = listFrom(
    await query('merchantCoupon', PREFLIGHT_METHODS.merchantCoupons, {
      merchantId: context.store.id,
      yqMerchantId: context.park.id,
      orderByType: 9,
      ...common
    })
  ).filter(
    item =>
      item?.id !== undefined &&
      item?.merchantId !== undefined &&
      item?.merchantCouponCode
  )
  const merchantCoupon =
    couponList.find(item => Number(item?.couponInfo?.couponType) === 1) ??
    couponList[0] ??
    null
  if (!merchantCoupon) {
    missing.push(
      missingItem(
        'merchantCoupon',
        PREFLIGHT_METHODS.merchantCoupons,
        'merchantCouponId/customerCouponCode'
      )
    )
  }

  const subShopList = listFrom(
    await query('subShop', PREFLIGHT_METHODS.subShops, {
      merchantId: merchantCoupon?.merchantId ?? context.store.id,
      ...common
    })
  )
  const subShopMatches = subShopList.filter(
    item => String(item?.subMerchantName ?? '').trim() === context.store.name
  )
  const subShop = subShopMatches.length === 1 ? subShopMatches[0] : null
  if (!subShop?.subMerchantId) {
    missing.push(
      missingItem(
        'subShop',
        PREFLIGHT_METHODS.subShops,
        `one exact subMerchantName=${context.store.name}`
      )
    )
  }

  const catalog = listFrom(
    await query('goodsCatalog', PREFLIGHT_METHODS.goods, {
      merchantId: context.store.id,
      sceneType: context.sceneType,
      baseSceneCode: baseScene?.baseSceneCode ?? options.baseSceneCode ?? '',
      ...common
    })
  )
  const ordinaryGoods = catalog.filter(item => {
    const goods = item?.goods
    const price = goods?.sellPrice ?? goods?.upgradePrice
    return (
      Number(item?.goodsFlag) === 1 &&
      goods?.merchantGoodsId !== undefined &&
      Number.isFinite(Number(price)) &&
      Number(price) > 0
    )
  })
  if (ordinaryGoods.length < 2) {
    missing.push(
      missingItem(
        'ordinaryGoods',
        PREFLIGHT_METHODS.goods,
        '2 x merchantGoodsId/sellPrice'
      )
    )
  }
  const multiSpecGoods =
    catalog.find(item => Number(item?.goodsFlag) === 2) ?? null
  const packageGoods = catalog.find(item => Number(item?.goodsFlag) === 3) ?? null

  const technicianData = await query(
    'technician',
    PREFLIGHT_METHODS.technicians,
    { yqMerchantId: context.park.id, ...common }
  )
  const technician = normalizeTechnician(listFrom(technicianData)[0])
  if (!technician) {
    missing.push(
      missingItem('technician', PREFLIGHT_METHODS.technicians, 'mainTechnicianList[].id')
    )
  }

  const serviceData = await query(
    'serviceItem',
    PREFLIGHT_METHODS.serviceItems,
    { subOrderCodeList: [], ...common }
  )
  const serviceItem = normalizeServiceItem(serviceData)
  if (!serviceItem) {
    missing.push(
      missingItem('serviceItem', PREFLIGHT_METHODS.serviceItems, 'serviceItemList[].id')
    )
  }

  let inventory = null
  const firstOrdinary = ordinaryGoods[0]?.goods
  if (firstOrdinary?.upgradeGoodsId !== undefined) {
    const filmRolls = listFrom(
      await query('inventory', PREFLIGHT_METHODS.filmRolls, {
        yqMerchantId: context.park.id,
        merchantId: context.store.id,
        upgradeGoodsId: firstOrdinary.upgradeGoodsId,
        ...common
      })
    )
    inventory = filmRolls.length
      ? { mode: 'film-roll', value: filmRolls[0], goods: firstOrdinary }
      : { mode: 'manual', goods: firstOrdinary }
  }
  if (!inventory) {
    missing.push(
      missingItem(
        'inventory',
        PREFLIGHT_METHODS.filmRolls,
        'upgradeGoodsId or hand-entered outbound candidate'
      )
    )
  }

  const constructionPictureUrl =
    options.constructionImageUrl || findImageUrl(catalog)
  if (!constructionPictureUrl) {
    missing.push(
      missingItem(
        'constructionPictureUrl',
        PREFLIGHT_METHODS.goods,
        'pictureList[].url'
      )
    )
  }

  return {
    ok: missing.length === 0,
    context: {
      park: context.park,
      store: context.store,
      sceneType: context.sceneType
    },
    resources: {
      employee,
      seller: employee,
      baseScene,
      merchantCoupon,
      subShop,
      ordinaryGoods,
      packageGoods,
      multiSpecGoods,
      technician,
      serviceItem,
      inventory,
      constructionPictureUrl
    },
    missing,
    diagnostics
  }
}

export { findImageUrl, listFrom }