采购单优化
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user