采购单优化
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user