feat: add stok opname management functionality

- Implemented StokOpnameEdit component for editing stock opname entries.
- Created StokOpnameIndex component for listing and managing stock opnames.
- Added StokOpnameCardRow and StokOpnameItemSubRow components for displaying stock opname details.
- Introduced routes for stok opname CRUD operations and actions (submit, verify, reject, cancel).
- Integrated UI components for better user interaction and data presentation.
This commit is contained in:
Yoga Pangestu 2026-08-16 19:38:36 +07:00
parent 28f88bb69c
commit 05707aad7d
14 changed files with 2394 additions and 1 deletions

View File

@ -65,7 +65,7 @@ ## Module Overview
| 7 | Cutting | `admin/manage/cuttings` | `Admin/Manage/CuttingController` | `Admin/Manage/CuttingService` |
| 8 | Transaksi | `admin/manage/transactions` | `Admin/Manage/TransactionController` | `Admin/Manage/TransactionService` |
| 9 | Restock | `admin/manage/restocks` | `Admin/Manage/RestockController` | `Admin/Manage/RestockService` |
| 10 | Stok Opname | `admin/manage/stok-opnames` | (via StockMutationController) | — |
| 10 | Stok Opname | `admin/manage/stok-opnames` | `Admin/Manage/StokOpnameController` | `Admin/Manage/StokOpnameService` |
| 11 | Kas Toko | `admin/finance/cash-accounts` | `Admin/Finance/CashAccountController` | `Admin/Finance/Cash/CashAccountService`, `Admin/Finance/Cash/CashTransactionService` |
| 12 | Pengeluaran | `admin/finance/expenses` | `Admin/Finance/ExpenseController` | `Admin/Finance/ExpenseService` |
| 13 | Kasbon | `admin/finance/employee-advances` | `Admin/Finance/EmployeeAdvanceController` | `Admin/Finance/EmployeeAdvanceService` |

View File

@ -0,0 +1,121 @@
<?php
namespace App\Http\Controllers\Admin\Manage;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\StokOpnameRequest;
use App\Http\Requests\Admin\Manage\StokOpnameVerifyRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\StokOpname;
use App\Services\Admin\Manage\StokOpnameService;
use App\Services\Admin\Master\Product\ProductVariantService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;
class StokOpnameController extends Controller
{
public function __construct(
private StokOpnameService $service,
private ProductVariantService $productVariantService,
) {}
public function index(PaginatedRequest $request): Response
{
return Inertia::render('admin/manage/stok-opname/index', [
'stokOpnames' => $this->service->paginated(
...$request->validatedWithDefaults(),
),
'highlight' => $request->input('highlight'),
]);
}
public function create(): Response
{
return Inertia::render('admin/manage/stok-opname/create', [
'products' => $this->productVariantService->getForStokOpname(),
]);
}
public function store(StokOpnameRequest $request): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->store($request->validated()),
'Stok opname berhasil ditambahkan.',
'admin.manage.stok-opnames.index',
'admin.manage.stok-opnames.create'
);
}
public function edit(StokOpname $stokOpname): Response
{
return Inertia::render('admin/manage/stok-opname/edit', [
'stokOpname' => $this->service->getForEdit($stokOpname),
'products' => $this->productVariantService->getForStokOpname(),
]);
}
public function update(StokOpnameRequest $request, StokOpname $stokOpname): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->update($stokOpname, $request->validated()),
'Stok opname berhasil diperbarui.',
'admin.manage.stok-opnames.index',
'admin.manage.stok-opnames.edit',
['stokOpname' => $stokOpname]
);
}
public function destroy(StokOpname $stokOpname): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->destroy($stokOpname),
'Stok opname berhasil dihapus.',
'admin.manage.stok-opnames.index'
);
}
public function submit(StokOpname $stokOpname): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->submit($stokOpname),
'Stok opname berhasil disubmit.',
'admin.manage.stok-opnames.index'
);
}
public function verify(StokOpnameVerifyRequest $request, StokOpname $stokOpname): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->verify($stokOpname, $request->validated()),
'Stok opname berhasil diverifikasi.',
'admin.manage.stok-opnames.index'
);
}
public function reject(StokOpname $stokOpname): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->reject($stokOpname),
'Stok opname ditolak.',
'admin.manage.stok-opnames.index'
);
}
public function cancel(StokOpname $stokOpname): RedirectResponse
{
return $this->handleAction(
fn () => $this->service->cancel($stokOpname),
'Stok opname berhasil dibatalkan.',
'admin.manage.stok-opnames.index'
);
}
public function items(StokOpname $stokOpname): JsonResponse
{
return response()->json([
'items' => $this->service->getItems($stokOpname),
]);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Http\Requests\Admin\Manage;
use App\Enums\ProductStockQuality;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StokOpnameRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('stok_opnames.create')
|| $this->user()->can('stok_opnames.update');
}
public function rules(): array
{
return [
'opname_date' => ['required', 'date'],
'items' => ['required', 'array', 'min:1'],
'items.*.product_variant_id' => ['required', 'integer', Rule::exists('product_variants', 'id')],
'items.*.stock_quality' => ['required', Rule::in(ProductStockQuality::values())],
'items.*.physical_stock' => ['required', 'integer', 'min:0'],
'notes' => ['nullable', 'string', 'max:100'],
];
}
public function attributes(): array
{
return [
'opname_date' => 'Tanggal Opname',
'items' => 'Item produk',
'items.*.product_variant_id' => 'Varian produk',
'items.*.stock_quality' => 'Jenis stok',
'items.*.physical_stock' => 'Stok fisik',
'notes' => 'Keterangan',
];
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Http\Requests\Admin\Manage;
use Illuminate\Foundation\Http\FormRequest;
class StokOpnameVerifyRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('stok_opnames.verify');
}
public function rules(): array
{
return [
'verification_notes' => ['nullable', 'string', 'max:100'],
];
}
public function attributes(): array
{
return [
'verification_notes' => 'Catatan Verifikasi',
];
}
}

View File

@ -0,0 +1,293 @@
<?php
namespace App\Services\Admin\Manage;
use App\Enums\ProductStockQuality;
use App\Enums\Role;
use App\Enums\StokOpnameStatus;
use App\Models\ProductVariant;
use App\Models\StokOpname;
use App\Models\StokOpnameItem;
use App\Services\Concerns\HasStockAdjustment;
use App\Services\NotificationService;
use App\Services\S3PresignedService;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class StokOpnameService
{
use HasStockAdjustment;
public function __construct(
private S3PresignedService $s3Service,
) {}
public function paginated(int $perPage = 25, string $search = '', string $sort = 'created_at', string $direction = 'desc', ?int $highlight = null, ?string $status = null): LengthAwarePaginator
{
$itemsCountQuery = '(SELECT COUNT(DISTINCT product_variant_id) FROM stok_opname_items WHERE stok_opname_items.stok_opname_id = stok_opnames.id)';
$totalDifferenceQuery = '(SELECT IFNULL(SUM(difference), 0) FROM stok_opname_items WHERE stok_opname_items.stok_opname_id = stok_opnames.id)';
$productNamesQuery = '(SELECT GROUP_CONCAT(DISTINCT p.name ORDER BY p.name SEPARATOR \', \') FROM stok_opname_items soi JOIN product_variants pv ON pv.id = soi.product_variant_id JOIN products p ON p.id = pv.product_id WHERE soi.stok_opname_id = stok_opnames.id)';
return StokOpname::query()
->select(['id', 'created_by_id', 'verified_by_id', 'opname_date', 'status', 'notes', 'verification_notes', 'created_at'])
->with([
'createdBy:id',
'createdBy.userProfile:id,user_id,full_name',
'verifiedBy:id',
'verifiedBy.userProfile:id,user_id,full_name',
])
->selectRaw("{$itemsCountQuery} as items_count")
->selectRaw("{$totalDifferenceQuery} as total_difference")
->selectRaw("{$productNamesQuery} as product_names")
->when($highlight, fn ($q) => $q->where('id', $highlight))
->when($status, fn ($q) => $q->where('status', $status))
->when($search, function ($q) use ($search) {
$q->whereHas('stokOpnameItems.productVariant.product', fn ($sq) => $sq->where('name', 'like', "%{$search}%"))
->orWhere('notes', 'like', "%{$search}%");
})
->orderBy($sort, $direction)
->paginate($perPage);
}
public function store(array $data): StokOpname
{
return DB::transaction(function () use ($data) {
$stokOpname = StokOpname::create([
'created_by_id' => auth()->id(),
'opname_date' => $data['opname_date'],
'status' => StokOpnameStatus::DRAFT,
'notes' => $data['notes'] ?? null,
]);
$this->createItems($stokOpname, $data['items']);
NotificationService::notify(
roles: [Role::OWNER, Role::DEVELOPER],
title: 'Stok Opname Baru',
body: 'Stok opname baru berhasil dibuat oleh '.auth()->user()->full_name.'.',
url: route('admin.manage.stok-opnames.index', ['highlight' => $stokOpname->id]),
);
return $stokOpname;
});
}
public function update(StokOpname $stokOpname, array $data): StokOpname
{
$this->assertDraft($stokOpname);
return DB::transaction(function () use ($stokOpname, $data) {
$stokOpname->stokOpnameItems()->delete();
$stokOpname->update([
'opname_date' => $data['opname_date'],
'notes' => $data['notes'] ?? null,
]);
$this->createItems($stokOpname, $data['items']);
return $stokOpname;
});
}
public function destroy(StokOpname $stokOpname): void
{
$this->assertDraft($stokOpname);
DB::transaction(function () use ($stokOpname) {
$stokOpname->stokOpnameItems()->delete();
$stokOpname->delete();
});
}
public function submit(StokOpname $stokOpname): StokOpname
{
$this->assertDraft($stokOpname);
$stokOpname->update(['status' => StokOpnameStatus::IN_PROGRESS]);
NotificationService::notify(
roles: [Role::OWNER, Role::DEVELOPER],
title: 'Stok Opname Disubmit',
body: 'Stok opname berhasil disubmit oleh '.auth()->user()->full_name.'.',
url: route('admin.manage.stok-opnames.index', ['highlight' => $stokOpname->id]),
);
return $stokOpname;
}
public function verify(StokOpname $stokOpname, array $data): StokOpname
{
$this->assertInProgress($stokOpname);
return DB::transaction(function () use ($stokOpname, $data) {
$stokOpname->load('stokOpnameItems');
foreach ($stokOpname->stokOpnameItems as $item) {
if ($item->difference != 0) {
$this->adjustVariantStock(
$item->product_variant_id,
abs($item->difference),
$item->difference > 0 ? 1 : -1,
$item->stock_quality->value,
);
}
}
$stokOpname->update([
'status' => StokOpnameStatus::VERIFIED,
'verified_by_id' => auth()->id(),
'verification_notes' => $data['verification_notes'] ?? null,
]);
NotificationService::notify(
roles: [Role::STOK_OPNAME, Role::ADMIN_TOKO],
title: 'Stok Opname Diverifikasi',
body: 'Stok opname berhasil diverifikasi oleh '.auth()->user()->full_name.'.',
url: route('admin.manage.stok-opnames.index', ['highlight' => $stokOpname->id]),
);
return $stokOpname;
});
}
public function reject(StokOpname $stokOpname): StokOpname
{
$this->assertInProgress($stokOpname);
$stokOpname->update([
'status' => StokOpnameStatus::DRAFT,
'verification_notes' => null,
]);
NotificationService::notify(
roles: [Role::STOK_OPNAME],
title: 'Stok Opname Ditolak',
body: 'Stok opname ditolak oleh '.auth()->user()->full_name.'. Silakan periksa dan submit ulang.',
url: route('admin.manage.stok-opnames.index', ['highlight' => $stokOpname->id]),
);
return $stokOpname;
}
public function cancel(StokOpname $stokOpname): StokOpname
{
if ($stokOpname->status === StokOpnameStatus::VERIFIED) {
throw ValidationException::withMessages([
'status' => 'Stok opname yang sudah diverifikasi tidak dapat dibatalkan.',
]);
}
$stokOpname->update(['status' => StokOpnameStatus::CANCELLED]);
return $stokOpname;
}
public function getForEdit(StokOpname $stokOpname): array
{
$stokOpname->load([
'stokOpnameItems' => fn ($q) => $q
->select(['id', 'stok_opname_id', 'product_variant_id', 'stock_quality', 'system_stock', 'physical_stock', 'difference', 'notes']),
'stokOpnameItems.productVariant:id,product_id,name,stock,reject_stock,retail_stock',
'stokOpnameItems.productVariant.product:id,name',
]);
return [
'id' => $stokOpname->id,
'opname_date' => $stokOpname->opname_date->format('Y-m-d'),
'status' => $stokOpname->status->value,
'notes' => $stokOpname->notes,
'items' => $stokOpname->stokOpnameItems->map(fn ($item) => [
'id' => $item->id,
'product_variant_id' => $item->product_variant_id,
'stock_quality' => $item->stock_quality->value,
'system_stock' => $item->system_stock,
'physical_stock' => $item->physical_stock,
'difference' => $item->difference,
'notes' => $item->notes,
'variant_name' => $item->productVariant?->name,
'product_name' => $item->productVariant?->product?->name,
]),
];
}
public function getItems(StokOpname $stokOpname): \Illuminate\Support\Collection
{
return $stokOpname->stokOpnameItems()
->select(['id', 'stok_opname_id', 'product_variant_id', 'stock_quality', 'system_stock', 'physical_stock', 'difference', 'notes'])
->with(['productVariant:id,product_id,name', 'productVariant.product:id,name'])
->orderByRaw('(SELECT name FROM product_variants WHERE product_variants.id = stok_opname_items.product_variant_id)')
->get()
->map(function (StokOpnameItem $item) {
$media = $item->productVariant?->getFirstMedia('images');
$photoUrl = $media ? $this->s3Service->getTemporaryUrl($media->getPath()) : null;
$photoConversionUrl = $media
? ($media->getGeneratedConversions()->contains('thumb')
? $this->s3Service->getTemporaryUrl($media->getPath('thumb'))
: $this->s3Service->getTemporaryUrl($media->getPath()))
: null;
return [
'id' => $item->id,
'product_variant_id' => $item->product_variant_id,
'stock_quality' => $item->stock_quality,
'system_stock' => $item->system_stock,
'physical_stock' => $item->physical_stock,
'difference' => $item->difference,
'notes' => $item->notes,
'variant_name' => $item->productVariant?->name,
'product_name' => $item->productVariant?->product?->name,
'photo_url' => $photoUrl,
'photo_conversion_url' => $photoConversionUrl,
];
});
}
private function createItems(StokOpname $stokOpname, array $items): void
{
$now = now();
$rows = collect($items)->map(function ($item) use ($stokOpname, $now) {
$variant = ProductVariant::findOrFail($item['product_variant_id']);
$stockQuality = ProductStockQuality::from($item['stock_quality']);
$systemStock = match ($stockQuality) {
ProductStockQuality::GOOD => $variant->stock,
ProductStockQuality::REJECT => $variant->reject_stock,
ProductStockQuality::RETAIL => $variant->retail_stock,
};
return [
'stok_opname_id' => $stokOpname->id,
'product_variant_id' => $item['product_variant_id'],
'stock_quality' => $stockQuality->value,
'system_stock' => $systemStock,
'physical_stock' => (int) $item['physical_stock'],
'difference' => (int) $item['physical_stock'] - $systemStock,
'notes' => $item['notes'] ?? null,
'created_at' => $now,
'updated_at' => $now,
];
})->toArray();
DB::table('stok_opname_items')->insert($rows);
}
private function assertDraft(StokOpname $stokOpname): void
{
if ($stokOpname->status !== StokOpnameStatus::DRAFT) {
throw ValidationException::withMessages([
'status' => 'Hanya stok opname dengan status draft yang dapat diubah.',
]);
}
}
private function assertInProgress(StokOpname $stokOpname): void
{
if ($stokOpname->status !== StokOpnameStatus::IN_PROGRESS) {
throw ValidationException::withMessages([
'status' => 'Hanya stok opname dengan status dalam proses yang dapat diproses.',
]);
}
}
}

View File

@ -0,0 +1,9 @@
import { createDraftHook } from '@/hooks/use-draft-save';
import { clearStokOpnameDraft, loadStokOpnameDraft, saveStokOpnameDraft } from '@/lib/stok-opname-draft';
import type { StokOpnameDraftData } from '@/lib/stok-opname-draft';
export const useStokOpnameDraftSave = createDraftHook<StokOpnameDraftData>({
save: saveStokOpnameDraft,
load: loadStokOpnameDraft,
clear: clearStokOpnameDraft,
});

View File

@ -0,0 +1,34 @@
import { createDraftStore } from '@/lib/draft-store';
export type StockType = 'good' | 'reject' | 'retail';
export type StokOpnameDraftData = {
selectedProductId: string;
physicalStocks: Record<string, Record<StockType, number>>;
notes: string;
};
export const stokOpnameDraftStore =
createDraftStore<StokOpnameDraftData>('stok-opname-draft');
export function saveStokOpnameDraft(
type: 'create' | 'edit',
data: StokOpnameDraftData,
userId?: number,
): boolean {
return stokOpnameDraftStore.save(type, data, userId);
}
export function loadStokOpnameDraft(
type: 'create' | 'edit',
userId?: number,
): StokOpnameDraftData | null {
return stokOpnameDraftStore.load(type, userId);
}
export function clearStokOpnameDraft(
type: 'create' | 'edit',
userId?: number,
): void {
stokOpnameDraftStore.clear(type, userId);
}

View File

@ -0,0 +1,79 @@
export type StokOpnameStatus = 'draft' | 'in_progress' | 'completed' | 'verified' | 'cancelled';
export type StockType = 'good' | 'reject' | 'retail';
export type StokOpnameItem = {
id: number;
product_variant_id: number;
stock_quality: StockType;
system_stock: number;
physical_stock: number;
difference: number;
notes: string | null;
variant_name: string;
product_name: string;
photo_url: string | null;
photo_conversion_url: string | null;
};
export type StokOpname = {
id: number;
created_by_id: number;
verified_by_id: number | null;
opname_date: string;
status: StokOpnameStatus;
notes: string | null;
verification_notes: string | null;
created_at: string;
items_count: number;
total_difference: number;
product_names: string | null;
created_by: {
id: number;
user_profile: {
full_name: string;
};
};
verified_by: {
id: number;
user_profile: {
full_name: string;
};
} | null;
};
export type StokOpnameForEdit = {
id: number;
opname_date: string;
status: StokOpnameStatus;
notes: string | null;
items: {
id: number;
product_variant_id: number;
stock_quality: StockType;
system_stock: number;
physical_stock: number;
difference: number;
notes: string | null;
variant_name: string;
product_name: string;
}[];
};
export type ProductForStokOpname = {
id: number;
name: string;
status: string;
product_variants: {
id: number;
name: string;
stock: number;
reject_stock: number;
retail_stock: number;
photo_url: string | null;
}[];
};
export type StokOpnameCreateData = {
products: ProductForStokOpname[];
};

View File

@ -0,0 +1,591 @@
'use no memo';
import { NumberInput } from '@/components/inputs';
import { InputError } from '@/components/ui';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Combobox,
ComboboxContent,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
} from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';
import { useStokOpnameDraftSave } from '@/hooks/use-stok-opname-draft';
import { formatNumber } from '@/lib/format';
import { loadStokOpnameDraft } from '@/lib/stok-opname-draft';
import { index as stokOpnameIndex, store } from '@/routes/admin/manage/stok-opnames';
import { Form, Head, Link, usePage } from '@inertiajs/react';
import { ArrowLeft, Minus, Plus, ShoppingCart, Trash2 } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { toast } from 'sonner';
import type { ProductForStokOpname, StokOpnameCreateData } from './columns';
type StockType = 'good' | 'reject' | 'retail';
type CartLine = {
key: string;
photoUrl: string | null;
title: string;
subtitle: string;
quantity: number;
onAdjust: (delta: number) => void;
onSet: (value: number) => void;
onRemove: () => void;
};
type Props = {
products: StokOpnameCreateData['products'];
};
export default function StokOpnameCreate({ products }: Props) {
const { auth } = usePage().props as { auth: { user?: { id?: number } } };
const userId = auth.user?.id;
const draft = loadStokOpnameDraft('create', userId);
const [selectedProductId, setSelectedProductId] = useState(
draft?.selectedProductId ?? '',
);
const [physicalStocks, setPhysicalStocks] = useState<Record<string, Record<StockType, number>>>(() => {
if (draft?.physicalStocks) {
return draft.physicalStocks;
}
return {};
});
const [notes, setNotes] = useState(draft?.notes ?? '');
const [cartOpen, setCartOpen] = useState(false);
const draftData = useMemo(
() => ({
selectedProductId,
physicalStocks,
notes,
}),
[selectedProductId, physicalStocks, notes],
);
useStokOpnameDraftSave('create', draftData, userId);
const physicalStocksRef = useRef(physicalStocks);
useEffect(() => {
physicalStocksRef.current = physicalStocks;
}, [physicalStocks]);
const selectedProduct = useMemo(
() => products.find((p) => String(p.id) === selectedProductId) ?? null,
[products, selectedProductId],
);
const variantById = useMemo(
() =>
new Map(
products.flatMap((p: ProductForStokOpname) =>
p.product_variants.map((v) => [v.id, v]),
),
),
[products],
);
const updatePhysicalStock = useCallback((variantId: number, stockType: StockType, value: number) => {
setPhysicalStocks((prev) => ({
...prev,
[variantId]: {
...prev[variantId],
[stockType]: Math.max(0, value),
},
}));
}, []);
const hasAnyStock = useCallback((variantId: number) => {
const stocks = physicalStocks[variantId];
if (!stocks) return false;
return stocks.good > 0 || stocks.reject > 0 || stocks.retail > 0;
}, [physicalStocks]);
const cartItems: CartLine[] = (() => {
const lines: CartLine[] = [];
for (const [variantId, stocks] of Object.entries(physicalStocks)) {
const id = Number(variantId);
const variant = variantById.get(id);
if (!variant) continue;
for (const [stockType, quantity] of Object.entries(stocks)) {
if (quantity <= 0) continue;
const type = stockType as StockType;
const typeLabel = type === 'good' ? 'Bagus' : type === 'reject' ? 'Reject' : 'Ecer';
lines.push({
key: `variant-${id}-${type}`,
photoUrl: variant.photo_url,
title: variant.name,
subtitle: `${typeLabel}: ${formatNumber(quantity)}`,
quantity,
onAdjust: (delta) => updatePhysicalStock(id, type, quantity + delta),
onSet: (value) => updatePhysicalStock(id, type, value),
onRemove: () => updatePhysicalStock(id, type, 0),
});
}
}
return lines.sort((a, b) => a.title.localeCompare(b.title));
})();
function formatQuantity(value: number): string {
return formatNumber(value, { maximumFractionDigits: 4 });
}
function getPayload() {
const items: Array<{ product_variant_id: number; stock_quality: StockType; physical_stock: number }> = [];
for (const [variantId, stocks] of Object.entries(physicalStocksRef.current)) {
const variant = variantById.get(Number(variantId));
if (!variant) continue;
for (const [stockType, quantity] of Object.entries(stocks)) {
if (quantity <= 0) continue;
items.push({
product_variant_id: Number(variantId),
stock_quality: stockType as StockType,
physical_stock: quantity,
});
}
}
return {
opname_date: new Date().toISOString().split('T')[0],
items,
notes: notes || null,
};
}
return (
<>
<Head title="Tambah Stok Opname" />
<div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-semibold tracking-tight">
Tambah Stok Opname
</h2>
<Button asChild variant="outline">
<Link href={stokOpnameIndex.url()}>
<ArrowLeft className="h-4 w-4" />
Kembali
</Link>
</Button>
</div>
<Form
action={store()}
transform={(formData) => ({
...formData,
...getPayload(),
})}
onError={() => {
toast.error('Ada data yang belum sesuai, silakan periksa kembali input Anda.');
}}
>
{({ errors, processing }) => (
<div className="grid gap-6 md:grid-cols-3">
<div className="space-y-6 md:col-span-2">
<Card>
<CardHeader>
<CardTitle>Pilih Produk</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-2">
<Label>
Nama Produk{' '}
<span className="text-destructive">
*
</span>
</Label>
<Combobox
items={products}
itemToStringLabel={(p) =>
p.name
}
value={selectedProduct}
onValueChange={(value) =>
setSelectedProductId(
value
? String(value.id)
: '',
)
}
>
<ComboboxInput
placeholder="Cari produk..."
className="w-full"
/>
<ComboboxContent>
<ComboboxEmpty>
Tidak ada produk
ditemukan.
</ComboboxEmpty>
<ComboboxList>
{(p) => (
<ComboboxItem
key={p.id}
value={p}
>
{p.name}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
<InputError
message={errors.items}
/>
</div>
{selectedProduct && (
<div className="space-y-4">
{selectedProduct.product_variants.map(
(variant) => {
const isActive = hasAnyStock(variant.id);
return (
<div
key={variant.id}
className={`rounded-lg border p-4 ${isActive ? 'border-primary bg-primary/5' : ''}`}
>
<div className="flex items-start gap-3">
{variant.photo_url ? (
<img
src={variant.photo_url}
alt={variant.name}
className="h-12 w-12 shrink-0 rounded-md object-cover"
/>
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
N/A
</div>
)}
<div className="min-w-0 flex-1">
<p className="font-medium">
{variant.name}
</p>
<div className="mt-2 flex gap-3">
<div className="flex-1 space-y-1 rounded-md border p-2">
<p className="text-xs text-muted-foreground">
Bagus: <span className="font-medium text-foreground">{formatQuantity(variant.stock)}</span>
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon"
disabled={!physicalStocks[variant.id]?.good}
onClick={() =>
updatePhysicalStock(variant.id, 'good', (physicalStocks[variant.id]?.good ?? 0) - 1)
}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="flex-1 text-center text-xs"
value={physicalStocks[variant.id]?.good ?? 0}
onValueChange={(val) =>
updatePhysicalStock(variant.id, 'good', val)
}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() =>
updatePhysicalStock(variant.id, 'good', (physicalStocks[variant.id]?.good ?? 0) + 1)
}
>
<Plus className="h-3 w-3" />
</Button>
</div>
</div>
<div className="flex-1 space-y-1 rounded-md border p-2">
<p className="text-xs text-muted-foreground">
Reject: <span className="font-medium text-foreground">{formatQuantity(variant.reject_stock)}</span>
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon"
disabled={!physicalStocks[variant.id]?.reject}
onClick={() =>
updatePhysicalStock(variant.id, 'reject', (physicalStocks[variant.id]?.reject ?? 0) - 1)
}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="flex-1 text-center text-xs"
value={physicalStocks[variant.id]?.reject ?? 0}
onValueChange={(val) =>
updatePhysicalStock(variant.id, 'reject', val)
}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() =>
updatePhysicalStock(variant.id, 'reject', (physicalStocks[variant.id]?.reject ?? 0) + 1)
}
>
<Plus className="h-3 w-3" />
</Button>
</div>
</div>
<div className="flex-1 space-y-1 rounded-md border p-2">
<p className="text-xs text-muted-foreground">
Ecer: <span className="font-medium text-foreground">{formatQuantity(variant.retail_stock)}</span>
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon"
disabled={!physicalStocks[variant.id]?.retail}
onClick={() =>
updatePhysicalStock(variant.id, 'retail', (physicalStocks[variant.id]?.retail ?? 0) - 1)
}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="flex-1 text-center text-xs"
value={physicalStocks[variant.id]?.retail ?? 0}
onValueChange={(val) =>
updatePhysicalStock(variant.id, 'retail', val)
}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() =>
updatePhysicalStock(variant.id, 'retail', (physicalStocks[variant.id]?.retail ?? 0) + 1)
}
>
<Plus className="h-3 w-3" />
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
);
},
)}
</div>
)}
</CardContent>
</Card>
</div>
<div className="space-y-6 md:col-span-1">
<Card className="sticky top-6">
<CardHeader>
<CardTitle>Ringkasan</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
Jumlah Item
</span>
<span className="font-medium">
{cartItems.length}
</span>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="notes">
Keterangan
</Label>
<Textarea
id="notes"
value={notes}
onChange={(e) =>
setNotes(e.target.value)
}
placeholder="Masukkan keterangan"
maxLength={100}
/>
<InputError
message={errors.notes}
/>
</div>
<Button
type="submit"
className="w-full"
disabled={
processing ||
cartItems.length === 0
}
>
{processing
? 'Menyimpan...'
: 'Simpan'}
</Button>
</CardContent>
</Card>
</div>
</div>
)}
</Form>
<Button
type="button"
onClick={() => setCartOpen(true)}
className="fixed top-1/2 right-4 z-50 h-14 w-14 -translate-y-1/2 rounded-full shadow-lg"
size="icon"
aria-label="Buka keranjang stok opname"
>
<ShoppingCart className="h-5 w-5" />
{cartItems.length > 0 && (
<span className="absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-xs font-semibold text-white">
{cartItems.length}
</span>
)}
</Button>
<Sheet open={cartOpen} onOpenChange={setCartOpen}>
<SheetContent side="right" className="w-full sm:max-w-md">
<SheetHeader>
<SheetTitle>Keranjang Stok Opname</SheetTitle>
</SheetHeader>
<div className="flex-1 space-y-4 overflow-y-auto px-6 pb-6">
{cartItems.length === 0 ? (
<p className="text-sm text-muted-foreground">
Keranjang kosong.
</p>
) : (
(() => {
const groupedByVariant: Record<string, { title: string; photoUrl: string | null; items: typeof cartItems }> = {};
for (const item of cartItems) {
const variantKey = item.key.split('-').slice(0, 2).join('-');
if (!groupedByVariant[variantKey]) {
groupedByVariant[variantKey] = {
title: item.title,
photoUrl: item.photoUrl,
items: [],
};
}
groupedByVariant[variantKey].items.push(item);
}
return Object.entries(groupedByVariant).map(([variantKey, group]) => (
<div key={variantKey} className="rounded-lg border p-3 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{group.photoUrl ? (
<div className="h-10 w-10 shrink-0 overflow-hidden rounded-md border">
<img
src={group.photoUrl}
alt={group.title}
className="h-full w-full object-cover"
/>
</div>
) : (
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
N/A
</div>
)}
<p className="font-medium">{group.title}</p>
</div>
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => {
for (const item of group.items) {
item.onRemove();
}
}}
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
<div className="space-y-2">
{group.items.map((item) => {
const stockType = item.key.split('-').pop();
const typeLabel = stockType === 'good' ? 'Bagus' : stockType === 'reject' ? 'Reject' : 'Ecer';
return (
<div key={item.key} className="flex items-center justify-between gap-2">
<span className="text-xs text-muted-foreground w-14">{typeLabel}</span>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon-sm"
disabled={item.quantity <= 0}
onClick={() => item.onAdjust(-1)}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="w-16 text-center text-xs"
value={item.quantity}
onValueChange={item.onSet}
/>
<Button
type="button"
variant="outline"
size="icon-sm"
onClick={() => item.onAdjust(1)}
>
<Plus className="h-3 w-3" />
</Button>
</div>
<span className="font-medium text-xs">
{formatQuantity(item.quantity)} pcs
</span>
</div>
);
})}
</div>
</div>
));
})()
)}
</div>
<SheetFooter>
<div className="flex items-center justify-between border-t pt-4">
<span className="text-sm">Total Item</span>
<span className="text-sm font-semibold">
{cartItems.length}
</span>
</div>
</SheetFooter>
</SheetContent>
</Sheet>
</div>
</>
);
}

View File

@ -0,0 +1,601 @@
'use no memo';
import { Form, Head, Link, usePage } from '@inertiajs/react';
import { ArrowLeft, Minus, Plus, ShoppingCart, Trash2 } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { toast } from 'sonner';
import { InputError } from '@/components/ui';
import { NumberInput } from '@/components/inputs';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Combobox,
ComboboxContent,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
} from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';
import { useStokOpnameDraftSave } from '@/hooks/use-stok-opname-draft';
import { formatNumber } from '@/lib/format';
import { loadStokOpnameDraft } from '@/lib/stok-opname-draft';
import { index as stokOpnameIndex, update } from '@/routes/admin/manage/stok-opnames';
import type { ProductForStokOpname, StokOpnameForEdit } from './columns';
type StockType = 'good' | 'reject' | 'retail';
type CartLine = {
key: string;
photoUrl: string | null;
title: string;
subtitle: string;
quantity: number;
onAdjust: (delta: number) => void;
onSet: (value: number) => void;
onRemove: () => void;
};
type Props = {
stokOpname: StokOpnameForEdit;
products: ProductForStokOpname[];
};
export default function StokOpnameEdit({ stokOpname, products }: Props) {
const { auth } = usePage().props as { auth: { user?: { id?: number } } };
const userId = auth.user?.id;
const draft = loadStokOpnameDraft('edit', userId);
const [selectedProductId, setSelectedProductId] = useState(
draft?.selectedProductId ?? '',
);
const [physicalStocks, setPhysicalStocks] = useState<Record<string, Record<StockType, number>>>(() => {
if (draft?.physicalStocks && Object.keys(draft.physicalStocks).length > 0) {
return draft.physicalStocks;
}
const initial: Record<string, Record<StockType, number>> = {};
for (const item of stokOpname.items) {
const variantId = String(item.product_variant_id);
if (!initial[variantId]) {
initial[variantId] = { good: 0, reject: 0, retail: 0 };
}
initial[variantId][item.stock_quality] = item.physical_stock;
}
return initial;
});
const [notes, setNotes] = useState(draft?.notes ?? stokOpname.notes ?? '');
const [cartOpen, setCartOpen] = useState(false);
const draftData = useMemo(
() => ({
selectedProductId,
physicalStocks,
notes,
}),
[selectedProductId, physicalStocks, notes],
);
useStokOpnameDraftSave('edit', draftData, userId);
const physicalStocksRef = useRef(physicalStocks);
useEffect(() => {
physicalStocksRef.current = physicalStocks;
}, [physicalStocks]);
const selectedProduct = useMemo(
() => products.find((p) => String(p.id) === selectedProductId) ?? null,
[products, selectedProductId],
);
const variantById = useMemo(
() =>
new Map(
products.flatMap((p: ProductForStokOpname) =>
p.product_variants.map((v) => [v.id, v]),
),
),
[products],
);
const updatePhysicalStock = useCallback((variantId: number, stockType: StockType, value: number) => {
setPhysicalStocks((prev) => ({
...prev,
[variantId]: {
...prev[variantId],
[stockType]: Math.max(0, value),
},
}));
}, []);
const hasAnyStock = useCallback((variantId: number) => {
const stocks = physicalStocks[variantId];
if (!stocks) return false;
return stocks.good > 0 || stocks.reject > 0 || stocks.retail > 0;
}, [physicalStocks]);
const cartItems: CartLine[] = (() => {
const lines: CartLine[] = [];
for (const [variantId, stocks] of Object.entries(physicalStocks)) {
const id = Number(variantId);
const variant = variantById.get(id);
if (!variant) continue;
for (const [stockType, quantity] of Object.entries(stocks)) {
if (quantity <= 0) continue;
const type = stockType as StockType;
const typeLabel = type === 'good' ? 'Bagus' : type === 'reject' ? 'Reject' : 'Ecer';
lines.push({
key: `variant-${id}-${type}`,
photoUrl: variant.photo_url,
title: variant.name,
subtitle: `${typeLabel}: ${formatNumber(quantity)}`,
quantity,
onAdjust: (delta) => updatePhysicalStock(id, type, quantity + delta),
onSet: (value) => updatePhysicalStock(id, type, value),
onRemove: () => updatePhysicalStock(id, type, 0),
});
}
}
return lines.sort((a, b) => a.title.localeCompare(b.title));
})();
function formatQuantity(value: number): string {
return formatNumber(value, { maximumFractionDigits: 4 });
}
function getPayload() {
const items: Array<{ product_variant_id: number; stock_quality: StockType; physical_stock: number }> = [];
for (const [variantId, stocks] of Object.entries(physicalStocksRef.current)) {
const variant = variantById.get(Number(variantId));
if (!variant) continue;
for (const [stockType, quantity] of Object.entries(stocks)) {
if (quantity <= 0) continue;
items.push({
product_variant_id: Number(variantId),
stock_quality: stockType as StockType,
physical_stock: quantity,
});
}
}
return {
opname_date: stokOpname.opname_date,
items,
notes: notes || null,
};
}
return (
<>
<Head title="Edit Stok Opname" />
<div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-semibold tracking-tight">
Edit Stok Opname
</h2>
<Button asChild variant="outline">
<Link href={stokOpnameIndex.url()}>
<ArrowLeft className="h-4 w-4" />
Kembali
</Link>
</Button>
</div>
<Form
action={update(stokOpname.id)}
transform={(formData) => ({
...formData,
...getPayload(),
})}
onError={() => {
toast.error('Ada data yang belum sesuai, silakan periksa kembali input Anda.');
}}
>
{({ errors, processing }) => (
<div className="grid gap-6 md:grid-cols-3">
<div className="space-y-6 md:col-span-2">
<Card>
<CardHeader>
<CardTitle>Pilih Produk</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-2">
<Label>
Nama Produk{' '}
<span className="text-destructive">
*
</span>
</Label>
<Combobox
items={products}
itemToStringLabel={(p) =>
p.name
}
value={selectedProduct}
onValueChange={(value) =>
setSelectedProductId(
value
? String(value.id)
: '',
)
}
>
<ComboboxInput
placeholder="Cari produk..."
className="w-full"
/>
<ComboboxContent>
<ComboboxEmpty>
Tidak ada produk
ditemukan.
</ComboboxEmpty>
<ComboboxList>
{(p) => (
<ComboboxItem
key={p.id}
value={p}
>
{p.name}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
<InputError
message={errors.items}
/>
</div>
{selectedProduct && (
<div className="space-y-4">
{selectedProduct.product_variants.map(
(variant) => {
const isActive = hasAnyStock(variant.id);
return (
<div
key={variant.id}
className={`rounded-lg border p-4 ${isActive ? 'border-primary bg-primary/5' : ''}`}
>
<div className="flex items-start gap-3">
{variant.photo_url ? (
<img
src={variant.photo_url}
alt={variant.name}
className="h-12 w-12 shrink-0 rounded-md object-cover"
/>
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
N/A
</div>
)}
<div className="min-w-0 flex-1">
<p className="font-medium">
{variant.name}
</p>
<div className="mt-2 flex gap-3">
<div className="flex-1 space-y-1 rounded-md border p-2">
<p className="text-xs text-muted-foreground">
Bagus: <span className="font-medium text-foreground">{formatQuantity(variant.stock)}</span>
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon"
disabled={!physicalStocks[variant.id]?.good}
onClick={() =>
updatePhysicalStock(variant.id, 'good', (physicalStocks[variant.id]?.good ?? 0) - 1)
}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="flex-1 text-center text-xs"
value={physicalStocks[variant.id]?.good ?? 0}
onValueChange={(val) =>
updatePhysicalStock(variant.id, 'good', val)
}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() =>
updatePhysicalStock(variant.id, 'good', (physicalStocks[variant.id]?.good ?? 0) + 1)
}
>
<Plus className="h-3 w-3" />
</Button>
</div>
</div>
<div className="flex-1 space-y-1 rounded-md border p-2">
<p className="text-xs text-muted-foreground">
Reject: <span className="font-medium text-foreground">{formatQuantity(variant.reject_stock)}</span>
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon"
disabled={!physicalStocks[variant.id]?.reject}
onClick={() =>
updatePhysicalStock(variant.id, 'reject', (physicalStocks[variant.id]?.reject ?? 0) - 1)
}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="flex-1 text-center text-xs"
value={physicalStocks[variant.id]?.reject ?? 0}
onValueChange={(val) =>
updatePhysicalStock(variant.id, 'reject', val)
}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() =>
updatePhysicalStock(variant.id, 'reject', (physicalStocks[variant.id]?.reject ?? 0) + 1)
}
>
<Plus className="h-3 w-3" />
</Button>
</div>
</div>
<div className="flex-1 space-y-1 rounded-md border p-2">
<p className="text-xs text-muted-foreground">
Ecer: <span className="font-medium text-foreground">{formatQuantity(variant.retail_stock)}</span>
</p>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon"
disabled={!physicalStocks[variant.id]?.retail}
onClick={() =>
updatePhysicalStock(variant.id, 'retail', (physicalStocks[variant.id]?.retail ?? 0) - 1)
}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="flex-1 text-center text-xs"
value={physicalStocks[variant.id]?.retail ?? 0}
onValueChange={(val) =>
updatePhysicalStock(variant.id, 'retail', val)
}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() =>
updatePhysicalStock(variant.id, 'retail', (physicalStocks[variant.id]?.retail ?? 0) + 1)
}
>
<Plus className="h-3 w-3" />
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
);
},
)}
</div>
)}
</CardContent>
</Card>
</div>
<div className="space-y-6 md:col-span-1">
<Card className="sticky top-6">
<CardHeader>
<CardTitle>Ringkasan</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
Jumlah Item
</span>
<span className="font-medium">
{cartItems.length}
</span>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="notes">
Keterangan
</Label>
<Textarea
id="notes"
value={notes}
onChange={(e) =>
setNotes(e.target.value)
}
placeholder="Masukkan keterangan"
maxLength={100}
/>
<InputError
message={errors.notes}
/>
</div>
<Button
type="submit"
className="w-full"
disabled={
processing ||
cartItems.length === 0
}
>
{processing
? 'Menyimpan...'
: 'Simpan'}
</Button>
</CardContent>
</Card>
</div>
</div>
)}
</Form>
<Button
type="button"
onClick={() => setCartOpen(true)}
className="fixed top-1/2 right-4 z-50 h-14 w-14 -translate-y-1/2 rounded-full shadow-lg"
size="icon"
aria-label="Buka keranjang stok opname"
>
<ShoppingCart className="h-5 w-5" />
{cartItems.length > 0 && (
<span className="absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-xs font-semibold text-white">
{cartItems.length}
</span>
)}
</Button>
<Sheet open={cartOpen} onOpenChange={setCartOpen}>
<SheetContent side="right" className="w-full sm:max-w-md">
<SheetHeader>
<SheetTitle>Keranjang Stok Opname</SheetTitle>
</SheetHeader>
<div className="flex-1 space-y-4 overflow-y-auto px-6 pb-6">
{cartItems.length === 0 ? (
<p className="text-sm text-muted-foreground">
Keranjang kosong.
</p>
) : (
(() => {
const groupedByVariant: Record<string, { title: string; photoUrl: string | null; items: typeof cartItems }> = {};
for (const item of cartItems) {
const variantKey = item.key.split('-').slice(0, 2).join('-');
if (!groupedByVariant[variantKey]) {
groupedByVariant[variantKey] = {
title: item.title,
photoUrl: item.photoUrl,
items: [],
};
}
groupedByVariant[variantKey].items.push(item);
}
return Object.entries(groupedByVariant).map(([variantKey, group]) => (
<div key={variantKey} className="rounded-lg border p-3 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{group.photoUrl ? (
<div className="h-10 w-10 shrink-0 overflow-hidden rounded-md border">
<img
src={group.photoUrl}
alt={group.title}
className="h-full w-full object-cover"
/>
</div>
) : (
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
N/A
</div>
)}
<p className="font-medium">{group.title}</p>
</div>
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => {
for (const item of group.items) {
item.onRemove();
}
}}
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
<div className="space-y-2">
{group.items.map((item) => {
const stockType = item.key.split('-').pop();
const typeLabel = stockType === 'good' ? 'Bagus' : stockType === 'reject' ? 'Reject' : 'Ecer';
return (
<div key={item.key} className="flex items-center justify-between gap-2">
<span className="text-xs text-muted-foreground w-14">{typeLabel}</span>
<div className="flex items-center gap-1">
<Button
type="button"
variant="outline"
size="icon-sm"
disabled={item.quantity <= 0}
onClick={() => item.onAdjust(-1)}
>
<Minus className="h-3 w-3" />
</Button>
<NumberInput
className="w-16 text-center text-xs"
value={item.quantity}
onValueChange={item.onSet}
/>
<Button
type="button"
variant="outline"
size="icon-sm"
onClick={() => item.onAdjust(1)}
>
<Plus className="h-3 w-3" />
</Button>
</div>
<span className="font-medium text-xs">
{formatQuantity(item.quantity)} pcs
</span>
</div>
);
})}
</div>
</div>
));
})()
)}
</div>
<SheetFooter>
<div className="flex items-center justify-between border-t pt-4">
<span className="text-sm">Total Item</span>
<span className="text-sm font-semibold">
{cartItems.length}
</span>
</div>
</SheetFooter>
</SheetContent>
</Sheet>
</div>
</>
);
}

View File

@ -0,0 +1,229 @@
import { Head, Link, router } from '@inertiajs/react';
import { ClipboardCheck, Plus, Send, XCircle } from 'lucide-react';
import { useCallback, useState } from 'react';
import { CardTable } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import { useCardTableExpand } from '@/components/hooks/use-card-table-expand';
import { PageHeader } from '@/components/layout';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
destroy,
create as stokOpnameCreate,
index as stokOpnameIndex,
edit as stokOpnameEdit,
items as stokOpnameItems,
submit as stokOpnameSubmit,
verify as stokOpnameVerify,
reject as stokOpnameReject,
cancel as stokOpnameCancel,
} from '@/routes/admin/manage/stok-opnames';
import type { StokOpname, StokOpnameItem, StokOpnameStatus } from './columns';
import { StokOpnameCardRow } from './stok-opname-card';
import { StokOpnameItemSubRow } from './stok-opname-sub-row';
type Props = {
stokOpnames: {
data: StokOpname[];
current_page: number;
last_page: number;
per_page: number;
total: number;
};
highlight?: number;
};
const STATUS_CONFIG: Record<StokOpnameStatus, { label: string; className: string }> = {
draft: { label: 'Draft', className: 'bg-gray-100 text-gray-800 hover:bg-gray-100' },
in_progress: { label: 'Diajukan', className: 'bg-blue-100 text-blue-800 hover:bg-blue-100' },
completed: { label: 'Selesai', className: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100' },
verified: { label: 'Terverifikasi', className: 'bg-green-100 text-green-800 hover:bg-green-100' },
cancelled: { label: 'Dibatalkan', className: 'bg-red-100 text-red-800 hover:bg-red-100' },
};
export default function StokOpnameIndex({ stokOpnames, highlight }: Props) {
const { can } = useCan();
const [deleting, setDeleting] = useState<StokOpname | null>(null);
const [loadedItems, setLoadedItems] = useState<Record<number, StokOpnameItem[]>>({});
const [loadingItems, setLoadingItems] = useState<Record<number, boolean>>({});
const expand = useCardTableExpand(false);
const pagination = {
current_page: stokOpnames.current_page,
last_page: stokOpnames.last_page,
per_page: stokOpnames.per_page,
total: stokOpnames.total,
};
const {
search,
handlePageChange,
handlePerPageChange,
handleSearchChange,
} = useServerTable({
route: () => stokOpnameIndex.url(),
pagination,
});
const fetchItems = useCallback((stokOpname: StokOpname) => {
if (loadedItems[stokOpname.id] || loadingItems[stokOpname.id]) {
return;
}
setLoadingItems((prev) => ({ ...prev, [stokOpname.id]: true }));
fetch(stokOpnameItems.url(stokOpname.id))
.then((res) => res.json())
.then((data) => {
setLoadedItems((prev) => ({
...prev,
[stokOpname.id]: data.items ?? [],
}));
})
.catch(() => {
setLoadedItems((prev) => ({ ...prev, [stokOpname.id]: [] }));
})
.finally(() => {
setLoadingItems((prev) => ({ ...prev, [stokOpname.id]: false }));
});
}, [loadedItems, loadingItems]);
function handleDelete() {
if (!deleting) {
return;
}
router.delete(destroy.url(deleting.id), {
onSuccess: () => setDeleting(null),
});
}
function handleSubmit(stokOpname: StokOpname) {
router.patch(stokOpnameSubmit.url(stokOpname.id));
}
function handleVerify(stokOpname: StokOpname) {
router.patch(stokOpnameVerify.url(stokOpname.id), {
data: { verification_notes: '' },
});
}
function handleReject(stokOpname: StokOpname) {
router.patch(stokOpnameReject.url(stokOpname.id));
}
function handleCancel(stokOpname: StokOpname) {
router.patch(stokOpnameCancel.url(stokOpname.id));
}
return (
<>
<Head title="Stok Opname" />
<div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
<PageHeader
title="Stok Opname"
description={
highlight && (
<p className="mt-1 text-sm text-muted-foreground">
Menampilkan stok opname dari notifikasi.
<button
onClick={() => {
router.get(
stokOpnameIndex.url(),
{},
{
replace: true,
preserveState: true,
},
);
}}
className="ml-1 text-primary underline underline-offset-4 hover:text-primary/80"
>
Tampilkan semua
</button>
</p>
)
}
actions={
can('stok_opnames.create') ? (
<Button asChild>
<Link href={stokOpnameCreate.url()}>
<Plus className="h-4 w-4" />
Tambah
</Link>
</Button>
) : undefined
}
/>
<CardTable
data={stokOpnames.data}
getItemKey={(s) => s.id}
expandedKeys={expand.expandedKeys}
onToggleExpand={(key) => {
const s = stokOpnames.data.find((item) => item.id === key);
const isCurrentlyExpanded = expand.expandedKeys === 'all' || expand.expandedKeys.has(key);
if (s && !isCurrentlyExpanded) {
fetchItems(s);
}
expand.toggleExpand(key);
}}
searchValue={search}
onSearchChange={handleSearchChange}
pagination={pagination}
onPageChange={handlePageChange}
onPerPageChange={handlePerPageChange}
renderCard={({
item,
index,
isExpanded,
onToggleExpand,
}) => (
<StokOpnameCardRow
stokOpname={item}
index={
(pagination.current_page - 1) *
pagination.per_page +
index +
1
}
isExpanded={isExpanded}
onToggleExpand={onToggleExpand}
onEdit={(s) => {
router.visit(stokOpnameEdit.url(s.id));
}}
onDelete={(s) => setDeleting(s)}
onSubmit={handleSubmit}
onVerify={handleVerify}
onReject={handleReject}
onCancel={handleCancel}
/>
)}
renderSubContent={(stokOpname) => (
<StokOpnameItemSubRow
stokOpname={stokOpname}
items={loadedItems[stokOpname.id] ?? []}
isLoading={loadingItems[stokOpname.id] ?? false}
/>
)}
/>
<DeleteConfirmDialog
target={deleting}
onOpenChange={(open) => {
if (!open) {
setDeleting(null);
}
}}
title="Hapus Stok Opname"
description="Apakah Anda yakin ingin menghapus stok opname ini? Tindakan ini tidak dapat dibatalkan."
onConfirm={handleDelete}
/>
</div>
</>
);
}

View File

@ -0,0 +1,188 @@
import { ClipboardCheck, ChevronDown, Pencil, Send, Trash2, XCircle } from 'lucide-react';
import { RowActions } from '@/components/data-display';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useCan } from '@/hooks/use-can';
import { formatDateTime, formatNumber } from '@/lib/format';
import type { StokOpname, StokOpnameStatus } from './columns';
const STATUS_CONFIG: Record<StokOpnameStatus, { label: string; className: string }> = {
draft: { label: 'Draft', className: 'bg-gray-100 text-gray-800 hover:bg-gray-100' },
in_progress: { label: 'Diajukan', className: 'bg-blue-100 text-blue-800 hover:bg-blue-100' },
completed: { label: 'Selesai', className: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100' },
verified: { label: 'Terverifikasi', className: 'bg-green-100 text-green-800 hover:bg-green-100' },
cancelled: { label: 'Dibatalkan', className: 'bg-red-100 text-red-800 hover:bg-red-100' },
};
export type StokOpnameCardRowParams = {
stokOpname: StokOpname;
index: number;
isExpanded: boolean;
onToggleExpand: () => void;
onEdit: (stokOpname: StokOpname) => void;
onDelete: (stokOpname: StokOpname) => void;
onSubmit: (stokOpname: StokOpname) => void;
onVerify: (stokOpname: StokOpname) => void;
onReject: (stokOpname: StokOpname) => void;
onCancel: (stokOpname: StokOpname) => void;
};
export function StokOpnameCardRow({
stokOpname,
index,
isExpanded,
onToggleExpand,
onEdit,
onDelete,
onSubmit,
onVerify,
onReject,
onCancel,
}: StokOpnameCardRowParams) {
const { can } = useCan();
const variantCount = stokOpname.items_count ?? 0;
const totalDifference = stokOpname.total_difference ?? 0;
const productNamesStr = stokOpname.product_names ?? '';
const productNames = productNamesStr ? productNamesStr.split(', ') : [];
const statusConfig = STATUS_CONFIG[stokOpname.status] ?? STATUS_CONFIG.draft;
return (
<Card className="overflow-hidden">
<CardContent className="p-0">
<div className="flex items-start gap-3 p-4">
<Button
variant="ghost"
size="icon"
className="mt-0.5 h-6 w-6 shrink-0"
onClick={onToggleExpand}
>
<ChevronDown
className={`h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
/>
</Button>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs text-muted-foreground">
{index}.
</span>
<h3>
{productNames.length > 0
? productNames.join(', ')
: '-'}
</h3>
<Badge
variant="secondary"
className={statusConfig.className}
>
{statusConfig.label}
</Badge>
</div>
<div className="mt-1 text-xs text-muted-foreground">
{variantCount > 0 && (
<span>({variantCount} varian)</span>
)}
</div>
<div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
<span className="inline-flex items-center rounded-md bg-muted px-2 py-1 font-medium text-foreground">
{formatDateTime(stokOpname.opname_date)}
</span>
<span className="text-muted-foreground">
Oleh:{' '}
<span className="font-medium text-foreground">
{stokOpname.created_by?.user_profile
?.full_name ?? '-'}
</span>
</span>
{stokOpname.notes && (
<span className="max-w-[200px] truncate">
{stokOpname.notes}
</span>
)}
</div>
<div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
<span>
<span className="text-muted-foreground">
Total Selisih:{' '}
</span>
<span className={totalDifference > 0 ? 'text-green-600 font-medium' : totalDifference < 0 ? 'text-red-600 font-medium' : ''}>
{totalDifference > 0 ? '+' : ''}{formatNumber(totalDifference)}
</span>
</span>
{stokOpname.verified_by && (
<span className="text-muted-foreground">
Diverifikasi oleh:{' '}
<span className="font-medium text-foreground">
{stokOpname.verified_by?.user_profile
?.full_name ?? '-'}
</span>
</span>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
{can('stok_opnames.update') && stokOpname.status === 'draft' && (
<RowActions
actions={[
{
label: 'Edit',
icon: <Pencil className="h-4 w-4" />,
show: true,
onClick: () => onEdit(stokOpname),
},
{
label: 'Submit',
icon: <Send className="h-4 w-4" />,
show: can('stok_opnames.submit'),
onClick: () => onSubmit(stokOpname),
},
{
label: 'Hapus',
icon: <Trash2 className="h-4 w-4 text-destructive" />,
show: can('stok_opnames.delete'),
onClick: () => onDelete(stokOpname),
},
]}
/>
)}
{can('stok_opnames.submit') && stokOpname.status === 'in_progress' && (
<RowActions
actions={[
{
label: 'Batal',
icon: <XCircle className="h-4 w-4 text-destructive" />,
show: true,
onClick: () => onCancel(stokOpname),
},
]}
/>
)}
{can('stok_opnames.verify') && stokOpname.status === 'in_progress' && (
<RowActions
actions={[
{
label: 'Verifikasi',
icon: <ClipboardCheck className="h-4 w-4" />,
show: true,
onClick: () => onVerify(stokOpname),
},
{
label: 'Tolak',
icon: <XCircle className="h-4 w-4 text-destructive" />,
show: true,
onClick: () => onReject(stokOpname),
},
]}
/>
)}
</div>
</div>
</CardContent>
</Card>
);
}

View File

@ -0,0 +1,171 @@
import { Fragment } from 'react';
import { ImagePreviewButton } from '@/components/dialogs';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { formatNumber } from '@/lib/format';
import type { StokOpname, StokOpnameItem } from './columns';
const STOCK_QUALITY_CONFIG: Record<string, { label: string; className: string }> = {
good: { label: 'Bagus', className: 'bg-green-100 text-green-800' },
reject: { label: 'Reject', className: 'bg-red-100 text-red-800' },
retail: { label: 'Ecer', className: 'bg-blue-100 text-blue-800' },
};
export function StokOpnameItemSubRow({
stokOpname,
items: loadedItems,
isLoading,
}: {
stokOpname: StokOpname;
items: StokOpnameItem[];
isLoading: boolean;
}) {
const items = loadedItems ?? [];
const groupedByProduct = items.reduce(
(acc, item) => {
const productName = item.product_name ?? 'Tanpa Produk';
if (!acc[productName]) {
acc[productName] = {};
}
const variantName = item.variant_name ?? '-';
if (!acc[productName][variantName]) {
acc[productName][variantName] = [];
}
acc[productName][variantName].push(item);
return acc;
},
{} as Record<string, Record<string, typeof items>>,
);
let counter = 0;
return (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[50px] text-center">
No
</TableHead>
<TableHead className="w-[60px]">Foto</TableHead>
<TableHead>Varian</TableHead>
<TableHead className="text-center">Jenis</TableHead>
<TableHead className="text-right">Stok Sistem</TableHead>
<TableHead className="text-right">Stok Fisik</TableHead>
<TableHead className="text-right">Selisih</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
<TableRow>
<TableCell
colSpan={7}
className="text-center text-muted-foreground"
>
Memuat item...
</TableCell>
</TableRow>
) : items.length === 0 ? (
<TableRow>
<TableCell
colSpan={7}
className="text-center text-muted-foreground"
>
Tidak ada item.
</TableCell>
</TableRow>
) : (
Object.entries(groupedByProduct).map(
([productName, variants]) => {
const variantEntries = Object.entries(variants);
return (
<Fragment key={productName}>
<TableRow>
<TableCell
colSpan={7}
className="font-semibold text-muted-foreground bg-muted/30"
>
{productName}
</TableCell>
</TableRow>
{variantEntries.map(([variantName, variantItems]) => {
const firstItem = variantItems[0];
return (
<Fragment key={`${productName}-${variantName}`}>
<TableRow>
<TableCell
colSpan={7}
className="font-medium text-muted-foreground"
>
<div className="flex items-center gap-2">
{firstItem?.photo_url ? (
<ImagePreviewButton
srcs={[
firstItem.photo_conversion_url ?? firstItem.photo_url,
]}
modalSrc={firstItem.photo_url}
title={variantName}
/>
) : (
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-muted text-[10px] text-muted-foreground">
N/A
</div>
)}
{variantName}
</div>
</TableCell>
</TableRow>
{variantItems.map((item) => {
counter++;
const qualityConfig = STOCK_QUALITY_CONFIG[item.stock_quality] ?? STOCK_QUALITY_CONFIG.good;
return (
<TableRow key={item.id}>
<TableCell className="text-center">
{counter}
</TableCell>
<TableCell />
<TableCell />
<TableCell className="text-center">
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${qualityConfig.className}`}>
{qualityConfig.label}
</span>
</TableCell>
<TableCell className="text-right">
{formatNumber(item.system_stock)}
</TableCell>
<TableCell className="text-right font-medium">
{formatNumber(item.physical_stock)}
</TableCell>
<TableCell className={`text-right font-medium ${item.difference > 0 ? 'text-green-600' : item.difference < 0 ? 'text-red-600' : ''}`}>
{item.difference > 0 ? '+' : ''}{formatNumber(item.difference)}
</TableCell>
</TableRow>
);
})}
</Fragment>
);
})}
</Fragment>
);
},
)
)}
</TableBody>
</Table>
</div>
);
}

View File

@ -13,6 +13,7 @@
use App\Http\Controllers\Admin\Manage\CuttingController;
use App\Http\Controllers\Admin\Manage\PurchaseController;
use App\Http\Controllers\Admin\Manage\RestockController;
use App\Http\Controllers\Admin\Manage\StokOpnameController;
use App\Http\Controllers\Admin\Manage\TransactionController;
use App\Http\Controllers\Admin\Master\CategoryController;
use App\Http\Controllers\Admin\Master\CustomerController;
@ -23,6 +24,7 @@
use App\Http\Controllers\Admin\Master\RawMaterial\RawMaterialVariantController;
use App\Http\Controllers\Admin\Master\SupplierController;
use App\Http\Controllers\Admin\RoleController;
use App\Http\Controllers\Admin\System\FormHistoryController;
use App\Http\Controllers\AnalysisController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\HomepageController;
@ -80,6 +82,13 @@
Route::resource('restocks', RestockController::class)->except(['show'])->middleware('permission:restocks.view|restocks.create|restocks.update|restocks.delete');
Route::get('restocks/{restock}/items', [RestockController::class, 'items'])->name('restocks.items')->middleware('permission:restocks.view');
Route::resource('stok-opnames', StokOpnameController::class)->except(['show'])->middleware('permission:stok_opnames.view|stok_opnames.create|stok_opnames.update|stok_opnames.delete');
Route::get('stok-opnames/{stokOpname}/items', [StokOpnameController::class, 'items'])->name('stok-opnames.items')->middleware('permission:stok_opnames.view');
Route::patch('stok-opnames/{stokOpname}/submit', [StokOpnameController::class, 'submit'])->name('stok-opnames.submit')->middleware('permission:stok_opnames.submit');
Route::patch('stok-opnames/{stokOpname}/verify', [StokOpnameController::class, 'verify'])->name('stok-opnames.verify')->middleware('permission:stok_opnames.verify');
Route::patch('stok-opnames/{stokOpname}/reject', [StokOpnameController::class, 'reject'])->name('stok-opnames.reject')->middleware('permission:stok_opnames.verify');
Route::patch('stok-opnames/{stokOpname}/cancel', [StokOpnameController::class, 'cancel'])->name('stok-opnames.cancel')->middleware('permission:stok_opnames.update');
});
Route::prefix('finance')->name('admin.finance.')->group(function () {
@ -139,6 +148,7 @@
Route::put('roles/{role}', [RoleController::class, 'update'])->name('roles.update')->middleware('permission:roles.update');
Route::delete('roles/{role}', [RoleController::class, 'destroy'])->name('roles.destroy')->middleware('permission:roles.delete');
});
});
});