generate_weekly_data.js 8.29 KB

const fs = require('fs');

// --- Configuration ---
const TOTAL_START_VALUE = 55397;
const TOTAL_MIN_VALUE = 3000;

// Weekly settings (scaled down)
const WEEKLY_AVG_START = 5000; 
const WEEKLY_MIN_VALUE = 200;

const ITEM_COUNT = 7;
const DEPTH_SCALE = 1

// Color Palette
const COLOR_MAP = {
  $启动APP: '#28b467ff',
  $关闭App: '#909399',
  App激活: '#67C23A',
  App浏览页面: '#E6A23C',
  App元素点击: '#F56C6C',
  App推送点击: '#9C27B0',
  web浏览页面: '#00BCD4',
  小程序首次启动: '#3F51B5',
  小程序浏览页面: '#2196F3',
  微信端内活跃: '#009688',
  搜索: '#FF9800',
  签到: '#795548',
  所有支付: '#607D8B',
  更多: '#DCDFE6'
}

const EVENT_POOL = Object.keys(COLOR_MAP).filter(k => !k.startsWith('$') && k !== '更多')

// --- Helper Functions ---

function shuffle(array) {
  const newArr = [...array]
  for (let i = newArr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[newArr[i], newArr[j]] = [newArr[j], newArr[i]]
  }
  return newArr
}

function generateDist(total, count, minVal) {
  let remaining = total - count * minVal
  if (remaining < 0) return Array(count).fill(Math.floor(total / count))

  let cuts = []
  for (let i = 0; i < count - 1; i++) cuts.push(Math.random())
  cuts.sort((a, b) => a - b)

  let parts = []
  let prev = 0
  for (let cut of cuts) {
    parts.push(cut - prev)
    prev = cut
  }
  parts.push(1 - prev)

  parts = parts.map(p => Math.floor(p * remaining) + minVal)
  let sum = parts.reduce((a, b) => a + b, 0)
  parts[0] += total - sum
  return parts
}

function generateMatrixWithLoss(rowSums, colSums) {
  let matrix = Array(rowSums.length)
    .fill(0)
    .map(() => Array(colSums.length).fill(0))
  let supply = [...rowSums]
  let demand = [...colSums]

  // Cap supply to create loss
  let caps = supply.map(s => Math.floor(s * (0.8 + Math.random() * 0.15))) // 5-20% loss

  let totalCapped = caps.reduce((a, b) => a + b, 0)
  let totalDemand = demand.reduce((a, b) => a + b, 0)

  if (totalCapped < totalDemand) {
    let ratio = totalDemand / totalCapped
    caps = caps.map(c => Math.ceil(c * ratio * 1.01))
  }

  let cells = []
  for (let i = 0; i < rowSums.length; i++) {
    for (let j = 0; j < colSums.length; j++) {
      cells.push([i, j])
    }
  }
  cells = shuffle(cells)

  let effectiveSupply = [...caps]

  for (let [i, j] of cells) {
    if (effectiveSupply[i] <= 0 || demand[j] <= 0) continue
    let maxPossible = Math.min(effectiveSupply[i], demand[j])
    let amount = maxPossible
    if (Math.random() > 0.2) {
      let ratio = 0.3 + Math.random() * 0.5
      amount = Math.floor(maxPossible * ratio)
      if (amount < 50) amount = maxPossible
    }
    matrix[i][j] += amount
    effectiveSupply[i] -= amount
    demand[j] -= amount
  }

  for (let i = 0; i < rowSums.length; i++) {
    for (let j = 0; j < colSums.length; j++) {
      if (demand[j] > 0 && effectiveSupply[i] > 0) {
        let maxPossible = Math.min(effectiveSupply[i], demand[j])
        matrix[i][j] += maxPossible
        effectiveSupply[i] -= maxPossible
        demand[j] -= maxPossible
      }
    }
  }
  return matrix
}

// --- Generator ---

function generateGraphData(startValue, minValue) {
  let nodes = []
  let links = []
  const minLayerTotal = ITEM_COUNT * minValue

  // Start Node
  nodes.push({ name: '$启动APP', depth: 0, itemStyle: { color: COLOR_MAP['$启动APP'] }, value: startValue })

  let currentLayerNodes = [{ name: '$启动APP', value: startValue }]
  let currentLayerTotal = startValue

  // Layers 1 to 5
  for (let d = 1; d <= 5; d++) {
    let currentDepth = (d - 1) * DEPTH_SCALE
    if (d === 1) currentDepth = 0
    let nextDepth = d * DEPTH_SCALE

    // Calculate Next Layer Total
    let retention = 0.85
    let nextLayerTotal = Math.floor(currentLayerTotal * retention)
    if (nextLayerTotal < minLayerTotal) nextLayerTotal = minLayerTotal

    // Generate Real Nodes
    let parts = generateDist(nextLayerTotal, ITEM_COUNT, minValue)
    parts.sort((a, b) => b - a) // Descending

    let eventSubset = shuffle([...EVENT_POOL]).slice(0, 6)
    let nextLayerNodes = []

    // Events
    for (let i = 0; i < 6; i++) {
      let eventName = eventSubset[i]
      nextLayerNodes.push({
        name: `${eventName} (${d})`,
        depth: nextDepth,
        value: parts[i + 1],
        itemStyle: { color: COLOR_MAP[eventName] || '#000' }
      })
    }

    // More
    nextLayerNodes.push({
      name: `更多 (${d})`,
      depth: nextDepth,
      value: parts[0],
      itemStyle: { color: COLOR_MAP['更多'] }
    })

    nextLayerNodes.forEach(n => nodes.push(n))

    // Links
    let sourceValues = currentLayerNodes.map(n => n.value)
    let targetValues = nextLayerNodes.map(n => n.value)

    let linkMatrix = generateMatrixWithLoss(sourceValues, targetValues)

    for (let i = 0; i < sourceValues.length; i++) {
      let sentTotal = 0
      for (let j = 0; j < targetValues.length; j++) {
        let val = linkMatrix[i][j]
        if (val > 0) {
          links.push({
            source: currentLayerNodes[i].name,
            target: nextLayerNodes[j].name,
            value: val
          })
          sentTotal += val
        }
      }

      // Loss
      let loss = currentLayerNodes[i].value - sentTotal
      if (loss > 0) {
        let lossNodeName = `${currentLayerNodes[i].name}__Loss`
        // Place loss node at same depth as next layer
        let lossDepth = nextDepth

        nodes.push({
          name: lossNodeName,
          depth: lossDepth,
          value: loss,
          itemStyle: { opacity: 0 },
          label: { show: false },
          isLoss: true
        })

        links.push({
          source: currentLayerNodes[i].name,
          target: lossNodeName,
          value: loss
        })
      }
    }

    currentLayerNodes = nextLayerNodes
    currentLayerTotal = nextLayerTotal
  }

  // End Node
  let lastDepth = 5 * DEPTH_SCALE
  let endDepth = 6 * DEPTH_SCALE
  let endValue = Math.floor(currentLayerTotal * 0.9)
  let endNode = { name: '$关闭App', depth: endDepth, itemStyle: { color: COLOR_MAP['$关闭App'] }, value: endValue }
  nodes.push(endNode)

  currentLayerNodes.forEach(node => {
    let val = Math.floor(node.value * 0.9)
    links.push({
      source: node.name,
      target: '$关闭App',
      value: val
    })

    let loss = node.value - val
    if (loss > 0) {
      let lossNodeName = `${node.name}__Loss`
      nodes.push({
        name: lossNodeName,
        depth: endDepth,
        value: loss,
        itemStyle: { opacity: 0 },
        label: { show: false },
        isLoss: true
      })
      links.push({
        source: node.name,
        target: lossNodeName,
        value: loss
      })
    }
  })

  // Sorting
  nodes.sort((a, b) => {
    if (a.depth !== b.depth) return a.depth - b.depth
    const getRank = n => {
      if (n.isLoss) return 2
      if (n.name.includes('更多')) return 1
      return 0
    }
    const rankA = getRank(a)
    const rankB = getRank(b)
    if (rankA !== rankB) return rankA - rankB
    return b.value - a.value
  })

  return { nodes, links }
}

// --- Main Execution ---

// 1. Generate Total Data
const totalData = generateGraphData(TOTAL_START_VALUE, TOTAL_MIN_VALUE);

// 2. Generate Weekly Data
const weeklyData = {};

// Date generation: 2025-11-01 to 2026-01-25
// Align to Mondays.
// Nov 1 2025 is Saturday. First Monday is Nov 3.
let currentDate = new Date('2025-11-03'); 
const endDate = new Date('2026-01-25');

function formatDate(date) {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
}

while (currentDate <= endDate) {
    const dateStr = formatDate(currentDate);
    
    // Randomize start value for this week (e.g., 3000 to 7000)
    const weekStart = Math.floor(3000 + Math.random() * 4000);
    const weekData = generateGraphData(weekStart, WEEKLY_MIN_VALUE);
    
    weeklyData[dateStr] = weekData;
    
    // Next week
    currentDate.setDate(currentDate.getDate() + 7);
}

// --- Output ---
const outputContent = `
export const nodes = ${JSON.stringify(totalData.nodes, null, 2)}

export const links = ${JSON.stringify(totalData.links, null, 2)}

export const weeklyData = ${JSON.stringify(weeklyData, null, 2)}
`;

fs.writeFileSync('src/views/behaviorManage/components/chartData.js', outputContent);
console.log('Done');