采购单优化
This commit is contained in:
+188
-101
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Exceptions\RepositoryException;
|
||||
use App\Models\ProductCategoryModel;
|
||||
use App\Models\ProductModel;
|
||||
use App\Models\PurchaseOrderModel;
|
||||
@@ -10,44 +11,54 @@ use App\Models\StoreOrderItemModel;
|
||||
use App\Models\SupplierModel;
|
||||
use Illuminate\Support\Collection;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
|
||||
use Maatwebsite\Excel\Concerns\WithStyles;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
|
||||
/**
|
||||
* 采购单导出
|
||||
* 采购单商品明细导出:系统全部商品行(含本采购单无订货的商品,数量 0),
|
||||
* 支持按供应商筛选;行尾合计 + 门店列合计;门店列整列填充突出颜色
|
||||
*/
|
||||
class PurchaseOrderExport implements FromCollection, WithHeadings, WithMapping, WithStyles
|
||||
class PurchaseOrderExport implements FromCollection, WithStrictNullComparison, WithStyles
|
||||
{
|
||||
/** @var array<int, string> 商品ID => 顶级分类名 */
|
||||
private array $categoryNames = [];
|
||||
/** 门店列填充色(浅橙,突出显示) */
|
||||
private const string STORE_FILL = 'FFFFF7E6';
|
||||
|
||||
/** @var array<int, string> 供应商ID => 名称 */
|
||||
private array $supplierNames = [];
|
||||
private ?Collection $rows = null;
|
||||
|
||||
/** @var array<int, string> 特殊行索引(1 起)=> 类型(title/scope/header/summary) */
|
||||
private array $specialRows = [];
|
||||
|
||||
/** 列头所在行索引 */
|
||||
private int $headerRow = 1;
|
||||
|
||||
/** 数据末行索引 */
|
||||
private int $lastRow = 1;
|
||||
|
||||
/** @var array<int, string> 门店ID => 名称(导出列) */
|
||||
private array $storeNames = [];
|
||||
|
||||
private ?Collection $items = null;
|
||||
|
||||
/**
|
||||
* @param PurchaseOrderModel $purchase 采购单
|
||||
* @param int $supplierId 供应商筛选(0=全部)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly PurchaseOrderModel $purchase,
|
||||
private readonly int $supplierId = 0,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出行(商品聚合行,按 分类sort → 商品sort 排序)
|
||||
* 导出行:标题/范围/列头/明细/合计全部手工构建(行位置不固定,不用 WithHeadings)
|
||||
*/
|
||||
public function collection(): Collection
|
||||
{
|
||||
if ($this->items !== null) {
|
||||
return $this->items;
|
||||
if ($this->rows !== null) {
|
||||
return $this->rows;
|
||||
}
|
||||
|
||||
// 本采购单订货明细(关联订单过滤软删)
|
||||
$orderItems = StoreOrderItemModel::query()
|
||||
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
|
||||
->where('store_order_item.purchase_id', $this->purchase->id)
|
||||
@@ -61,135 +72,210 @@ class PurchaseOrderExport implements FromCollection, WithHeadings, WithMapping,
|
||||
->pluck('name', 'id')
|
||||
->toArray();
|
||||
|
||||
$products = ProductModel::withTrashed()
|
||||
->with('category:id,sort')
|
||||
->whereIn('id', $orderItems->pluck('product_id')->unique())
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
$rows = [];
|
||||
// 明细按商品聚合(快照字段取首条;有订货的商品以快照供应商为准)
|
||||
$itemGroups = [];
|
||||
foreach ($orderItems->groupBy('product_id') as $productId => $group) {
|
||||
$first = $group->first();
|
||||
$product = $products->get((int) $productId);
|
||||
$unitCost = $first->cost_price ?? '0';
|
||||
|
||||
$quantity = '0';
|
||||
$weight = '0';
|
||||
$amount = '0';
|
||||
$storeQuantities = array_fill_keys(array_keys($this->storeNames), '0');
|
||||
$storeQuantities = array_fill_keys(array_keys($this->storeNames), 0);
|
||||
foreach ($group as $item) {
|
||||
$quantity = bcadd($quantity, (string) $item->quantity, 2);
|
||||
$weight = bcadd($weight, (string) $item->weight, 3);
|
||||
// 金额 = 数量 × 每包成本价(单价/包规不参与金额计算)
|
||||
$amount = bcadd($amount, bcmul((string) $item->quantity, (string) $item->cost_price, 2), 2);
|
||||
$storeQuantities[(int) $item->store_id] = bcadd(
|
||||
$storeQuantities[(int) $item->store_id] ?? '0',
|
||||
(string) $item->quantity,
|
||||
2
|
||||
);
|
||||
$storeQuantities[(int) $item->store_id] = ($storeQuantities[(int) $item->store_id] ?? 0) + (int) $item->quantity;
|
||||
}
|
||||
$itemGroups[(int) $productId] = [
|
||||
'snapshot' => $first,
|
||||
'quantity' => $quantity,
|
||||
'weight' => $weight,
|
||||
'amount' => $amount,
|
||||
'store_quantities' => $storeQuantities,
|
||||
];
|
||||
}
|
||||
|
||||
// 导出范围:系统全部上架商品 ∪ 本采购单有订货的商品(含已删/下架)
|
||||
$products = ProductModel::withTrashed()
|
||||
->with('category:id,sort')
|
||||
->where('status', ProductModel::STATUS_ON)
|
||||
->orWhereIn('id', array_keys($itemGroups))
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
$categoryNames = $this->rootCategoryNames($products->pluck('category_id', 'id')->all());
|
||||
$supplierNames = SupplierModel::withTrashed()->pluck('name', 'id')->toArray();
|
||||
|
||||
// 组装商品行(供应商筛选:有订货按快照 supplier_id,无订货按档案 supplier_id)
|
||||
$items = [];
|
||||
foreach ($products as $productId => $product) {
|
||||
$group = $itemGroups[(int) $productId] ?? null;
|
||||
$snapshot = $group['snapshot'] ?? null;
|
||||
$rowSupplierId = (int) ($snapshot->supplier_id ?? $product->supplier_id);
|
||||
if ($this->supplierId > 0 && $rowSupplierId !== $this->supplierId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
$quantity = $group['quantity'] ?? '0';
|
||||
$amount = $group['amount'] ?? '0';
|
||||
$spec = (string) ($snapshot->product_spec ?? $product->spec);
|
||||
|
||||
$items[] = [
|
||||
'product_id' => (int) $productId,
|
||||
'supplier_id' => (int) $first->supplier_id,
|
||||
'product_name' => $first->product_name,
|
||||
'product_spec' => $first->product_spec,
|
||||
'unit' => $first->unit,
|
||||
'cost_price' => (float) ($first->cost_price ?? 0),
|
||||
'unit_cost' => (float) $unitCost,
|
||||
'category' => $categoryNames[(int) $productId] ?? '',
|
||||
'product_name' => (string) ($snapshot->product_name ?? $product->name),
|
||||
'supplier' => $supplierNames[$rowSupplierId] ?? '',
|
||||
'product_spec' => $spec,
|
||||
'unit' => (string) ($snapshot->unit ?? $product->unit),
|
||||
'cost_price' => (float) ($snapshot->cost_price ?? $product->cost_price),
|
||||
// 参考零售价 = 加权平均售价 ÷ 包规数值(无订货行无售价数据,留空)
|
||||
'retail_price' => $group !== null && (float) $quantity > 0
|
||||
? $this->unitRefPrice((float) bcdiv($amount, $quantity, 4), $spec)
|
||||
: null,
|
||||
'quantity' => (float) $quantity,
|
||||
'weight' => (float) $weight,
|
||||
'weight' => (float) ($group['weight'] ?? '0'),
|
||||
'amount' => (float) $amount,
|
||||
'store_quantities' => array_map('floatval', $storeQuantities),
|
||||
'store_quantities' => $group['store_quantities']
|
||||
?? array_fill_keys(array_keys($this->storeNames), 0),
|
||||
'category_sort' => (int) ($product->category->sort ?? 9999),
|
||||
'product_sort' => (int) ($product->sort ?? 9999),
|
||||
];
|
||||
}
|
||||
usort($rows, static fn (array $a, array $b): int =>
|
||||
usort($items, 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']]);
|
||||
|
||||
$items = collect($rows);
|
||||
$this->loadLookups($items);
|
||||
if ($items === []) {
|
||||
throw new RepositoryException('该供应商在系统中无商品行,无法导出');
|
||||
}
|
||||
|
||||
$sort = 1;
|
||||
return $this->items = $items->map(static function (array $row) use (&$sort): array {
|
||||
$row['sort'] = $sort++;
|
||||
return $row;
|
||||
})->values();
|
||||
}
|
||||
// ===== 手工建行 =====
|
||||
$rows = [];
|
||||
$rowIndex = 0;
|
||||
|
||||
public function headings(): array
|
||||
{
|
||||
$this->collection();
|
||||
// 标题行
|
||||
$rows[] = ['采购单 ' . $this->purchase->purchase_no . '(采购日期 ' . $this->purchase->purchase_date->toDateString() . ')'];
|
||||
$this->specialRows[++$rowIndex] = 'title';
|
||||
|
||||
return array_merge(
|
||||
['序号', '分类', '品名', '供应商', '包规', '单位', '成本', '单价', '数量', '实际称重', '金额'],
|
||||
// 范围行:供应商筛选 / 导出时间
|
||||
$scopeSupplier = '全部';
|
||||
if ($this->supplierId > 0) {
|
||||
$scopeSupplier = $supplierNames[$this->supplierId] ?? ('供应商#' . $this->supplierId);
|
||||
}
|
||||
$rows[] = ['供应商:' . $scopeSupplier . ' 导出时间:' . now()->format('Y-m-d H:i:s')];
|
||||
$this->specialRows[++$rowIndex] = 'scope';
|
||||
|
||||
// 空行
|
||||
$rows[] = [''];
|
||||
$rowIndex++;
|
||||
|
||||
// 列头
|
||||
$rows[] = array_merge(
|
||||
['序号', '分类', '品名', '供应商', '包规', '单位', '成本', '参考零售价', '数量', '实际称重', '金额'],
|
||||
array_values($this->storeNames),
|
||||
);
|
||||
}
|
||||
$this->specialRows[++$rowIndex] = 'header';
|
||||
$this->headerRow = $rowIndex;
|
||||
|
||||
public function map($row): array
|
||||
{
|
||||
return array_merge([
|
||||
$row['sort'],
|
||||
$this->categoryNames[$row['product_id']] ?? '',
|
||||
$row['product_name'],
|
||||
$this->supplierNames[$row['supplier_id']] ?? '',
|
||||
$row['product_spec'],
|
||||
$row['unit'],
|
||||
$row['cost_price'],
|
||||
$row['unit_cost'],
|
||||
$row['quantity'],
|
||||
$row['weight'],
|
||||
$row['amount'],
|
||||
], array_values($row['store_quantities']));
|
||||
// 明细行
|
||||
$totalQuantity = '0';
|
||||
$totalWeight = '0';
|
||||
$totalAmount = '0';
|
||||
$storeTotals = array_fill_keys(array_keys($this->storeNames), 0);
|
||||
foreach (array_values($items) as $sort => $item) {
|
||||
$rows[] = array_merge([
|
||||
$sort + 1,
|
||||
$item['category'],
|
||||
$item['product_name'],
|
||||
$item['supplier'],
|
||||
$item['product_spec'],
|
||||
$item['unit'],
|
||||
$item['cost_price'],
|
||||
$item['retail_price'] !== null ? $item['retail_price'] : '',
|
||||
$item['quantity'],
|
||||
$item['weight'],
|
||||
$item['amount'],
|
||||
], array_values($item['store_quantities']));
|
||||
$rowIndex++;
|
||||
$totalQuantity = bcadd($totalQuantity, (string) $item['quantity'], 2);
|
||||
$totalWeight = bcadd($totalWeight, (string) $item['weight'], 3);
|
||||
$totalAmount = bcadd($totalAmount, (string) $item['amount'], 2);
|
||||
foreach ($item['store_quantities'] as $storeId => $qty) {
|
||||
$storeTotals[$storeId] += $qty;
|
||||
}
|
||||
}
|
||||
|
||||
// 合计行(行合计 + 门店列合计)
|
||||
$rows[] = array_merge(
|
||||
['', '', '合计', '', '', '', '', '', (float) $totalQuantity, (float) $totalWeight, (float) $totalAmount],
|
||||
array_values($storeTotals),
|
||||
);
|
||||
$this->specialRows[++$rowIndex] = 'summary';
|
||||
$this->lastRow = $rowIndex;
|
||||
|
||||
return $this->rows = collect($rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 表头加粗 + 冻结首行
|
||||
* 标题/列头/合计加粗,门店列整列填充突出颜色,冻结列头
|
||||
*/
|
||||
public function styles(Worksheet $sheet): array
|
||||
{
|
||||
$sheet->freezePane('A2');
|
||||
$this->collection();
|
||||
|
||||
return [
|
||||
1 => ['font' => ['bold' => true]],
|
||||
];
|
||||
$sheet->freezePane('A' . ($this->headerRow + 1));
|
||||
$widths = [6, 10, 20, 12, 12, 8, 10, 12, 10, 12, 12];
|
||||
foreach ($widths as $index => $width) {
|
||||
$sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width);
|
||||
}
|
||||
|
||||
// 门店列整列(列头 → 合计行)填充突出颜色
|
||||
$storeCount = count($this->storeNames);
|
||||
for ($i = 0; $i < $storeCount; $i++) {
|
||||
$column = Coordinate::stringFromColumnIndex(12 + $i);
|
||||
$sheet->getColumnDimension($column)->setWidth(12);
|
||||
$sheet->getStyle($column . $this->headerRow . ':' . $column . $this->lastRow)
|
||||
->getFill()
|
||||
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
|
||||
->getStartColor()
|
||||
->setARGB(self::STORE_FILL);
|
||||
}
|
||||
|
||||
$styles = [];
|
||||
foreach ($this->specialRows as $row => $type) {
|
||||
$style = match ($type) {
|
||||
'title' => ['font' => ['bold' => true, 'size' => 14]],
|
||||
'header', 'summary' => ['font' => ['bold' => true]],
|
||||
default => [],
|
||||
};
|
||||
if ($style !== []) {
|
||||
$styles[$row] = $style;
|
||||
}
|
||||
}
|
||||
|
||||
return $styles;
|
||||
}
|
||||
|
||||
/**
|
||||
* PDF 模板视图数据
|
||||
* 每单位参考价 = 整单价 ÷ 包规数值(包规解析不出正数时按 1 处理;仅展示参考)
|
||||
*/
|
||||
private function unitRefPrice(float $price, string $spec): float
|
||||
{
|
||||
$pack = (float) preg_replace('/[^0-9.].*$/', '', $spec);
|
||||
return $pack > 0 ? round($price / $pack, 2) : round($price, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品ID => 顶级分类名(沿 parent_id 上溯取根分类)
|
||||
*
|
||||
* @return array{purchase: PurchaseOrderModel, items: Collection, storeNames: array<int, string>, categoryNames: array<int, string>, supplierNames: array<int, string>}
|
||||
* @param array<int, int> $productCategoryIds 商品ID => 分类ID
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function viewData(): array
|
||||
private function rootCategoryNames(array $productCategoryIds): array
|
||||
{
|
||||
return [
|
||||
'purchase' => $this->purchase,
|
||||
'items' => $this->collection(),
|
||||
'storeNames' => $this->storeNames,
|
||||
'categoryNames' => $this->categoryNames,
|
||||
'supplierNames' => $this->supplierNames,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 预加载供应商名与商品顶级分类名(商品/供应商均含软删除,保证历史单据可导出)
|
||||
*/
|
||||
private function loadLookups(Collection $items): void
|
||||
{
|
||||
$this->supplierNames = SupplierModel::withTrashed()
|
||||
->whereIn('id', $items->pluck('supplier_id')->unique())
|
||||
->pluck('name', 'id')
|
||||
->toArray();
|
||||
|
||||
$productCategoryIds = ProductModel::withTrashed()
|
||||
->whereIn('id', $items->pluck('product_id')->unique())
|
||||
->pluck('category_id', 'id');
|
||||
|
||||
$categories = ProductCategoryModel::all()->keyBy('id');
|
||||
$this->categoryNames = [];
|
||||
$names = [];
|
||||
foreach ($productCategoryIds as $productId => $categoryId) {
|
||||
$rootName = '';
|
||||
$cursor = (int) $categoryId;
|
||||
@@ -202,7 +288,8 @@ class PurchaseOrderExport implements FromCollection, WithHeadings, WithMapping,
|
||||
$rootName = $category->name;
|
||||
$cursor = (int) $category->parent_id;
|
||||
}
|
||||
$this->categoryNames[(int) $productId] = $rootName;
|
||||
$names[(int) $productId] = $rootName;
|
||||
}
|
||||
return $names;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Exceptions\RepositoryException;
|
||||
use App\Models\PurchaseOrderModel;
|
||||
use App\Models\StoreModel;
|
||||
use App\Models\StoreOrderItemModel;
|
||||
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
|
||||
|
||||
/**
|
||||
* 门店购买详情导出:多门店合并为一个 XLSX(每门店一个工作表,工作表名=门店名称);
|
||||
* 构造传入 storeId 时仅导出该门店(单工作表)
|
||||
*/
|
||||
class PurchaseStoreExport implements WithMultipleSheets
|
||||
{
|
||||
/**
|
||||
* @param PurchaseOrderModel $purchase 采购单
|
||||
* @param int $storeId 单门店导出(0=全部门店)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly PurchaseOrderModel $purchase,
|
||||
private readonly int $storeId = 0,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, PurchaseStoreSheet>
|
||||
*/
|
||||
public function sheets(): array
|
||||
{
|
||||
// 本采购单内有明细的门店(含软删除,保证历史单据可导出)
|
||||
$query = StoreOrderItemModel::query()
|
||||
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
|
||||
->where('store_order_item.purchase_id', $this->purchase->id)
|
||||
->whereNull('store_order.deleted_at');
|
||||
if ($this->storeId > 0) {
|
||||
$query->where('store_order_item.store_id', $this->storeId);
|
||||
}
|
||||
$storeIds = $query->distinct()->pluck('store_order_item.store_id');
|
||||
|
||||
if ($storeIds->isEmpty()) {
|
||||
throw new RepositoryException(
|
||||
$this->storeId > 0 ? '该门店在此采购单中无采购商品' : '该采购单无门店采购明细,无法导出'
|
||||
);
|
||||
}
|
||||
|
||||
$stores = StoreModel::withTrashed()
|
||||
->whereIn('id', $storeIds)
|
||||
->orderBy('id')
|
||||
->get(['id', 'name']);
|
||||
|
||||
$usedNames = [];
|
||||
$sheets = [];
|
||||
foreach ($stores as $store) {
|
||||
$sheets[] = new PurchaseStoreSheet(
|
||||
$this->purchase,
|
||||
$store,
|
||||
SheetName::make((string) $store->name, (int) $store->id, $usedNames),
|
||||
);
|
||||
}
|
||||
|
||||
return $sheets;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\PurchaseOrderModel;
|
||||
use App\Models\StoreModel;
|
||||
use App\Services\PurchaseItemService;
|
||||
use Illuminate\Support\Collection;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
|
||||
use Maatwebsite\Excel\Concerns\WithStyles;
|
||||
use Maatwebsite\Excel\Concerns\WithTitle;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
|
||||
/**
|
||||
* 门店购买详情导出 · 单门店工作表
|
||||
*/
|
||||
class PurchaseStoreSheet implements FromCollection, WithStrictNullComparison, WithStyles, WithTitle
|
||||
{
|
||||
private ?Collection $rows = null;
|
||||
|
||||
/** @var array<int, string> 特殊行索引(1 起)=> 类型(title/header/summary) */
|
||||
private array $specialRows = [];
|
||||
|
||||
/** 列头所在行索引 */
|
||||
private int $headerRow = 1;
|
||||
|
||||
public function __construct(
|
||||
private readonly PurchaseOrderModel $purchase,
|
||||
private readonly StoreModel $store,
|
||||
private readonly string $sheetTitle,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出行:标题/空行/列头/明细/合计
|
||||
*/
|
||||
public function collection(): Collection
|
||||
{
|
||||
if ($this->rows !== null) {
|
||||
return $this->rows;
|
||||
}
|
||||
|
||||
$items = app(PurchaseItemService::class)->storeSummaryRows($this->purchase->id, $this->store->id);
|
||||
|
||||
$rows = [];
|
||||
$rowIndex = 0;
|
||||
|
||||
// 标题行
|
||||
$rows[] = [$this->store->name . ' · 采购单 ' . $this->purchase->purchase_no];
|
||||
$this->specialRows[++$rowIndex] = 'title';
|
||||
|
||||
// 空行
|
||||
$rows[] = [''];
|
||||
$rowIndex++;
|
||||
|
||||
// 列头
|
||||
$rows[] = ['序号', '品名', '包规', '单位', '单价', '数量', '重量(斤)', '预计金额'];
|
||||
$this->specialRows[++$rowIndex] = 'header';
|
||||
$this->headerRow = $rowIndex;
|
||||
|
||||
// 明细行
|
||||
$totalQuantity = 0;
|
||||
$totalWeight = '0';
|
||||
$totalAmount = '0';
|
||||
foreach (array_values($items) as $sort => $item) {
|
||||
$rows[] = [
|
||||
$sort + 1,
|
||||
$item['product_name'],
|
||||
$item['product_spec'],
|
||||
$item['unit'],
|
||||
(float) $item['price'],
|
||||
(int) $item['quantity'],
|
||||
(float) $item['weight'],
|
||||
(float) $item['amount'],
|
||||
];
|
||||
$rowIndex++;
|
||||
$totalQuantity += (int) $item['quantity'];
|
||||
$totalWeight = bcadd($totalWeight, (string) $item['weight'], 3);
|
||||
$totalAmount = bcadd($totalAmount, (string) $item['amount'], 2);
|
||||
}
|
||||
|
||||
// 合计行
|
||||
$rows[] = ['', '合计', '', '', '', $totalQuantity, (float) $totalWeight, (float) $totalAmount];
|
||||
$this->specialRows[++$rowIndex] = 'summary';
|
||||
|
||||
return $this->rows = collect($rows);
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
return $this->sheetTitle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标题/列头/合计加粗,冻结列头
|
||||
*/
|
||||
public function styles(Worksheet $sheet): array
|
||||
{
|
||||
$this->collection();
|
||||
|
||||
$sheet->freezePane('A' . ($this->headerRow + 1));
|
||||
$widths = [6, 24, 14, 8, 10, 10, 12, 12];
|
||||
foreach ($widths as $index => $width) {
|
||||
$sheet->getColumnDimension(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($index + 1))
|
||||
->setWidth($width);
|
||||
}
|
||||
|
||||
$styles = [];
|
||||
foreach ($this->specialRows as $row => $type) {
|
||||
$style = match ($type) {
|
||||
'title' => ['font' => ['bold' => true, 'size' => 14]],
|
||||
'header', 'summary' => ['font' => ['bold' => true]],
|
||||
default => [],
|
||||
};
|
||||
if ($style !== []) {
|
||||
$styles[$row] = $style;
|
||||
}
|
||||
}
|
||||
|
||||
return $styles;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Exceptions\RepositoryException;
|
||||
use App\Models\PurchaseOrderModel;
|
||||
use App\Models\StoreOrderItemModel;
|
||||
use App\Models\SupplierModel;
|
||||
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
|
||||
|
||||
/**
|
||||
* 供应商采购明细导出:多供应商合并为一个 XLSX(每供应商一个工作表,工作表名=供应商名称);
|
||||
* 构造传入 supplierId 时仅导出该供应商(单工作表)
|
||||
*/
|
||||
class PurchaseSupplierExport implements WithMultipleSheets
|
||||
{
|
||||
/**
|
||||
* @param PurchaseOrderModel $purchase 采购单
|
||||
* @param int $supplierId 单供应商导出(0=全部供应商)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly PurchaseOrderModel $purchase,
|
||||
private readonly int $supplierId = 0,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, PurchaseSupplierSheet>
|
||||
*/
|
||||
public function sheets(): array
|
||||
{
|
||||
// 本采购单内有明细的供应商(按订货明细快照 supplier_id 归集)
|
||||
$query = StoreOrderItemModel::query()
|
||||
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
|
||||
->where('store_order_item.purchase_id', $this->purchase->id)
|
||||
->whereNull('store_order.deleted_at')
|
||||
->where('store_order_item.supplier_id', '>', 0);
|
||||
if ($this->supplierId > 0) {
|
||||
$query->where('store_order_item.supplier_id', $this->supplierId);
|
||||
}
|
||||
$supplierIds = $query->distinct()->pluck('store_order_item.supplier_id');
|
||||
|
||||
if ($supplierIds->isEmpty()) {
|
||||
throw new RepositoryException(
|
||||
$this->supplierId > 0 ? '该供应商在此采购单中无采购明细' : '该采购单无供应商采购明细,无法导出'
|
||||
);
|
||||
}
|
||||
|
||||
$suppliers = SupplierModel::withTrashed()
|
||||
->whereIn('id', $supplierIds)
|
||||
->orderBy('id')
|
||||
->get(['id', 'name']);
|
||||
|
||||
$usedNames = [];
|
||||
$sheets = [];
|
||||
foreach ($suppliers as $supplier) {
|
||||
$sheets[] = new PurchaseSupplierSheet(
|
||||
$this->purchase,
|
||||
$supplier,
|
||||
SheetName::make((string) $supplier->name, (int) $supplier->id, $usedNames),
|
||||
);
|
||||
}
|
||||
|
||||
return $sheets;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\PurchaseOrderModel;
|
||||
use App\Models\SupplierModel;
|
||||
use App\Services\PurchaseItemService;
|
||||
use Illuminate\Support\Collection;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
|
||||
use Maatwebsite\Excel\Concerns\WithStyles;
|
||||
use Maatwebsite\Excel\Concerns\WithTitle;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
|
||||
/**
|
||||
* 供应商采购明细导出 · 单供应商工作表(成本口径:金额=Σ数量×成本价)
|
||||
*/
|
||||
class PurchaseSupplierSheet implements FromCollection, WithStrictNullComparison, WithStyles, WithTitle
|
||||
{
|
||||
private ?Collection $rows = null;
|
||||
|
||||
/** @var array<int, string> 特殊行索引(1 起)=> 类型(title/header/summary) */
|
||||
private array $specialRows = [];
|
||||
|
||||
/** 列头所在行索引 */
|
||||
private int $headerRow = 1;
|
||||
|
||||
public function __construct(
|
||||
private readonly PurchaseOrderModel $purchase,
|
||||
private readonly SupplierModel $supplier,
|
||||
private readonly string $sheetTitle,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出行:标题/空行/列头/明细/合计
|
||||
*/
|
||||
public function collection(): Collection
|
||||
{
|
||||
if ($this->rows !== null) {
|
||||
return $this->rows;
|
||||
}
|
||||
|
||||
$items = app(PurchaseItemService::class)->supplierRows($this->purchase->id, $this->supplier->id);
|
||||
|
||||
$rows = [];
|
||||
$rowIndex = 0;
|
||||
|
||||
// 标题行
|
||||
$rows[] = [$this->supplier->name . ' · 采购单 ' . $this->purchase->purchase_no];
|
||||
$this->specialRows[++$rowIndex] = 'title';
|
||||
|
||||
// 空行
|
||||
$rows[] = [''];
|
||||
$rowIndex++;
|
||||
|
||||
// 列头
|
||||
$rows[] = ['序号', '品名', '包规', '单位', '成本价', '数量', '重量(斤)', '金额'];
|
||||
$this->specialRows[++$rowIndex] = 'header';
|
||||
$this->headerRow = $rowIndex;
|
||||
|
||||
// 明细行
|
||||
$totalQuantity = 0;
|
||||
$totalWeight = '0';
|
||||
$totalAmount = '0';
|
||||
foreach (array_values($items) as $sort => $item) {
|
||||
$rows[] = [
|
||||
$sort + 1,
|
||||
$item['product_name'],
|
||||
$item['product_spec'],
|
||||
$item['unit'],
|
||||
(float) $item['cost_price'],
|
||||
(int) $item['quantity'],
|
||||
(float) $item['weight'],
|
||||
(float) $item['amount'],
|
||||
];
|
||||
$rowIndex++;
|
||||
$totalQuantity += (int) $item['quantity'];
|
||||
$totalWeight = bcadd($totalWeight, (string) $item['weight'], 3);
|
||||
$totalAmount = bcadd($totalAmount, (string) $item['amount'], 2);
|
||||
}
|
||||
|
||||
// 合计行
|
||||
$rows[] = ['', '合计', '', '', '', $totalQuantity, (float) $totalWeight, (float) $totalAmount];
|
||||
$this->specialRows[++$rowIndex] = 'summary';
|
||||
|
||||
return $this->rows = collect($rows);
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
return $this->sheetTitle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标题/列头/合计加粗,冻结列头
|
||||
*/
|
||||
public function styles(Worksheet $sheet): array
|
||||
{
|
||||
$this->collection();
|
||||
|
||||
$sheet->freezePane('A' . ($this->headerRow + 1));
|
||||
$widths = [6, 24, 14, 8, 10, 10, 12, 12];
|
||||
foreach ($widths as $index => $width) {
|
||||
$sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width);
|
||||
}
|
||||
|
||||
$styles = [];
|
||||
foreach ($this->specialRows as $row => $type) {
|
||||
$style = match ($type) {
|
||||
'title' => ['font' => ['bold' => true, 'size' => 14]],
|
||||
'header', 'summary' => ['font' => ['bold' => true]],
|
||||
default => [],
|
||||
};
|
||||
if ($style !== []) {
|
||||
$styles[$row] = $style;
|
||||
}
|
||||
}
|
||||
|
||||
return $styles;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
/**
|
||||
* Excel 工作表名合法化:剥离非法字符、31 字截断、重名追加 #id
|
||||
*/
|
||||
final class SheetName
|
||||
{
|
||||
/**
|
||||
* @param string $name 原始名称(门店名/供应商名)
|
||||
* @param int $id 实体ID(重名时追加)
|
||||
* @param array<int, string> $used 已用名列表(引用传入,调用方维护)
|
||||
*/
|
||||
public static function make(string $name, int $id, array &$used): string
|
||||
{
|
||||
$base = str_replace(['[', ']', ':', '*', '?', '/', '\\'], '', $name);
|
||||
$base = mb_substr($base === '' ? '未命名' : $base, 0, 28);
|
||||
$title = $base;
|
||||
if (in_array($title, $used, true)) {
|
||||
$title = mb_substr($base, 0, 25) . '#' . $id;
|
||||
}
|
||||
$used[] = $title;
|
||||
return $title;
|
||||
}
|
||||
}
|
||||
@@ -4,22 +4,29 @@ namespace App\Http\Controllers\Purchase;
|
||||
|
||||
use App\Exceptions\RepositoryException;
|
||||
use App\Exports\PurchaseOrderExport;
|
||||
use App\Exports\PurchaseStoreExport;
|
||||
use App\Exports\PurchaseSupplierExport;
|
||||
use App\Http\Requests\Purchase\PurchaseBillGenerateRequest;
|
||||
use App\Http\Requests\Purchase\PurchaseCellUpdateRequest;
|
||||
use App\Http\Requests\Purchase\PurchaseRowUpdateRequest;
|
||||
use App\Http\Requests\Purchase\PurchaseStoreItemRequest;
|
||||
use App\Models\BillModel;
|
||||
use App\Models\CustomerLevelModel;
|
||||
use App\Models\ProductModel;
|
||||
use App\Models\PurchaseOrderModel;
|
||||
use App\Models\StoreModel;
|
||||
use App\Models\StoreOrderItemModel;
|
||||
use App\Models\StoreOrderModel;
|
||||
use App\Models\SupplierModel;
|
||||
use App\Services\BillGenerateService;
|
||||
use App\Services\ItemImageResolver;
|
||||
use App\Services\PurchaseGenerateService;
|
||||
use App\Services\PurchaseItemService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use Modules\AnnoRoute\Attribute\DeleteRoute;
|
||||
use Modules\AnnoRoute\Attribute\GetRoute;
|
||||
use Modules\AnnoRoute\Attribute\PostRoute;
|
||||
use Modules\AnnoRoute\Attribute\PutRoute;
|
||||
@@ -98,6 +105,8 @@ class PurchaseOrderController extends BaseController
|
||||
$quantity = 0;
|
||||
// 采购总重量
|
||||
$weight = '0';
|
||||
// 采购总金额(Σ明细 amount,参考零售价按 金额÷数量 加权)
|
||||
$amount = '0';
|
||||
// 门店明细
|
||||
$cellsMap = [];
|
||||
|
||||
@@ -106,6 +115,7 @@ class PurchaseOrderController extends BaseController
|
||||
// 累加总量
|
||||
$quantity += (int) $item->quantity;
|
||||
$weight = bcadd($weight, (string) $item->weight, 3);
|
||||
$amount = bcadd($amount, (string) $item->amount, 2);
|
||||
|
||||
// 按门店合并
|
||||
if (!isset($cellsMap[$storeId])) {
|
||||
@@ -127,6 +137,7 @@ class PurchaseOrderController extends BaseController
|
||||
'cost_price' => $first->cost_price, // 成本价
|
||||
'quantity' => $quantity,
|
||||
'weight' => (float) $weight,
|
||||
'amount' => $amount,
|
||||
'cells' => $cellsMap,
|
||||
'category_sort' => (int) ($product->category->sort ?? 9999),
|
||||
'product_sort' => (int) ($product->sort ?? 9999),
|
||||
@@ -247,22 +258,68 @@ class PurchaseOrderController extends BaseController
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出采购单 Excel 表格
|
||||
* 导出采购单商品明细 Excel 表格(系统全部商品行,支持按供应商筛选)
|
||||
*
|
||||
* @throws
|
||||
*/
|
||||
#[GetRoute(route: '/{id}/export', authorize: 'export', where: ['id' => '[0-9]+'])]
|
||||
public function export(int $id): Response
|
||||
public function export(int $id, Request $request): Response
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$supplierId = (int) $request->query('supplier_id', 0);
|
||||
|
||||
return Excel::download(
|
||||
new PurchaseOrderExport($purchase),
|
||||
$purchase->purchase_no . '_采购单.xlsx',
|
||||
);
|
||||
$filename = $purchase->purchase_no . '_采购单.xlsx';
|
||||
if ($supplierId > 0) {
|
||||
$supplier = SupplierModel::withTrashed()->find($supplierId);
|
||||
$filename = $purchase->purchase_no . '_采购单_' . ($supplier->name ?? ('供应商' . $supplierId)) . '.xlsx';
|
||||
}
|
||||
|
||||
return Excel::download(new PurchaseOrderExport($purchase, $supplierId), $filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出门店购买详情(多工作表:每门店一个工作表;?store_id= 单门店导出)
|
||||
*/
|
||||
#[GetRoute(route: '/{id}/exportStores', authorize: 'export', where: ['id' => '[0-9]+'])]
|
||||
public function exportStores(int $id, Request $request): Response
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$storeId = (int) $request->query('store_id', 0);
|
||||
|
||||
$filename = $purchase->purchase_no . '_门店购买详情.xlsx';
|
||||
if ($storeId > 0) {
|
||||
$store = StoreModel::withTrashed()->find($storeId);
|
||||
$filename = $purchase->purchase_no . '_门店购买详情_' . ($store->name ?? ('门店' . $storeId)) . '.xlsx';
|
||||
}
|
||||
|
||||
return Excel::download(new PurchaseStoreExport($purchase, $storeId), $filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出供应商采购明细(多工作表:每供应商一个工作表;?supplier_id= 单供应商导出)
|
||||
*/
|
||||
#[GetRoute(route: '/{id}/exportSuppliers', authorize: 'export', where: ['id' => '[0-9]+'])]
|
||||
public function exportSuppliers(int $id, Request $request): Response
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$supplierId = (int) $request->query('supplier_id', 0);
|
||||
|
||||
$filename = $purchase->purchase_no . '_供应商采购明细.xlsx';
|
||||
if ($supplierId > 0) {
|
||||
$supplier = SupplierModel::withTrashed()->find($supplierId);
|
||||
$filename = $purchase->purchase_no . '_供应商采购明细_' . ($supplier->name ?? ('供应商' . $supplierId)) . '.xlsx';
|
||||
}
|
||||
|
||||
return Excel::download(new PurchaseSupplierExport($purchase, $supplierId), $filename);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -348,68 +405,191 @@ class PurchaseOrderController extends BaseController
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
|
||||
$items = StoreOrderItemModel::query()
|
||||
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
|
||||
->where('store_order_item.purchase_id', $purchase->id)
|
||||
->where('store_order_item.store_id', $storeId)
|
||||
->whereNull('store_order.deleted_at')
|
||||
->select('store_order_item.*')
|
||||
->orderBy('store_order_item.id')
|
||||
->get();
|
||||
|
||||
// 排序键:分类 sort → 商品 sort(与明细矩阵同序)
|
||||
$products = ProductModel::withTrashed()
|
||||
->with('category:id,sort')
|
||||
->whereIn('id', $items->pluck('product_id')->unique())
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
$rows = [];
|
||||
foreach ($items->groupBy('product_id') as $productId => $group) {
|
||||
$product = $products->get((int) $productId);
|
||||
$first = $group->first();
|
||||
// 采购总数量(包数)
|
||||
$quantity = 0;
|
||||
// 预计金额 = Σ 明细 amount
|
||||
$amount = '0';
|
||||
// 总重量
|
||||
$weight = '0';
|
||||
foreach ($group as $item) {
|
||||
$weight = bcadd($weight, (string) $item->weight, 3);
|
||||
$quantity += (int) $item->quantity;
|
||||
$amount = bcadd($amount, (string) $item->amount, 2);
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'product_id' => (int) $productId,
|
||||
'product_name' => $first->product_name,
|
||||
'product_spec' => $first->product_spec, // 包规
|
||||
'unit' => $first->unit, // 单位
|
||||
'price' => $quantity > 0 // 加权平均单价
|
||||
? bcdiv($amount, (string) $quantity, 2)
|
||||
: (string) $first->price,
|
||||
'quantity' => $quantity,
|
||||
'amount' => $amount,
|
||||
'weight' => $weight,
|
||||
'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']]);
|
||||
|
||||
$store = StoreModel::withTrashed()->find($storeId);
|
||||
|
||||
return $this->success([
|
||||
'store' => $store ? ['id' => $store->id, 'name' => $store->name] : null,
|
||||
'items' => array_map(static function (array $row): array {
|
||||
unset($row['category_sort'], $row['product_sort']);
|
||||
return $row;
|
||||
}, $rows),
|
||||
'items' => app(PurchaseItemService::class)->storeSummaryRows($purchase->id, $storeId),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 门店购买详情:新增单品(挂靠该门店在采购单中的最新一笔订单,
|
||||
* 单价按门店等级上浮比例换算,无等级按成本价兜底)
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
#[PostRoute(route: '/{id}/store/{storeId}/item', authorize: 'update', where: ['id' => '[0-9]+', 'storeId' => '[0-9]+'])]
|
||||
public function storeItemStore(int $id, int $storeId, PurchaseStoreItemRequest $request): JsonResponse
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$this->assertPurchaseEditable($purchase);
|
||||
|
||||
$validated = $request->validated();
|
||||
$productId = (int) $validated['product_id'];
|
||||
$product = ProductModel::find($productId);
|
||||
if ($product === null) {
|
||||
throw new RepositoryException('商品不存在或已被删除,无法添加');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($purchase, $storeId, $product, $validated) {
|
||||
// 该门店在采购单中的最新一笔订单
|
||||
$order = StoreOrderModel::query()
|
||||
->where('purchase_id', $purchase->id)
|
||||
->where('store_id', $storeId)
|
||||
->orderByDesc('id')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
if ($order === null) {
|
||||
throw new RepositoryException('该门店不在此采购单中,无法添加单品');
|
||||
}
|
||||
|
||||
$duplicated = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchase->id)
|
||||
->where('store_id', $storeId)
|
||||
->where('product_id', $product->id)
|
||||
->exists();
|
||||
if ($duplicated) {
|
||||
throw new RepositoryException('该商品已在此门店采购明细中,请直接修改数量');
|
||||
}
|
||||
|
||||
// 单价:门店等级上浮换算价(无等级按成本价兜底)
|
||||
$store = StoreModel::withTrashed()->find($storeId);
|
||||
$level = ($store !== null && $store->level_id > 0) ? $store->level : null;
|
||||
$price = $level !== null
|
||||
? CustomerLevelModel::calcLevelPrice($product->cost_price, $level->percent)
|
||||
: bcadd((string) $product->cost_price, '0', 2);
|
||||
$quantity = (int) $validated['quantity'];
|
||||
|
||||
$item = StoreOrderItemModel::create([
|
||||
'order_id' => $order->id,
|
||||
'purchase_id' => $purchase->id,
|
||||
'bill_id' => 0,
|
||||
'store_id' => $storeId,
|
||||
'product_id' => $product->id,
|
||||
'category_id' => (int) $product->category_id,
|
||||
'supplier_id' => (int) $product->supplier_id,
|
||||
'product_name' => $product->name,
|
||||
'product_spec' => $product->spec,
|
||||
'unit' => (string) $product->unit,
|
||||
'price' => $price,
|
||||
'image_ids' => implode(',', (array) $product->image_ids),
|
||||
'content' => (string) $product->content,
|
||||
'shelf_life' => (int) $product->shelf_life,
|
||||
'quantity' => $quantity,
|
||||
'weight' => bcadd((string) ($validated['weight'] ?? 0), '0', 3),
|
||||
'amount' => bcmul($price, (string) $quantity, 2),
|
||||
'cost_price' => (string) $product->cost_price,
|
||||
'remark' => '',
|
||||
]);
|
||||
|
||||
$service = app(PurchaseItemService::class);
|
||||
$service->recalcOrder($order->id);
|
||||
$service->recalcPurchase($purchase->id);
|
||||
|
||||
return $this->success(['id' => $item->id], '已添加单品');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 门店购买详情:修改单品(数量/称重/单价);同门店同商品多笔订单明细时合并到最早一条
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
#[PutRoute(route: '/{id}/store/{storeId}/item/{productId}', authorize: 'update', where: ['id' => '[0-9]+', 'storeId' => '[0-9]+', 'productId' => '[0-9]+'])]
|
||||
public function storeItemUpdate(int $id, int $storeId, int $productId, PurchaseStoreItemRequest $request): JsonResponse
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$this->assertPurchaseEditable($purchase);
|
||||
|
||||
$validated = $request->validated();
|
||||
|
||||
return DB::transaction(function () use ($purchase, $storeId, $productId, $validated) {
|
||||
$items = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchase->id)
|
||||
->where('store_id', $storeId)
|
||||
->where('product_id', $productId)
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
if ($items->isEmpty()) {
|
||||
throw new RepositoryException('该门店在此采购单中无此商品明细');
|
||||
}
|
||||
|
||||
$affectedOrderIds = $items->pluck('order_id')->unique()->all();
|
||||
|
||||
// 多笔订单明细合并到最早一条
|
||||
$survivor = $items->first();
|
||||
foreach ($items->skip(1) as $extra) {
|
||||
$extra->delete();
|
||||
}
|
||||
|
||||
$survivor->quantity = (int) $validated['quantity'];
|
||||
if (isset($validated['price'])) {
|
||||
$survivor->price = bcadd((string) $validated['price'], '0', 2);
|
||||
}
|
||||
if (isset($validated['weight'])) {
|
||||
$survivor->weight = bcadd((string) $validated['weight'], '0', 3);
|
||||
}
|
||||
$survivor->amount = bcmul((string) $survivor->quantity, (string) $survivor->price, 2);
|
||||
$survivor->save();
|
||||
|
||||
$service = app(PurchaseItemService::class);
|
||||
foreach ($affectedOrderIds as $orderId) {
|
||||
$service->recalcOrder((int) $orderId);
|
||||
}
|
||||
$service->recalcPurchase($purchase->id);
|
||||
|
||||
return $this->success([], '单品已更新');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 门店购买详情:移除单品(该门店此商品的全部订货明细一并删除)
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
#[DeleteRoute(route: '/{id}/store/{storeId}/item/{productId}', authorize: 'update', where: ['id' => '[0-9]+', 'storeId' => '[0-9]+', 'productId' => '[0-9]+'])]
|
||||
public function storeItemDelete(int $id, int $storeId, int $productId): JsonResponse
|
||||
{
|
||||
$purchase = PurchaseOrderModel::find($id);
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
$this->assertPurchaseEditable($purchase);
|
||||
|
||||
DB::transaction(function () use ($purchase, $storeId, $productId) {
|
||||
$items = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchase->id)
|
||||
->where('store_id', $storeId)
|
||||
->where('product_id', $productId)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
if ($items->isEmpty()) {
|
||||
throw new RepositoryException('该门店在此采购单中无此商品明细');
|
||||
}
|
||||
|
||||
$affectedOrderIds = $items->pluck('order_id')->unique()->all();
|
||||
foreach ($items as $item) {
|
||||
$item->delete();
|
||||
}
|
||||
|
||||
$service = app(PurchaseItemService::class);
|
||||
foreach ($affectedOrderIds as $orderId) {
|
||||
$service->recalcOrder((int) $orderId);
|
||||
}
|
||||
$service->recalcPurchase($purchase->id);
|
||||
});
|
||||
|
||||
return $this->success([], '已移除单品');
|
||||
}
|
||||
|
||||
/**
|
||||
* 账单生成预览
|
||||
*/
|
||||
@@ -489,7 +669,7 @@ class PurchaseOrderController extends BaseController
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品行修改:品名/供应商/包规/单位/成本
|
||||
* 商品行修改:品名/供应商/包规/单位/成本(同步更新商品档案;商品已删除则跳过档案同步)
|
||||
* @throws Throwable
|
||||
*/
|
||||
#[PutRoute(route: '/{id}/row/{productId}', authorize: 'update', where: ['id' => '[0-9]+', 'productId' => '[0-9]+'])]
|
||||
@@ -499,31 +679,45 @@ class PurchaseOrderController extends BaseController
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
if ($purchase->status !== PurchaseOrderModel::STATUS_PENDING) {
|
||||
throw new RepositoryException('采购单已完成,不允许修改明细');
|
||||
}
|
||||
$this->assertPurchaseEditable($purchase);
|
||||
|
||||
$validated = $request->validated();
|
||||
|
||||
$items = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchase->id)
|
||||
->where('product_id', $productId)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
if ($items->isEmpty()) {
|
||||
throw new RepositoryException('该采购单下无此商品的订货明细');
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
$item->fill($validated)->save();
|
||||
}
|
||||
return DB::transaction(function () use ($purchase, $productId, $validated) {
|
||||
$items = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchase->id)
|
||||
->where('product_id', $productId)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
if ($items->isEmpty()) {
|
||||
throw new RepositoryException('该采购单下无此商品的订货明细');
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
$item->fill($validated)->save();
|
||||
}
|
||||
|
||||
// 重算采购单成本
|
||||
$query = StoreOrderItemModel::query()->where('purchase_id', $purchase->id);
|
||||
$purchase->total_quantity = $query->sum('quantity');
|
||||
$purchase->estimate_amount = $query->sum(DB::raw('quantity * cost_price'));
|
||||
$purchase->save();
|
||||
// 同步保存到商品档案(软删除商品跳过,明细照常更新)
|
||||
$product = ProductModel::find($productId);
|
||||
$productSynced = $product !== null;
|
||||
if ($productSynced) {
|
||||
$product->update([
|
||||
'name' => $validated['product_name'],
|
||||
'supplier_id' => $validated['supplier_id'],
|
||||
'spec' => $validated['product_spec'],
|
||||
'unit' => $validated['unit'],
|
||||
'cost_price' => $validated['cost_price'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->success(['count' => $items->count()], '已同步 ' . $items->count() . ' 条订货明细');
|
||||
app(PurchaseItemService::class)->recalcPurchase($purchase->id);
|
||||
|
||||
return $this->success(
|
||||
['count' => $items->count()],
|
||||
$productSynced
|
||||
? '已同步 ' . $items->count() . ' 条订货明细与商品档案'
|
||||
: '已同步 ' . $items->count() . ' 条订货明细;商品已删除,档案未同步'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -544,31 +738,31 @@ class PurchaseOrderController extends BaseController
|
||||
if (empty($purchase)) {
|
||||
throw new RepositoryException('采购单不存在');
|
||||
}
|
||||
if ($purchase->status !== PurchaseOrderModel::STATUS_PENDING) {
|
||||
throw new RepositoryException('采购单已完成,不允许修改明细');
|
||||
}
|
||||
$this->assertPurchaseEditable($purchase);
|
||||
|
||||
$item->quantity = $validated['quantity'];
|
||||
$item->price = $validated['price'];
|
||||
if (array_key_exists('weight', $validated)) {
|
||||
$item->weight = bcadd((string) $validated['weight'], '0', 3);
|
||||
}
|
||||
$item->amount = bcmul($validated['quantity'], $validated['price'], 3);
|
||||
$item->amount = bcmul((string) $validated['quantity'], (string) $validated['price'], 2);
|
||||
$item->save();
|
||||
|
||||
// 重算订单金额
|
||||
$order = StoreOrderModel::query()->lockForUpdate()->find($item->order_id);
|
||||
$order->total_weight = $order->items()->sum('weight');
|
||||
$order->total_amount = $order->items()->sum('amount');
|
||||
$order->save();
|
||||
|
||||
// 重算采购单重量
|
||||
$purchase->total_weight = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchase->id)
|
||||
->sum('weight');
|
||||
$purchase->save();
|
||||
$service = app(PurchaseItemService::class);
|
||||
$service->recalcOrder((int) $item->order_id);
|
||||
$service->recalcPurchase($purchase->id);
|
||||
|
||||
return $this->success();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 采购单编辑闸:仅进行中(待采购)允许修改明细
|
||||
*/
|
||||
private function assertPurchaseEditable(PurchaseOrderModel $purchase): void
|
||||
{
|
||||
if ($purchase->status !== PurchaseOrderModel::STATUS_PENDING) {
|
||||
throw new RepositoryException('采购单已完成,不允许修改明细');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Purchase;
|
||||
|
||||
use Modules\Common\Http\Requests\BaseFormRequest;
|
||||
|
||||
/**
|
||||
* 采购单门店单品 新增/修改 验证(amount = 数量×单价 由后端重算)
|
||||
*/
|
||||
class PurchaseStoreItemRequest extends BaseFormRequest
|
||||
{
|
||||
protected $stopOnFirstFailure = true;
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
if ($this->isUpdate()) {
|
||||
return [
|
||||
'quantity' => 'required|integer|min:0',
|
||||
'price' => 'nullable|numeric|min:0',
|
||||
'weight' => 'nullable|numeric|min:0',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'product_id' => 'required|integer|exists:product,id',
|
||||
'quantity' => 'required|integer|min:1',
|
||||
'weight' => 'nullable|numeric|min:0',
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'product_id.required' => '请选择商品',
|
||||
'product_id.exists' => '商品不存在或已删除',
|
||||
'quantity.required' => '采购数量不能为空',
|
||||
'quantity.integer' => '采购数量必须为整数',
|
||||
'quantity.min' => '采购数量不能小于 0',
|
||||
'price.numeric' => '单价必须为数字',
|
||||
'price.min' => '单价不能小于 0',
|
||||
'weight.numeric' => '称重必须为数字',
|
||||
'weight.min' => '称重不能小于 0',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ProductModel;
|
||||
use App\Models\PurchaseOrderModel;
|
||||
use App\Models\StoreOrderItemModel;
|
||||
use App\Models\StoreOrderModel;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 采购单明细共享服务:订单/采购单汇总重算 + 门店/供应商维度的商品行聚合
|
||||
*
|
||||
* 汇总口径(勿偏离):
|
||||
* - 订单:total_quantity=Σ数量、total_weight=Σ称重、total_amount=Σ金额
|
||||
* - 采购单:total_quantity=Σ数量、estimate_amount=Σ(数量×成本价)(预估成本)、total_weight=Σ称重
|
||||
*/
|
||||
class PurchaseItemService
|
||||
{
|
||||
/**
|
||||
* 重算门店订单汇总(明细增删改后调用)
|
||||
*/
|
||||
public function recalcOrder(int $orderId): void
|
||||
{
|
||||
$order = StoreOrderModel::query()->find($orderId);
|
||||
if ($order === null) {
|
||||
return;
|
||||
}
|
||||
$order->total_quantity = (int) $order->items()->sum('quantity');
|
||||
$order->total_weight = $order->items()->sum('weight');
|
||||
$order->total_amount = $order->items()->sum('amount');
|
||||
$order->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重算采购单汇总(明细增删改后调用)
|
||||
*/
|
||||
public function recalcPurchase(int $purchaseId): void
|
||||
{
|
||||
$purchase = PurchaseOrderModel::query()->find($purchaseId);
|
||||
if ($purchase === null) {
|
||||
return;
|
||||
}
|
||||
$purchase->total_quantity = (int) StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchaseId)->sum('quantity');
|
||||
$purchase->estimate_amount = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchaseId)->sum(DB::raw('quantity * cost_price'));
|
||||
$purchase->total_weight = StoreOrderItemModel::query()
|
||||
->where('purchase_id', $purchaseId)->sum('weight');
|
||||
$purchase->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* 采购单内指定门店的采购汇总行(按商品聚合,单价=加权平均 Σ金额÷Σ数量,
|
||||
* 排序:分类 sort → 商品 sort,与明细矩阵同序)
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function storeSummaryRows(int $purchaseId, int $storeId): array
|
||||
{
|
||||
$items = $this->purchaseItems($purchaseId)
|
||||
->where('store_id', $storeId)
|
||||
->sortBy('id');
|
||||
|
||||
$rows = [];
|
||||
foreach ($items->groupBy('product_id') as $productId => $group) {
|
||||
$first = $group->first();
|
||||
$quantity = 0;
|
||||
$amount = '0';
|
||||
$weight = '0';
|
||||
foreach ($group as $item) {
|
||||
$weight = bcadd($weight, (string) $item->weight, 3);
|
||||
$quantity += (int) $item->quantity;
|
||||
$amount = bcadd($amount, (string) $item->amount, 2);
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'product_id' => (int) $productId,
|
||||
'product_name' => $first->product_name,
|
||||
'product_spec' => $first->product_spec,
|
||||
'unit' => $first->unit,
|
||||
// 加权平均单价(保证 单价×数量=预计金额)
|
||||
'price' => $quantity > 0
|
||||
? bcdiv($amount, (string) $quantity, 2)
|
||||
: (string) $first->price,
|
||||
'quantity' => $quantity,
|
||||
'amount' => $amount,
|
||||
'weight' => $weight,
|
||||
'category_sort' => (int) data_get($first, 'category_sort', 9999),
|
||||
'product_sort' => (int) data_get($first, 'product_sort', 9999),
|
||||
];
|
||||
}
|
||||
|
||||
return $this->sortRows($rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 采购单内指定供应商的商品聚合行(成本口径:金额=Σ数量×成本价,
|
||||
* 排序:分类 sort → 商品 sort)
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function supplierRows(int $purchaseId, int $supplierId): array
|
||||
{
|
||||
$items = $this->purchaseItems($purchaseId)
|
||||
->where('supplier_id', $supplierId)
|
||||
->sortBy('id');
|
||||
|
||||
$rows = [];
|
||||
foreach ($items->groupBy('product_id') as $productId => $group) {
|
||||
$first = $group->first();
|
||||
$quantity = 0;
|
||||
$weight = '0';
|
||||
$amount = '0';
|
||||
foreach ($group as $item) {
|
||||
$quantity += (int) $item->quantity;
|
||||
$weight = bcadd($weight, (string) $item->weight, 3);
|
||||
$amount = bcadd($amount, bcmul((string) $item->quantity, (string) $item->cost_price, 2), 2);
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'product_id' => (int) $productId,
|
||||
'product_name' => $first->product_name,
|
||||
'product_spec' => $first->product_spec,
|
||||
'unit' => $first->unit,
|
||||
'cost_price' => (string) $first->cost_price,
|
||||
'quantity' => $quantity,
|
||||
'weight' => $weight,
|
||||
'amount' => $amount,
|
||||
'category_sort' => (int) data_get($first, 'category_sort', 9999),
|
||||
'product_sort' => (int) data_get($first, 'product_sort', 9999),
|
||||
];
|
||||
}
|
||||
|
||||
return $this->sortRows($rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 采购单订货明细(关联订单过滤软删、成本价可见、附分类/商品排序键)
|
||||
*
|
||||
* @return Collection<int, StoreOrderItemModel>
|
||||
*/
|
||||
private function purchaseItems(int $purchaseId): Collection
|
||||
{
|
||||
$items = StoreOrderItemModel::query()
|
||||
->join('store_order', 'store_order.id', '=', 'store_order_item.order_id')
|
||||
->where('store_order_item.purchase_id', $purchaseId)
|
||||
->whereNull('store_order.deleted_at')
|
||||
->select('store_order_item.*')
|
||||
->get()
|
||||
->makeVisible('cost_price');
|
||||
|
||||
// 排序键:商品分类 sort → 商品 sort(商品含软删除,保证历史单据可导出)
|
||||
$products = ProductModel::withTrashed()
|
||||
->with('category:id,sort')
|
||||
->whereIn('id', $items->pluck('product_id')->unique())
|
||||
->get(['id', 'category_id', 'sort'])
|
||||
->keyBy('id');
|
||||
|
||||
foreach ($items as $item) {
|
||||
$product = $products->get((int) $item->product_id);
|
||||
$item->setAttribute('category_sort', (int) ($product?->category?->sort ?? 9999));
|
||||
$item->setAttribute('product_sort', (int) ($product?->sort ?? 9999));
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 排序并剥离排序键
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $rows
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function sortRows(array $rows): array
|
||||
{
|
||||
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 array_map(static function (array $row): array {
|
||||
unset($row['category_sort'], $row['product_sort']);
|
||||
return $row;
|
||||
}, $rows);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user