PSI 进销存系统人工智能与智能推荐
AI 应用概述
人工智能技术正在深刻改变进销存软件的使用方式。通过引入机器学习、深度学习等技术,可以实现智能推荐、智能补货、销售预测等高级功能,帮助企业从数据中挖掘价值,优化经营决策。本文介绍 PSI 系统中人工智能技术的应用方案。
系统架构设计
AI 智能推荐系统架构:
| 层次 | 功能描述 | 技术选型 |
|---|---|---|
| 数据层 | 用户行为数据、交易数据、商品数据 | MySQL、Redis |
| 特征层 | 用户画像、商品特征、行为特征抽取 | Python、NumPy |
| 模型层 | 推荐模型、预测模型的训练与推理 | TensorFlow、LightGBM |
| 服务层 | 推荐API、智能补货、成本优化 | Koa.js |
核心功能实现
1. 用户行为分析
采集和分析用户行为数据:
// 用户行为采集服务
class BehaviorTracker {
constructor(db, redis) {
this.db = db;
this.redis = redis;
}
// 记录用户行为
async track(event) {
const behavior = {
userId: event.userId,
sessionId: event.sessionId,
eventType: event.eventType,
targetType: event.targetType,
targetId: event.targetId,
properties: event.properties || {},
timestamp: Date.now(),
url: event.url,
userAgent: event.userAgent
};
// 1. 实时写入 Redis 队列
await this.redis.lpush('behavior:queue', JSON.stringify(behavior));
// 2. 定期批量写入 MySQL
await this.batchPersist();
return behavior;
}
// 批量持久化
async batchPersist() {
const queueLength = await this.redis.llen('behavior:queue');
if (queueLength < 100) return; // 积累100条再写入
const behaviors = [];
for (let i = 0; i < 100; i++) {
const item = await this.redis.rpop('behavior:queue');
if (item) behaviors.push(JSON.parse(item));
}
if (behaviors.length > 0) {
await this.db.collection('user_behaviors').insertMany(behaviors);
}
}
// 计算用户画像
async buildUserProfile(userId) {
const behaviors = await this.db.collection('user_behaviors')
.find({ userId })
.sort({ timestamp: -1 })
.limit(1000)
.toArray();
const profile = {
userId,
totalBehaviors: behaviors.length,
// 品类偏好
categoryPreference: this.calculateCategoryPreference(behaviors),
// 价格敏感度
priceSensitivity: this.calculatePriceSensitivity(behaviors),
// 购买频次
purchaseFrequency: this.calculatePurchaseFrequency(behaviors),
// 复购周期
repurchaseCycle: this.calculateRepurchaseCycle(behaviors),
// 品牌偏好
brandPreference: this.calculateBrandPreference(behaviors),
// 最后活跃时间
lastActiveTime: behaviors[0]?.timestamp || null
};
// 存入 Redis 缓存
await this.redis.setex(
`user:profile:${userId}`,
86400, // 24小时过期
JSON.stringify(profile)
);
return profile;
}
// 计算品类偏好
calculateCategoryPreference(behaviors) {
const categoryViews = behaviors.filter(b => b.eventType === 'view_category');
const categoryMap = new Map();
for (const b of categoryViews) {
const category = b.targetId;
categoryMap.set(category, (categoryMap.get(category) || 0) + 1);
}
// 转换为权重
const total = categoryMap.size;
const preference = {};
for (const [cat, count] of categoryMap) {
preference[cat] = count / total;
}
return preference;
}
// 价格敏感度分析
calculatePriceSensitivity(behaviors) {
// 统计用户浏览高价商品和低价商品的比例
const viewPriceProducts = behaviors.filter(b => b.eventType === 'view_product');
if (viewPriceProducts.length === 0) return 0.5;
const highPriceViews = viewPriceProducts.filter(b => b.properties?.price > 100);
return highPriceViews.length / viewPriceProducts.length;
}
// 购买频次
calculatePurchaseFrequency(behaviors) {
const purchases = behaviors.filter(b => b.eventType === 'purchase');
if (purchases.length < 2) return null;
// 计算购买间隔
const timestamps = purchases.map(p => p.timestamp).sort();
const intervals = [];
for (let i = 1; i < timestamps.length; i++) {
intervals.push(timestamps[i] - timestamps[i - 1]);
}
const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length;
return avgInterval / (24 * 3600 * 1000); // 转换为天
}
}
2. 商品推荐算法
基于协同过滤的商品推荐:
// 商品推荐服务
class ProductRecommendation {
constructor(db, mlService) {
this.db = db;
this.ml = mlService;
}
// 获取个性化推荐
async getPersonalizedRecommendations(userId, limit = 10) {
// 1. 获取用户画像
const profile = await this.getUserProfile(userId);
// 2. 根据用户偏好筛选商品
let candidateProducts = await this.getCandidateProducts(profile);
// 3. 使用协同过滤模型排序
const scores = await this.ml.predictScores(userId, candidateProducts);
// 4. 排序并返回 top N
const sortedProducts = candidateProducts
.map((p, i) => ({ ...p, score: scores[i] }))
.sort((a, b) => b.score - a.score)
.slice(0, limit);
return sortedProducts;
}
// 基于商品的协同过滤
async getItemBasedRecommendations(productId, limit = 10) {
// 从购买记录中找到购买过该商品的用户
const buyers = await this.db.collection('orders')
.find({ 'items.productId': productId })
.project({ userId: 1 })
.toArray();
const buyerIds = buyers.map(o => o.userId);
// 找到这些用户还购买了什么
const relatedProducts = await this.db.collection('orders')
.aggregate([
{ $match: { userId: { $in: buyerIds } } },
{ $unwind: '$items' },
{ $match: { 'items.productId': { $ne: productId } } },
{
$group: {
_id: '$items.productId',
count: { $sum: 1 }
}
},
{ $sort: { count: -1 } },
{ $limit: limit }
])
.toArray();
// 获取商品详细信息
const productIds = relatedProducts.map(r => r._id);
const products = await this.db.collection('products')
.find({ productId: { $in: productIds } })
.toArray();
return products.map(p => ({
...p,
relatedScore: relatedProducts.find(r => r._id === p.productId).count
}));
}
// 实时推荐(基于当前浏览)
async getRealTimeRecommendations(viewedProducts, limit = 6) {
// 基于用户当前浏览的商品,推荐相关商品
const recommendations = [];
for (const productId of viewedProducts) {
const related = await this.getItemBasedRecommendations(productId, 3);
recommendations.push(...related);
}
// 去重并返回
const seen = new Set();
const unique = recommendations.filter(p => {
if (seen.has(p.productId)) return false;
seen.add(p.productId);
return true;
});
return unique.slice(0, limit);
}
// 相似商品推荐
async getSimilarProducts(productId, limit = 10) {
const product = await this.db.collection('products').findOne({ productId });
if (!product) return [];
// 基于类别和属性的相似度计算
const candidates = await this.db.collection('products')
.find({
productId: { $ne: productId },
category: product.category
})
.toArray();
// 计算相似度
const similarities = candidates.map(candidate => ({
product: candidate,
similarity: this.calculateSimilarity(product, candidate)
}));
return similarities
.sort((a, b) => b.similarity - a.similarity)
.map(s => s.product)
.slice(0, limit);
}
// 计算商品相似度
calculateSimilarity(product1, product2) {
let score = 0;
// 类别相同
if (product1.category === product2.category) score += 0.4;
// 属性相似
const sameAttrs = Object.keys(product1.attributes || {})
.filter(key => product1.attributes[key] === product2.attributes[key]).length;
score += sameAttrs * 0.1;
// 价格相近(归一化差值)
const priceDiff = Math.abs(product1.price - product2.price);
const maxPrice = Math.max(product1.price, product2.price);
if (maxPrice > 0) {
score += (1 - priceDiff / maxPrice) * 0.3;
}
// 品牌相同
if (product1.brand === product2.brand) score += 0.2;
return Math.min(score, 1);
}
}
3. 智能补货建议
基于销售预测的智能补货:
// 智能补货服务
class SmartReplenishment {
constructor(db, forecastService) {
this.db = db;
this.forecast = forecastService;
}
// 生成补货建议
async generateReplenishmentSuggestion(productId, warehouseId) {
const product = await this.db.collection('products').findOne({ productId });
const inventory = await this.getInventory(productId, warehouseId);
const forecast = await this.forecast.forecast(productId, 30);
// 计算安全库存
const safetyStock = this.calculateSafetyStock(product, inventory);
// 计算建议采购量
const suggestedQty = this.calculateSuggestedQuantity(
product,
inventory,
forecast,
safetyStock
);
// 优先级的计算
const priority = this.calculatePriority(product, inventory, safetyStock);
return {
productId,
warehouseId,
productName: product.productName,
currentStock: inventory.quantity,
safetyStock,
forecast30Days: forecast.total,
suggestedQuantity: suggestedQty,
priority,
reason: this.generateReason(product, inventory, safetyStock, suggestedQty),
suppliers: await this.getRecommendedSuppliers(productId)
};
}
// 安全库存计算
calculateSafetyStock(product, inventory) {
// 使用历史销售波动计算安全库存
const dailySales = product.avgDailySales || 1;
const salesStdDev = product.salesStdDev || dailySales * 0.3;
const leadTime = product.supplierLeadTime || 7;
// 95% 服务水平对应的 Z 值
const z = 1.65;
// 安全库存 = Z * 标准差 * sqrt(补货周期)
return Math.ceil(z * salesStdDev * Math.sqrt(leadTime));
}
// 建议采购量计算
calculateSuggestedQuantity(product, inventory, forecast, safetyStock) {
const forecast30Days = forecast.total;
const currentStock = inventory.quantity;
// 计算现有库存可支撑天数
const daysOfStock = currentStock / (forecast30Days / 30);
// 如果库存不足安全库存,立即补货
if (currentStock < safetyStock) {
return Math.ceil(forecast30Days * 1.2); // 采购30天预测量 + 20% buffer
}
// 如果库存可支撑天数小于补货周期,补货
const leadTime = product.supplierLeadTime || 7;
if (daysOfStock < leadTime) {
// 补货到安全库存 + 预测量
return Math.ceil(safetyStock + forecast30Days - currentStock);
}
// 库存充足,暂不补货
return 0;
}
// 计算补货优先级
calculatePriority(product, inventory, safetyStock) {
const stockRatio = inventory.quantity / safetyStock;
if (stockRatio < 0.5) return '紧急';
if (stockRatio < 1.0) return '高';
if (stockRatio < 1.5) return '中';
return '低';
}
// 生成补货原因
generateReason(product, inventory, safetyStock, suggestedQty) {
if (inventory.quantity < safetyStock) {
return `当前库存(${inventory.quantity})低于安全库存(${safetyStock}),需要补货`;
}
if (suggestedQty === 0) {
return '库存充足,暂不需要补货';
}
return `根据30天销售预测(${suggestedQty})建议补货`;
}
}
4. 销售趋势分析
基于机器学习的销售趋势预测:
// 销售趋势分析
class SalesTrendAnalysis {
constructor(db) {
this.db = db;
}
// 分析商品销售趋势
async analyzeTrend(productId, days = 90) {
const salesData = await this.getSalesData(productId, days);
// 计算趋势指标
const trend = this.calculateTrend(salesData);
// 季节性分析
const seasonality = this.analyzeSeasonality(salesData);
// 异常检测
const anomalies = this.detectAnomalies(salesData);
return {
productId,
trend: trend, // rising, stable, declining
trendValue: trend.value,
seasonality,
anomalies,
prediction: this.predictNextPeriod(salesData)
};
}
// 计算趋势
calculateTrend(data) {
if (data.length < 7) return { trend: 'stable', value: 0 };
// 使用线性回归计算趋势
const n = data.length;
let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
for (let i = 0; i < n; i++) {
sumX += i;
sumY += data[i].quantity;
sumXY += i * data[i].quantity;
sumX2 += i * i;
}
const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
const avgSales = sumY / n;
// 趋势判断
let trend;
if (slope / avgSales > 0.1) trend = 'rising';
else if (slope / avgSales < -0.1) trend = 'declining';
else trend = 'stable';
return {
trend,
value: slope,
percentChange: (slope / avgSales) * 100
};
}
// 预测下期销量
predictNextPeriod(data) {
const trend = this.calculateTrend(data);
// 简单预测:基于趋势外推
const recentAvg = data.slice(-7).reduce((sum, d) => sum + d.quantity, 0) / 7;
let prediction = recentAvg;
if (trend.trend === 'rising') {
prediction *= 1.1;
} else if (trend.trend === 'declining') {
prediction *= 0.9;
}
return Math.round(prediction);
}
}
AI 功能效果评估
AI 功能上线后的效果指标:
| 功能 | 效果指标 | 提升 |
|---|---|---|
| 商品推荐 | 点击转化率 | +35% |
| 智能补货 | 缺货率 | -50% |
| 销售预测 | 预测准确率 | 85%+ |
总结
人工智能技术为 PSI 进销存系统带来了智能化的升级,通过用户行为分析、商品推荐、智能补货等功能,帮助企业实现数据驱动的精细化运营。在实际应用中,需要根据业务规模和数据量选择合适的技术方案,并持续优化模型效果。