优化订单搜索和对账的批量取数与索引查询
This commit is contained in:
1 parent
3aebb62252
commit
cf0b0be83f
16 files changed
+671
-186
No files matched your search
+114
-50
@@ -10,6 +10,7 @@ const FeeEstimates = require('../public/fee-estimates');
|
||||
const CreditCardFees = require('../public/credit-card-fees');
|
||||
const CreditCardRates = require('../domains/team/credit-card-rates');
|
||||
const { orderBook } = require('../domains/orders/order-book');
|
||||
const OrderDetailRows = require('../domains/orders/order-detail-rows');
|
||||
const { reportByOrderDate, dailyFundsReceipts } = require('../domains/funds/daily-report');
|
||||
const DailyFunds = require('../domains/funds/daily-funds');
|
||||
const PriceLocks = require('../domains/price-locks/price-locks');
|
||||
@@ -525,7 +526,7 @@ class Ledger {
|
||||
return TeamFunds.report(this, query, actor, this.businessEnv());
|
||||
}
|
||||
teamProfits(query = {}, actor = this.actor) {
|
||||
return TeamProfits.report(this, query, actor, this.businessEnv());
|
||||
return this.readSnapshot(() => TeamProfits.report(this, query, actor, this.businessEnv()));
|
||||
}
|
||||
customerMaterials(query = {}, actor = this.actor) {
|
||||
return require('../domains/recoveries/customer-materials').list(this, query, actor, this.businessEnv());
|
||||
@@ -594,6 +595,18 @@ class Ledger {
|
||||
run(sql, ...args) {
|
||||
return this.db.prepare(sql).run(...args);
|
||||
}
|
||||
readSnapshot(read) {
|
||||
if (this.db.isTransaction) return read(this);
|
||||
this.db.exec('BEGIN');
|
||||
try {
|
||||
const result = read(this);
|
||||
this.db.exec('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
this.db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
meta(key, fallback = null) {
|
||||
const v = this.one('SELECT value FROM meta WHERE key=?', key);
|
||||
return v ? JSON.parse(v.value) : fallback;
|
||||
@@ -688,9 +701,13 @@ class Ledger {
|
||||
this.assertAccess('order', id, actor);
|
||||
const o = this.one('SELECT * FROM orders WHERE id=?', id);
|
||||
if (!o) fail('订单不存在', 404);
|
||||
this.#decodeOrder(o);
|
||||
if (this.teamMode) o.member = this.entityMember('order', id);
|
||||
return o;
|
||||
}
|
||||
#decodeOrder(o) {
|
||||
o.lines = JSON.parse(o.lines);
|
||||
o.fee_items = JSON.parse(o.fee_items);
|
||||
if (this.teamMode) o.member = this.entityMember('order', id);
|
||||
return o;
|
||||
}
|
||||
orderEdit(id, actor) {
|
||||
@@ -811,38 +828,67 @@ class Ledger {
|
||||
return OrderAfterSales.listLots(this, query, actor);
|
||||
}
|
||||
detail(id) {
|
||||
const o = this.rawOrder(id);
|
||||
return this.#projectOrderDetail(this.rawOrder(id));
|
||||
}
|
||||
orderDetails(ids, { includeAudit = true } = {}) {
|
||||
if (!ids.length) return [];
|
||||
return this.readSnapshot(() => this.#readOrderDetails(ids, includeAudit));
|
||||
}
|
||||
#readOrderDetails(ids, includeAudit) {
|
||||
const selectedIds = JSON.stringify(ids),
|
||||
orders = OrderDetailRows.visibleOrders(this, selectedIds),
|
||||
byId = new Map(orders.map(order => [order.id, order]));
|
||||
for (const id of ids) {
|
||||
if (byId.has(id)) continue;
|
||||
this.assertAccess('order', id);
|
||||
if (this.teamMode && this.memberFilter && this.entityMember('order', id) !== this.memberFilter)
|
||||
fail('记录不存在或无权访问', 404);
|
||||
fail('订单不存在', 404);
|
||||
}
|
||||
const records = OrderDetailRows.forOrders(this, selectedIds, orders, { includeAudit });
|
||||
return ids.map(id => {
|
||||
const source = records.get(id);
|
||||
// 重复 ID 的每份结果仍独立,和分别读取单笔一样。
|
||||
records.delete(id);
|
||||
return this.#projectOrderDetail(this.#decodeOrder({ ...byId.get(id) }), source, includeAudit);
|
||||
});
|
||||
}
|
||||
#projectOrderDetail(o, records, includeAudit = true) {
|
||||
const id = o.id;
|
||||
Object.assign(
|
||||
o,
|
||||
OrderCancellations.projection(this, id),
|
||||
OrderChanges.projection(this, id),
|
||||
OrderOwnership.projection(this, id),
|
||||
OrderCancellations.projection(this, id, records?.cancellations),
|
||||
OrderChanges.projection(this, id, records?.changes),
|
||||
OrderOwnership.projection(this, id, records?.ownership),
|
||||
);
|
||||
o.payments = this.rows('SELECT * FROM payments WHERE order_id=? ORDER BY date,created', id);
|
||||
const priceLock = this.one('SELECT * FROM price_locks WHERE final_order_id=?', id);
|
||||
o.payments = records?.payments ?? this.rows('SELECT * FROM payments WHERE order_id=? ORDER BY date,created', id);
|
||||
const priceLock = records ? records.priceLock : this.one('SELECT * FROM price_locks WHERE final_order_id=?', id);
|
||||
if (priceLock) {
|
||||
o.price_lock_id = priceLock.id;
|
||||
o.payments.push(...PriceLocks.inheritedPayments(this, id));
|
||||
o.payments.sort((a, b) => a.date.localeCompare(b.date) || a.created.localeCompare(b.created));
|
||||
}
|
||||
o.expenses = this.rows('SELECT * FROM expenses WHERE order_id=? ORDER BY date,created', id);
|
||||
o.settlements = this.rows('SELECT * FROM settlements WHERE order_id=? ORDER BY date,created', id);
|
||||
o.corrections = this.rows(
|
||||
'SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?)',
|
||||
id,
|
||||
id,
|
||||
id,
|
||||
);
|
||||
o.expenses = records?.expenses ?? this.rows('SELECT * FROM expenses WHERE order_id=? ORDER BY date,created', id);
|
||||
o.settlements =
|
||||
records?.settlements ?? this.rows('SELECT * FROM settlements WHERE order_id=? ORDER BY date,created', id);
|
||||
o.corrections =
|
||||
records?.corrections ??
|
||||
this.rows(
|
||||
'SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?)',
|
||||
id,
|
||||
id,
|
||||
id,
|
||||
);
|
||||
o.received = sum(o.payments, r => (r.kind === 'receipt' ? r.amount : 0));
|
||||
o.refunded = sum(o.payments, r => (r.kind === 'refund' ? r.amount : 0));
|
||||
o.netReceived = o.received - o.refunded;
|
||||
o.balance = (['cancelled', 'returned'].includes(o.status) ? -o.netReceived : o.total - o.netReceived) || 0;
|
||||
const orderAfterSale = OrderAfterSales.read(this, id);
|
||||
const orderAfterSale = OrderAfterSales.read(this, id, records ? (records.orderAfterSale ?? null) : undefined);
|
||||
if (orderAfterSale) {
|
||||
o.orderAfterSale = orderAfterSale;
|
||||
o.balance = 0;
|
||||
}
|
||||
const recovery = Recoveries.forOrder(this, id);
|
||||
const recovery = Recoveries.forOrder(this, id, records ? (records.recovery ?? null) : undefined);
|
||||
if (recovery) {
|
||||
o.recovery_id = recovery.id;
|
||||
o.recovery_mode = 'exchange';
|
||||
@@ -878,8 +924,9 @@ class Ledger {
|
||||
o.goodsCost === null || o.pendingFees.some(f => f.amount === null)
|
||||
? null
|
||||
: o.total - o.goodsCost - o.directCost - o.draftFees;
|
||||
const j = this.one('SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?', id);
|
||||
o.profit = o.materialCostPending && o.status === 'delivered' ? null : j.profit;
|
||||
const profit =
|
||||
records?.profit ?? this.one('SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?', id).profit;
|
||||
o.profit = o.materialCostPending && o.status === 'delivered' ? null : profit;
|
||||
o.knownProfit = o.profit ?? 0;
|
||||
o.ownerCost = o.status === 'delivered' ? Calc.orderCosts(o).byPayer.owner.goods : 0;
|
||||
if (['delivered', 'returned', 'cancelled'].includes(o.status))
|
||||
@@ -1002,15 +1049,21 @@ class Ledger {
|
||||
? o.costDue + o.profitDue - o.ownerCredit
|
||||
: 0;
|
||||
o.knownSettlementDue = o.settlementDue ?? 0;
|
||||
o.audit = this.rows(
|
||||
'SELECT action,actor,detail,created FROM audit WHERE entity=? ORDER BY id DESC LIMIT 100',
|
||||
id,
|
||||
).map(r => ({ ...r, detail: JSON.parse(r.detail) }));
|
||||
o.sync = this.one('SELECT revision,done_revision,error,updated FROM sync WHERE entity=?', 'order:' + id) || null;
|
||||
if (includeAudit) {
|
||||
const audit = records
|
||||
? (records.audit ?? [])
|
||||
: this.rows('SELECT action,actor,detail,created FROM audit WHERE entity=? ORDER BY id DESC LIMIT 100', id);
|
||||
o.audit = audit.map(r => ({ ...r, detail: JSON.parse(r.detail) }));
|
||||
}
|
||||
o.sync =
|
||||
(records
|
||||
? records.sync
|
||||
: this.one('SELECT revision,done_revision,error,updated FROM sync WHERE entity=?', 'order:' + id)) || null;
|
||||
if (this.teamMode) {
|
||||
o.funds_mode = this.one("SELECT source_id FROM team_fund_sources WHERE kind='order' AND source_id=?", id)
|
||||
? 'team'
|
||||
: 'legacy';
|
||||
const teamFunds = records
|
||||
? records.teamFunds
|
||||
: this.one("SELECT source_id FROM team_fund_sources WHERE kind='order' AND source_id=?", id);
|
||||
o.funds_mode = teamFunds ? 'team' : 'legacy';
|
||||
if (o.funds_mode === 'team') {
|
||||
o.costDue = 0;
|
||||
o.profitDue = 0;
|
||||
@@ -1018,7 +1071,12 @@ class Ledger {
|
||||
o.knownSettlementDue = 0;
|
||||
}
|
||||
}
|
||||
return { ...o, credit_card_rate_permille: CreditCardRates.read(this, 'order', id) };
|
||||
return {
|
||||
...o,
|
||||
credit_card_rate_permille: records
|
||||
? CreditCardRates.forOrder(o, records.cardRate)
|
||||
: CreditCardRates.read(this, 'order', id),
|
||||
};
|
||||
}
|
||||
validateLines(lines, historicalLines = [], businessDate = null, { orderId = null, member = null } = {}) {
|
||||
if (!Array.isArray(lines) || !lines.length || lines.length > 60) fail('每单需要1~60行商品');
|
||||
@@ -2834,21 +2892,24 @@ class Ledger {
|
||||
});
|
||||
return this.peopleCount(date, actor);
|
||||
}
|
||||
orderBook(query = {}) {
|
||||
const member = TeamMembers.queryMember(this, query, this.actor) || this.memberFilter;
|
||||
return this.scope(
|
||||
this.actor,
|
||||
() =>
|
||||
orderBook(this, query, {
|
||||
today: today(),
|
||||
validateDay: day,
|
||||
pockets: this.pocketCatalog().map(row => row.key),
|
||||
accounts: this.teamMode
|
||||
? [...new Set([...ACCOUNTS, ...this.paymentAccounts()])]
|
||||
: ACCOUNTS.filter(account => !account.startsWith('助理2')),
|
||||
}),
|
||||
member,
|
||||
);
|
||||
orderBook(query = {}, { getOrderDetails } = {}) {
|
||||
return this.readSnapshot(() => {
|
||||
const member = TeamMembers.queryMember(this, query, this.actor) || this.memberFilter;
|
||||
return this.scope(
|
||||
this.actor,
|
||||
() =>
|
||||
orderBook(this, query, {
|
||||
today: today(),
|
||||
validateDay: day,
|
||||
pockets: this.pocketCatalog().map(row => row.key),
|
||||
accounts: this.teamMode
|
||||
? [...new Set([...ACCOUNTS, ...this.paymentAccounts()])]
|
||||
: ACCOUNTS.filter(account => !account.startsWith('助理2')),
|
||||
getOrderDetails,
|
||||
}),
|
||||
member,
|
||||
);
|
||||
});
|
||||
}
|
||||
reportFor(query = {}, actor = this.actor) {
|
||||
const date = query.date || today(),
|
||||
@@ -2899,9 +2960,12 @@ class Ledger {
|
||||
return DailyFunds.report(this, query, actor, this.businessEnv(), date => dailyFundsReceipts(this, date));
|
||||
}
|
||||
reportByOrderDate(date, from = date, actor = null) {
|
||||
return reportByOrderDate(this, date, from, actor, this.businessEnv());
|
||||
return this.readSnapshot(() => reportByOrderDate(this, date, from, actor, this.businessEnv()));
|
||||
}
|
||||
report(date, from = date) {
|
||||
report(date, from = date, { getOrderDetails = ids => this.orderDetails(ids, { includeAudit: false }) } = {}) {
|
||||
return this.readSnapshot(() => this.#report(date, from, getOrderDetails));
|
||||
}
|
||||
#report(date, from, getOrderDetails) {
|
||||
day(date);
|
||||
day(from);
|
||||
if (from > date) fail('开始日期不能晚于结束日期');
|
||||
@@ -2942,9 +3006,8 @@ class Ledger {
|
||||
'after_sale',
|
||||
this.rows('SELECT * FROM after_sales WHERE date>=? AND date<=? ORDER BY date,created,id', from, date),
|
||||
);
|
||||
const orders = this.visibleRows('order', this.rows('SELECT id FROM orders ORDER BY created DESC')).map(r =>
|
||||
this.detail(r.id),
|
||||
);
|
||||
const orderIds = this.visibleRows('order', this.rows('SELECT id FROM orders ORDER BY created DESC')).map(r => r.id);
|
||||
const orders = getOrderDetails(orderIds);
|
||||
const accounts = ACCOUNTS.map(account => ({
|
||||
account,
|
||||
receipt: sum(payments, p => (p.account === account && p.kind === 'receipt' ? p.amount : 0)),
|
||||
@@ -2983,8 +3046,9 @@ class Ledger {
|
||||
const close = this.one('SELECT * FROM closes WHERE date=?', date),
|
||||
poolSettlement = this.materialPoolSettlement(),
|
||||
poolActivity = this.materialPoolReporting({ from, to: date });
|
||||
const journalOrderIds = new Set(j.map(row => row.order_id));
|
||||
const pendingMaterialOrders = orders.filter(
|
||||
o => o.status === 'delivered' && o.materialCostPending && j.some(row => row.order_id === o.id),
|
||||
o => o.status === 'delivered' && o.materialCostPending && journalOrderIds.has(o.id),
|
||||
);
|
||||
const hasPendingSettlement = orders.some(o => o.settlementDue === null) || poolSettlement.pendingCount > 0;
|
||||
const pendingIds = new Set(pendingMaterialOrders.map(order => order.id));
|
||||
|
||||
Reference in new issue
Block a user