orderFlow.mjs 11.6 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
export const ORDER_FLOW_METHODS = {
  create: 'dj.api.smartcarlife.order.createWithPay',
  pay: 'dj.api.smartcarlife.payOrder.create',
  detail: 'dj.api.smartcarlife.order.detail',
  refundGuard: 'dj.api.smartcarlife.refundApplyRecord.isExist',
  revoke: 'dj.api.smartcarlife.order.revoke',
  correction: 'dj.api.smartcarlife.order.correctionOrder',
  couponDetail: 'dj.api.smartCarLife.customer.coupon.detail',
  constructionRisk: 'dj.api.smartcarlife.construction.summary.status'
}

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

const requireSuccess = (method, response) => {
  if (!isSuccess(response)) {
    throw new Error(
      `ROP business call failed: ${method} (code ${response?.code ?? 'missing'})`
    )
  }
  return response.data
}

const withSession = (context, payload) => ({
  ...payload,
  sessionId: context.sessionId
})

const pad = value => String(value).padStart(2, '0')

const formatDateTime = value => {
  const date = value instanceof Date ? value : new Date(value)
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
    date.getDate()
  )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

const defaultWait = milliseconds =>
  new Promise(resolve => setTimeout(resolve, milliseconds))

const timestamp = value => {
  const resolved = typeof value === 'function' ? value() : value
  return resolved instanceof Date ? resolved.getTime() : Number(resolved)
}

async function waitForOrderStatus({
  client,
  context,
  orderCode,
  expectedStatus,
  wait = defaultWait,
  now = () => new Date(),
  timeoutMs = 60_000,
  intervalMs = 1_000
}) {
  const startedAt = timestamp(now)
  let lastStatus
  while (true) {
    const detail = requireSuccess(
      ORDER_FLOW_METHODS.detail,
      await client.post(
        ORDER_FLOW_METHODS.detail,
        withSession(context, { orderCode })
      )
    )
    lastStatus = Number(detail?.status)
    if (lastStatus === Number(expectedStatus)) return detail
    if (timestamp(now) - startedAt >= timeoutMs) {
      throw new Error(
        `Timed out waiting for order ${orderCode} status ${expectedStatus}; last status ${lastStatus}`
      )
    }
    await wait(intervalMs)
  }
}

const ensureNoRefund = async (client, context, orderCode) => {
  const result = requireSuccess(
    ORDER_FLOW_METHODS.refundGuard,
    await client.post(
      ORDER_FLOW_METHODS.refundGuard,
      withSession(context, { orderCode })
    )
  )
  if (result === 'Y') {
    throw new Error(`Order ${orderCode} refund is in progress`)
  }
  return result
}

async function createAndPay({
  client,
  context,
  fixtures,
  now,
  wait,
  onOrderCreated = () => {}
}) {
  const created = requireSuccess(
    ORDER_FLOW_METHODS.create,
    await client.post(
      ORDER_FLOW_METHODS.create,
      withSession(context, fixtures.orderPayload)
    )
  )
  const orderCode = created?.orderCode
  if (!orderCode) throw new Error('createWithPay response missing orderCode')
  await onOrderCreated({ orderCode, role: 'source' })

  const paymentResponse = await client.post(
    ORDER_FLOW_METHODS.pay,
    withSession(context, {
      orderCode,
      payType: fixtures.orderPayload.selectPayType,
      payeeType: fixtures.orderPayload.payeeType,
      outTradeNo: `AUTO-${orderCode}`,
      successDate: formatDateTime(now())
    })
  )
  if (!isSuccess(paymentResponse)) {
    try {
      await client.post(
        ORDER_FLOW_METHODS.revoke,
        withSession(context, { orderCode })
      )
    } catch {
      // Preserve the primary payment failure; cleanup status is verified by live QA.
    }
  }
  requireSuccess(ORDER_FLOW_METHODS.pay, paymentResponse)
  const paidOrder = await waitForOrderStatus({
    client,
    context,
    orderCode,
    expectedStatus: 4,
    now,
    wait
  })
  return { orderCode, created, paidOrder }
}

export async function runCancelableOrderFlow({
  client,
  context,
  fixtures,
  now = () => new Date(),
  wait = defaultWait,
  onOrderCreated = () => {}
}) {
  const paid = await createAndPay({
    client,
    context,
    fixtures,
    now,
    wait,
    onOrderCreated
  })
  await ensureNoRefund(client, context, paid.orderCode)
  await ensureNoRefund(client, context, paid.orderCode)
  requireSuccess(
    ORDER_FLOW_METHODS.revoke,
    await client.post(
      ORDER_FLOW_METHODS.revoke,
      withSession(context, { orderCode: paid.orderCode })
    )
  )
  const revokedOrder = await waitForOrderStatus({
    client,
    context,
    orderCode: paid.orderCode,
    expectedStatus: 9,
    now,
    wait
  })
  return { ...paid, revokedOrder }
}

const assertCorrectionRelation = ({ oldCode, newCode, correction, oldOrder, newOrder }) => {
  if (oldCode === newCode) throw new Error('Correction returned the original orderCode')
  const relationCandidates = [
    correction?.oldOrderCode,
    correction?.associateOrderCode,
    correction?.associatedOrderCode,
    oldOrder?.associatedOrderCode,
    newOrder?.oldOrderCode,
    newOrder?.associateOrderCode,
    newOrder?.associatedOrderCode
  ].filter(Boolean)
  if (!relationCandidates.includes(oldCode)) {
    throw new Error('Corrected order response is missing the old/new relation')
  }
}

const buildCorrectionPayload = (fixtures, paidOrder, oldOrderCode) => {
  const sourceSubOrders =
    paidOrder?.subOrderList ?? fixtures.orderPayload.subOrderList
  const correctionSubOrders = sourceSubOrders.map(item => {
    const number = Number(item.number ?? 1)
    const total = Number(item.totalPrice ?? item.finalPrice ?? 0)
    const unitPrice = Number(item.sellPrice ?? total / number)
    const line = {
      baseGoodsId: item.baseGoodsId,
      totalPrice: unitPrice,
      number,
      merchantGoodsId: item.merchantGoodsId,
      discountType: item.discountType,
      discountValue: item.discountValue,
      discountAmount: item.discountAmount,
      finalPrice: item.finalPrice ?? total,
      singleProductFinalPrice:
        item.singleProductFinalPrice ?? Number(item.finalPrice ?? total) / number,
      djOrderType: paidOrder?.djOrderType ?? fixtures.orderPayload.djOrderType,
      marketingFlag: item.marketingFlag,
      modifyFlag: item.modifyFlag
    }
    if (item.activityId !== null && item.activityId !== undefined) {
      line.activityId = item.activityId
    }
    for (const [key, value] of Object.entries(line)) {
      if (value === null || value === undefined) delete line[key]
    }
    return line
  })
  const payload = {
    ...fixtures.orderPayload,
    ...paidOrder,
    customer: paidOrder?.customer ?? fixtures.orderPayload.customer,
    subOrderList: correctionSubOrders,
    oldOrderCode,
    associateOrderCode: oldOrderCode,
    selectPayType: 2
  }
  delete payload.orderCode
  delete payload.payOrder
  delete payload.technicianList
  for (const field of [
    'profitAllocatinList',
    'packageGoodsList',
    'expenseCategoryList',
    'merchantDistributionList',
    'baseSceneName',
    'orderTime',
    'createdBy',
    'createdDate',
    'updatedBy',
    'updatedDate'
  ]) {
    delete payload[field]
  }
  if (!paidOrder?.customerCoupon?.id || !paidOrder.customerCoupon.customerCouponCode) {
    throw new Error('Paid source order detail is missing the claimed customer coupon')
  }
  payload.customerCouponId = paidOrder.customerCoupon.id
  payload.merchantCouponId = paidOrder.customerCoupon.merchantCouponId
  payload.customerCouponCode = String(
    paidOrder.customerCoupon.customerCouponCode
  )
  payload.couponName = paidOrder.customerCoupon.couponName
  payload.selectPayType = 5
  payload.payeeType = 0
  payload.filmOrder = 0
  if (payload.customer) {
    delete payload.customer.buyTime
    delete payload.customer.createdDate
  }
  for (const [key, value] of Object.entries(payload)) {
    if (value === null || value === undefined) {
      delete payload[key]
      continue
    }
    if (typeof value === 'object' && !Array.isArray(value)) {
      const cleaned = { ...value }
      for (const [nestedKey, nestedValue] of Object.entries(cleaned)) {
        if (nestedValue === null || nestedValue === undefined) {
          delete cleaned[nestedKey]
        }
      }
      payload[key] = cleaned
    }
  }
  return payload
}

export async function runCorrectedOrderFlow({
  client,
  context,
  fixtures,
  now = () => new Date(),
  wait = defaultWait,
  onOrderCreated = () => {}
}) {
  const correctionFixtures = {
    ...fixtures,
    orderPayload: {
      ...fixtures.orderPayload,
      selectPayType: 7,
      payeeType: 0
    }
  }
  const paid = await createAndPay({
    client,
    context,
    fixtures: correctionFixtures,
    now,
    wait,
    onOrderCreated
  })
  await ensureNoRefund(client, context, paid.orderCode)
  const risk = requireSuccess(
    ORDER_FLOW_METHODS.constructionRisk,
    await client.post(
      ORDER_FLOW_METHODS.constructionRisk,
      withSession(context, {
        merchantId: context.store.id,
        orderCode: paid.orderCode
      })
    )
  )
  if (Number(risk?.incompleteTotal ?? 0) > 0) {
    throw new Error(`Order ${paid.orderCode} has incomplete construction`)
  }
  await ensureNoRefund(client, context, paid.orderCode)

  let correctionPayload
  try {
    const couponDetail = requireSuccess(
      ORDER_FLOW_METHODS.couponDetail,
      await client.post(
        ORDER_FLOW_METHODS.couponDetail,
        withSession(context, { id: paid.paidOrder?.customerCoupon?.id })
      )
    )
    correctionPayload = buildCorrectionPayload(
      fixtures,
      {
        ...paid.paidOrder,
        customerCoupon: {
          ...paid.paidOrder.customerCoupon,
          ...couponDetail
        }
      },
      paid.orderCode
    )
  } catch (error) {
    try {
      await client.post(
        ORDER_FLOW_METHODS.revoke,
        withSession(context, { orderCode: paid.orderCode })
      )
    } catch {}
    throw error
  }
  const correctionResponse = await client.post(
    ORDER_FLOW_METHODS.correction,
    withSession(context, correctionPayload)
  )
  if (!isSuccess(correctionResponse)) {
    try {
      await client.post(
        ORDER_FLOW_METHODS.revoke,
        withSession(context, { orderCode: paid.orderCode })
      )
    } catch {}
  }
  const correction = requireSuccess(
    ORDER_FLOW_METHODS.correction,
    correctionResponse
  )
  const newOrderCode = correction?.orderCode
  if (!newOrderCode) throw new Error('correctionOrder response missing orderCode')
  await onOrderCreated({ orderCode: newOrderCode, role: 'corrected' })

  let correctedOrder = requireSuccess(
    ORDER_FLOW_METHODS.detail,
    await client.post(
      ORDER_FLOW_METHODS.detail,
      withSession(context, { orderCode: newOrderCode })
    )
  )
  if (Number(correctedOrder?.status) !== 4) {
    const correctedPayment = await client.post(
      ORDER_FLOW_METHODS.pay,
      withSession(context, {
        orderCode: newOrderCode,
        payType: 5,
        payeeType: 0,
        outTradeNo: `AUTO-${newOrderCode}`
      })
    )
    if (!isSuccess(correctedPayment)) {
      try {
        await client.post(
          ORDER_FLOW_METHODS.revoke,
          withSession(context, { orderCode: newOrderCode })
        )
      } catch {}
    }
    requireSuccess(ORDER_FLOW_METHODS.pay, correctedPayment)
    correctedOrder = await waitForOrderStatus({
      client,
      context,
      orderCode: newOrderCode,
      expectedStatus: 4,
      now,
      wait
    })
  }
  const oldOrder = await waitForOrderStatus({
    client,
    context,
    orderCode: paid.orderCode,
    expectedStatus: 11,
    now,
    wait
  })
  assertCorrectionRelation({
    oldCode: paid.orderCode,
    newCode: newOrderCode,
    correction,
    oldOrder,
    newOrder: correctedOrder
  })
  return { oldOrder, correctedOrder, correction }
}

export {
  assertCorrectionRelation,
  buildCorrectionPayload,
  createAndPay,
  formatDateTime,
  waitForOrderStatus
}