优化订单搜索和对账的批量取数与索引查询
This commit is contained in:
1 parent
3aebb62252
commit
cf0b0be83f
16 files changed
+671
-186
No files matched your search
@@ -4,6 +4,7 @@ const Calc = require('../../public/calculations');
|
||||
const TeamMembers = require('../team/team-members');
|
||||
const Amounts = require('../materials/material-member-amounts');
|
||||
const OrderAfterSaleReporting = require('./order-after-sale-reporting');
|
||||
const PrintStatus = require('../printing/print-status');
|
||||
const AMOUNTS = [
|
||||
'sale',
|
||||
'material',
|
||||
@@ -56,7 +57,7 @@ function lineType(line, pocketLabel = key => key) {
|
||||
return source + (Calc.isSilver(line.name) ? ' · 银饰' : '');
|
||||
}
|
||||
|
||||
function orderRow(order, pocketLabel, members = []) {
|
||||
function orderRow(order, pocketLabel) {
|
||||
const draft = order.status === 'draft',
|
||||
excluded = ['returned', 'cancelled'].includes(order.status);
|
||||
const materialPoolIds = [
|
||||
@@ -225,7 +226,7 @@ function orderRow(order, pocketLabel, members = []) {
|
||||
};
|
||||
}
|
||||
|
||||
function afterSaleRow(record, members = []) {
|
||||
function afterSaleRow(record) {
|
||||
const known = {
|
||||
sale: 0,
|
||||
material: 0,
|
||||
@@ -323,6 +324,23 @@ function compareDisplay(a, b) {
|
||||
);
|
||||
}
|
||||
|
||||
function sortDisplay(ledger, entries) {
|
||||
const entities = entries.flatMap(entry => (entry.creation ? [entry.creation] : []));
|
||||
if (entities.length) {
|
||||
const rows = ledger.rows(
|
||||
`SELECT a.entity,a.action,MIN(a.id) AS sequence FROM audit a
|
||||
WHERE (a.entity,a.action) IN (SELECT value->>0,value->>1 FROM json_each(?))
|
||||
GROUP BY a.entity,a.action`,
|
||||
JSON.stringify(entities),
|
||||
);
|
||||
// 同毫秒按原创建审计编号排序;没有旧审计时以原表插入次序稳定回退。
|
||||
const sequences = new Map(rows.map(row => [`${row.entity}\0${row.action}`, row.sequence]));
|
||||
for (const entry of entries)
|
||||
if (entry.creation) entry.sequence = sequences.get(entry.creation.join('\0')) ?? entry.sequence;
|
||||
}
|
||||
return entries.sort(compareDisplay);
|
||||
}
|
||||
|
||||
function summarize(rows) {
|
||||
const orders = rows.filter(row => !['afterSale', 'orderAfterSale'].includes(row.kind)),
|
||||
actualOrders = orders.filter(row => row.status !== 'draft');
|
||||
@@ -551,18 +569,16 @@ function materialPoolActivity(ledger, from, date) {
|
||||
};
|
||||
}
|
||||
|
||||
function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
const pocketLabel = typeof ledger.pocketLabel === 'function' ? key => ledger.pocketLabel(key) : key => key;
|
||||
const date = validateDay(query.date ?? today),
|
||||
from = validateDay(query.from ?? date);
|
||||
if (from > date) invalid('开始日期不能晚于结束日期');
|
||||
const status = String(query.status ?? 'all');
|
||||
if (!STATUSES.includes(status)) invalid('订单状态无效');
|
||||
const pocket = query.pocket ?? '';
|
||||
if (typeof pocket !== 'string' || (pocket && pocket !== 'external' && !pockets.includes(pocket)))
|
||||
invalid('出货货盘筛选无效');
|
||||
const q = String(query.q ?? '').trim();
|
||||
if (q.length > 100) invalid('搜索内容请填写不超过100字');
|
||||
function projectFinancialRows(
|
||||
ledger,
|
||||
{ from, date, status = 'all', pocket = '', q = '', includeLockActivity = false },
|
||||
getOrderDetails = ids => ledger.orderDetails(ids, { includeAudit: false }),
|
||||
) {
|
||||
const pocketLabels = new Map();
|
||||
const pocketLabel = key => {
|
||||
if (!pocketLabels.has(key)) pocketLabels.set(key, ledger.pocketLabel(key));
|
||||
return pocketLabels.get(key);
|
||||
};
|
||||
const terms = q.toLocaleLowerCase('zh-CN'),
|
||||
weight = weightSearch(q),
|
||||
matchesText = values =>
|
||||
@@ -573,18 +589,7 @@ function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
.toLocaleLowerCase('zh-CN')
|
||||
.includes(terms),
|
||||
));
|
||||
// 旧读取顺序仅用于保持收款投影兼容;显示行在合并售后后按真实创建先后排序。
|
||||
const orderSources = ledger.visibleRows(
|
||||
'order',
|
||||
ledger.rows(
|
||||
"SELECT o.id,o.rowid AS position,(SELECT MIN(a.id) FROM audit a WHERE a.entity=o.id AND a.action='保存草稿') AS creation_sequence FROM orders o WHERE o.date>=? AND o.date<=? ORDER BY o.date DESC,o.paper_number DESC,o.created DESC,o.id",
|
||||
from,
|
||||
date,
|
||||
),
|
||||
);
|
||||
const positions = new Map(orderSources.map(row => [row.id, row.creation_sequence ?? row.position]));
|
||||
const sourceOrders = orderSources.map(row => ledger.detail(row.id));
|
||||
const orders = sourceOrders.filter(order => {
|
||||
const matchesOrder = (order, lines) => {
|
||||
if (['reviewed', 'unreviewed'].includes(status)) {
|
||||
const reviewed =
|
||||
Number.isSafeInteger(order.revision) && order.revision > 0 && order.reviewed_revision === order.revision;
|
||||
@@ -592,14 +597,13 @@ function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
} else if (status === 'price_lock') {
|
||||
if (!order.price_lock_id) return false;
|
||||
} else if (status !== 'all' && order.status !== status) return false;
|
||||
if (!pocket && !q) return true;
|
||||
// 一个商品行匹配就纳入整单,克重、金额和收款仍按整单汇总。
|
||||
if (pocket && !order.lines.some(line => (pocket === 'external' ? !line.pocket : line.pocket === pocket)))
|
||||
return false;
|
||||
const items = lines();
|
||||
if (pocket && !items.some(line => (pocket === 'external' ? !line.pocket : line.pocket === pocket))) return false;
|
||||
if (!q) return true;
|
||||
return (
|
||||
matchesWeight(
|
||||
weight,
|
||||
order.lines.filter(line => line.unit === 'g').map(line => line.quantity),
|
||||
) ||
|
||||
matchesWeight(weight, weight ? items.filter(line => line.unit === 'g').map(line => line.quantity) : []) ||
|
||||
matchesText([
|
||||
order.number,
|
||||
order.paper_number,
|
||||
@@ -607,17 +611,52 @@ function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
order.note,
|
||||
order.salesperson,
|
||||
...(order.recovery_id ? ['置换'] : []),
|
||||
...order.lines.flatMap(line => [line.name, line.code, line.pocket, pocketLabel(line.pocket)]),
|
||||
...items.flatMap(line => [line.name, line.code, line.pocket, pocketLabel(line.pocket)]),
|
||||
])
|
||||
);
|
||||
});
|
||||
};
|
||||
// 保持订单日收款汇总的读取顺序。显示行在合并售后后按真实创建顺序排列。
|
||||
const member = ledger.teamMode && ledger.queryMember();
|
||||
const searchFields = q || pocket ? ',o.number,o.paper_number,o.customer,o.note,o.salesperson,o.lines' : '';
|
||||
const orderSources = ledger.rows(
|
||||
`SELECT o.id,o.status,o.revision,o.reviewed_revision,o.rowid AS position,l.id AS price_lock_id,
|
||||
r.id AS recovery_id,a.order_id AS after_sale_order_id${searchFields}
|
||||
FROM orders o
|
||||
LEFT JOIN price_locks l ON l.final_order_id=o.id
|
||||
LEFT JOIN recoveries r ON r.order_id=o.id
|
||||
LEFT JOIN order_after_sales a ON a.order_id=o.id
|
||||
WHERE o.date>=? AND o.date<=?
|
||||
${member ? "AND o.id IN (SELECT entity_id FROM team_entities WHERE kind='order' AND member=?)" : ''}
|
||||
ORDER BY o.date DESC,o.paper_number DESC,o.created DESC,o.id`,
|
||||
from,
|
||||
date,
|
||||
...(member ? [member] : []),
|
||||
);
|
||||
const positions = new Map(orderSources.map(row => [row.id, row.position]));
|
||||
// 锁价交付的支出和售后保存的原单仍参与整段日期的活动。置换继续使用完整详情判断关联信息。
|
||||
const detailIds = orderSources
|
||||
.filter(
|
||||
row =>
|
||||
(includeLockActivity && (row.price_lock_id || row.after_sale_order_id)) ||
|
||||
row.recovery_id ||
|
||||
matchesOrder(row, () => JSON.parse(row.lines)),
|
||||
)
|
||||
.map(row => row.id);
|
||||
const sourceOrders = getOrderDetails(detailIds);
|
||||
const orders = sourceOrders.filter(order => matchesOrder(order, () => order.lines));
|
||||
const originalOrders = new Map(
|
||||
sourceOrders.map(order => [
|
||||
order.id,
|
||||
order.orderAfterSale ? OrderAfterSaleReporting.originalOrder(ledger, order) : order,
|
||||
]),
|
||||
);
|
||||
const afterSales =
|
||||
!pocket && ['all', 'after_sale'].includes(status)
|
||||
? ledger
|
||||
.visibleRows(
|
||||
'after_sale',
|
||||
ledger.rows(
|
||||
"SELECT s.*,COALESCE(v.revision,1) AS revision,s.rowid AS position,(SELECT MIN(a.id) FROM audit a WHERE a.entity='after-sale:'||s.id AND a.action='登记售后') AS creation_sequence FROM after_sales s LEFT JOIN after_sale_revisions v ON v.after_sale_id=s.id WHERE s.date>=? AND s.date<=? ORDER BY s.date DESC,s.created DESC,s.id",
|
||||
'SELECT s.*,COALESCE(v.revision,1) AS revision,s.rowid AS position FROM after_sales s LEFT JOIN after_sale_revisions v ON v.after_sale_id=s.id WHERE s.date>=? AND s.date<=? ORDER BY s.date DESC,s.created DESC,s.id',
|
||||
from,
|
||||
date,
|
||||
),
|
||||
@@ -640,13 +679,50 @@ function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
]),
|
||||
)
|
||||
: [];
|
||||
const entries = [
|
||||
...orders.map(order => ({
|
||||
row: orderRow(originalOrders.get(order.id), pocketLabel),
|
||||
creation: [order.id, '保存草稿'],
|
||||
sequence: positions.get(order.id),
|
||||
})),
|
||||
...afterSales.map(record => ({
|
||||
row: afterSaleRow(record),
|
||||
creation: ['after-sale:' + record.id, '登记售后'],
|
||||
sequence: record.position,
|
||||
})),
|
||||
...orderAfterSales.map(record => ({ row: OrderAfterSaleReporting.financialRow(ledger, record), sequence: 0 })),
|
||||
];
|
||||
return { entries, orders, originalOrders, orderAfterSales, matchesText, weight };
|
||||
}
|
||||
|
||||
function orderBookRows(ledger, from, date) {
|
||||
const { entries } = projectFinancialRows(ledger, { from, date });
|
||||
return sortDisplay(ledger, entries).map(entry => entry.row);
|
||||
}
|
||||
|
||||
function orderBook(ledger, query, { today, validateDay, accounts, pockets, getOrderDetails }) {
|
||||
const date = validateDay(query.date ?? today),
|
||||
from = validateDay(query.from ?? date);
|
||||
if (from > date) invalid('开始日期不能晚于结束日期');
|
||||
const status = String(query.status ?? 'all');
|
||||
if (!STATUSES.includes(status)) invalid('订单状态无效');
|
||||
const pocket = query.pocket ?? '';
|
||||
if (typeof pocket !== 'string' || (pocket && pocket !== 'external' && !pockets.includes(pocket)))
|
||||
invalid('出货货盘筛选无效');
|
||||
const q = String(query.q ?? '').trim();
|
||||
if (q.length > 100) invalid('搜索内容请填写不超过100字');
|
||||
const { entries, orders, originalOrders, orderAfterSales, matchesText, weight } = projectFinancialRows(
|
||||
ledger,
|
||||
{ from, date, status, pocket, q, includeLockActivity: true },
|
||||
getOrderDetails,
|
||||
);
|
||||
const recoveries =
|
||||
!pocket && ['all', 'recovery'].includes(status)
|
||||
? ledger
|
||||
.visibleRows(
|
||||
'recovery',
|
||||
ledger.rows(
|
||||
"SELECT r.*,r.rowid AS position,(SELECT MIN(a.id) FROM audit a WHERE a.entity='recovery:'||r.id AND a.action='登记直接回收') AS creation_sequence FROM recoveries r WHERE r.mode='direct' AND r.status='active' AND r.date>=? AND r.date<=? ORDER BY r.created,r.rowid",
|
||||
"SELECT r.*,r.rowid AS position FROM recoveries r WHERE r.mode='direct' AND r.status='active' AND r.date>=? AND r.date<=? ORDER BY r.created,r.rowid",
|
||||
from,
|
||||
date,
|
||||
),
|
||||
@@ -670,46 +746,21 @@ function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
);
|
||||
})
|
||||
: [];
|
||||
// 同毫秒创建的记录按原创建审计编号排序;没有旧审计时以原表插入次序稳定回退。
|
||||
const displayed = [
|
||||
...orders.map(order => ({
|
||||
row: orderRow(OrderAfterSaleReporting.originalOrder(ledger, order), pocketLabel, TeamMembers.keys(ledger)),
|
||||
sequence: positions.get(order.id),
|
||||
})),
|
||||
...afterSales.map(record => ({
|
||||
row: afterSaleRow(record, TeamMembers.keys(ledger)),
|
||||
sequence: record.creation_sequence ?? record.position,
|
||||
})),
|
||||
...orderAfterSales.map(record => ({ row: OrderAfterSaleReporting.financialRow(ledger, record), sequence: 0 })),
|
||||
];
|
||||
displayed.sort(compareDisplay);
|
||||
const rows = displayed.map(record => record.row);
|
||||
// 财务行与汇总继续沿用原口径;直接回收只加入订单页显示,不能改变日报和已复核快照。
|
||||
const displayRows = [
|
||||
...displayed,
|
||||
...recoveries.map(record => ({ row: recoveryRow(record), sequence: record.creation_sequence ?? record.position })),
|
||||
]
|
||||
.sort(compareDisplay)
|
||||
.map(record => {
|
||||
const row = record.row.current_status ? { ...record.row, status: record.row.current_status } : record.row;
|
||||
return ['afterSale', 'orderAfterSale'].includes(row.kind)
|
||||
? row
|
||||
: {
|
||||
...row,
|
||||
printStatus: require('../printing/print-status').projection(
|
||||
ledger,
|
||||
row.kind === 'recovery' ? 'recovery' : 'order',
|
||||
row.id,
|
||||
),
|
||||
};
|
||||
});
|
||||
const priceLockActivity = lockActivity(
|
||||
const displayed = sortDisplay(ledger, [
|
||||
...entries,
|
||||
...recoveries.map(record => ({
|
||||
row: recoveryRow(record),
|
||||
creation: ['recovery:' + record.id, '登记直接回收'],
|
||||
sequence: record.position,
|
||||
})),
|
||||
]);
|
||||
const rows = displayed.filter(entry => entry.row.kind !== 'recovery').map(entry => entry.row);
|
||||
const displayRows = PrintStatus.displayRows(
|
||||
ledger,
|
||||
from,
|
||||
date,
|
||||
accounts,
|
||||
sourceOrders.map(order => OrderAfterSaleReporting.originalOrder(ledger, order)),
|
||||
displayed.map(({ row }) => (row.current_status ? { ...row, status: row.current_status } : row)),
|
||||
);
|
||||
const priceLockActivity = lockActivity(ledger, from, date, accounts, [...originalOrders.values()]);
|
||||
const poolActivity = materialPoolActivity(ledger, from, date);
|
||||
const lockCash = [...priceLockActivity.customerCash, ...priceLockActivity.orderPayments];
|
||||
const matchingFinalLocks = new Set(orders.filter(order => order.price_lock_id).map(order => order.price_lock_id));
|
||||
@@ -734,7 +785,9 @@ function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
.filter(order => !order.price_lock_id)
|
||||
.flatMap(order =>
|
||||
order.payments.filter(
|
||||
payment => !payment.price_lock_event_id && !OrderAfterSaleReporting.isPayment(ledger, payment),
|
||||
payment =>
|
||||
!payment.price_lock_event_id &&
|
||||
!OrderAfterSaleReporting.addedEntry(order.orderAfterSale, payment, 'payments'),
|
||||
),
|
||||
);
|
||||
const matchingAfterSaleIds = new Set(orderAfterSales.map(record => record.order_id));
|
||||
@@ -786,4 +839,4 @@ function orderBook(ledger, query, { today, validateDay, accounts, pockets }) {
|
||||
},
|
||||
};
|
||||
}
|
||||
module.exports = { orderBook };
|
||||
module.exports = { orderBook, orderBookRows };
|
||||
Reference in new issue
Block a user