采购单优化

This commit is contained in:
liu
2026-08-12 14:38:20 +08:00
parent ce1f36b5b4
commit dadfdc1511
30 changed files with 1059 additions and 1441 deletions
-113
View File
@@ -1,113 +0,0 @@
<?php
namespace App\Services;
use App\Exceptions\RepositoryException;
use App\Models\PurchaseAllocationModel;
use App\Models\PurchaseOrderItemModel;
use App\Models\PurchaseOrderModel;
use App\Models\StoreOrderItemModel;
use Illuminate\Support\Facades\DB;
/**
* D3 采购金额分摊
*
* 流程(事务内):
* 1. 采购单须已录入实际金额(存在 amount>0 的明细),否则拒绝
* 2. 每个采购明细按 purchase_id 溯源该采购单合并的门店订单明细(生成采购单时回写)
* 3. 按订货数量比例分摊实际金额/数量/重量:bcmul(item.amount, bcdiv(item_qty, total_qty, 6), 2)
* 尾差修正——最后一行承担舍入差额,保证 Σallocation.amount === item.amount(金额守恒)
* 4. 重复分摊先删旧记录再重建(幂等)
*/
class PurchaseAllocateService
{
/**
* @return int 生成的分摊记录数
*/
public function allocate(PurchaseOrderModel $purchase): int
{
return DB::transaction(function () use ($purchase) {
$items = PurchaseOrderItemModel::query()
->where('purchase_id', $purchase->id)
->lockForUpdate()
->get();
// 1. 须已录入实际金额
if (! $items->contains(static fn ($item) => (float) $item->amount > 0)) {
throw new RepositoryException('采购单尚未录入实际金额,无法分摊');
}
// 2. 按 purchase_id 溯源本采购单合并的门店订单明细,按商品分组
$orderItems = StoreOrderItemModel::query()
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
->where('store_order.purchase_id', $purchase->id)
->whereNull('store_order.deleted_at')
->select('store_order_item.*')
->get()
->groupBy('product_id');
// 4. 幂等:删除旧分摊记录
PurchaseAllocationModel::query()
->whereIn('purchase_item_id', $items->pluck('id'))
->delete();
$count = 0;
$now = now();
foreach ($items as $item) {
$sources = $orderItems->get((int) $item->product_id);
if ($sources === null || $sources->isEmpty()) {
continue;
}
$totalQty = $sources->reduce(
static fn (string $carry, $orderItem): string => bcadd($carry, (string) $orderItem->quantity, 2),
'0'
);
if ((float) $totalQty <= 0) {
continue;
}
$sourceValues = $sources->values();
$lastIndex = $sourceValues->count() - 1;
$allocatedAmount = '0';
$allocatedQuantity = '0';
$allocatedWeight = '0';
$records = [];
foreach ($sourceValues as $index => $orderItem) {
if ($index === $lastIndex) {
// 3. 尾差修正:最后一行 = 总额 − 已分摊,保证守恒
$amount = bcsub((string) $item->amount, $allocatedAmount, 2);
$quantity = bcsub((string) $item->quantity, $allocatedQuantity, 2);
$weight = bcsub((string) $item->weight, $allocatedWeight, 3);
} else {
$ratio = bcdiv((string) $orderItem->quantity, $totalQty, 6);
$amount = bcmul((string) $item->amount, $ratio, 2);
$quantity = bcmul((string) $item->quantity, $ratio, 2);
$weight = bcmul((string) $item->weight, $ratio, 3);
$allocatedAmount = bcadd($allocatedAmount, $amount, 2);
$allocatedQuantity = bcadd($allocatedQuantity, $quantity, 2);
$allocatedWeight = bcadd($allocatedWeight, $weight, 3);
}
$records[] = [
'purchase_item_id' => $item->id,
'order_item_id' => $orderItem->id,
'store_id' => $orderItem->store_id,
'product_id' => $item->product_id,
'quantity' => $quantity,
'weight' => $weight,
'amount' => $amount,
'created_at' => $now,
'updated_at' => $now,
];
}
PurchaseAllocationModel::insert($records);
$count += count($records);
}
return $count;
});
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
namespace App\Services;
use App\Exceptions\RepositoryException;
use App\Models\PurchaseOrderModel;
use App\Models\StoreOrderItemModel;
use App\Models\StoreOrderModel;
use Illuminate\Support\Facades\DB;
/**
* C4 采购单数据修改(明细矩阵:门店单元格 / 商品行)
*
* 采购单无独立明细表,修改直接回写订货明细(store_order_item),并重算:
* 1. 受影响订单汇总(recalculateOrderTotals 同口径:商品金额 + 附加金额)
* 2. 采购单头汇总:estimate_amount = Σ订货金额;actual_amount = Σ(称重>0 ? 称重×成本 : 数量×成本)
*/
class PurchaseEditService
{
/**
* 门店单元格修改:数量(必填)/ 称重(可空),金额按 数量×单价 重算
*/
public function updateCell(StoreOrderItemModel $item, int $quantity, ?float $weight): StoreOrderItemModel
{
return DB::transaction(function () use ($item, $quantity, $weight) {
$item->quantity = $quantity;
if ($weight !== null) {
$item->weight = bcadd((string) $weight, '0', 3);
}
$item->amount = bcmul((string) $quantity, (string) $item->price, 2);
$item->save();
$order = StoreOrderModel::find($item->order_id);
if ($order !== null) {
$this->recalculateOrderTotals($order);
}
if ($item->purchase_id > 0) {
$purchase = PurchaseOrderModel::find($item->purchase_id);
if ($purchase !== null) {
$this->recalculatePurchaseTotals($purchase);
}
}
return $item->refresh();
});
}
/**
* 商品行修改:采购成本(写入该商品全部订货明细)/ 实际称重(按数量比例分摊,尾差修正守恒)
*
* @param float|null $costPrice 采购成本(每包规),NULL 不修改
* @param float|null $weight 行实际称重合计,NULL 不修改
*/
public function updateRow(PurchaseOrderModel $purchase, int $productId, ?float $costPrice, ?float $weight): int
{
return DB::transaction(function () use ($purchase, $productId, $costPrice, $weight) {
$items = StoreOrderItemModel::query()
->where('purchase_id', $purchase->id)
->where('product_id', $productId)
->lockForUpdate()
->get();
if ($items->isEmpty()) {
throw new RepositoryException('该采购单下无此商品的订货明细');
}
if ($costPrice !== null) {
$cost = bcadd((string) $costPrice, '0', 2);
foreach ($items as $item) {
$item->cost_price = $cost;
$item->save();
}
}
if ($weight !== null) {
$totalQty = $items->reduce(
static fn (string $carry, $item): string => bcadd($carry, (string) $item->quantity, 2),
'0'
);
$target = bcadd((string) $weight, '0', 3);
$allocated = '0';
$lastIndex = $items->count() - 1;
foreach ($items->values() as $index => $item) {
if ($index === $lastIndex) {
// 尾差修正:最后一行 = 总称重 − 已分摊,保证守恒
$rowWeight = bcsub($target, $allocated, 3);
} elseif ((float) $totalQty > 0) {
$ratio = bcdiv((string) $item->quantity, $totalQty, 6);
$rowWeight = bcmul($target, $ratio, 3);
$allocated = bcadd($allocated, $rowWeight, 3);
} else {
$rowWeight = '0';
}
$item->weight = $rowWeight;
$item->save();
}
}
$orderIds = $items->pluck('order_id')->unique()->all();
StoreOrderModel::whereIn('id', $orderIds)->get()
->each(fn (StoreOrderModel $order) => $this->recalculateOrderTotals($order));
$this->recalculatePurchaseTotals($purchase);
return $items->count();
});
}
/**
* 重算订单汇总(与 StoreOrderController::recalculateOrderTotals 同口径)
*/
public function recalculateOrderTotals(StoreOrderModel $order): void
{
$totals = StoreOrderItemModel::query()
->where('order_id', $order->id)
->selectRaw('COALESCE(SUM(quantity), 0) as total_quantity')
->selectRaw('COALESCE(SUM(weight), 0) as total_weight')
->selectRaw('COALESCE(SUM(amount), 0) as product_amount')
->first();
$productAmount = bcadd((string) $totals->product_amount, '0', 2);
$order->total_quantity = (int) $totals->total_quantity;
$order->total_weight = bcadd((string) $totals->total_weight, '0', 3);
$order->product_amount = $productAmount;
$order->total_amount = bcadd($productAmount, (string) $order->added_amount, 2);
$order->save();
}
/**
* 重算采购单头汇总:estimate_amount = Σ订货金额(销售口径);
* actual_amount = Σ(称重>0 ? 称重×成本 : 数量×成本)(采购成本口径)
*/
public function recalculatePurchaseTotals(PurchaseOrderModel $purchase): void
{
$items = StoreOrderItemModel::query()
->where('purchase_id', $purchase->id)
->get(['quantity', 'weight', 'amount', 'cost_price', 'product_spec']);
$totalQuantity = '0';
$totalWeight = '0';
$estimate = '0';
$actual = '0';
foreach ($items as $item) {
$unitCost = self::unitCost((string) ($item->cost_price ?? '0'), (string) $item->product_spec);
$totalQuantity = bcadd($totalQuantity, (string) $item->quantity, 2);
$totalWeight = bcadd($totalWeight, (string) $item->weight, 3);
$estimate = bcadd($estimate, (string) $item->amount, 2);
$actual = bcadd($actual, self::costAmount((string) $item->quantity, (string) $item->weight, $unitCost), 2);
}
$purchase->total_quantity = $totalQuantity;
$purchase->total_weight = $totalWeight;
$purchase->estimate_amount = $estimate;
$purchase->actual_amount = $actual;
$purchase->save();
}
/**
* 采购成本金额:称重>0 按 称重×单价,否则按 数量×单价
*/
public static function costAmount(string $quantity, string $weight, string $unitCost): string
{
return (float) $weight > 0
? bcmul($weight, $unitCost, 2)
: bcmul($quantity, $unitCost, 2);
}
/**
* 单价 = 成本 / 包规数值(spec 解析不出正数时按 1 处理,即单价=成本)
*/
public static function unitCost(string $costPrice, string $spec): string
{
if (preg_match('/\d+(?:\.\d+)?/', $spec, $matches) === 1 && (float) $matches[0] > 0) {
return bcdiv($costPrice, $matches[0], 2);
}
return bcadd($costPrice, '0', 2);
}
}
+15 -108
View File
@@ -3,10 +3,8 @@
namespace App\Services;
use App\Exceptions\RepositoryException;
use App\Models\ProductModel;
use App\Models\ProductPriceModel;
use App\Models\PurchaseOrderItemModel;
use App\Models\PurchaseOrderModel;
use App\Models\StoreOrderItemModel;
use App\Models\StoreOrderModel;
use Illuminate\Support\Facades\DB;
@@ -15,11 +13,9 @@ use Illuminate\Support\Facades\DB;
*
* 流程(事务内):
* 1. 行锁「已接单」订单(可传 orderIds 只合并指定订单;状态条件天然排除已归集订单,幂等)
* 2. 展开明细按商品聚合(Σquantity,快照品名/规格;供应商取商品默认供应商
* 3. 估算单价 = 该商品最低实际等级价(按计价类型换算后取 min,PHP 侧兼容 MySQL/SQLite),amount = quantity × 估算单价
* 4. 创建采购单头(PO 单号,estimate_amount = Σitems.amount
* 5. 明细按「分类 sort → 商品 sort」排序写入 sort 行号
* 6. 源订单批量回写 status = 采购中、purchase_id = 采购单ID(分摊按 purchase_id 溯源)
* 2. 创建采购单头(PO 单号;total_quantity / estimate_amount 取订货明细汇总
* 3. 源订单批量回写 status = 采购中、purchase_id = 采购单ID
* 订货明细同步回写 purchase_id(采购明细直接溯源订货明细,无独立采购明细表
*/
class PurchaseGenerateService
{
@@ -53,96 +49,23 @@ class PurchaseGenerateService
throw new RepositoryException('无已接单订单,无法生成采购单');
}
// 2. 展开明细按商品聚合
$aggregated = [];
$sourceOrderIds = [];
foreach ($orders as $order) {
$sourceOrderIds[] = $order->id;
foreach ($order->items as $item) {
$productId = (int) $item->product_id;
if (! isset($aggregated[$productId])) {
$aggregated[$productId] = [
'product_id' => $productId,
'product_name' => $item->product_name,
'product_spec' => $item->product_spec,
'quantity' => '0',
];
}
$aggregated[$productId]['quantity'] = bcadd(
$aggregated[$productId]['quantity'],
(string) $item->quantity,
2
);
}
}
$sourceOrderIds = $orders->pluck('id')->all();
if ($aggregated === []) {
// 2. 订货明细汇总(采购单头数据)
$items = StoreOrderItemModel::query()->whereIn('order_id', $sourceOrderIds)->get();
if ($items->isEmpty()) {
throw new RepositoryException('已接单订单均无明细,无法生成采购单');
}
$products = ProductModel::withTrashed()
->with('category:id,sort')
->whereIn('id', array_keys($aggregated))
->get()
->keyBy('id');
// 3. 估算单价 = 最低实际等级价(逐行按计价类型换算后取 min;数量级 = 当日 SKU × 等级,可控)
$priceRows = ProductPriceModel::query()
->whereIn('product_id', array_keys($aggregated))
->get(['product_id', 'price', 'price_type', 'percent'])
->groupBy('product_id');
$minPrices = [];
foreach ($aggregated as $productId => $item) {
$product = $products->get($productId);
$minPrice = null;
foreach ($priceRows->get($productId, collect()) as $priceRow) {
$actual = ProductPriceModel::calcActualPrice(
(int) $priceRow->price_type,
$priceRow->price,
$priceRow->percent,
(float) ($product->cost_price ?? 0),
);
if ($minPrice === null || bccomp($actual, $minPrice, 2) < 0) {
$minPrice = $actual;
}
}
$minPrices[$productId] = $minPrice ?? '0';
}
// 组装明细行并按「分类 sort → 商品 sort」排序
$rows = [];
foreach ($aggregated as $productId => $item) {
$product = $products->get($productId);
$price = (string) ($minPrices[$productId] ?? '0');
$rows[] = [
'product_id' => $productId,
'supplier_id' => (int) ($product->supplier_id ?? 0),
'product_name' => $item['product_name'],
'product_spec' => $item['product_spec'],
'price' => $price,
'quantity' => $item['quantity'],
'amount' => bcmul($item['quantity'], $price, 2),
'category_sort' => (int) ($product->category->sort ?? 9999),
'product_sort' => (int) ($product->sort ?? 9999),
];
}
usort($rows, static fn (array $a, array $b): int =>
[$a['category_sort'], $a['product_sort'], $a['product_id']]
<=> [$b['category_sort'], $b['product_sort'], $b['product_id']]);
$estimateAmount = array_reduce(
$rows,
static fn (string $carry, array $row): string => bcadd($carry, $row['amount'], 2),
$totalQuantity = $items->reduce(
static fn (string $carry, $item): string => bcadd($carry, (string) $item->quantity, 2),
'0'
);
$totalQuantity = array_reduce(
$rows,
static fn (string $carry, array $row): string => bcadd($carry, $row['quantity'], 2),
$estimateAmount = $items->reduce(
static fn (string $carry, $item): string => bcadd($carry, (string) $item->amount, 2),
'0'
);
// 4. 采购单头
$purchase = PurchaseOrderModel::create([
'purchase_no' => $this->billNumberService->make('PO'),
'purchase_date' => $date,
@@ -154,30 +77,14 @@ class PurchaseGenerateService
'operator_id' => $operatorId,
]);
// 5. 采购明细(sort 行号)
$sort = 1;
foreach ($rows as $row) {
PurchaseOrderItemModel::create([
'purchase_id' => $purchase->id,
'product_id' => $row['product_id'],
'supplier_id' => $row['supplier_id'],
'product_name' => $row['product_name'],
'product_spec' => $row['product_spec'],
'price' => $row['price'],
'quantity' => $row['quantity'],
'weight' => 0,
'amount' => $row['amount'],
'sort' => $sort++,
'is_sent' => PurchaseOrderItemModel::NOT_SENT,
]);
}
// 6. 源订单回写「采购中」并关联采购单(分摊按 purchase_id 溯源)
// 3. 源订单回写「采购中」并关联采购单;订货明细同步回写 purchase_id
StoreOrderModel::whereIn('id', $sourceOrderIds)
->update([
'status' => StoreOrderModel::STATUS_DELIVERING,
'purchase_id' => $purchase->id,
]);
StoreOrderItemModel::whereIn('order_id', $sourceOrderIds)
->update(['purchase_id' => $purchase->id]);
return $purchase;
});
+54 -71
View File
@@ -5,25 +5,22 @@ namespace App\Services;
use App\Exceptions\RepositoryException;
use App\Models\ProductCategoryModel;
use App\Models\ProductModel;
use App\Models\PurchaseAllocationModel;
use App\Models\PurchaseOrderItemModel;
use App\Models\PurchaseOrderModel;
use App\Models\ReconciliationItemModel;
use App\Models\ReconciliationModel;
use App\Models\StoreOrderItemModel;
use App\Models\StoreOrderModel;
use Illuminate\Support\Facades\DB;
/**
* 对账明细构建(D1 品类 / D2 供应商筛选)
*
* 流程(事务内,可重复 build:先清后建):
* 1. 按周期 + 品类(含子孙分类)+ 供应商拉取 purchase_order_item
* 2. 校验命中的采购明细均已完成 D3 分摊(分摊是门店/单品粒度的对账数据源)
* 3. 每条分摊记录 → 一条对账明细:
* publish_amount = 订货金额(溯源 order_item.amount
* actual_amount = 分摊金额
* 1. 按周期 + 品类(含子孙分类)+ 供应商拉取「已完成」门店订单的订货明细
* 2. 每条订货明细 → 一条对账明细:
* publish_amount = 订货金额(order_item.amount
* actual_amount = 采购成本(称重>0 ? 称重×单价 : 数量×单价,单价 = 成本/包规
* diff = publish actual,冗余 product_name / store_id
* 4. 汇总写回头的 publish/actual/diff_amountstatus → 对账中
* 3. 汇总写回头的 publish/actual/diff_amountstatus → 对账中
*/
class ReconciliationBuildService
{
@@ -33,49 +30,31 @@ class ReconciliationBuildService
public function build(ReconciliationModel $recon): int
{
return DB::transaction(function () use ($recon) {
// 1. 按周期 + 品类 + 供应商拉取采购明细
$itemQuery = PurchaseOrderItemModel::query()
->join('purchase_order', 'purchase_order.id', '=', 'purchase_order_item.purchase_id')
->whereDate('purchase_order.purchase_date', '>=', $recon->period_start)
->whereDate('purchase_order.purchase_date', '<=', $recon->period_end)
->select('purchase_order_item.*');
// 1. 按周期 + 品类 + 供应商拉取已完成订单的订货明细
$itemQuery = StoreOrderItemModel::query()
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
->where('store_order.status', StoreOrderModel::STATUS_COMPLETED)
->whereNull('store_order.deleted_at')
->whereDate('store_order.order_date', '>=', $recon->period_start)
->whereDate('store_order.order_date', '<=', $recon->period_end)
->select('store_order_item.*');
if ((int) $recon->supplier_id > 0) {
$itemQuery->where('purchase_order_item.supplier_id', $recon->supplier_id);
$itemQuery->where('store_order_item.supplier_id', $recon->supplier_id);
}
if ((int) $recon->category_id > 0) {
$productIds = ProductModel::withTrashed()
->whereIn('category_id', $this->descendantCategoryIds((int) $recon->category_id))
->pluck('id');
$itemQuery->whereIn('purchase_order_item.product_id', $productIds);
$itemQuery->whereIn(
'store_order_item.category_id',
$this->descendantCategoryIds((int) $recon->category_id)
);
}
$purchaseItems = $itemQuery->get();
if ($purchaseItems->isEmpty()) {
throw new RepositoryException('周期内无符合筛选条件的采购数据,无法生成对账明细');
$orderItems = $itemQuery->get()->makeVisible('cost_price');
if ($orderItems->isEmpty()) {
throw new RepositoryException('周期内无符合筛选条件的已完成订单数据,无法生成对账明细');
}
// 2. 分摊记录(未完成分摊的采购单拒绝,保证对账数据到门店/单品粒度
$allocations = PurchaseAllocationModel::query()
->whereIn('purchase_item_id', $purchaseItems->pluck('id'))
->get()
->groupBy('purchase_item_id');
$missing = $purchaseItems->filter(fn ($item) => ! $allocations->has($item->id));
if ($missing->isNotEmpty()) {
$purchaseNos = PurchaseOrderModel::query()
->whereIn('id', $missing->pluck('purchase_id')->unique())
->pluck('purchase_no')
->implode('、');
throw new RepositoryException('采购单 ' . $purchaseNos . ' 尚未完成金额分摊,请先执行分摊再生成对账明细');
}
// 3. 溯源订货金额(公布金额)
$orderAmounts = StoreOrderItemModel::query()
->whereIn('id', $allocations->flatten()->pluck('order_item_id')->unique())
->pluck('amount', 'id');
// 4. 先清后建(幂等)
// 2. 先清后建(幂等
ReconciliationItemModel::where('recon_id', $recon->id)->delete();
$publishTotal = '0';
@@ -83,37 +62,41 @@ class ReconciliationBuildService
$rows = [];
$sort = 1;
$now = now();
foreach ($allocations as $purchaseItemId => $group) {
$purchaseItem = $purchaseItems->firstWhere('id', $purchaseItemId);
foreach ($group as $allocation) {
$publish = (string) ($orderAmounts[$allocation->order_item_id] ?? '0');
$actual = (string) $allocation->amount;
$publishTotal = bcadd($publishTotal, $publish, 2);
$actualTotal = bcadd($actualTotal, $actual, 2);
foreach ($orderItems as $orderItem) {
$publish = (string) $orderItem->amount;
$unitCost = PurchaseEditService::unitCost(
(string) ($orderItem->cost_price ?? '0'),
(string) $orderItem->product_spec
);
$actual = PurchaseEditService::costAmount(
(string) $orderItem->quantity,
(string) $orderItem->weight,
$unitCost
);
$publishTotal = bcadd($publishTotal, $publish, 2);
$actualTotal = bcadd($actualTotal, $actual, 2);
$rows[] = [
'recon_id' => $recon->id,
'store_id' => $allocation->store_id,
'purchase_item_id' => $allocation->purchase_item_id,
'order_item_id' => $allocation->order_item_id,
'product_id' => $allocation->product_id,
'product_name' => $purchaseItem->product_name,
'quantity' => $allocation->quantity,
'weight' => $allocation->weight,
'publish_amount' => $publish,
'actual_amount' => $actual,
'diff_amount' => bcsub($publish, $actual, 2),
'is_reconciled' => ReconciliationItemModel::NOT_RECONCILED,
'store_remark' => '',
'sort' => $sort++,
'created_at' => $now,
'updated_at' => $now,
];
}
$rows[] = [
'recon_id' => $recon->id,
'store_id' => $orderItem->store_id,
'order_item_id' => $orderItem->id,
'product_id' => $orderItem->product_id,
'product_name' => $orderItem->product_name,
'quantity' => $orderItem->quantity,
'weight' => $orderItem->weight,
'publish_amount' => $publish,
'actual_amount' => $actual,
'diff_amount' => bcsub($publish, $actual, 2),
'is_reconciled' => ReconciliationItemModel::NOT_RECONCILED,
'store_remark' => '',
'sort' => $sort++,
'created_at' => $now,
'updated_at' => $now,
];
}
ReconciliationItemModel::insert($rows);
// 5. 汇总写回头 + 状态流转
// 3. 汇总写回头 + 状态流转
$recon->publish_amount = $publishTotal;
$recon->actual_amount = $actualTotal;
$recon->diff_amount = bcsub($publishTotal, $actualTotal, 2);