feat: 實作出貨單模組並暫時導向通用製作中頁面,同步優化盤點與調撥功能的活動日誌顯示
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 1m11s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped

This commit is contained in:
2026-02-05 09:33:36 +08:00
parent 4299e985e9
commit 04f3891275
23 changed files with 1410 additions and 30 deletions

View File

@@ -106,6 +106,16 @@ interface InventoryServiceInterface
*/
public function decreaseInventoryQuantity(int $inventoryId, float $quantity, ?string $reason = null, ?string $referenceType = null, $referenceId = null);
/**
* Find a specific inventory record by warehouse, product and batch.
*
* @param int $warehouseId
* @param int $productId
* @param string|null $batchNumber
* @return object|null
*/
public function findInventoryByBatch(int $warehouseId, int $productId, ?string $batchNumber);
/**
* Get statistics for the dashboard.
*

View File

@@ -127,7 +127,7 @@ class TransferOrderController extends Controller
'batch_number' => $item->batch_number,
'unit' => $item->product->baseUnit?->name,
'quantity' => (float) $item->quantity,
'max_quantity' => $stock ? (float) $stock->quantity : 0.0,
'max_quantity' => $item->snapshot_quantity ? (float) $item->snapshot_quantity : ($stock ? (float) $stock->quantity : 0.0),
'notes' => $item->notes,
];
}),
@@ -154,14 +154,22 @@ class TransferOrderController extends Controller
]);
// 1. 先更新資料
$itemsChanged = false;
if ($request->has('items')) {
$this->transferService->updateItems($order, $validated['items']);
$itemsChanged = $this->transferService->updateItems($order, $validated['items']);
}
$order->fill($request->only(['remarks']));
$remarksChanged = $order->remarks !== ($validated['remarks'] ?? null);
// [IMPORTANT] 使用 touch() 確保即便只有品項異動,也會因為 updated_at 變更而觸發自動日誌
$order->touch();
if ($itemsChanged || $remarksChanged) {
$order->remarks = $validated['remarks'] ?? null;
// [IMPORTANT] 使用 touch() 確保即便只有品項異動,也會因為 updated_at 變更而觸發自動日誌
$order->touch();
$message = '儲存成功';
} else {
$message = '資料未變更';
// 如果沒變更,就不執行 touch(),也不會產生 Activity Log
}
// 2. 判斷是否需要過帳
if ($request->input('action') === 'post') {
@@ -174,7 +182,7 @@ class TransferOrderController extends Controller
}
}
return redirect()->back()->with('success', '儲存成功');
return redirect()->back()->with('success', $message);
}
public function destroy(InventoryTransferOrder $order)

View File

@@ -15,6 +15,7 @@ class InventoryTransferItem extends Model
'product_id',
'batch_number',
'quantity',
'snapshot_quantity',
'notes',
];

View File

@@ -188,6 +188,14 @@ class InventoryService implements InventoryServiceInterface
});
}
public function findInventoryByBatch(int $warehouseId, int $productId, ?string $batchNumber)
{
return Inventory::where('warehouse_id', $warehouseId)
->where('product_id', $productId)
->where('batch_number', $batchNumber)
->first();
}
public function getDashboardStats(): array
{
// 庫存總表 join 安全庫存表,計算低庫存

View File

@@ -31,9 +31,9 @@ class TransferService
/**
* 更新調撥單明細 (支援精確 Diff 與自動日誌整合)
*/
public function updateItems(InventoryTransferOrder $order, array $itemsData): void
public function updateItems(InventoryTransferOrder $order, array $itemsData): bool
{
DB::transaction(function () use ($order, $itemsData) {
return DB::transaction(function () use ($order, $itemsData) {
// 1. 準備舊資料索引 (Key: product_id . '_' . batch_number)
$oldItemsMap = $order->items->mapWithKeys(function ($item) {
$key = $item->product_id . '_' . ($item->batch_number ?? '');
@@ -88,9 +88,13 @@ class TransferService
];
}
} else {
// 新增
$diff['added'][] = [
// 新增 (使用者需求:顯示為更新,從 0 -> X)
$diff['updated'][] = [
'product_name' => $item->product->name,
'old' => [
'quantity' => 0,
'notes' => null,
],
'new' => [
'quantity' => (float)$item->quantity,
'notes' => $item->notes,
@@ -113,10 +117,12 @@ class TransferService
}
// 4. 將 Diff 注入到 Model 的暫存屬性中
// 如果 Diff 有內容,才注入
if (!empty($diff['added']) || !empty($diff['removed']) || !empty($diff['updated'])) {
$hasChanged = !empty($diff['added']) || !empty($diff['removed']) || !empty($diff['updated']);
if ($hasChanged) {
$order->activityProperties['items_diff'] = $diff;
}
return $hasChanged;
});
}
@@ -150,6 +156,9 @@ class TransferService
$oldSourceQty = $sourceInventory->quantity;
$newSourceQty = $oldSourceQty - $item->quantity;
// 儲存庫存快照
$item->update(['snapshot_quantity' => $oldSourceQty]);
$sourceInventory->quantity = $newSourceQty;
// 更新總值 (假設成本不變)
$sourceInventory->total_value = $sourceInventory->quantity * $sourceInventory->unit_cost;

View File

@@ -0,0 +1,133 @@
<?php
namespace App\Modules\Procurement\Controllers;
use App\Http\Controllers\Controller;
use App\Modules\Procurement\Models\ShippingOrder;
use App\Modules\Inventory\Contracts\InventoryServiceInterface;
use App\Modules\Core\Contracts\CoreServiceInterface;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\DB;
class ShippingOrderController extends Controller
{
protected $inventoryService;
protected $coreService;
protected $shippingService;
public function __construct(
InventoryServiceInterface $inventoryService,
CoreServiceInterface $coreService,
\App\Modules\Procurement\Services\ShippingService $shippingService
) {
$this->inventoryService = $inventoryService;
$this->coreService = $coreService;
$this->shippingService = $shippingService;
}
public function index(Request $request)
{
return Inertia::render('Common/UnderConstruction', [
'featureName' => '出貨單管理'
]);
/* 原有邏輯暫存
$query = ShippingOrder::query();
// 搜尋
if ($request->search) {
$query->where(function($q) use ($request) {
$q->where('doc_no', 'like', "%{$request->search}%")
->orWhere('customer_name', 'like', "%{$request->search}%");
});
}
// 狀態篩選
if ($request->status && $request->status !== 'all') {
$query->where('status', $request->status);
}
$perPage = $request->input('per_page', 10);
$orders = $query->orderBy('id', 'desc')->paginate($perPage)->withQueryString();
// 水和倉庫與使用者
$warehouses = $this->inventoryService->getAllWarehouses();
$userIds = $orders->getCollection()->pluck('created_by')->filter()->unique()->toArray();
$users = $this->coreService->getUsersByIds($userIds)->keyBy('id');
$orders->getCollection()->transform(function ($order) use ($warehouses, $users) {
$order->warehouse_name = $warehouses->firstWhere('id', $order->warehouse_id)?->name ?? 'Unknown';
$order->creator_name = $users->get($order->created_by)?->name ?? 'System';
return $order;
});
return Inertia::render('ShippingOrder/Index', [
'orders' => $orders,
'filters' => $request->only(['search', 'status', 'per_page']),
'warehouses' => $warehouses->map(fn($w) => ['id' => $w->id, 'name' => $w->name]),
]);
*/
}
public function create()
{
return Inertia::render('Common/UnderConstruction', [
'featureName' => '出貨單建立'
]);
/* 原有邏輯暫存
$warehouses = $this->inventoryService->getAllWarehouses();
$products = $this->inventoryService->getAllProducts();
return Inertia::render('ShippingOrder/Create', [
'warehouses' => $warehouses->map(fn($w) => ['id' => $w->id, 'name' => $w->name]),
'products' => $products->map(fn($p) => [
'id' => $p->id,
'name' => $p->name,
'code' => $p->code,
'unit_name' => $p->baseUnit?->name,
]),
]);
*/
}
public function store(Request $request)
{
return back()->with('error', '出貨單管理功能正在製作中');
}
public function show($id)
{
return Inertia::render('Common/UnderConstruction', [
'featureName' => '出貨單詳情'
]);
}
public function edit($id)
{
return Inertia::render('Common/UnderConstruction', [
'featureName' => '出貨單編輯'
]);
}
public function update(Request $request, $id)
{
return back()->with('error', '出貨單管理功能正在製作中');
}
public function post($id)
{
return back()->with('error', '出貨單管理功能正在製作中');
}
public function destroy($id)
{
$order = ShippingOrder::findOrFail($id);
if ($order->status !== 'draft') {
return back()->withErrors(['error' => '僅能刪除草稿狀態的單據']);
}
$order->delete();
return redirect()->route('delivery-notes.index')->with('success', '出貨單已刪除');
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace App\Modules\Procurement\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Contracts\Activity;
class ShippingOrder extends Model
{
use HasFactory, LogsActivity;
protected $fillable = [
'doc_no',
'customer_name',
'warehouse_id',
'status',
'shipping_date',
'total_amount',
'tax_amount',
'grand_total',
'remarks',
'created_by',
'posted_by',
'posted_at',
];
protected $casts = [
'shipping_date' => 'date',
'posted_at' => 'datetime',
'total_amount' => 'decimal:2',
'tax_amount' => 'decimal:2',
'grand_total' => 'decimal:2',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll()
->logOnlyDirty()
->dontSubmitEmptyLogs();
}
public function tapActivity(Activity $activity, string $eventName)
{
$snapshot = $activity->properties['snapshot'] ?? [];
$snapshot['doc_no'] = $this->doc_no;
$snapshot['customer_name'] = $this->customer_name;
$activity->properties = $activity->properties->merge([
'snapshot' => $snapshot
]);
}
public function items()
{
return $this->hasMany(ShippingOrderItem::class);
}
/**
* 自動產生單號
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->doc_no)) {
$today = date('Ymd');
$prefix = 'SHP-' . $today . '-';
$lastDoc = static::where('doc_no', 'like', $prefix . '%')
->orderBy('doc_no', 'desc')
->first();
if ($lastDoc) {
$lastNumber = substr($lastDoc->doc_no, -2);
$nextNumber = str_pad((int)$lastNumber + 1, 2, '0', STR_PAD_LEFT);
} else {
$nextNumber = '01';
}
$model->doc_no = $prefix . $nextNumber;
}
});
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Modules\Procurement\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ShippingOrderItem extends Model
{
use HasFactory;
protected $fillable = [
'shipping_order_id',
'product_id',
'batch_number',
'quantity',
'unit_price',
'subtotal',
'remark',
];
protected $casts = [
'quantity' => 'decimal:4',
'unit_price' => 'decimal:4',
'subtotal' => 'decimal:2',
];
public function shippingOrder()
{
return $this->belongsTo(ShippingOrder::class);
}
// 注意:在模組化架構下,跨模組關聯應謹慎使用或是直接在 Controller 水和 (Hydration)
// 但為了開發便利,暫時保留對 Product 的關聯(如果 Product 在不同模組,可能無法直接 lazy load
}

View File

@@ -35,4 +35,24 @@ Route::middleware('auth')->group(function () {
Route::put('/purchase-orders/{id}', [PurchaseOrderController::class, 'update'])->middleware('permission:purchase_orders.edit')->name('purchase-orders.update');
Route::delete('/purchase-orders/{id}', [PurchaseOrderController::class, 'destroy'])->middleware('permission:purchase_orders.delete')->name('purchase-orders.destroy');
});
// 出貨單管理 (Delivery Notes)
Route::middleware('permission:delivery_notes.view')->group(function () {
Route::get('/delivery-notes', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'index'])->name('delivery-notes.index');
Route::middleware('permission:delivery_notes.create')->group(function () {
Route::get('/delivery-notes/create', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'create'])->name('delivery-notes.create');
Route::post('/delivery-notes', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'store'])->name('delivery-notes.store');
});
Route::get('/delivery-notes/{id}', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'show'])->name('delivery-notes.show');
Route::middleware('permission:delivery_notes.edit')->group(function () {
Route::get('/delivery-notes/{id}/edit', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'edit'])->name('delivery-notes.edit');
Route::put('/delivery-notes/{id}', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'update'])->name('delivery-notes.update');
Route::post('/delivery-notes/{id}/post', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'post'])->name('delivery-notes.post');
});
Route::delete('/delivery-notes/{id}', [\App\Modules\Procurement\Controllers\ShippingOrderController::class, 'destroy'])->middleware('permission:delivery_notes.delete')->name('delivery-notes.destroy');
});
});

View File

@@ -0,0 +1,118 @@
<?php
namespace App\Modules\Procurement\Services;
use App\Modules\Procurement\Models\ShippingOrder;
use App\Modules\Procurement\Models\ShippingOrderItem;
use App\Modules\Inventory\Contracts\InventoryServiceInterface;
use Illuminate\Support\Facades\DB;
class ShippingService
{
protected $inventoryService;
public function __construct(InventoryServiceInterface $inventoryService)
{
$this->inventoryService = $inventoryService;
}
public function createShippingOrder(array $data)
{
return DB::transaction(function () use ($data) {
$order = ShippingOrder::create([
'warehouse_id' => $data['warehouse_id'],
'customer_name' => $data['customer_name'] ?? null,
'shipping_date' => $data['shipping_date'],
'status' => 'draft',
'remarks' => $data['remarks'] ?? null,
'created_by' => auth()->id(),
'total_amount' => $data['total_amount'] ?? 0,
'tax_amount' => $data['tax_amount'] ?? 0,
'grand_total' => $data['grand_total'] ?? 0,
]);
foreach ($data['items'] as $item) {
$order->items()->create([
'product_id' => $item['product_id'],
'batch_number' => $item['batch_number'] ?? null,
'quantity' => $item['quantity'],
'unit_price' => $item['unit_price'] ?? 0,
'subtotal' => $item['subtotal'] ?? ($item['quantity'] * ($item['unit_price'] ?? 0)),
'remark' => $item['remark'] ?? null,
]);
}
return $order;
});
}
public function updateShippingOrder(ShippingOrder $order, array $data)
{
return DB::transaction(function () use ($order, $data) {
$order->update([
'warehouse_id' => $data['warehouse_id'],
'customer_name' => $data['customer_name'] ?? null,
'shipping_date' => $data['shipping_date'],
'remarks' => $data['remarks'] ?? null,
'total_amount' => $data['total_amount'] ?? 0,
'tax_amount' => $data['tax_amount'] ?? 0,
'grand_total' => $data['grand_total'] ?? 0,
]);
// 簡單處理:刪除舊項目並新增
$order->items()->delete();
foreach ($data['items'] as $item) {
$order->items()->create([
'product_id' => $item['product_id'],
'batch_number' => $item['batch_number'] ?? null,
'quantity' => $item['quantity'],
'unit_price' => $item['unit_price'] ?? 0,
'subtotal' => $item['subtotal'] ?? ($item['quantity'] * ($item['unit_price'] ?? 0)),
'remark' => $item['remark'] ?? null,
]);
}
return $order;
});
}
public function post(ShippingOrder $order)
{
if ($order->status !== 'draft') {
throw new \Exception('該單據已過帳或已取消。');
}
return DB::transaction(function () use ($order) {
foreach ($order->items as $item) {
// 尋找對應的庫存紀錄
$inventory = $this->inventoryService->findInventoryByBatch(
$order->warehouse_id,
$item->product_id,
$item->batch_number
);
if (!$inventory || $inventory->quantity < $item->quantity) {
$productName = $this->inventoryService->getProduct($item->product_id)?->name ?? 'Unknown';
throw new \Exception("商品 [{$productName}] (批號: {$item->batch_number}) 庫存不足。");
}
// 扣除庫存
$this->inventoryService->decreaseInventoryQuantity(
$inventory->id,
$item->quantity,
"出貨扣款: 單號 [{$order->doc_no}]",
'ShippingOrder',
$order->id
);
}
$order->update([
'status' => 'completed',
'posted_by' => auth()->id(),
'posted_at' => now(),
]);
return $order;
});
}
}

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('inventory_transfer_items', function (Blueprint $table) {
$table->decimal('snapshot_quantity', 10, 2)->nullable()->comment('過帳時的來源倉可用庫存快照')->after('quantity');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('inventory_transfer_items', function (Blueprint $table) {
$table->dropColumn('snapshot_quantity');
});
}
};

View File

@@ -0,0 +1,62 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('shipping_orders', function (Blueprint $table) {
$table->id();
$table->string('doc_no')->unique()->comment('出貨單號');
$table->string('customer_name')->nullable()->comment('客戶名稱');
$table->unsignedBigInteger('warehouse_id')->comment('來源倉庫');
$table->string('status')->default('draft')->comment('狀態: draft, completed, cancelled');
$table->date('shipping_date')->comment('出貨日期');
$table->decimal('total_amount', 15, 2)->default(0)->comment('總金額 (不含稅)');
$table->decimal('tax_amount', 15, 2)->default(0)->comment('稅額');
$table->decimal('grand_total', 15, 2)->default(0)->comment('總計');
$table->text('remarks')->nullable()->comment('備註');
$table->unsignedBigInteger('created_by')->nullable();
$table->unsignedBigInteger('posted_by')->nullable();
$table->timestamp('posted_at')->nullable();
$table->timestamps();
$table->index('warehouse_id');
$table->index('status');
$table->index('shipping_date');
});
Schema::create('shipping_order_items', function (Blueprint $table) {
$table->id();
$table->foreignId('shipping_order_id')->constrained('shipping_orders')->onDelete('cascade');
$table->unsignedBigInteger('product_id')->comment('商品 ID');
$table->string('batch_number')->nullable()->comment('批號');
$table->decimal('quantity', 15, 4)->comment('出貨數量');
$table->decimal('unit_price', 15, 4)->default(0)->comment('單價');
$table->decimal('subtotal', 15, 2)->default(0)->comment('小計');
$table->string('remark')->nullable()->comment('項目備註');
$table->timestamps();
$table->index('product_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('shipping_order_items');
Schema::dropIfExists('shipping_orders');
}
};

View File

@@ -61,6 +61,12 @@ class PermissionSeeder extends Seeder
'goods_receipts.edit',
'goods_receipts.delete',
// 出貨單管理 (Delivery Notes / Shipping Orders)
'delivery_notes.view',
'delivery_notes.create',
'delivery_notes.edit',
'delivery_notes.delete',
// 生產工單管理
'production_orders.view',
'production_orders.create',
@@ -138,6 +144,7 @@ class PermissionSeeder extends Seeder
'inventory_adjust.view', 'inventory_adjust.create', 'inventory_adjust.edit', 'inventory_adjust.delete',
'inventory_transfer.view', 'inventory_transfer.create', 'inventory_transfer.edit', 'inventory_transfer.delete',
'goods_receipts.view', 'goods_receipts.create', 'goods_receipts.edit', 'goods_receipts.delete',
'delivery_notes.view', 'delivery_notes.create', 'delivery_notes.edit', 'delivery_notes.delete',
'production_orders.view', 'production_orders.create', 'production_orders.edit', 'production_orders.delete',
'recipes.view', 'recipes.create', 'recipes.edit', 'recipes.delete',
'vendors.view', 'vendors.create', 'vendors.edit', 'vendors.delete',

View File

@@ -150,13 +150,13 @@ export default function AuthenticatedLayout({
route: "/goods-receipts",
permission: "goods_receipts.view",
},
// {
// id: "delivery-note-list",
// label: "出貨單管理 (開發中)",
// icon: <Package className="h-4 w-4" />,
// // route: "/delivery-notes",
// permission: "delivery_notes.view",
// },
{
id: "delivery-note-list",
label: "出貨單管理 (功能製作中)",
icon: <Package className="h-4 w-4" />,
route: "/delivery-notes",
permission: "delivery_notes.view",
},
],
},
{

View File

@@ -0,0 +1,61 @@
import { Head, Link } from "@inertiajs/react";
import { Hammer, Home, ArrowLeft } from "lucide-react";
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
interface Props {
featureName?: string;
}
export default function UnderConstruction({ featureName = "此功能" }: Props) {
return (
<AuthenticatedLayout breadcrumbs={[
{ label: '系統訊息', href: '#' },
{ label: '功能製作中', isPage: true }
] as any}>
<Head title="功能製作中" />
<div className="flex flex-col items-center justify-center min-h-[70vh] px-4 text-center">
<div className="relative mb-8">
<div className="absolute inset-0 bg-primary/10 rounded-full animate-ping opacity-25"></div>
<div className="relative bg-white p-8 rounded-full shadow-xl border-4 border-primary/20">
<Hammer className="h-20 w-20 text-primary-main animate-bounce" />
</div>
</div>
<h1 className="text-3xl font-bold text-gray-900 mb-4">
{featureName}
</h1>
<p className="text-gray-500 max-w-md mb-10 text-lg leading-relaxed">
</p>
<div className="flex flex-col sm:flex-row gap-4">
<Button
variant="outline"
size="lg"
className="button-outlined-primary gap-2 min-w-[150px]"
onClick={() => window.history.back()}
>
<ArrowLeft className="h-5 w-5" />
</Button>
<Link href={route('dashboard')}>
<Button
variant="default"
size="lg"
className="button-filled-primary gap-2 min-w-[150px]"
>
<Home className="h-5 w-5" />
</Button>
</Link>
</div>
<div className="mt-16 text-sm text-gray-400 font-mono">
Coming Soon | Star ERP Design System
</div>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -253,7 +253,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
<>
<span className="mx-1">|</span>
<Link
href={route('inventory.count.show', [doc.count_doc_id])}
href={route('inventory.count.show', [doc.count_doc_id]) + `?from=adjust&adjust_id=${doc.id}`}
className="flex items-center gap-1 text-primary-main hover:underline"
>
: {doc.count_doc_no}

View File

@@ -157,7 +157,7 @@ export default function Index({ docs, warehouses, filters }: any) {
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存管理', href: '#' },
{ label: '商品與庫存管理', href: '#' },
{ label: '庫存盤點', href: route('inventory.count.index'), isPage: true },
]}
>

View File

@@ -28,6 +28,17 @@ import { Can } from '@/Components/Permission/Can';
export default function Show({ doc }: any) {
// Get query parameters for dynamic back button
const urlParams = new URLSearchParams(window.location.search);
const fromSource = urlParams.get('from');
const adjustId = urlParams.get('adjust_id');
const backUrl = fromSource === 'adjust' && adjustId
? route('inventory.adjust.show', [adjustId])
: route('inventory.count.index');
const backLabel = fromSource === 'adjust' ? '返回盤調單' : '返回盤點單列表';
// Transform items to form data structure
const { data, setData, put, delete: destroy, processing, transform } = useForm({
items: doc.items.map((item: any) => ({
@@ -77,21 +88,28 @@ export default function Show({ doc }: any) {
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存管理', href: '#' },
{ label: '庫存盤點', href: route('inventory.count.index') },
{
label: fromSource === 'adjust' ? '庫存盤調' : '庫存盤點',
href: fromSource === 'adjust' ? route('inventory.adjust.index') : route('inventory.count.index')
},
fromSource === 'adjust' && adjustId ? {
label: `盤調單詳情`,
href: route('inventory.adjust.show', [adjustId])
} : null,
{ label: `盤點單: ${doc.doc_no}`, href: route('inventory.count.show', [doc.id]), isPage: true },
]}
].filter(Boolean) as any}
>
<Head title={`盤點單 ${doc.doc_no}`} />
<div className="container mx-auto p-6 max-w-7xl animate-in fade-in duration-500 space-y-6">
<div>
<Link href={route('inventory.count.index')}>
<Link href={backUrl}>
<Button
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-4 w-4" />
{backLabel}
</Button>
</Link>

View File

@@ -173,7 +173,7 @@ export default function Index({ warehouses, orders, filters }: any) {
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存管理', href: '#' },
{ label: '商品與庫存管理', href: '#' },
{ label: '庫存調撥', href: route('inventory.transfer.index'), isPage: true },
]}
>

View File

@@ -154,7 +154,7 @@ export default function Show({ order }: any) {
items: items,
remarks: remarks,
}, {
onSuccess: () => toast.success("儲存成功"),
onSuccess: () => { },
onError: () => toast.error("儲存失敗,請檢查輸入"),
});
} finally {
@@ -168,7 +168,6 @@ export default function Show({ order }: any) {
}, {
onSuccess: () => {
setIsPostDialogOpen(false);
toast.success("過帳成功");
}
});
};
@@ -177,7 +176,6 @@ export default function Show({ order }: any) {
router.delete(route('inventory.transfer.destroy', [order.id]), {
onSuccess: () => {
setDeleteId(null);
toast.success("已成功刪除");
}
});
};
@@ -469,7 +467,9 @@ export default function Show({ order }: any) {
<TableHead className="w-[50px] text-center font-medium text-grey-600">#</TableHead>
<TableHead className="font-medium text-grey-600"> / </TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="text-right w-32 font-medium text-grey-600"></TableHead>
<TableHead className="text-right w-32 font-medium text-grey-600">
{order.status === 'completed' ? '過帳時庫存' : '可用庫存'}
</TableHead>
<TableHead className="text-right w-40 font-medium text-grey-600">調</TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>

View File

@@ -0,0 +1,330 @@
import { useState, useEffect } from "react";
import { ArrowLeft, Plus, Trash2, Package, Info, Calculator } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { toast } from "sonner";
import axios from "axios";
interface Product {
id: number;
name: string;
code: string;
unit_name: string;
}
interface Item {
product_id: number | null;
product_name?: string;
product_code?: string;
unit_name?: string;
batch_number: string;
quantity: number;
unit_price: number;
subtotal: number;
remark: string;
available_batches: any[];
}
interface Props {
order?: any;
warehouses: { id: number; name: string }[];
products: Product[];
}
export default function ShippingOrderCreate({ order, warehouses, products }: Props) {
const isEdit = !!order;
const [warehouseId, setWarehouseId] = useState<string>(order?.warehouse_id?.toString() || "");
const [customerName, setCustomerName] = useState(order?.customer_name || "");
const [shippingDate, setShippingDate] = useState(order?.shipping_date || new Date().toISOString().split('T')[0]);
const [remarks, setRemarks] = useState(order?.remarks || "");
const [items, setItems] = useState<Item[]>(order?.items?.map((item: any) => ({
product_id: item.product_id,
batch_number: item.batch_number,
quantity: Number(item.quantity),
unit_price: Number(item.unit_price),
subtotal: Number(item.subtotal),
remark: item.remark || "",
available_batches: [],
})) || []);
const [taxAmount, setTaxAmount] = useState(Number(order?.tax_amount) || 0);
const totalAmount = items.reduce((sum, item) => sum + item.subtotal, 0);
const grandTotal = totalAmount + taxAmount;
// 當品項變動時,自動計算稅額 (預設 5%)
useEffect(() => {
if (!isEdit || (isEdit && order.status === 'draft')) {
setTaxAmount(Math.round(totalAmount * 0.05));
}
}, [totalAmount]);
const addItem = () => {
setItems([...items, {
product_id: null,
batch_number: "",
quantity: 1,
unit_price: 0,
subtotal: 0,
remark: "",
available_batches: [],
}]);
};
const removeItem = (index: number) => {
setItems(items.filter((_, i) => i !== index));
};
const updateItem = (index: number, updates: Partial<Item>) => {
const newItems = [...items];
newItems[index] = { ...newItems[index], ...updates };
// 計算小計
if ('quantity' in updates || 'unit_price' in updates) {
newItems[index].subtotal = Number(newItems[index].quantity) * Number(newItems[index].unit_price);
}
setItems(newItems);
// 如果商品變動,抓取批號
if ('product_id' in updates && updates.product_id && warehouseId) {
fetchBatches(index, updates.product_id, warehouseId);
}
};
const fetchBatches = async (index: number, productId: number, wId: string) => {
try {
const response = await axios.get(route('api.warehouses.inventory.batches', { warehouse: wId, productId }));
const newItems = [...items];
newItems[index].available_batches = response.data;
setItems(newItems);
} catch (error) {
console.error("Failed to fetch batches", error);
}
};
const handleSave = () => {
if (!warehouseId) {
toast.error("請選擇出貨倉庫");
return;
}
if (!shippingDate) {
toast.error("請選擇出貨日期");
return;
}
if (items.length === 0) {
toast.error("請至少新增一個品項");
return;
}
const data = {
warehouse_id: warehouseId,
customer_name: customerName,
shipping_date: shippingDate,
remarks: remarks,
total_amount: totalAmount,
tax_amount: taxAmount,
grand_total: grandTotal,
items: items.map(item => ({
product_id: item.product_id,
batch_number: item.batch_number,
quantity: item.quantity,
unit_price: item.unit_price,
subtotal: item.subtotal,
remark: item.remark,
})),
};
if (isEdit) {
router.put(route('delivery-notes.update', order.id), data);
} else {
router.post(route('delivery-notes.store'), data);
}
};
return (
<AuthenticatedLayout breadcrumbs={[
{ label: '供應鏈管理', href: '#' },
{ label: '出貨單管理', href: route('delivery-notes.index') },
{ label: isEdit ? '編輯出貨單' : '建立出貨單', isPage: true }
] as any}>
<Head title={isEdit ? "編輯出貨單" : "建立出貨單"} />
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<Link href={route('delivery-notes.index')}>
<Button variant="outline" className="gap-2 button-outlined-primary mb-4">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<h1 className="text-2xl font-bold flex items-center gap-2">
<Package className="h-6 w-6 text-primary-main" />
{isEdit ? `編輯出貨單 ${order.doc_no}` : "建立新出貨單"}
</h1>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* 左側:基本資訊 */}
<div className="lg:col-span-2 space-y-6">
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<h2 className="text-lg font-bold mb-4 flex items-center gap-2">
<Info className="h-5 w-5 text-primary-main" />
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-sm font-medium"> *</label>
<SearchableSelect
value={warehouseId}
onValueChange={setWarehouseId}
options={warehouses.map(w => ({ label: w.name, value: w.id.toString() }))}
placeholder="選擇倉庫"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium"> *</label>
<Input
type="date"
value={shippingDate}
onChange={e => setShippingDate(e.target.value)}
/>
</div>
<div className="space-y-2 md:col-span-2">
<label className="text-sm font-medium"></label>
<Input
placeholder="輸入客戶或專案名稱"
value={customerName}
onChange={e => setCustomerName(e.target.value)}
/>
</div>
<div className="space-y-2 md:col-span-2">
<label className="text-sm font-medium"></label>
<Textarea
placeholder="其他說明..."
value={remarks}
onChange={e => setRemarks(e.target.value)}
rows={3}
/>
</div>
</div>
</div>
{/* 品項明細 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-bold flex items-center gap-2">
<Package className="h-5 w-5 text-primary-main" />
</h2>
<Button onClick={addItem} size="sm" className="button-filled-primary gap-1">
<Plus className="h-4 w-4" />
</Button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-gray-50">
<th className="p-2 text-left w-[250px]"></th>
<th className="p-2 text-left w-[180px]"></th>
<th className="p-2 text-left w-[120px]"></th>
<th className="p-2 text-left w-[120px]"></th>
<th className="p-2 text-left"></th>
<th className="p-2 text-right"></th>
</tr>
</thead>
<tbody className="divide-y">
{items.map((item, index) => (
<tr key={index}>
<td className="p-2">
<SearchableSelect
value={item.product_id?.toString() || ""}
onValueChange={(val) => updateItem(index, { product_id: parseInt(val) })}
options={products.map(p => ({ label: `[${p.code}] ${p.name}`, value: p.id.toString() }))}
placeholder="選擇商品"
/>
</td>
<td className="p-2">
<SearchableSelect
value={item.batch_number}
disabled={!item.product_id || !warehouseId}
onValueChange={(val) => updateItem(index, { batch_number: val })}
options={item.available_batches.map(b => ({ label: `${b.batch_number} (剩餘 ${b.quantity})`, value: b.batch_number }))}
placeholder="選擇批號"
/>
</td>
<td className="p-2">
<Input
type="number"
value={item.quantity}
onChange={e => updateItem(index, { quantity: parseFloat(e.target.value) || 0 })}
min={0.0001}
step={0.0001}
/>
</td>
<td className="p-2">
<Input
type="number"
value={item.unit_price}
onChange={e => updateItem(index, { unit_price: parseFloat(e.target.value) || 0 })}
min={0}
/>
</td>
<td className="p-2 font-medium">
${item.subtotal.toLocaleString()}
</td>
<td className="p-2 text-right">
<Button variant="ghost" size="sm" onClick={() => removeItem(index)} className="text-red-500 hover:text-red-700">
<Trash2 className="h-4 w-4" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
{items.length === 0 && (
<div className="text-center py-8 text-gray-500"></div>
)}
</div>
</div>
</div>
{/* 右側:金額總計 */}
<div className="space-y-6">
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 sticky top-6">
<h2 className="text-lg font-bold mb-4 flex items-center gap-2">
<Calculator className="h-5 w-5 text-primary-main" />
</h2>
<div className="space-y-4">
<div className="flex justify-between text-sm text-gray-600">
<span></span>
<span>${totalAmount.toLocaleString()}</span>
</div>
<div className="flex justify-between items-center text-sm text-gray-600">
<span> (5%)</span>
<div className="w-24">
<Input
type="number"
value={taxAmount}
onChange={e => setTaxAmount(parseInt(e.target.value) || 0)}
className="h-8 text-right p-1"
/>
</div>
</div>
<div className="border-t pt-4 flex justify-between font-bold text-lg">
<span></span>
<span className="text-primary-main">${grandTotal.toLocaleString()}</span>
</div>
<Button onClick={handleSave} className="w-full button-filled-primary mt-4 py-6 text-lg font-bold">
{isEdit ? "更新出貨單" : "建立出貨單"}
</Button>
</div>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,207 @@
import { useState, useEffect } from "react";
import { Plus, Package, Search, RotateCcw, ChevronDown, ChevronUp } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, Link } from "@inertiajs/react";
import Pagination from "@/Components/shared/Pagination";
import { Can } from "@/Components/Permission/Can";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { Badge } from "@/Components/ui/badge";
interface Props {
orders: {
data: any[];
links: any[];
};
filters: {
search?: string;
status?: string;
};
warehouses: { id: number; name: string }[];
}
export default function ShippingOrderIndex({ orders, filters, warehouses }: Props) {
const [search, setSearch] = useState(filters.search || "");
const [status, setStatus] = useState<string>(filters.status || "all");
const handleFilter = () => {
router.get(
route('delivery-notes.index'),
{
search,
status: status === 'all' ? undefined : status,
},
{ preserveState: true, replace: true }
);
};
const handleReset = () => {
setSearch("");
setStatus("all");
router.get(route('delivery-notes.index'));
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'draft':
return <Badge variant="secondary">稿</Badge>;
case 'completed':
return <Badge className="bg-green-100 text-green-800"></Badge>;
case 'cancelled':
return <Badge variant="destructive"></Badge>;
default:
return <Badge>{status}</Badge>;
}
};
return (
<AuthenticatedLayout breadcrumbs={[
{ label: '供應鏈管理', href: '#' },
{ label: '出貨單管理', href: route('delivery-notes.index'), isPage: true }
] as any}>
<Head title="出貨單管理" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Package className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
<div className="flex gap-2">
<Can permission="delivery_notes.create">
<Button
onClick={() => router.get(route('delivery-notes.create'))}
className="gap-2 button-filled-primary"
>
<Plus className="h-4 w-4" />
</Button>
</Can>
</div>
</div>
<div className="bg-white p-5 rounded-lg shadow-sm border border-gray-200 mb-6">
<div className="grid grid-cols-1 md:grid-cols-12 gap-4">
<div className="md:col-span-6 space-y-1">
<Label className="text-xs font-medium text-grey-1"></Label>
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
<Input
placeholder="搜尋單號、客戶名稱..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10 h-9 block"
onKeyDown={(e) => e.key === 'Enter' && handleFilter()}
/>
</div>
</div>
<div className="md:col-span-4 space-y-1">
<Label className="text-xs font-medium text-grey-1"></Label>
<SearchableSelect
value={status}
onValueChange={setStatus}
options={[
{ label: "全部狀態", value: "all" },
{ label: "草稿", value: "draft" },
{ label: "已過帳", value: "completed" },
{ label: "已取消", value: "cancelled" },
]}
className="h-9"
showSearch={false}
/>
</div>
<div className="md:col-span-2 flex items-end gap-2">
<Button
variant="outline"
onClick={handleReset}
className="flex-1 h-9"
>
<RotateCcw className="h-4 w-4" />
</Button>
<Button
onClick={handleFilter}
className="flex-[2] button-filled-primary h-9"
>
<Search className="h-4 w-4 mr-2" />
</Button>
</div>
</div>
</div>
<div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50 hover:bg-gray-50">
<TableHead className="w-[180px]"></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{orders.data.length > 0 ? (
orders.data.map((order) => (
<TableRow key={order.id}>
<TableCell className="font-medium text-primary-main">
<Link href={route('delivery-notes.show', order.id)}>
{order.doc_no}
</Link>
</TableCell>
<TableCell>{order.customer_name || '-'}</TableCell>
<TableCell>{order.warehouse_name}</TableCell>
<TableCell>{order.shipping_date}</TableCell>
<TableCell>${Number(order.grand_total).toLocaleString()}</TableCell>
<TableCell>{getStatusBadge(order.status)}</TableCell>
<TableCell>{order.creator_name}</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
asChild
>
<Link href={route('delivery-notes.show', order.id)}>
</Link>
</Button>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={8} className="h-24 text-center text-gray-500">
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="mt-4 flex justify-end">
<Pagination links={orders.links} />
</div>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,236 @@
import { ArrowLeft, Package, Clock, User, CheckCircle2, AlertCircle, Trash2, Edit } from "lucide-react";
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { Badge } from "@/Components/ui/badge";
import { toast } from "sonner";
import ActivityLogSection from "@/Components/ActivityLog/ActivityLogSection";
interface Props {
order: any;
}
export default function ShippingOrderShow({ order }: Props) {
const isDraft = order.status === 'draft';
const isCompleted = order.status === 'completed';
const handlePost = () => {
if (confirm('確定要執行過帳嗎?這將會從倉庫中扣除庫存數量。')) {
router.post(route('delivery-notes.post', order.id), {}, {
onSuccess: () => toast.success('過帳成功'),
onError: (errors: any) => toast.error(errors.error || '過帳失敗')
});
}
};
const handleDelete = () => {
if (confirm('確定要刪除這張出貨單嗎?')) {
router.delete(route('delivery-notes.destroy', order.id));
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'draft':
return <Badge variant="secondary" className="px-3 py-1">稿</Badge>;
case 'completed':
return <Badge className="bg-green-100 text-green-800 px-3 py-1"></Badge>;
case 'cancelled':
return <Badge variant="destructive" className="px-3 py-1"></Badge>;
default:
return <Badge>{status}</Badge>;
}
};
return (
<AuthenticatedLayout breadcrumbs={[
{ label: '供應鏈管理', href: '#' },
{ label: '出貨單管理', href: route('delivery-notes.index') },
{ label: `出貨單詳情 (${order.doc_no})`, isPage: true }
] as any}>
<Head title={`出貨單詳情 - ${order.doc_no}`} />
<div className="container mx-auto p-6 max-w-7xl">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
<div>
<Link href={route('delivery-notes.index')}>
<Button variant="outline" size="sm" className="gap-2 mb-4">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold">{order.doc_no}</h1>
{getStatusBadge(order.status)}
</div>
<p className="text-gray-500 mt-1">
: {new Date(order.created_at).toLocaleString()} | : {order.creator_name}
</p>
</div>
<div className="flex items-center gap-2">
{isDraft && (
<>
<Button variant="outline" className="gap-2" asChild>
<Link href={route('delivery-notes.edit', order.id)}>
<Edit className="h-4 w-4" />
</Link>
</Button>
<Button variant="destructive" className="gap-2" onClick={handleDelete}>
<Trash2 className="h-4 w-4" />
</Button>
<Button className="button-filled-primary gap-2" onClick={handlePost}>
<CheckCircle2 className="h-4 w-4" />
</Button>
</>
)}
{isCompleted && (
<div className="flex items-center gap-2 text-green-600 font-medium bg-green-50 px-4 py-2 rounded-lg border border-green-200">
<CheckCircle2 className="h-5 w-5" />
{new Date(order.posted_at).toLocaleString()}
</div>
)}
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
{/* 基本資訊 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<h2 className="text-lg font-bold mb-6 flex items-center gap-2 border-b pb-4">
<Info className="h-5 w-5 text-primary-main" />
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-6">
<div>
<label className="text-sm text-gray-500 block"></label>
<div className="font-medium text-lg">{order.warehouse_name}</div>
</div>
<div>
<label className="text-sm text-gray-500 block"></label>
<div className="font-medium text-lg">{order.shipping_date}</div>
</div>
<div>
<label className="text-sm text-gray-500 block"></label>
<div className="font-medium text-lg">{order.customer_name || '-'}</div>
</div>
<div>
<label className="text-sm text-gray-500 block"></label>
<div className="font-medium text-lg">{isCompleted ? '已完成 (已扣庫存)' : '草稿 (暫存中)'}</div>
</div>
<div className="md:col-span-2">
<label className="text-sm text-gray-500 block"></label>
<div className="text-gray-700 mt-1 bg-gray-50 p-3 rounded">{order.remarks || '無備註'}</div>
</div>
</div>
</div>
{/* 品項明細 */}
<div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
<div className="p-6 border-b border-gray-100 flex items-center justify-between">
<h2 className="text-lg font-bold flex items-center gap-2">
<Package className="h-5 w-5 text-primary-main" />
</h2>
<Badge variant="outline">{order.items.length} </Badge>
</div>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="bg-gray-50 text-gray-600">
<th className="px-6 py-4 text-left font-semibold"> / </th>
<th className="px-6 py-4 text-left font-semibold"></th>
<th className="px-6 py-4 text-right font-semibold"></th>
<th className="px-6 py-4 text-right font-semibold"></th>
<th className="px-6 py-4 text-right font-semibold"></th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{order.items.map((item: any) => (
<tr key={item.id} className="hover:bg-gray-50 transition-colors">
<td className="px-6 py-4">
<div className="font-medium text-gray-900">{item.product_name}</div>
<div className="text-xs text-gray-500 font-mono">{item.product_code}</div>
</td>
<td className="px-6 py-4">
<Badge variant="outline" className="font-mono">{item.batch_number || 'N/A'}</Badge>
</td>
<td className="px-6 py-4 text-right">
<span className="font-medium text-gray-900">{parseFloat(item.quantity).toLocaleString()}</span>
<span className="text-xs text-gray-500 ml-1">{item.unit_name}</span>
</td>
<td className="px-6 py-4 text-right text-gray-600">
${parseFloat(item.unit_price).toLocaleString()}
</td>
<td className="px-6 py-4 text-right font-bold text-gray-900">
${parseFloat(item.subtotal).toLocaleString()}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* 活動日誌區塊 */}
<div className="mt-8">
<ActivityLogSection
targetType="App\Modules\Procurement\Models\ShippingOrder"
targetId={order.id}
/>
</div>
</div>
{/* 右側:金額摘要 */}
<div className="space-y-6">
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 sticky top-6">
<h2 className="text-lg font-bold mb-6 flex items-center gap-2 border-b pb-4">
<CalculatorIcon className="h-5 w-5 text-primary-main" />
</h2>
<div className="space-y-4">
<div className="flex justify-between items-center py-2 border-b border-dashed">
<span className="text-gray-500"></span>
<span className="font-medium">${Number(order.total_amount).toLocaleString()}</span>
</div>
<div className="flex justify-between items-center py-2 border-b border-dashed">
<span className="text-gray-500"> (5%)</span>
<span className="font-medium">${Number(order.tax_amount).toLocaleString()}</span>
</div>
<div className="flex justify-between items-center py-4">
<span className="font-bold text-lg text-gray-900"></span>
<span className="font-black text-2xl text-primary-main">
${Number(order.grand_total).toLocaleString()}
</span>
</div>
{isDraft && (
<div className="mt-6 p-4 bg-amber-50 rounded-lg border border-amber-200 text-sm text-amber-800 flex gap-3">
<AlertCircle className="h-5 w-5 shrink-0" />
<div>
<p className="font-bold mb-1"></p>
<p>稿</p>
</div>
</div>
)}
</div>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);
}
function CalculatorIcon({ className }: { className?: string }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
<rect width="16" height="20" x="4" y="2" rx="2" />
<line x1="8" x2="16" y1="6" y2="6" />
<line x1="16" x2="16" y1="14" y2="18" />
<path d="M16 10h.01" />
<path d="M12 10h.01" />
<path d="M8 10h.01" />
<path d="M12 14h.01" />
<path d="M8 14h.01" />
<path d="M12 18h.01" />
<path d="M8 18h.01" />
</svg>
);
}