report.js 1.75 KB
const _ = require('lodash')
const MysqlAdapter = require('./mysql')
const config = require('../config/index')
const logger = global.logger

const mysql = new MysqlAdapter(config.database.connect, config.database.database)

const sknCache = {}

module.exports = async (data) => {
  let dataId = 0
  const {productId, sizeId, price, time} = data
  const cachekey = `p:${productId}_s:${sizeId}`

  if (sknCache[cachekey]) {
    dataId = sknCache[cachekey].id
  }
  if (!dataId) {
    try {
      const result = await mysql.query('SELECT * FROM `channel_sku_compare` WHERE `product_id` = :productId AND `size_id` = :sizeId', {
        productId,
        sizeId
      })

      if (result.length) {
        dataId =_.first(result).id
      } else {
        logger.error(`channel_sku_compare表未找到对应的数据, productId: ${productId}, sizeId: ${sizeId}`)
        // mysql.insert('INSERT `channel_sku_compare` (`product_id`, `sku`, `size_id`, `channel_price`, `update_time`) VALUES (:productId, 0, :sizeId, 0, 0)', {
        //   productId,
        // sizeId
        // })
        return Promise.resolve()
      }
    } catch(error) {
      logger.error(`channel_sku_compare表查询失败: ${error.message}`)
      return Promise.resolve()
    }
  }

  try {
    const changedRows = await mysql.update('UPDATE `channel_sku_compare` SET `channel_price` = :channelPrice, `update_time` = :updateTime WHERE `id` = :dataId', {
      channelPrice: price,
      updateTime: time / 1000,
      dataId
    })

    if (changedRows <= 0) {
      logger.error(`更新channel_sku_compare表失败 dataId: ${dataId} ${JSON.stringify(data)}`)
    }
  } catch (error) {
    logger.error(`更新channel_sku_compare表错误: ${JSON.stringify(data)}, ${error.message}`)
  }
  return Promise.resolve()
}