Compare commits

...

11 Commits

Author SHA1 Message Date
9793ab774b refactor: revert composer install location and clean up workflow
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Has been skipped
Koori-ERP-Deploy-System / deploy-production (push) Successful in 55s
2026-01-12 09:56:22 +08:00
5da14da58e chore: formatting and minor updates to deploy workflow
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 47s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-12 09:42:49 +08:00
6e174a09a5 refactor: move composer install to host level in deploy workflow
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 49s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-12 09:32:28 +08:00
0f45a539de feat: add common exclusions to rsync in deploy workflow
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 2m20s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-12 09:19:52 +08:00
268fc10ded feat: implement SSH action for container management and health checks
Some checks failed
Koori-ERP-Deploy-System / deploy-demo (push) Failing after 45s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-12 09:12:16 +08:00
822a83f700 feat: configure SSH key for demo deployment
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 32s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-12 08:59:30 +08:00
c84d6f7600 feat: install rsync and openssh-client in deploy workflow
Some checks failed
Koori-ERP-Deploy-System / deploy-demo (push) Failing after 29s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-12 08:45:45 +08:00
1dd50473ce chore: update deploy workflow
Some checks failed
Koori-ERP-Deploy-System / deploy-demo (push) Failing after 5s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-12 08:44:07 +08:00
24ae6f3eee feat: 新增採購單發票欄位、更新 SearchableSelect 樣式與搜尋門檻至 10 個項目
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 1m17s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-09 10:18:52 +08:00
d60367ac57 Save progress on test-demo before deploy
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 37s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-09 09:07:27 +08:00
3088959c7c 管理採購單的商品金額修正
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 29s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
2026-01-08 17:51:06 +08:00
15 changed files with 604 additions and 349 deletions

View File

@@ -0,0 +1,9 @@
---
description: 把程式推上demo分之
---
1.先把現有程式推上現有分支
2.要先看一下目前git的分支是在哪裡 如果不是demo要轉到demo分支
3.轉換到demo分支後 merge剛剛的那個分支
4.然後commit以及push
5.之後再切換原有分支

View File

@@ -18,16 +18,53 @@ jobs:
github-server-url: http://192.168.0.103:3000 github-server-url: http://192.168.0.103:3000
repository: ${{ github.repository }} repository: ${{ github.repository }}
- name: Deploy to 103 Demo - name: Step 1 - Push Code to Demo
run: | run: |
cp .env.example .env apt-get update && apt-get install -y rsync openssh-client
# 設定 Demo 專用的 Key mkdir -p ~/.ssh
sed -i "s|APP_KEY=.*|APP_KEY=${{ secrets.APP_KEY }}|g" .env echo "${{ secrets.DEMO_SSH_KEY }}" > ~/.ssh/id_rsa_demo
docker compose up -d --build --wait chmod 600 ~/.ssh/id_rsa_demo
# 同步檔案到容器內 rsync -avz --delete \
tar --exclude='.git' --exclude='node_modules' --exclude='vendor' -cf - . | docker exec -i koori-erp-laravel tar -xf - -C /var/www/html --exclude='.git' \
docker exec koori-erp-laravel chown -R 1000:1000 /var/www/html --exclude='node_modules' \
docker exec -u 1000:1000 -w /var/www/html koori-erp-laravel sh -c "composer install && npm install && npm run build && php artisan migrate --force && php artisan optimize:clear" --exclude='vendor' \
--exclude='storage' \
--exclude='.env' \
-e "ssh -i ~/.ssh/id_rsa_demo -o StrictHostKeyChecking=no" \
./ amba@192.168.0.103:/home/amba/koori-erp/
rm ~/.ssh/id_rsa_demo
# 2. 啟動或重建容器502 最容易發生在這裡的瞬間)
- name: Step 2 - Container Up & Health Check
uses: appleboy/ssh-action@master
with:
host: 192.168.0.103
port: 22
username: amba
key: ${{ secrets.DEMO_SSH_KEY }}
script: |
cd /home/amba/koori-erp
chown -R 1000:1000 .
WWWGROUP=1000 WWWUSER=1000 docker compose up -d --build --wait
echo "容器狀態:" && docker ps --filter "name=koori-erp-laravel"
- name: Step 3 - Composer & NPM Build
run: |
docker exec -u 1000:1000 -w /var/www/html koori-erp-laravel sh -c "
# 1. 後端依賴 (Demo 環境建議加上 --no-interaction 避免卡住)
composer install --no-dev --optimize-autoloader --no-interaction &&
# 2. 前端編譯
npm install &&
npm run build &&
# 3. Laravel 初始化與優化
php artisan migrate --force &&
php artisan optimize:clear &&
php artisan optimize &&
php artisan view:cache
"
docker exec koori-erp-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache docker exec koori-erp-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache
# --- 2. 正式環境部署 (erp.koori.tw:2224) --- # --- 2. 正式環境部署 (erp.koori.tw:2224) ---
@@ -70,46 +107,59 @@ jobs:
WWWGROUP=1000 WWWUSER=1000 docker compose up -d --build --wait WWWGROUP=1000 WWWUSER=1000 docker compose up -d --build --wait
echo "容器狀態:" && docker ps --filter "name=koori-erp-laravel" echo "容器狀態:" && docker ps --filter "name=koori-erp-laravel"
# 3. 處理後端與前端依賴(這時網站可能因為沒 vendor 呈現 500/502
- name: Step 3 - Composer & NPM Build
uses: appleboy/ssh-action@master
with:
host: erp.koori.tw
port: 2224
username: root
key: ${{ secrets.PROD_SSH_KEY }}
script: |
docker exec -u 1000:1000 -w /var/www/html koori-erp-laravel sh -c " docker exec -u 1000:1000 -w /var/www/html koori-erp-laravel sh -c "
composer install --no-dev --optimize-autoloader && composer install --no-dev --optimize-autoloader &&
npm install && npm install &&
npm run build npm run build
"
# 4. 處理資料庫與 Laravel 快取
- name: Step 4 - Database & Optimization
uses: appleboy/ssh-action@master
with:
host: erp.koori.tw
port: 2224
username: root
key: ${{ secrets.PROD_SSH_KEY }}
script: |
docker exec -u 1000:1000 -w /var/www/html koori-erp-laravel sh -c "
php artisan migrate --force && php artisan migrate --force &&
php artisan optimize:clear && php artisan optimize:clear &&
php artisan optimize && php artisan optimize &&
php artisan view:cache php artisan view:cache
" "
# 5. 最後權限修正與重啟(一發入魂,解決 502
- name: Step 5 - Final Permission & Service Restart
uses: appleboy/ssh-action@master
with:
host: erp.koori.tw
port: 2224
username: root
key: ${{ secrets.PROD_SSH_KEY }}
script: |
docker exec koori-erp-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache docker exec koori-erp-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache
echo "正在進行最後重啟以確保服務生效..."
# docker restart koori-erp-laravel
echo "部署完成!" # 3. 處理後端與前端依賴(這時網站可能因為沒 vendor 呈現 500/502
# - name: Step 3 - Composer & NPM Build
# uses: appleboy/ssh-action@master
# with:
# host: erp.koori.tw
# port: 2224
# username: root
# key: ${{ secrets.PROD_SSH_KEY }}
# script: |
# docker exec -u 1000:1000 -w /var/www/html koori-erp-laravel sh -c "
# composer install --no-dev --optimize-autoloader &&
# npm install &&
# npm run build
# "
# # 4. 處理資料庫與 Laravel 快取
# - name: Step 4 - Database & Optimization
# uses: appleboy/ssh-action@master
# with:
# host: erp.koori.tw
# port: 2224
# username: root
# key: ${{ secrets.PROD_SSH_KEY }}
# script: |
# docker exec -u 1000:1000 -w /var/www/html koori-erp-laravel sh -c "
# php artisan migrate --force &&
# php artisan optimize:clear &&
# php artisan optimize &&
# php artisan view:cache
# "
# # 5. 最後權限修正與重啟(一發入魂,解決 502
# - name: Step 5 - Final Permission & Service Restart
# uses: appleboy/ssh-action@master
# with:
# host: erp.koori.tw
# port: 2224
# username: root
# key: ${{ secrets.PROD_SSH_KEY }}
# script: |
# docker exec koori-erp-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache
# echo "正在進行最後重啟以確保服務生效..."
# # docker restart koori-erp-laravel
# echo "部署完成!"

View File

@@ -94,11 +94,14 @@ class PurchaseOrderController extends Controller
'warehouse_id' => 'required|exists:warehouses,id', 'warehouse_id' => 'required|exists:warehouses,id',
'expected_delivery_date' => 'nullable|date', 'expected_delivery_date' => 'nullable|date',
'remark' => 'nullable|string', 'remark' => 'nullable|string',
'invoice_number' => ['nullable', 'string', 'max:11', 'regex:/^[A-Z]{2}-\d{8}$/'],
'invoice_date' => 'nullable|date',
'invoice_amount' => 'nullable|numeric|min:0',
'items' => 'required|array|min:1', 'items' => 'required|array|min:1',
'items.*.productId' => 'required|exists:products,id', 'items.*.productId' => 'required|exists:products,id',
'items.*.quantity' => 'required|numeric|min:0.01', 'items.*.quantity' => 'required|numeric|min:0.01',
'items.*.unitPrice' => 'required|numeric|min:0', 'items.*.subtotal' => 'required|numeric|min:0', // 總金額
'items.*.unitId' => 'nullable|exists:units,id', // 驗證單位ID 'items.*.unitId' => 'nullable|exists:units,id',
]); ]);
try { try {
@@ -122,7 +125,7 @@ class PurchaseOrderController extends Controller
$totalAmount = 0; $totalAmount = 0;
foreach ($validated['items'] as $item) { foreach ($validated['items'] as $item) {
$totalAmount += $item['quantity'] * $item['unitPrice']; $totalAmount += $item['subtotal'];
} }
// Simple tax calculation (e.g., 5%) // Simple tax calculation (e.g., 5%)
@@ -154,15 +157,21 @@ class PurchaseOrderController extends Controller
'tax_amount' => $taxAmount, 'tax_amount' => $taxAmount,
'grand_total' => $grandTotal, 'grand_total' => $grandTotal,
'remark' => $validated['remark'], 'remark' => $validated['remark'],
'invoice_number' => $validated['invoice_number'] ?? null,
'invoice_date' => $validated['invoice_date'] ?? null,
'invoice_amount' => $validated['invoice_amount'] ?? null,
]); ]);
foreach ($validated['items'] as $item) { foreach ($validated['items'] as $item) {
// 反算單價
$unitPrice = $item['quantity'] > 0 ? $item['subtotal'] / $item['quantity'] : 0;
$order->items()->create([ $order->items()->create([
'product_id' => $item['productId'], 'product_id' => $item['productId'],
'quantity' => $item['quantity'], 'quantity' => $item['quantity'],
'unit_id' => $item['unitId'] ?? null, // 儲存單位ID 'unit_id' => $item['unitId'] ?? null,
'unit_price' => $item['unitPrice'], 'unit_price' => $unitPrice,
'subtotal' => $item['quantity'] * $item['unitPrice'], 'subtotal' => $item['subtotal'],
]); ]);
} }
@@ -307,11 +316,14 @@ class PurchaseOrderController extends Controller
'expected_delivery_date' => 'nullable|date', 'expected_delivery_date' => 'nullable|date',
'remark' => 'nullable|string', 'remark' => 'nullable|string',
'status' => 'required|string|in:draft,pending,processing,shipping,confirming,completed,cancelled', 'status' => 'required|string|in:draft,pending,processing,shipping,confirming,completed,cancelled',
'invoice_number' => ['nullable', 'string', 'max:11', 'regex:/^[A-Z]{2}-\d{8}$/'],
'invoice_date' => 'nullable|date',
'invoice_amount' => 'nullable|numeric|min:0',
'items' => 'required|array|min:1', 'items' => 'required|array|min:1',
'items.*.productId' => 'required|exists:products,id', 'items.*.productId' => 'required|exists:products,id',
'items.*.quantity' => 'required|numeric|min:0.01', 'items.*.quantity' => 'required|numeric|min:0.01',
'items.*.unitPrice' => 'required|numeric|min:0', 'items.*.subtotal' => 'required|numeric|min:0', // 總金額
'items.*.unitId' => 'nullable|exists:units,id', // 驗證單位ID 'items.*.unitId' => 'nullable|exists:units,id',
]); ]);
try { try {
@@ -319,7 +331,7 @@ class PurchaseOrderController extends Controller
$totalAmount = 0; $totalAmount = 0;
foreach ($validated['items'] as $item) { foreach ($validated['items'] as $item) {
$totalAmount += $item['quantity'] * $item['unitPrice']; $totalAmount += $item['subtotal'];
} }
// Simple tax calculation (e.g., 5%) // Simple tax calculation (e.g., 5%)
@@ -335,17 +347,23 @@ class PurchaseOrderController extends Controller
'grand_total' => $grandTotal, 'grand_total' => $grandTotal,
'remark' => $validated['remark'], 'remark' => $validated['remark'],
'status' => $validated['status'], 'status' => $validated['status'],
'invoice_number' => $validated['invoice_number'] ?? null,
'invoice_date' => $validated['invoice_date'] ?? null,
'invoice_amount' => $validated['invoice_amount'] ?? null,
]); ]);
// Sync items // Sync items
$order->items()->delete(); $order->items()->delete();
foreach ($validated['items'] as $item) { foreach ($validated['items'] as $item) {
// 反算單價
$unitPrice = $item['quantity'] > 0 ? $item['subtotal'] / $item['quantity'] : 0;
$order->items()->create([ $order->items()->create([
'product_id' => $item['productId'], 'product_id' => $item['productId'],
'quantity' => $item['quantity'], 'quantity' => $item['quantity'],
'unit_id' => $item['unitId'] ?? null, // 儲存單位ID 'unit_id' => $item['unitId'] ?? null,
'unit_price' => $item['unitPrice'], 'unit_price' => $unitPrice,
'subtotal' => $item['quantity'] * $item['unitPrice'], 'subtotal' => $item['subtotal'],
]); ]);
} }

View File

@@ -22,13 +22,18 @@ class PurchaseOrder extends Model
'tax_amount', 'tax_amount',
'grand_total', 'grand_total',
'remark', 'remark',
'invoice_number',
'invoice_date',
'invoice_amount',
]; ];
protected $casts = [ protected $casts = [
'expected_delivery_date' => 'date', 'expected_delivery_date' => 'date',
'invoice_date' => 'date',
'total_amount' => 'decimal:2', 'total_amount' => 'decimal:2',
'tax_amount' => 'decimal:2', 'tax_amount' => 'decimal:2',
'grand_total' => 'decimal:2', 'grand_total' => 'decimal:2',
'invoice_amount' => 'decimal:2',
]; ];
protected $appends = [ protected $appends = [
@@ -40,6 +45,9 @@ class PurchaseOrder extends Model
'createdBy', 'createdBy',
'warehouse_name', 'warehouse_name',
'createdAt', 'createdAt',
'invoiceNumber',
'invoiceDate',
'invoiceAmount',
]; ];
public function getCreatedAtAttribute() public function getCreatedAtAttribute()
@@ -82,6 +90,22 @@ class PurchaseOrder extends Model
return $this->warehouse ? $this->warehouse->name : ''; return $this->warehouse ? $this->warehouse->name : '';
} }
public function getInvoiceNumberAttribute(): ?string
{
return $this->attributes['invoice_number'] ?? null;
}
public function getInvoiceDateAttribute(): ?string
{
$date = $this->attributes['invoice_date'] ?? null;
return $date ? \Illuminate\Support\Carbon::parse($date)->format('Y-m-d') : null;
}
public function getInvoiceAmountAttribute(): ?float
{
return isset($this->attributes['invoice_amount']) ? (float) $this->attributes['invoice_amount'] : null;
}
public function vendor(): BelongsTo public function vendor(): BelongsTo
{ {
return $this->belongsTo(Vendor::class); return $this->belongsTo(Vendor::class);

View File

@@ -0,0 +1,30 @@
<?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('purchase_orders', function (Blueprint $table) {
$table->string('invoice_number', 11)->nullable()->comment('發票號碼 (格式: AB-12345678)');
$table->date('invoice_date')->nullable()->comment('發票日期');
$table->decimal('invoice_amount', 12, 2)->nullable()->comment('發票金額');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('purchase_orders', function (Blueprint $table) {
$table->dropColumn(['invoice_number', 'invoice_date', 'invoice_amount']);
});
}
};

View File

@@ -11,13 +11,7 @@ import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label"; import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea"; import { Textarea } from "@/Components/ui/textarea";
import { import { SearchableSelect } from "@/Components/ui/searchable-select";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { useForm } from "@inertiajs/react"; import { useForm } from "@inertiajs/react";
import { toast } from "sonner"; import { toast } from "sonner";
import type { Product, Category } from "@/Pages/Product/Index"; import type { Product, Category } from "@/Pages/Product/Index";
@@ -123,21 +117,14 @@ export default function ProductDialog({
<Label htmlFor="category_id"> <Label htmlFor="category_id">
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</Label> </Label>
<Select <SearchableSelect
value={data.category_id} value={data.category_id}
onValueChange={(value) => setData("category_id", value)} onValueChange={(value) => setData("category_id", value)}
> options={categories.map((c) => ({ label: c.name, value: c.id.toString() }))}
<SelectTrigger id="category_id" className={errors.category_id ? "border-red-500" : ""}> placeholder="選擇分類"
<SelectValue placeholder="選擇分類" /> searchPlaceholder="搜尋分類..."
</SelectTrigger> className={errors.category_id ? "border-red-500" : ""}
<SelectContent> />
{categories.map((category) => (
<SelectItem key={category.id} value={category.id.toString()}>
{category.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.category_id && <p className="text-sm text-red-500">{errors.category_id}</p>} {errors.category_id && <p className="text-sm text-red-500">{errors.category_id}</p>}
</div> </div>
@@ -188,42 +175,30 @@ export default function ProductDialog({
<Label htmlFor="base_unit_id"> <Label htmlFor="base_unit_id">
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</Label> </Label>
<Select <SearchableSelect
value={data.base_unit_id} value={data.base_unit_id}
onValueChange={(value) => setData("base_unit_id", value)} onValueChange={(value) => setData("base_unit_id", value)}
> options={units.map((u) => ({ label: u.name, value: u.id.toString() }))}
<SelectTrigger id="base_unit_id" className={errors.base_unit_id ? "border-red-500" : ""}> placeholder="選擇單位"
<SelectValue placeholder="選擇單位" /> searchPlaceholder="搜尋單位..."
</SelectTrigger> className={errors.base_unit_id ? "border-red-500" : ""}
<SelectContent> />
{units.map((unit) => (
<SelectItem key={unit.id} value={unit.id.toString()}>
{unit.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.base_unit_id && <p className="text-sm text-red-500">{errors.base_unit_id}</p>} {errors.base_unit_id && <p className="text-sm text-red-500">{errors.base_unit_id}</p>}
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="large_unit_id"></Label> <Label htmlFor="large_unit_id"></Label>
<Select <SearchableSelect
value={data.large_unit_id} value={data.large_unit_id}
onValueChange={(value) => setData("large_unit_id", value)} onValueChange={(value) => setData("large_unit_id", value)}
> options={[
<SelectTrigger id="large_unit_id" className={errors.large_unit_id ? "border-red-500" : ""}> { label: "無", value: "none" },
<SelectValue placeholder="無" /> ...units.map((u) => ({ label: u.name, value: u.id.toString() }))
</SelectTrigger> ]}
<SelectContent> placeholder="無"
<SelectItem value="none"></SelectItem> searchPlaceholder="搜尋單位..."
{units.map((unit) => ( className={errors.large_unit_id ? "border-red-500" : ""}
<SelectItem key={unit.id} value={unit.id.toString()}> />
{unit.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.large_unit_id && <p className="text-sm text-red-500">{errors.large_unit_id}</p>} {errors.large_unit_id && <p className="text-sm text-red-500">{errors.large_unit_id}</p>}
</div> </div>

View File

@@ -5,13 +5,7 @@
import { Trash2 } from "lucide-react"; import { Trash2 } from "lucide-react";
import { Button } from "@/Components/ui/button"; import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { import { SearchableSelect } from "@/Components/ui/searchable-select";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { import {
Table, Table,
TableBody, TableBody,
@@ -50,8 +44,7 @@ export function PurchaseOrderItemsTable({
<TableHead className="w-[10%] text-left"></TableHead> <TableHead className="w-[10%] text-left"></TableHead>
<TableHead className="w-[12%] text-left"></TableHead> <TableHead className="w-[12%] text-left"></TableHead>
<TableHead className="w-[12%] text-left"></TableHead> <TableHead className="w-[12%] text-left"></TableHead>
<TableHead className="w-[12%] text-left"></TableHead> <TableHead className="w-[15%] text-left"></TableHead>
<TableHead className="w-[12%] text-left"></TableHead>
<TableHead className="w-[15%] text-left"> / </TableHead> <TableHead className="w-[15%] text-left"> / </TableHead>
{!isReadOnly && <TableHead className="w-[5%]"></TableHead>} {!isReadOnly && <TableHead className="w-[5%]"></TableHead>}
</TableRow> </TableRow>
@@ -60,7 +53,7 @@ export function PurchaseOrderItemsTable({
{items.length === 0 ? ( {items.length === 0 ? (
<TableRow> <TableRow>
<TableCell <TableCell
colSpan={isReadOnly ? 7 : 8} colSpan={isReadOnly ? 6 : 7}
className="text-center text-gray-400 py-12 italic" className="text-center text-gray-400 py-12 italic"
> >
{isDisabled ? "請先選擇供應商後才能新增商品" : "尚未新增任何商品項"} {isDisabled ? "請先選擇供應商後才能新增商品" : "尚未新增任何商品項"}
@@ -69,9 +62,12 @@ export function PurchaseOrderItemsTable({
) : ( ) : (
items.map((item, index) => { items.map((item, index) => {
// 計算換算後的單價 (基本單位單價) // 計算換算後的單價 (基本單位單價)
// unitPrice is derived from subtotal / quantity
const currentUnitPrice = item.unitPrice;
const convertedUnitPrice = item.selectedUnit === 'large' && item.conversion_rate const convertedUnitPrice = item.selectedUnit === 'large' && item.conversion_rate
? item.unitPrice / item.conversion_rate ? currentUnitPrice / item.conversion_rate
: item.unitPrice; : currentUnitPrice;
return ( return (
<TableRow key={index}> <TableRow key={index}>
@@ -80,27 +76,18 @@ export function PurchaseOrderItemsTable({
{isReadOnly ? ( {isReadOnly ? (
<span className="font-medium">{item.productName}</span> <span className="font-medium">{item.productName}</span>
) : ( ) : (
<Select <SearchableSelect
value={item.productId} value={item.productId}
onValueChange={(value) => onValueChange={(value) =>
onItemChange?.(index, "productId", value) onItemChange?.(index, "productId", value)
} }
disabled={isDisabled} disabled={isDisabled}
> options={supplier?.commonProducts.map((p) => ({ label: p.productName, value: p.productId })) || []}
<SelectTrigger className="h-10 border-gray-200"> placeholder="選擇商品"
<SelectValue placeholder="選擇商品" /> searchPlaceholder="搜尋商品..."
</SelectTrigger> emptyText="無可用商品"
<SelectContent> className="w-full"
{supplier?.commonProducts.map((product) => ( />
<SelectItem key={product.productId} value={product.productId}>
{product.productName}
</SelectItem>
))}
{(!supplier || supplier.commonProducts.length === 0) && (
<div className="p-2 text-sm text-gray-400 text-center"></div>
)}
</SelectContent>
</Select>
)} )}
</TableCell> </TableCell>
@@ -126,21 +113,18 @@ export function PurchaseOrderItemsTable({
{/* 單位選擇 */} {/* 單位選擇 */}
<TableCell> <TableCell>
{!isReadOnly && item.large_unit_id ? ( {!isReadOnly && item.large_unit_id ? (
<Select <SearchableSelect
value={item.selectedUnit || 'base'} value={item.selectedUnit || 'base'}
onValueChange={(value) => onValueChange={(value) =>
onItemChange?.(index, "selectedUnit", value) onItemChange?.(index, "selectedUnit", value)
} }
disabled={isDisabled} disabled={isDisabled}
> options={[
<SelectTrigger className="h-10 border-gray-200 w-24"> { label: item.base_unit_name || "個", value: "base" },
<SelectValue /> { label: item.large_unit_name || "", value: "large" }
</SelectTrigger> ]}
<SelectContent className="z-[9999]"> className="w-24"
<SelectItem value="base">{item.base_unit_name || "個"}</SelectItem> />
<SelectItem value="large">{item.large_unit_name}</SelectItem>
</SelectContent>
</Select>
) : ( ) : (
<span className="text-gray-500 font-medium"> <span className="text-gray-500 font-medium">
{item.selectedUnit === 'large' && item.large_unit_name {item.selectedUnit === 'large' && item.large_unit_name
@@ -162,44 +146,39 @@ export function PurchaseOrderItemsTable({
</div> </div>
</TableCell> </TableCell>
{/* 單價 */} {/* 總金額 (主要輸入欄位) */}
<TableCell className="text-left"> <TableCell className="text-left">
{isReadOnly ? ( {isReadOnly ? (
<span className="font-medium text-gray-900">{formatCurrency(item.unitPrice)}</span> <span className="font-bold text-primary">{formatCurrency(item.subtotal)}</span>
) : ( ) : (
<div className="space-y-1"> <div className="space-y-1">
<Input <Input
type="number" type="number"
min="0" min="0"
step="0.1" step="1"
value={item.unitPrice || ""} value={item.subtotal || ""}
onChange={(e) => onChange={(e) =>
onItemChange?.(index, "unitPrice", Number(e.target.value)) onItemChange?.(index, "subtotal", Number(e.target.value))
} }
disabled={isDisabled} disabled={isDisabled}
className={`h-10 text-left w-32 ${ className={`h-10 text-left w-32 ${
// 如果有數量但沒有單價,顯示錯誤樣式 // 如果有數量但沒有金額,顯示錯誤樣式
item.quantity > 0 && (!item.unitPrice || item.unitPrice <= 0) item.quantity > 0 && (!item.subtotal || item.subtotal <= 0)
? "border-red-400 bg-red-50 focus-visible:ring-red-500" ? "border-red-400 bg-red-50 focus-visible:ring-red-500"
: "border-gray-200" : "border-gray-200"
}`} }`}
/> />
{/* 錯誤提示 (保留必填提示) */} {/* 錯誤提示 */}
{item.quantity > 0 && (!item.unitPrice || item.unitPrice <= 0) && ( {item.quantity > 0 && (!item.subtotal || item.subtotal <= 0) && (
<p className="text-[10px] text-red-600 font-medium"> <p className="text-[10px] text-red-600 font-medium">
</p> </p>
)} )}
</div> </div>
)} )}
</TableCell> </TableCell>
{/* 小計 */} {/* 換算採購單價 / 基本單位 (顯示換算結果) */}
<TableCell className="text-left">
<span className="font-bold text-primary">{formatCurrency(item.subtotal)}</span>
</TableCell>
{/* 換算採購單價 / 基本單位 */}
<TableCell className="text-left"> <TableCell className="text-left">
<div className="flex flex-col"> <div className="flex flex-col">
<div className="text-gray-500 font-medium text-sm"> <div className="text-gray-500 font-medium text-sm">

View File

@@ -18,13 +18,7 @@ import {
import { Label } from "@/Components/ui/label"; import { Label } from "@/Components/ui/label";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { Button } from "@/Components/ui/button"; import { Button } from "@/Components/ui/button";
import { import { SearchableSelect } from "@/Components/ui/searchable-select";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { Textarea } from "@/Components/ui/textarea"; import { Textarea } from "@/Components/ui/textarea";
import { toast } from "sonner"; import { toast } from "sonner";
import { Warehouse, TransferOrder, TransferOrderStatus } from "@/types/warehouse"; import { Warehouse, TransferOrder, TransferOrderStatus } from "@/types/warehouse";
@@ -194,7 +188,7 @@ export default function TransferOrderDialog({
<Label htmlFor="sourceWarehouse"> <Label htmlFor="sourceWarehouse">
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</Label> </Label>
<Select <SearchableSelect
value={formData.sourceWarehouseId} value={formData.sourceWarehouseId}
onValueChange={(value) => onValueChange={(value) =>
setFormData({ setFormData({
@@ -207,44 +201,28 @@ export default function TransferOrderDialog({
}) })
} }
disabled={!!order} disabled={!!order}
> options={warehouses.map((warehouse) => ({ label: warehouse.name, value: warehouse.id }))}
<SelectTrigger id="sourceWarehouse"> placeholder="選擇來源倉庫"
<SelectValue placeholder="選擇來源倉庫" /> searchPlaceholder="搜尋倉庫..."
</SelectTrigger> />
<SelectContent>
{warehouses.map((warehouse) => (
<SelectItem key={warehouse.id} value={warehouse.id}>
{warehouse.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="targetWarehouse"> <Label htmlFor="targetWarehouse">
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</Label> </Label>
<Select <SearchableSelect
value={formData.targetWarehouseId} value={formData.targetWarehouseId}
onValueChange={(value) => onValueChange={(value) =>
setFormData({ ...formData, targetWarehouseId: value }) setFormData({ ...formData, targetWarehouseId: value })
} }
disabled={!!order} disabled={!!order}
> options={warehouses
<SelectTrigger id="targetWarehouse"> .filter((w) => w.id !== formData.sourceWarehouseId)
<SelectValue placeholder="選擇目標倉庫" /> .map((warehouse) => ({ label: warehouse.name, value: warehouse.id }))}
</SelectTrigger> placeholder="選擇目標倉庫"
<SelectContent> searchPlaceholder="搜尋倉庫..."
{warehouses />
.filter((w) => w.id !== formData.sourceWarehouseId)
.map((warehouse) => (
<SelectItem key={warehouse.id} value={warehouse.id}>
{warehouse.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
</div> </div>
@@ -253,7 +231,7 @@ export default function TransferOrderDialog({
<Label htmlFor="product"> <Label htmlFor="product">
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</Label> </Label>
<Select <SearchableSelect
value={ value={
formData.productId && formData.batchNumber formData.productId && formData.batchNumber
? `${formData.productId}|||${formData.batchNumber}` ? `${formData.productId}|||${formData.batchNumber}`
@@ -261,28 +239,14 @@ export default function TransferOrderDialog({
} }
onValueChange={handleProductChange} onValueChange={handleProductChange}
disabled={!formData.sourceWarehouseId || !!order} disabled={!formData.sourceWarehouseId || !!order}
> options={availableProducts.map((product) => ({
<SelectTrigger id="product"> label: `${product.productName} (庫存: ${product.availableQty} ${product.unit})`,
<SelectValue placeholder="選擇商品與批號" /> value: `${product.productId}|||${product.batchNumber}`,
</SelectTrigger> }))}
<SelectContent> placeholder="選擇商品與批號"
{availableProducts.length === 0 ? ( searchPlaceholder="搜尋商品..."
<div className="p-2 text-sm text-gray-500 text-center"> emptyText={formData.sourceWarehouseId ? "該倉庫無可用庫存" : "請先選擇來源倉庫"}
{formData.sourceWarehouseId ? "該倉庫無可用庫存" : "請先選擇來源倉庫"} />
</div>
) : (
availableProducts.map((product) => (
<SelectItem
key={`${product.productId}|||${product.batchNumber}`}
value={`${product.productId}|||${product.batchNumber}`}
>
{product.productName} (:{" "}
{product.availableQty} {product.unit})
</SelectItem>
))
)}
</SelectContent>
</Select>
</div> </div>
{/* 數量和日期 */} {/* 數量和日期 */}
@@ -329,22 +293,18 @@ export default function TransferOrderDialog({
{order && ( {order && (
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="status"></Label> <Label htmlFor="status"></Label>
<Select <SearchableSelect
value={formData.status} value={formData.status}
onValueChange={(value) => onValueChange={(value) =>
setFormData({ ...formData, status: value as TransferOrderStatus }) setFormData({ ...formData, status: value as TransferOrderStatus })
} }
> options={[
<SelectTrigger id="status"> { label: "待處理", value: "待處理" },
<SelectValue /> { label: "處理中", value: "處理中" },
</SelectTrigger> { label: "已完成", value: "已完成" },
<SelectContent> { label: "已取消", value: "已取消" },
<SelectItem value="待處理"></SelectItem> ]}
<SelectItem value="處理中"></SelectItem> />
<SelectItem value="已完成"></SelectItem>
<SelectItem value="已取消"></SelectItem>
</SelectContent>
</Select>
</div> </div>
)} )}

View File

@@ -0,0 +1,139 @@
import * as React from "react";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/Components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/Components/ui/popover";
interface Option {
label: string;
value: string;
sublabel?: string;
disabled?: boolean;
}
interface SearchableSelectProps {
value: string;
onValueChange: (value: string) => void;
options: Option[];
placeholder?: string;
searchPlaceholder?: string;
emptyText?: string;
disabled?: boolean;
className?: string;
/** 當選項數量超過此閾值時顯示搜尋框,預設為 10。若設為 0 則總是顯示。 */
searchThreshold?: number;
/** 強制控制是否顯示搜尋框。若設定此值,則忽略 searchThreshold */
showSearch?: boolean;
}
export function SearchableSelect({
value,
onValueChange,
options,
placeholder = "請選擇...",
searchPlaceholder = "搜尋...",
emptyText = "找不到符合的項目",
disabled = false,
className,
searchThreshold = 10,
showSearch,
}: SearchableSelectProps) {
const [open, setOpen] = React.useState(false);
// 決定是否顯示搜尋框
const shouldShowSearch =
showSearch !== undefined ? showSearch : options.length > searchThreshold;
const selectedOption = options.find((option) => option.value === value);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
role="combobox"
aria-expanded={open}
disabled={disabled}
className={cn(
// Base styles matching SelectTrigger
"flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none",
// Outlined default state - 2px border with grey-3
"border-2 border-grey-3 bg-grey-5",
// Text colors
"text-grey-0",
!selectedOption && "text-grey-3",
// Focus state - primary border with ring
"focus-visible:border-primary-main focus-visible:ring-primary-main/20 focus-visible:ring-[3px]",
// Disabled state
"disabled:border-grey-4 disabled:bg-background-light-grey disabled:text-grey-2 disabled:cursor-not-allowed disabled:opacity-50",
// Height
"h-9",
className
)}
>
<span className="truncate">
{selectedOption ? selectedOption.label : placeholder}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50 text-grey-2" />
</button>
</PopoverTrigger>
<PopoverContent
className="p-0 z-[9999]"
align="start"
style={{ width: "var(--radix-popover-trigger-width)" }}
>
<Command>
{shouldShowSearch && (
<CommandInput placeholder={searchPlaceholder} />
)}
<CommandList>
<CommandEmpty>{emptyText}</CommandEmpty>
<CommandGroup>
{options.map((option) => (
<CommandItem
key={option.value}
value={option.label}
onSelect={() => {
onValueChange(option.value);
setOpen(false);
}}
disabled={option.disabled}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4 text-primary",
value === option.value
? "opacity-100"
: "opacity-0"
)}
/>
<div className="flex items-center justify-between flex-1">
<span>{option.label}</span>
{option.sublabel && (
<span className="text-xs text-muted-foreground ml-2">
{option.sublabel}
</span>
)}
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}

View File

@@ -1,13 +1,7 @@
import { useState, useEffect, useCallback } from "react"; import { useState, useEffect, useCallback } from "react";
import { Button } from "@/Components/ui/button"; import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { import { SearchableSelect } from "@/Components/ui/searchable-select";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { Plus, Search, X } from "lucide-react"; import { Plus, Search, X } from "lucide-react";
import ProductTable from "@/Components/Product/ProductTable"; import ProductTable from "@/Components/Product/ProductTable";
import ProductDialog from "@/Components/Product/ProductDialog"; import ProductDialog from "@/Components/Product/ProductDialog";
@@ -209,17 +203,16 @@ export default function ProductManagement({ products, categories, units, filters
</div> </div>
{/* Type Filter */} {/* Type Filter */}
<Select value={typeFilter} onValueChange={handleCategoryChange}> <SearchableSelect
<SelectTrigger className="w-full md:w-[180px]"> value={typeFilter}
<SelectValue placeholder="商品分類" /> onValueChange={handleCategoryChange}
</SelectTrigger> options={[
<SelectContent> { label: "全部分類", value: "all" },
<SelectItem value="all"></SelectItem> ...categories.map((cat) => ({ label: cat.name, value: cat.id.toString() }))
{categories.map(cat => ( ]}
<SelectItem key={cat.id} value={cat.id.toString()}>{cat.name}</SelectItem> placeholder="商品分類"
))} className="w-full md:w-[180px]"
</SelectContent> />
</Select>
{/* Add Button */} {/* Add Button */}
<div className="flex gap-2 w-full md:w-auto"> <div className="flex gap-2 w-full md:w-auto">
@@ -260,17 +253,18 @@ export default function ProductManagement({ products, categories, units, filters
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4"> <div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500"> <div className="flex items-center gap-2 text-sm text-gray-500">
<span></span> <span></span>
<Select value={perPage} onValueChange={handlePerPageChange}> <SearchableSelect
<SelectTrigger className="w-[80px] h-8"> value={perPage}
<SelectValue placeholder="10" /> onValueChange={handlePerPageChange}
</SelectTrigger> options={[
<SelectContent> { label: "10", value: "10" },
<SelectItem value="10">10</SelectItem> { label: "20", value: "20" },
<SelectItem value="20">20</SelectItem> { label: "50", value: "50" },
<SelectItem value="50">50</SelectItem> { label: "100", value: "100" }
<SelectItem value="100">100</SelectItem> ]}
</SelectContent> className="w-[80px] h-8"
</Select> showSearch={false}
/>
<span></span> <span></span>
</div> </div>
<Pagination links={products.links} /> <Pagination links={products.links} />

View File

@@ -7,13 +7,7 @@ import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea"; import { Textarea } from "@/Components/ui/textarea";
import { Alert, AlertDescription } from "@/Components/ui/alert"; import { Alert, AlertDescription } from "@/Components/ui/alert";
import { import { SearchableSelect } from "@/Components/ui/searchable-select";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"; import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react"; import { Head, Link, router } from "@inertiajs/react";
import { PurchaseOrderItemsTable } from "@/Components/PurchaseOrder/PurchaseOrderItemsTable"; import { PurchaseOrderItemsTable } from "@/Components/PurchaseOrder/PurchaseOrderItemsTable";
@@ -58,6 +52,12 @@ export default function CreatePurchaseOrder({
updateItem, updateItem,
status, status,
setStatus, setStatus,
invoiceNumber,
invoiceDate,
invoiceAmount,
setInvoiceNumber,
setInvoiceDate,
setInvoiceAmount,
} = usePurchaseOrderForm({ order, suppliers }); } = usePurchaseOrderForm({ order, suppliers });
@@ -110,11 +110,15 @@ export default function CreatePurchaseOrder({
expected_delivery_date: expectedDate, expected_delivery_date: expectedDate,
remark: notes, remark: notes,
status: status, status: status,
invoice_number: invoiceNumber || null,
invoice_date: invoiceDate || null,
invoice_amount: invoiceAmount ? parseFloat(invoiceAmount) : null,
items: validItems.map(item => ({ items: validItems.map(item => ({
productId: item.productId, productId: item.productId,
quantity: item.quantity, quantity: item.quantity,
unitPrice: item.unitPrice, unitPrice: item.unitPrice,
unitId: item.unitId, unitId: item.unitId,
subtotal: item.subtotal,
})), })),
}; };
@@ -190,40 +194,26 @@ export default function CreatePurchaseOrder({
<label className="text-sm font-bold text-gray-700"> <label className="text-sm font-bold text-gray-700">
</label> </label>
<Select <SearchableSelect
value={String(warehouseId)} value={String(warehouseId)}
onValueChange={setWarehouseId} onValueChange={setWarehouseId}
disabled={isOrderSent} disabled={isOrderSent}
> options={warehouses.map((w) => ({ label: w.name, value: String(w.id) }))}
<SelectTrigger className="h-12 border-gray-200 focus:ring-primary/20"> placeholder="請選擇倉庫"
<SelectValue placeholder="請選擇倉庫" /> searchPlaceholder="搜尋倉庫..."
</SelectTrigger> />
<SelectContent>
{warehouses.map((w) => (
<SelectItem key={w.id} value={String(w.id)}>
{w.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
<div className="space-y-3"> <div className="space-y-3">
<label className="text-sm font-bold text-gray-700"></label> <label className="text-sm font-bold text-gray-700"></label>
<Select <SearchableSelect
value={String(supplierId)} value={String(supplierId)}
onValueChange={setSupplierId} onValueChange={setSupplierId}
disabled={isOrderSent} disabled={isOrderSent}
> options={suppliers.map((s) => ({ label: s.name, value: String(s.id) }))}
<SelectTrigger className="h-12 border-gray-200"> placeholder="選擇供應商"
<SelectValue placeholder="選擇供應商" /> searchPlaceholder="搜尋供應商..."
</SelectTrigger> />
<SelectContent>
{suppliers.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
</div> </div>
@@ -244,21 +234,12 @@ export default function CreatePurchaseOrder({
{order && ( {order && (
<div className="space-y-3"> <div className="space-y-3">
<label className="text-sm font-bold text-gray-700"></label> <label className="text-sm font-bold text-gray-700"></label>
<Select <SearchableSelect
value={status} value={status}
onValueChange={(v) => setStatus(v as any)} onValueChange={(v) => setStatus(v as any)}
> options={STATUS_OPTIONS.map((opt) => ({ label: opt.label, value: opt.value }))}
<SelectTrigger className="h-12 border-gray-200"> placeholder="選擇狀態"
<SelectValue placeholder="選擇狀態" /> />
</SelectTrigger>
<SelectContent>
{STATUS_OPTIONS.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
)} )}
</div> </div>
@@ -275,11 +256,71 @@ export default function CreatePurchaseOrder({
</div> </div>
</div> </div>
{/* 步驟二:品項明細 */} {/* 發票資訊 */}
<div className="bg-white rounded-lg border shadow-sm overflow-hidden">
<div className="p-6 bg-gray-50/50 border-b flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center font-bold">2</div>
<h2 className="text-lg font-bold"></h2>
<span className="text-sm text-gray-500"></span>
</div>
<div className="p-8 space-y-8">
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
<div className="space-y-3">
<label className="text-sm font-bold text-gray-700">
</label>
<Input
type="text"
value={invoiceNumber}
onChange={(e) => setInvoiceNumber(e.target.value)}
placeholder="AB-12345678"
maxLength={11}
className="h-12 border-gray-200"
/>
<p className="text-xs text-gray-500">2 + + 8 </p>
</div>
<div className="space-y-3">
<label className="text-sm font-bold text-gray-700">
</label>
<Input
type="date"
value={invoiceDate}
onChange={(e) => setInvoiceDate(e.target.value)}
className="h-12 border-gray-200"
/>
</div>
<div className="space-y-3">
<label className="text-sm font-bold text-gray-700">
</label>
<Input
type="number"
value={invoiceAmount}
onChange={(e) => setInvoiceAmount(e.target.value)}
placeholder="0"
min="0"
step="0.01"
className="h-12 border-gray-200"
/>
{invoiceAmount && totalAmount > 0 && parseFloat(invoiceAmount) !== totalAmount && (
<p className="text-xs text-amber-600">
{formatCurrency(totalAmount)}
</p>
)}
</div>
</div>
</div>
</div>
{/* 步驟三:品項明細 */}
<div className={`bg-white rounded-lg border shadow-sm overflow-hidden transition-all duration-300 ${!hasSupplier ? 'opacity-60 saturate-50' : ''}`}> <div className={`bg-white rounded-lg border shadow-sm overflow-hidden transition-all duration-300 ${!hasSupplier ? 'opacity-60 saturate-50' : ''}`}>
<div className="p-6 bg-gray-50/50 border-b flex items-center justify-between"> <div className="p-6 bg-gray-50/50 border-b flex items-center justify-between">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center font-bold">2</div> <div className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center font-bold">3</div>
<h2 className="text-lg font-bold"></h2> <h2 className="text-lg font-bold"></h2>
</div> </div>
<Button <Button

View File

@@ -100,6 +100,36 @@ export default function ViewPurchaseOrderPage({ order }: Props) {
)} )}
</div> </div>
{/* 發票資訊卡片 */}
{(order.invoiceNumber || order.invoiceDate || (order.invoiceAmount !== null && order.invoiceAmount !== undefined)) && (
<div className="bg-white rounded-lg border shadow-sm p-6">
<h2 className="text-lg font-bold text-gray-900 mb-6"></h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-x-8 gap-y-6">
{order.invoiceNumber && (
<div>
<span className="text-sm text-gray-500 block mb-1"></span>
<div className="flex items-center gap-1.5">
<span className="font-mono font-medium text-gray-900">{order.invoiceNumber}</span>
<CopyButton text={order.invoiceNumber} label="複製發票號碼" />
</div>
</div>
)}
{order.invoiceDate && (
<div>
<span className="text-sm text-gray-500 block mb-1"></span>
<span className="font-medium text-gray-900">{order.invoiceDate}</span>
</div>
)}
{order.invoiceAmount !== null && order.invoiceAmount !== undefined && (
<div>
<span className="text-sm text-gray-500 block mb-1"></span>
<span className="font-medium text-gray-900">{formatCurrency(order.invoiceAmount)}</span>
</div>
)}
</div>
</div>
)}
{/* 採購項目卡片 */} {/* 採購項目卡片 */}
<div className="bg-white rounded-lg border shadow-sm overflow-hidden"> <div className="bg-white rounded-lg border shadow-sm overflow-hidden">
<div className="p-6 border-b border-gray-100"> <div className="p-6 border-b border-gray-100">

View File

@@ -8,13 +8,7 @@ import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label"; import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea"; import { Textarea } from "@/Components/ui/textarea";
import { import { SearchableSelect } from "@/Components/ui/searchable-select";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { import {
Table, Table,
TableBody, TableBody,
@@ -242,18 +236,13 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
<Label htmlFor="reason" className="text-gray-700"> <Label htmlFor="reason" className="text-gray-700">
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</Label> </Label>
<Select value={reason} onValueChange={(value) => setReason(value as InboundReason)}> <SearchableSelect
<SelectTrigger id="reason" className="border-gray-300"> value={reason}
<SelectValue /> onValueChange={(value) => setReason(value as InboundReason)}
</SelectTrigger> options={INBOUND_REASONS.map((r) => ({ label: r, value: r }))}
<SelectContent> placeholder="選擇入庫原因"
{INBOUND_REASONS.map((r) => ( className="border-gray-300"
<SelectItem key={r} value={r}> />
{r}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.reason && ( {errors.reason && (
<p className="text-sm text-red-500">{errors.reason}</p> <p className="text-sm text-red-500">{errors.reason}</p>
)} )}
@@ -331,23 +320,16 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
<TableRow key={item.tempId}> <TableRow key={item.tempId}>
{/* 商品 */} {/* 商品 */}
<TableCell> <TableCell>
<Select <SearchableSelect
value={item.productId} value={item.productId}
onValueChange={(value) => onValueChange={(value) =>
handleProductChange(item.tempId, value) handleProductChange(item.tempId, value)
} }
> options={products.map((p) => ({ label: p.name, value: p.id }))}
<SelectTrigger className="border-gray-300"> placeholder="選擇商品"
<SelectValue /> searchPlaceholder="搜尋商品..."
</SelectTrigger> className="border-gray-300"
<SelectContent className="z-[9999]"> />
{products.map((product) => (
<SelectItem key={product.id} value={product.id}>
{product.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors[`item-${index}-product`] && ( {errors[`item-${index}-product`] && (
<p className="text-xs text-red-500 mt-1"> <p className="text-xs text-red-500 mt-1">
{errors[`item-${index}-product`]} {errors[`item-${index}-product`]}
@@ -378,23 +360,20 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
{/* 單位 */} {/* 單位 */}
<TableCell> <TableCell>
{item.largeUnit ? ( {item.largeUnit ? (
<Select <SearchableSelect
value={item.selectedUnit} value={item.selectedUnit || ""}
onValueChange={(value) => onValueChange={(value) =>
handleUpdateItem(item.tempId, { handleUpdateItem(item.tempId, {
selectedUnit: value as 'base' | 'large', selectedUnit: value as 'base' | 'large',
unit: value === 'base' ? item.baseUnit : item.largeUnit unit: value === 'base' ? item.baseUnit : item.largeUnit
}) })
} }
> options={[
<SelectTrigger className="border-gray-300"> { label: item.baseUnit || "個", value: "base" },
<SelectValue /> { label: item.largeUnit || "", value: "large" }
</SelectTrigger> ]}
<SelectContent className="z-[9999]"> className="border-gray-300"
<SelectItem value="base">{item.baseUnit}</SelectItem> />
<SelectItem value="large">{item.largeUnit}</SelectItem>
</SelectContent>
</Select>
) : ( ) : (
<Input <Input
value={item.baseUnit || "個"} value={item.baseUnit || "個"}

View File

@@ -18,6 +18,9 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
const [notes, setNotes] = useState(""); const [notes, setNotes] = useState("");
const [status, setStatus] = useState<PurchaseOrderStatus>("draft"); const [status, setStatus] = useState<PurchaseOrderStatus>("draft");
const [warehouseId, setWarehouseId] = useState<string | number>(""); const [warehouseId, setWarehouseId] = useState<string | number>("");
const [invoiceNumber, setInvoiceNumber] = useState("");
const [invoiceDate, setInvoiceDate] = useState("");
const [invoiceAmount, setInvoiceAmount] = useState("");
// 載入編輯訂單資料 // 載入編輯訂單資料
useEffect(() => { useEffect(() => {
@@ -28,6 +31,9 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
setNotes(order.remark || ""); setNotes(order.remark || "");
setStatus(order.status); setStatus(order.status);
setWarehouseId(order.warehouse_id || ""); setWarehouseId(order.warehouse_id || "");
setInvoiceNumber(order.invoiceNumber || "");
setInvoiceDate(order.invoiceDate || "");
setInvoiceAmount(order.invoiceAmount ? String(order.invoiceAmount) : "");
} }
}, [order]); }, [order]);
@@ -38,6 +44,9 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
setNotes(""); setNotes("");
setStatus("draft"); setStatus("draft");
setWarehouseId(""); setWarehouseId("");
setInvoiceNumber("");
setInvoiceDate("");
setInvoiceAmount("");
}; };
const selectedSupplier = suppliers.find((s) => String(s.id) === String(supplierId)); const selectedSupplier = suppliers.find((s) => String(s.id) === String(supplierId));
@@ -87,7 +96,6 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
item.previousPrice = product.lastPrice; item.previousPrice = product.lastPrice;
// 決定預設單位 // 決定預設單位
// 若有採購單位且等於大單位,預設為大單位
const isPurchaseUnitLarge = product.purchase_unit_id && product.large_unit_id && product.purchase_unit_id === product.large_unit_id; const isPurchaseUnitLarge = product.purchase_unit_id && product.large_unit_id && product.purchase_unit_id === product.large_unit_id;
if (isPurchaseUnitLarge) { if (isPurchaseUnitLarge) {
@@ -97,6 +105,9 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
item.selectedUnit = 'base'; item.selectedUnit = 'base';
item.unitId = product.base_unit_id; item.unitId = product.base_unit_id;
} }
// 初始小計 = 數量 * 單價
item.subtotal = calculateSubtotal(Number(item.quantity), Number(item.unitPrice));
} }
} else if (field === "selectedUnit") { } else if (field === "selectedUnit") {
// @ts-ignore // @ts-ignore
@@ -106,17 +117,24 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
} else { } else {
item.unitId = item.base_unit_id; item.unitId = item.base_unit_id;
} }
// Switch unit doesn't change Total Amount (Subtotal), but implies Unit Price changes?
// Actually if I switch unit, the Quantity is usually for that unit.
// If I have 1 Box ($100), and switch to Pc. Quantity is still 1.
// Total is $100. So Unit Price (per Pc) becomes $100.
// This seems safely consistent with "Total Amount" anchor.
} else { } else {
// @ts-ignore // @ts-ignore
item[field] = value; item[field] = value;
} }
// 計算小計 // 重新計算 (Always derive UnitPrice from Subtotal and Quantity)
if (field === "quantity" || field === "unitPrice" || field === "productId") { // 除了剛剛已經算過 subtotal 的 productId case
item.subtotal = calculateSubtotal( if (field !== "productId") {
Number(item.quantity), if (item.quantity > 0) {
Number(item.unitPrice) item.unitPrice = Number(item.subtotal) / Number(item.quantity);
); } else {
item.unitPrice = 0;
}
} }
newItems[index] = item; newItems[index] = item;
@@ -133,6 +151,9 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
selectedSupplier, selectedSupplier,
isOrderSent, isOrderSent,
warehouseId, warehouseId,
invoiceNumber,
invoiceDate,
invoiceAmount,
// Setters // Setters
setSupplierId, setSupplierId,
@@ -140,6 +161,9 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
setNotes, setNotes,
setStatus, setStatus,
setWarehouseId, setWarehouseId,
setInvoiceNumber,
setInvoiceDate,
setInvoiceAmount,
// Methods // Methods
addItem, addItem,

View File

@@ -78,6 +78,9 @@ export interface PurchaseOrder {
remark?: string; remark?: string;
reviewInfo?: ReviewInfo; // 審核資訊 reviewInfo?: ReviewInfo; // 審核資訊
paymentInfo?: PaymentInfo; // 付款資訊 paymentInfo?: PaymentInfo; // 付款資訊
invoiceNumber?: string; // 發票號碼
invoiceDate?: string; // 發票日期
invoiceAmount?: number; // 發票金額
} }
export interface CommonProduct { export interface CommonProduct {