Commit 57a8a53f by tdgiang

Add tax-aware random product combo picker for Sổ Bán Lẻ auto-order

parent 00a6931c
"use strict";
var DEFAULT_TOLERANCE = 50000;
var DEFAULT_MAX_ATTEMPTS = 20;
var DEFAULT_MAX_QTY_PER_LINE = 3;
function shuffle(list, random) {
var arr = list.slice();
for (var i = arr.length - 1; i > 0; i--) {
var j = Math.floor(random() * (i + 1));
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
}
function computeLineTotal(product, qty) {
var rate = product.tax && typeof product.tax.rate === "number" ? product.tax.rate : 0;
return Math.round(qty * product.price * (1 + rate / 100));
}
function pickProductCombo(products, targetAmount, options) {
options = options || {};
var tolerance = typeof options.tolerance === "number" ? options.tolerance : DEFAULT_TOLERANCE;
var maxAttempts = options.maxAttempts || DEFAULT_MAX_ATTEMPTS;
var random = options.random || Math.random;
var maxQtyPerLine = options.maxQtyPerLine || DEFAULT_MAX_QTY_PER_LINE;
var candidates = products.filter(function (p) {
return p.qty > 0 && p.price > 0;
});
if (candidates.length === 0) {
return null;
}
var minAcceptable = Math.max(1, targetAmount - tolerance);
for (var attempt = 0; attempt < maxAttempts; attempt++) {
var shuffled = shuffle(candidates, random);
var total = 0;
var lines = [];
for (var i = 0; i < shuffled.length; i++) {
var product = shuffled[i];
var maxQty = Math.min(maxQtyPerLine, product.qty);
var qty = 1 + Math.floor(random() * maxQty);
var lineTotal = computeLineTotal(product, qty);
if (total + lineTotal > targetAmount) {
continue;
}
total += lineTotal;
lines.push({ product_id: product.id, qty: qty });
if (total >= minAcceptable) {
break;
}
}
if (total >= minAcceptable && total <= targetAmount) {
return { lines: lines, total: total };
}
}
return null;
}
module.exports = {
pickProductCombo: pickProductCombo,
computeLineTotal: computeLineTotal,
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment