采购单优化
This commit is contained in:
@@ -3,12 +3,14 @@
|
||||
namespace App\Http\Controllers\Purchase;
|
||||
|
||||
use App\Exceptions\RepositoryException;
|
||||
use App\Http\Requests\Purchase\PurchaseItemUpdateRequest;
|
||||
use App\Models\PurchaseAllocationModel;
|
||||
use App\Models\PurchaseOrderItemModel;
|
||||
use App\Http\Requests\Purchase\PurchaseCellUpdateRequest;
|
||||
use App\Http\Requests\Purchase\PurchaseRowUpdateRequest;
|
||||
use App\Models\ProductModel;
|
||||
use App\Models\PurchaseOrderModel;
|
||||
use App\Models\StoreModel;
|
||||
use App\Models\StoreOrderItemModel;
|
||||
use App\Services\ExportService;
|
||||
use App\Services\PurchaseAllocateService;
|
||||
use App\Services\PurchaseEditService;
|
||||
use App\Services\PurchaseGenerateService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -20,7 +22,8 @@ use Modules\Common\Http\Controllers\BaseController;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* 采购单管理(C1 汇总生成 / C2-C3 导出 / C4 修改 / C5-C6 发送供应商 / D3 金额分摊)
|
||||
* 采购单管理(C1 汇总生成 / C2-C3 导出 / C4 修改)
|
||||
* 采购单无独立明细表,明细直接溯源门店订货明细(store_order_item.purchase_id)
|
||||
*/
|
||||
#[RequestAttribute('/purchase/order', 'purchase.order')]
|
||||
class PurchaseOrderController extends BaseController
|
||||
@@ -45,30 +48,110 @@ class PurchaseOrderController extends BaseController
|
||||
return $this->success($data);
|
||||
}
|
||||
|
||||
/** 采购单详情:头 + 明细(含供应商)+ 分摊记录 */
|
||||
/**
|
||||
* 采购单详情:头 + 明细矩阵(商品行 × 门店列)
|
||||
* 行 = 商品(按分类 sort → 商品 sort 排序),列 = 商品信息 + 每个门店一格(数量/金额)
|
||||
*/
|
||||
#[GetRoute(route: '/{id}', authorize: 'query', where: ['id' => '[0-9]+'])]
|
||||
public function detail(int $id): JsonResponse
|
||||
{
|
||||
$purchase = PurchaseOrderModel::with([
|
||||
'operator:id,nickname',
|
||||
'items.supplier:id,name',
|
||||
'items.allocations.store:id,name',
|
||||
])->find($id);
|
||||
$purchase = PurchaseOrderModel::with('operator:id,nickname')->find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
return $this->error('采购单不存在');
|
||||
}
|
||||
return $this->success($purchase->toArray());
|
||||
|
||||
// 订货明细
|
||||
$orderItems = StoreOrderItemModel::query()
|
||||
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
|
||||
->where('store_order_item.purchase_id', $purchase->id)
|
||||
->whereNull('store_order.deleted_at')
|
||||
->with('supplier:id,name')
|
||||
->select('store_order_item.*')
|
||||
->get()
|
||||
->makeVisible('cost_price');
|
||||
|
||||
// 门店列(含软删除门店,保证历史单据可见)
|
||||
$stores = StoreModel::withTrashed()
|
||||
->whereIn('id', $orderItems->pluck('store_id')->unique())
|
||||
->get(['id', 'name'])
|
||||
->map(static fn (StoreModel $store) => ['id' => $store->id, 'name' => $store->name])
|
||||
->values();
|
||||
|
||||
// 排序键:分类 sort → 商品 sort
|
||||
$products = ProductModel::withTrashed()
|
||||
->with('category:id,sort')
|
||||
->whereIn('id', $orderItems->pluck('product_id')->unique())
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
$rows = [];
|
||||
foreach ($orderItems->groupBy('product_id') as $productId => $group) {
|
||||
$first = $group->first();
|
||||
// 商品
|
||||
$product = $products->get((int) $productId);
|
||||
// 采购总数
|
||||
$quantity = 0;
|
||||
// 采购总重量
|
||||
$weight = '0';
|
||||
// 门店明细
|
||||
$cellsMap = [];
|
||||
|
||||
foreach ($group as $item) {
|
||||
$storeId = $item->store_id;
|
||||
// 累加总量
|
||||
$quantity += (int) $item->quantity;
|
||||
$weight = bcadd($weight, (string) $item->weight, 3);
|
||||
|
||||
// 按门店合并
|
||||
if (!isset($cellsMap[$storeId])) {
|
||||
$cellsMap[$storeId] = 0;
|
||||
}
|
||||
|
||||
$cellsMap[$storeId] += (int) $item->quantity;
|
||||
}
|
||||
|
||||
// 供应商
|
||||
$supplier = $first->supplier ? ['id' => $first->supplier->id, 'name' => $first->supplier->name] : null;
|
||||
$rows[] = [
|
||||
'product_id' => (int) $productId,
|
||||
'product_name' => $first->product_name, // 品名
|
||||
'product_spec' => $first->product_spec, // 包规
|
||||
'unit' => $first->unit, // 单位
|
||||
'supplier_id' => (int) $first->supplier_id, // 供应商id
|
||||
'supplier' => $supplier, // 供应商
|
||||
'cost_price' => $first->cost_price, // 成本价
|
||||
'quantity' => $quantity,
|
||||
'weight' => (float) $weight,
|
||||
'cells' => $cellsMap,
|
||||
'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']]);
|
||||
|
||||
return $this->success([
|
||||
'purchase' => $purchase->toArray(),
|
||||
'stores' => $stores->toArray(),
|
||||
'items' => array_map(static function (array $row): array {
|
||||
unset($row['category_sort'], $row['product_sort']);
|
||||
return $row;
|
||||
}, $rows),
|
||||
]);
|
||||
}
|
||||
|
||||
/** C4 修改采购单头信息(采购日期、备注) */
|
||||
/** C4 修改采购单头信息(采购日期、状态、备注) */
|
||||
#[PutRoute(route: '/{id}', authorize: 'update', where: ['id' => '[0-9]+'])]
|
||||
public function update(int $id, Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'purchase_date' => 'nullable|date_format:Y-m-d',
|
||||
'status' => 'nullable|integer|in:' . PurchaseOrderModel::STATUS_PENDING . ',' . PurchaseOrderModel::STATUS_COMPLETED,
|
||||
'remark' => 'nullable|string|max:255',
|
||||
], [
|
||||
'purchase_date.date_format' => '采购日期格式为 Y-m-d',
|
||||
'status.in' => '采购单状态不正确',
|
||||
]);
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
@@ -80,7 +163,7 @@ class PurchaseOrderController extends BaseController
|
||||
|
||||
/**
|
||||
* C1 生成采购单:合并全部「已接单」门店订单(或指定的 order_ids),
|
||||
* 生成后源订单转为「采购中」并回写 purchase_id
|
||||
* 生成后源订单转为「采购中」并回写 purchase_id(订单与订货明细同步归集)
|
||||
*/
|
||||
#[PostRoute('/generate', 'generate')]
|
||||
public function generate(Request $request): JsonResponse
|
||||
@@ -130,128 +213,49 @@ class PurchaseOrderController extends BaseController
|
||||
}
|
||||
|
||||
/**
|
||||
* C4 采购明细修改:amount 后端重算(weight>0 ? weight×price : quantity×price),
|
||||
* 同步回写采购单头汇总(Σ total_weight / actual_amount)
|
||||
* C4 门店单元格修改:数量/称重回写订货明细,金额重算并同步订单/采购单汇总
|
||||
*/
|
||||
#[PutRoute(route: '/item/{id}', authorize: 'update', where: ['id' => '[0-9]+'])]
|
||||
public function updateItem(int $id, PurchaseItemUpdateRequest $request): JsonResponse
|
||||
#[PutRoute(route: '/cell/{id}', authorize: 'update', where: ['id' => '[0-9]+'])]
|
||||
public function updateCell(int $id, PurchaseCellUpdateRequest $request): JsonResponse
|
||||
{
|
||||
$item = PurchaseOrderItemModel::find($id);
|
||||
$item = StoreOrderItemModel::find($id);
|
||||
if (empty($item)) {
|
||||
throw new RepositoryException('采购明细不存在');
|
||||
throw new RepositoryException('订货明细不存在');
|
||||
}
|
||||
$validated = $request->validated();
|
||||
|
||||
$price = (string) $validated['price'];
|
||||
$quantity = (string) $validated['quantity'];
|
||||
$weight = (string) ($validated['weight'] ?? 0);
|
||||
$amount = (float) $weight > 0
|
||||
? bcmul($weight, $price, 2)
|
||||
: bcmul($quantity, $price, 2);
|
||||
|
||||
$item->update([
|
||||
'product_name' => $validated['product_name'] ?? $item->product_name,
|
||||
'product_spec' => $validated['product_spec'] ?? $item->product_spec,
|
||||
'price' => $price,
|
||||
'quantity' => $quantity,
|
||||
'weight' => $weight,
|
||||
'amount' => $amount,
|
||||
'remark' => $validated['remark'] ?? $item->remark,
|
||||
]);
|
||||
|
||||
// 回写采购单头汇总
|
||||
$sums = PurchaseOrderItemModel::query()
|
||||
->where('purchase_id', $item->purchase_id)
|
||||
->selectRaw('COALESCE(SUM(weight), 0) as total_weight, COALESCE(SUM(amount), 0) as actual_amount')
|
||||
->first();
|
||||
PurchaseOrderModel::whereKey($item->purchase_id)->update([
|
||||
'total_weight' => $sums->total_weight,
|
||||
'actual_amount' => $sums->actual_amount,
|
||||
]);
|
||||
|
||||
return $this->success(['amount' => $amount]);
|
||||
}
|
||||
|
||||
/** C5/C6 明细发送供应商:is_sent=1 + sent_at;联动采购单状态(全发送→ALL_SENT,否则 PART_SENT) */
|
||||
#[PutRoute(route: '/item/{id}/send', authorize: 'send', where: ['id' => '[0-9]+'])]
|
||||
public function sendItem(int $id): JsonResponse
|
||||
{
|
||||
$item = PurchaseOrderItemModel::find($id);
|
||||
if (empty($item)) {
|
||||
throw new RepositoryException('采购明细不存在');
|
||||
}
|
||||
if ($item->is_sent === PurchaseOrderItemModel::SENT) {
|
||||
throw new RepositoryException('该明细已发送,请勿重复操作');
|
||||
}
|
||||
$item->is_sent = PurchaseOrderItemModel::SENT;
|
||||
$item->sent_at = now();
|
||||
$item->save();
|
||||
|
||||
$purchase = $item->purchase;
|
||||
$hasUnsent = $purchase->items()
|
||||
->where('is_sent', PurchaseOrderItemModel::NOT_SENT)
|
||||
->exists();
|
||||
$purchase->status = $hasUnsent
|
||||
? PurchaseOrderModel::STATUS_PART_SENT
|
||||
: PurchaseOrderModel::STATUS_ALL_SENT;
|
||||
$purchase->save();
|
||||
|
||||
return $this->success();
|
||||
}
|
||||
|
||||
/** D3 执行金额分摊(按订货比例摊到门店/单品,尾差修正守恒;可重复执行) */
|
||||
#[PostRoute(route: '/{id}/allocate', authorize: 'allocate', where: ['id' => '[0-9]+'])]
|
||||
public function allocate(int $id): JsonResponse
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$count = app(PurchaseAllocateService::class)->allocate($purchase);
|
||||
return $this->success(['count' => $count], '分摊完成');
|
||||
}
|
||||
|
||||
/** 分摊结果:按门店、按商品两个聚合维度 */
|
||||
#[GetRoute(route: '/{id}/allocation', authorize: 'query', where: ['id' => '[0-9]+'])]
|
||||
public function allocation(int $id): JsonResponse
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
|
||||
$allocations = PurchaseAllocationModel::query()
|
||||
->whereIn('purchase_item_id', $purchase->items()->pluck('id'))
|
||||
->with(['store:id,name', 'product:id,name,unit'])
|
||||
->get();
|
||||
|
||||
$byStore = $allocations->groupBy('store_id')->map(function ($group) {
|
||||
$first = $group->first();
|
||||
return [
|
||||
'store_id' => $first->store_id,
|
||||
'store_name' => $first->store?->name ?? '',
|
||||
'quantity' => (float) $group->sum('quantity'),
|
||||
'weight' => (float) $group->sum('weight'),
|
||||
'amount' => (float) $group->sum('amount'),
|
||||
];
|
||||
})->values();
|
||||
|
||||
$byProduct = $allocations->groupBy('product_id')->map(function ($group) {
|
||||
$first = $group->first();
|
||||
return [
|
||||
'product_id' => $first->product_id,
|
||||
'product_name' => $first->product?->name ?? '',
|
||||
'unit' => $first->product?->unit ?? '',
|
||||
'quantity' => (float) $group->sum('quantity'),
|
||||
'weight' => (float) $group->sum('weight'),
|
||||
'amount' => (float) $group->sum('amount'),
|
||||
];
|
||||
})->values();
|
||||
$item = app(PurchaseEditService::class)->updateCell(
|
||||
$item,
|
||||
(int) $validated['quantity'],
|
||||
isset($validated['weight']) ? (float) $validated['weight'] : null,
|
||||
);
|
||||
|
||||
return $this->success([
|
||||
'by_store' => $byStore->toArray(),
|
||||
'by_product' => $byProduct->toArray(),
|
||||
'total_amount' => (float) $allocations->sum('amount'),
|
||||
'quantity' => (int) $item->quantity,
|
||||
'weight' => (float) $item->weight,
|
||||
'amount' => (float) $item->amount,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* C4 商品行修改:采购成本同步该商品全部订货明细;实际称重按数量比例分摊(尾差修正守恒)
|
||||
*/
|
||||
#[PutRoute(route: '/{id}/row/{productId}', authorize: 'update', where: ['id' => '[0-9]+', 'productId' => '[0-9]+'])]
|
||||
public function updateRow(int $id, int $productId, PurchaseRowUpdateRequest $request): JsonResponse
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$validated = $request->validated();
|
||||
$costPrice = isset($validated['cost_price']) ? (float) $validated['cost_price'] : null;
|
||||
$weight = isset($validated['weight']) ? (float) $validated['weight'] : null;
|
||||
if ($costPrice === null && $weight === null) {
|
||||
throw new RepositoryException('采购成本与实际称重至少填写一项');
|
||||
}
|
||||
|
||||
$count = app(PurchaseEditService::class)->updateRow($purchase, $productId, $costPrice, $weight);
|
||||
|
||||
return $this->success(['count' => $count], '已同步 ' . $count . ' 条订货明细');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user