All checks were successful
ERP-Deploy-Demo / deploy-demo (push) Successful in 56s
302 lines
11 KiB
PHP
302 lines
11 KiB
PHP
<?php
|
||
|
||
namespace App\Modules\Inventory\Services;
|
||
|
||
use App\Modules\Inventory\Models\StoreRequisition;
|
||
use App\Modules\Inventory\Models\StoreRequisitionItem;
|
||
use App\Modules\Inventory\Models\InventoryTransferOrder;
|
||
use App\Modules\Inventory\Models\InventoryTransferItem;
|
||
use App\Modules\Inventory\Notifications\StoreRequisitionNotification;
|
||
use App\Modules\Core\Models\User;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Validation\ValidationException;
|
||
|
||
class StoreRequisitionService
|
||
{
|
||
protected TransferService $transferService;
|
||
|
||
public function __construct(TransferService $transferService)
|
||
{
|
||
$this->transferService = $transferService;
|
||
}
|
||
|
||
/**
|
||
* 建立叫貨單(含明細)
|
||
*/
|
||
public function create(array $data, array $items, int $userId): StoreRequisition
|
||
{
|
||
return DB::transaction(function () use ($data, $items, $userId) {
|
||
$requisition = StoreRequisition::create([
|
||
'store_warehouse_id' => $data['store_warehouse_id'],
|
||
'status' => 'draft',
|
||
'remark' => $data['remark'] ?? null,
|
||
'created_by' => $userId,
|
||
]);
|
||
|
||
foreach ($items as $item) {
|
||
$requisition->items()->create([
|
||
'product_id' => $item['product_id'],
|
||
'requested_qty' => $item['requested_qty'],
|
||
'remark' => $item['remark'] ?? null,
|
||
]);
|
||
}
|
||
|
||
return $requisition->load('items');
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 更新叫貨單(僅限 draft / rejected 狀態)
|
||
*/
|
||
public function update(StoreRequisition $requisition, array $data, array $items): StoreRequisition
|
||
{
|
||
if (!in_array($requisition->status, ['draft', 'rejected'])) {
|
||
throw ValidationException::withMessages([
|
||
'status' => '僅能編輯草稿或被駁回的叫貨單',
|
||
]);
|
||
}
|
||
|
||
return DB::transaction(function () use ($requisition, $data, $items) {
|
||
$requisition->update([
|
||
'store_warehouse_id' => $data['store_warehouse_id'],
|
||
'remark' => $data['remark'] ?? null,
|
||
'reject_reason' => null, // 清除駁回原因
|
||
]);
|
||
|
||
// 重建明細
|
||
$requisition->items()->delete();
|
||
foreach ($items as $item) {
|
||
$requisition->items()->create([
|
||
'product_id' => $item['product_id'],
|
||
'requested_qty' => $item['requested_qty'],
|
||
'remark' => $item['remark'] ?? null,
|
||
]);
|
||
}
|
||
|
||
return $requisition->load('items');
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 提交審核(draft → pending)
|
||
*/
|
||
public function submit(StoreRequisition $requisition, int $userId): StoreRequisition
|
||
{
|
||
if ($requisition->status !== 'draft' && $requisition->status !== 'rejected') {
|
||
throw ValidationException::withMessages([
|
||
'status' => '僅能提交草稿或被駁回的叫貨單',
|
||
]);
|
||
}
|
||
|
||
if ($requisition->items()->count() === 0) {
|
||
throw ValidationException::withMessages([
|
||
'items' => '叫貨單必須至少有一項商品',
|
||
]);
|
||
}
|
||
|
||
$requisition->update([
|
||
'status' => 'pending',
|
||
'submitted_at' => now(),
|
||
'reject_reason' => null,
|
||
]);
|
||
|
||
// 通知有審核權限的使用者
|
||
$this->notifyApprovers($requisition, 'submitted', $userId);
|
||
|
||
return $requisition;
|
||
}
|
||
|
||
/**
|
||
* 核准叫貨單(pending → approved),選擇供貨倉庫並自動產生調撥單
|
||
*/
|
||
public function approve(StoreRequisition $requisition, array $data, int $userId): StoreRequisition
|
||
{
|
||
if ($requisition->status !== 'pending') {
|
||
throw ValidationException::withMessages([
|
||
'status' => '僅能核准待審核的叫貨單',
|
||
]);
|
||
}
|
||
|
||
return DB::transaction(function () use ($requisition, $data, $userId) {
|
||
// 處理前端傳來的明細與批號資料
|
||
$processedItems = []; // 暫存處理後的明細,用於轉入調撥單
|
||
|
||
if (isset($data['items'])) {
|
||
foreach ($data['items'] as $itemData) {
|
||
$reqItemId = $itemData['id'];
|
||
$totalApprovedQty = 0;
|
||
$batches = $itemData['batches'] ?? [];
|
||
|
||
// 如果有批號,根據批號展開。若有多個無批號(null)的批次(例如來自不同貨道),則將其數量加總
|
||
if (!empty($batches)) {
|
||
$batchGroups = [];
|
||
foreach ($batches as $batch) {
|
||
$qty = (float)($batch['qty'] ?? 0);
|
||
$bNum = $batch['batch_number'] ?? null;
|
||
if ($qty > 0) {
|
||
$totalApprovedQty += $qty;
|
||
$batchKey = $bNum ?? '';
|
||
$batchGroups[$batchKey] = ($batchGroups[$batchKey] ?? 0) + $qty;
|
||
}
|
||
}
|
||
|
||
foreach ($batchGroups as $bNumKey => $qty) {
|
||
$processedItems[] = [
|
||
'req_item_id' => $reqItemId,
|
||
'batch_number' => $bNumKey === '' ? null : $bNumKey,
|
||
'quantity' => $qty,
|
||
];
|
||
}
|
||
} else {
|
||
// 無批號,傳統輸入
|
||
$qty = (float)($itemData['approved_qty'] ?? 0);
|
||
if ($qty > 0) {
|
||
$totalApprovedQty += $qty;
|
||
$processedItems[] = [
|
||
'req_item_id' => $reqItemId,
|
||
'batch_number' => null,
|
||
'quantity' => $qty,
|
||
];
|
||
}
|
||
}
|
||
|
||
// 更新叫貨單明細的核准數量總和
|
||
StoreRequisitionItem::where('id', $reqItemId)
|
||
->where('store_requisition_id', $requisition->id)
|
||
->update(['approved_qty' => $totalApprovedQty]);
|
||
}
|
||
}
|
||
|
||
// 優先使用傳入的供貨倉庫,若無則從單據中取得
|
||
$supplyWarehouseId = $requisition->supply_warehouse_id;
|
||
|
||
if (!$supplyWarehouseId) {
|
||
throw ValidationException::withMessages([
|
||
'supply_warehouse_id' => '請指定供貨倉庫',
|
||
]);
|
||
}
|
||
|
||
// 查詢供貨倉庫是否有預設在途倉
|
||
$supplyWarehouse = \App\Modules\Inventory\Models\Warehouse::find($supplyWarehouseId);
|
||
$defaultTransitId = $supplyWarehouse?->default_transit_warehouse_id;
|
||
|
||
// 產生調撥單(供貨倉庫 → 門市倉庫)
|
||
$transferOrder = $this->transferService->createOrder(
|
||
fromWarehouseId: $supplyWarehouseId,
|
||
toWarehouseId: $requisition->store_warehouse_id,
|
||
remarks: "由叫貨單 {$requisition->doc_no} 自動產生",
|
||
userId: $userId,
|
||
transitWarehouseId: $defaultTransitId,
|
||
);
|
||
|
||
// 將核准的明細寫入調撥單
|
||
$requisition->load('items');
|
||
$transferItems = [];
|
||
|
||
// 建立 req_item_id 對應 product_id 的 lookup
|
||
$reqItemMap = $requisition->items->keyBy('id');
|
||
|
||
foreach ($processedItems as $pItem) {
|
||
$reqItem = $reqItemMap->get($pItem['req_item_id']);
|
||
if ($reqItem) {
|
||
$transferItems[] = [
|
||
'product_id' => $reqItem->product_id,
|
||
'batch_number' => $pItem['batch_number'],
|
||
'quantity' => $pItem['quantity'],
|
||
];
|
||
}
|
||
}
|
||
|
||
if (!empty($transferItems)) {
|
||
$this->transferService->updateItems($transferOrder, $transferItems);
|
||
}
|
||
|
||
// 更新叫貨單狀態
|
||
$requisition->update([
|
||
'status' => 'approved',
|
||
'supply_warehouse_id' => $supplyWarehouseId,
|
||
'approved_by' => $userId,
|
||
'approved_at' => now(),
|
||
'transfer_order_id' => $transferOrder->id,
|
||
]);
|
||
|
||
// 通知申請人
|
||
$this->notifyCreator($requisition, 'approved', $userId);
|
||
|
||
return $requisition->load(['items', 'transferOrder']);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 駁回叫貨單(pending → rejected)
|
||
*/
|
||
public function reject(StoreRequisition $requisition, string $reason, int $userId): StoreRequisition
|
||
{
|
||
if ($requisition->status !== 'pending') {
|
||
throw ValidationException::withMessages([
|
||
'status' => '僅能駁回待審核的叫貨單',
|
||
]);
|
||
}
|
||
|
||
$requisition->update([
|
||
'status' => 'rejected',
|
||
'reject_reason' => $reason,
|
||
'approved_by' => $userId,
|
||
'approved_at' => now(),
|
||
]);
|
||
|
||
// 通知申請人
|
||
$this->notifyCreator($requisition, 'rejected', $userId);
|
||
|
||
return $requisition;
|
||
}
|
||
|
||
/**
|
||
* 取消叫貨單
|
||
*/
|
||
public function cancel(StoreRequisition $requisition): StoreRequisition
|
||
{
|
||
if (!in_array($requisition->status, ['draft', 'pending'])) {
|
||
throw ValidationException::withMessages([
|
||
'status' => '僅能取消草稿或待審核的叫貨單',
|
||
]);
|
||
}
|
||
|
||
$requisition->update(['status' => 'cancelled']);
|
||
|
||
return $requisition;
|
||
}
|
||
|
||
/**
|
||
* 通知有審核權限的使用者
|
||
*/
|
||
protected function notifyApprovers(StoreRequisition $requisition, string $action, int $actorId): void
|
||
{
|
||
$actor = User::find($actorId);
|
||
$actorName = $actor?->name ?? 'System';
|
||
|
||
// 找出有 store_requisitions.approve 權限的使用者
|
||
$approvers = User::permission('store_requisitions.approve')->get();
|
||
|
||
foreach ($approvers as $approver) {
|
||
if ($approver->id !== $actorId) {
|
||
$approver->notify(new StoreRequisitionNotification($requisition, $action, $actorName));
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 通知叫貨單申請人
|
||
*/
|
||
protected function notifyCreator(StoreRequisition $requisition, string $action, int $actorId): void
|
||
{
|
||
$actor = User::find($actorId);
|
||
$actorName = $actor?->name ?? 'System';
|
||
|
||
$creator = User::find($requisition->created_by);
|
||
if ($creator && $creator->id !== $actorId) {
|
||
$creator->notify(new StoreRequisitionNotification($requisition, $action, $actorName));
|
||
}
|
||
}
|
||
}
|