liveProfiles.mjs 2.65 KB
/**
 * @file 人工触发的 Live 自动化配置。凭证只从环境变量读取,定义中不保存手机号或验证码。
 */

export const LIVE_PROFILE_DEFINITIONS = Object.freeze({
  'mingming-dev': Object.freeze({
    name: 'mingming-dev',
    environment: 'development',
    baseUrl: 'http://dj.dev.glsx.com.cn/rop-dj-car-boutique',
    mobileEnv: 'LIVE_MINGMING_MOBILE',
    codeEnv: 'LIVE_MINGMING_CODE',
    yqNameEnv: 'LIVE_MINGMING_YQ_NAME',
    storeName: '明明崇文4S店',
    sceneName: '精品升级',
  }),
  'bobo-test': Object.freeze({
    name: 'bobo-test',
    environment: 'test',
    baseUrl: 'http://dj.test.glsx.com.cn/rop-dj-car-boutique',
    mobileEnv: 'LIVE_BOBO_MOBILE',
    codeEnv: 'LIVE_BOBO_CODE',
    yqName: '流程测试园区门店',
    storeName: '波波的单店门店',
    sceneName: '精品升级',
  }),
})

function requiredValue(env, name, missing) {
  const value = String(env[name] ?? '').trim()
  if (!value) missing.push(name)
  return value
}

/**
 * 解析一个已批准的 Live 测试身份和门店上下文。
 *
 * @param {string} profileName 配置名。
 * @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
 * @returns {Readonly<object>} 可传给既有订单 Live 测试的配置。
 */
export function resolveLiveProfile(profileName, env = process.env) {
  if (!String(profileName || '').trim()) throw new Error('Live profile is required')
  const definition = LIVE_PROFILE_DEFINITIONS[profileName]
  if (!definition) throw new Error(`Unknown live profile: ${profileName}`)
  const missing = []
  const mobile = requiredValue(env, definition.mobileEnv, missing)
  const code = requiredValue(env, definition.codeEnv, missing)
  const yqName = definition.yqNameEnv
    ? requiredValue(env, definition.yqNameEnv, missing)
    : definition.yqName
  if (missing.length) {
    throw new Error(`Missing Live environment variables: ${missing.join(', ')}`)
  }
  return Object.freeze({
    name: definition.name,
    environment: definition.environment,
    baseUrl: definition.baseUrl,
    mobile,
    code,
    yqName,
    storeName: definition.storeName,
    sceneName: definition.sceneName,
  })
}

/**
 * 校验写操作的独立人工开关。
 *
 * @param {object} profile 已解析配置。
 * @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
 * @returns {true} 校验通过。
 */
export function assertLiveWriteAllowed(profile, env = process.env) {
  if (!LIVE_PROFILE_DEFINITIONS[profile?.name]) throw new Error('Approved Live profile is required')
  if (env.LIVE_ALLOW_WRITES !== '1') {
    throw new Error('LIVE_ALLOW_WRITES=1 is required for Live write tests')
  }
  return true
}