js 实现POS


使用JavaScript实现POS(销售点)系统
POS系统通常包含商品管理、订单处理、支付结算等功能。以下是一个基础的JavaScript实现方案:
商品管理模块
class Product {
constructor(id, name, price, stock) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
}
}
const productCatalog = [
new Product(1, '商品A', 100, 50),
new Product(2, '商品B', 200, 30)
];
购物车模块
class Cart {
constructor() {
this.items = [];
}
addItem(product, quantity) {
const existingItem = this.items.find(item => item.product.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
this.items.push({ product, quantity });
}
}
calculateTotal() {
return this.items.reduce((total, item) => {
return total + (item.product.price * item.quantity);
}, 0);
}
}
支付处理模块
class PaymentProcessor {
static processPayment(amount, paymentMethod) {
switch(paymentMethod) {
case 'cash':
return { success: true, message: '现金支付成功' };
case 'card':
return { success: true, message: '信用卡支付成功' };
default:
return { success: false, message: '不支持的支付方式' };
}
}
}
主系统集成
class POSSystem {
constructor() {
this.cart = new Cart();
this.products = productCatalog;
}
scanProduct(productId, quantity = 1) {
const product = this.products.find(p => p.id === productId);
if (product) {
this.cart.addItem(product, quantity);
return `已添加 ${quantity} 件 ${product.name}`;
}
return '商品未找到';
}
checkout(paymentMethod) {
const total = this.cart.calculateTotal();
const paymentResult = PaymentProcessor.processPayment(total, paymentMethod);
if (paymentResult.success) {
const receipt = {
items: this.cart.items,
total,
paymentMethod,
timestamp: new Date()
};
this.cart = new Cart(); // 清空购物车
return { success: true, receipt };
}
return { success: false, message: paymentResult.message };
}
}
使用示例
const pos = new POSSystem();
// 扫描商品
console.log(pos.scanProduct(1, 2)); // 添加商品A两件
console.log(pos.scanProduct(2, 1)); // 添加商品B一件
// 结账
const result = pos.checkout('card');
if (result.success) {
console.log('支付成功', result.receipt);
} else {
console.log('支付失败:', result.message);
}
扩展功能建议
- 添加本地存储功能,使用localStorage保存交易记录
- 实现折扣和促销功能
- 添加用户界面(可使用React/Vue等框架)
- 集成打印机API生成纸质小票
- 添加库存管理功能,自动更新商品库存
这个基础实现可以根据具体需求进行扩展,比如添加数据库连接、用户认证等功能。对于生产环境,建议使用Node.js作为后端处理更复杂的业务逻辑。






