feat: phase 3 — stock balances, restock/adjust mutations with activity logging, movements page

This commit is contained in:
sean
2026-08-25 18:46:03 +07:00
parent 4298544381
commit 002fdce854
7 changed files with 601 additions and 2 deletions
@@ -0,0 +1,104 @@
<?php
namespace App\Filament\Pages\Inventory;
use App\Services\StockMovementService;
use BackedEnum;
use Filament\Forms\Components\Select;
use Filament\Pages\Page;
use Filament\Schemas\Components\EmbeddedTable;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
use UnitEnum;
class StockMovements extends Page implements HasTable
{
use InteractsWithTable;
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-arrows-right-left';
protected static string|UnitEnum|null $navigationGroup = 'Inventori';
protected static ?int $navigationSort = 2;
protected static ?string $navigationLabel = 'Mutasi Stok';
protected static ?string $slug = 'inventory/stock-movements';
protected string $view = 'filament.pages.blank';
public function getTitle(): string|Htmlable
{
return 'Mutasi Stok';
}
public function table(Table $table): Table
{
/** @var StockMovementService $service */
$service = app(StockMovementService::class);
return $table
->records(function (?string $search, ?string $sortColumn, ?string $sortDirection, int|string $page, int|string $recordsPerPage, ?array $filters) use ($service) {
$type = Arr::get($filters, 'type.value') ?? Arr::get($filters, 'type');
return $service->paginate(
search: $search,
sortColumn: $sortColumn,
sortDirection: $sortDirection,
page: (int) $page,
perPage: (int) $recordsPerPage,
filters: array_filter(['type' => is_array($type) ? ($type['value'] ?? null) : $type]),
);
})
->columns([
TextColumn::make('created_at')->label('Waktu')->dateTime('d M Y H:i', 'Asia/Jakarta')->sortable(),
TextColumn::make('products.code')->label('Kode')->badge(),
TextColumn::make('products.name')->label('Produk'),
TextColumn::make('type')
->label('Tipe')
->badge()
->color(fn (string $state): string => match ($state) {
'restock' => 'success',
'adjustment' => 'warning',
'order_out' => 'info',
default => 'gray',
})
->formatStateUsing(fn (string $state): string => match ($state) {
'restock' => 'Restok',
'adjustment' => 'Koreksi',
'order_out' => 'Order Keluar',
default => $state,
}),
TextColumn::make('quantity')
->label('Qty')
->numeric()
->color(fn (string $state): string => str_starts_with((string) $state, '-') ? 'danger' : 'success'),
TextColumn::make('notes')->label('Catatan')->limit(40),
])
->filters([
Filter::make('type')
->schema([
Select::make('value')->label('Tipe Mutasi')->options([
'restock' => 'Restok',
'adjustment' => 'Koreksi',
'order_out' => 'Order Keluar',
]),
]),
])
->paginated([10, 25, 50]);
}
public function content(Schema $schema): Schema
{
return $schema
->components([
EmbeddedTable::make(),
]);
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
namespace App\Filament\Pages\Inventory;
use App\Services\StockService;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Pages\Page;
use Filament\Schemas\Components\EmbeddedTable;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Facades\Gate;
use UnitEnum;
class Stocks extends Page implements HasTable
{
use InteractsWithTable;
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-archive-box';
protected static string|UnitEnum|null $navigationGroup = 'Inventori';
protected static ?int $navigationSort = 0;
protected static ?string $navigationLabel = 'Stok';
protected static ?string $slug = 'inventory/stocks';
protected string $view = 'filament.pages.blank';
public function getTitle(): string|Htmlable
{
return 'Stok';
}
public function table(Table $table): Table
{
/** @var StockService $service */
$service = app(StockService::class);
return $table
->records(fn (?string $sortColumn, ?string $sortDirection, int|string $page, int|string $recordsPerPage) => $service->paginate(
sortColumn: $sortColumn,
sortDirection: $sortDirection,
page: (int) $page,
perPage: (int) $recordsPerPage,
))
->columns([
TextColumn::make('products.code')->label('Kode')->badge()->sortable(false),
TextColumn::make('products.name')->label('Produk')->weight(FontWeight::SemiBold),
TextColumn::make('quantity')->label('Saldo')->numeric()->sortable(),
TextColumn::make('products.stock_minimum')->label('Min.'),
TextColumn::make('status')
->label('Status')
->state(fn (array $record): string => (int) $record['quantity'] <= (int) ($record['products']['stock_minimum'] ?? 0) ? 'kritis' : 'aman')
->badge()
->color(fn (string $state): string => match ($state) {
'kritis' => 'danger',
default => 'success',
}),
TextColumn::make('updated_at')->label('Diperbarui')->dateTime('d M Y H:i', 'Asia/Jakarta')->sortable(),
])
->recordActions([
Action::make('restok')
->label('Restok')
->icon('heroicon-o-plus-circle')
->visible(fn (): bool => Gate::check('manage-stock'))
->schema(fn (Schema $schema): Schema => $schema->components([
TextInput::make('quantity')->label('Jumlah Masuk')->numeric()->minValue(1)->required(),
Textarea::make('notes')->label('Catatan'),
]))
->action(function (array $data, array $record): void {
app(StockService::class)->restock(
$record['product_id'],
(int) $data['quantity'],
$data['notes'] ?? null,
auth()->user(),
);
}),
Action::make('koreksi')
->label('Koreksi')
->icon('heroicon-o-adjustments-horizontal')
->color('warning')
->visible(fn (): bool => Gate::check('manage-stock'))
->schema(fn (Schema $schema): Schema => $schema->components([
TextInput::make('new_quantity')->label('Saldo Baru')->numeric()->minValue(0)->required()
->default(fn (array $record): int => (int) $record['quantity']),
Textarea::make('notes')->label('Alasan Koreksi'),
]))
->action(function (array $data, array $record): void {
app(StockService::class)->adjust(
$record['product_id'],
(int) $data['new_quantity'],
$data['notes'] ?? null,
auth()->user(),
);
}),
])
->paginated([10, 25, 50]);
}
public function content(Schema $schema): Schema
{
return $schema
->components([
EmbeddedTable::make(),
]);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\InsForge\InsForgeClient;
class ActivityLogger
{
public function __construct(private readonly InsForgeClient $client) {}
public function log(string $action, string $entityType, ?string $entityId, string $description, ?User $actor = null): void
{
$entry = array_filter([
'user_id' => $actor?->id,
'action' => $action,
'entity_type' => $entityType,
'entity_id' => $entityId,
'description' => $description,
], fn ($value) => $value !== null && $value !== '');
$this->client->insertRecord('activity_logs', [$entry], asUser: false);
}
}
@@ -25,6 +25,11 @@ abstract class InsForgeTableService
return 'desc';
}
protected function select(): string
{
return '*';
}
/** @param array<string, mixed> $filters column => value (eq) */
public function paginate(
?string $search = null,
@@ -35,7 +40,7 @@ abstract class InsForgeTableService
array $filters = [],
): LengthAwarePaginator {
$query = [
'select' => '*',
'select' => $this->select(),
'limit' => max(1, min($perPage, 100)),
'offset' => ($page - 1) * $perPage,
'order' => sprintf(
@@ -122,7 +127,7 @@ abstract class InsForgeTableService
*
* @return array{0: InsForgeClient, 1: bool}
*/
private function scoped(): array
protected function scoped(): array
{
$token = session(InsForgeAuthService::SESSION_ACCESS_TOKEN);
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Services;
use App\Services\InsForge\InsForgeTableService;
use Illuminate\Pagination\LengthAwarePaginator;
class StockMovementService extends InsForgeTableService
{
public const TYPES = ['restock', 'adjustment', 'order_out'];
protected function table(): string
{
return 'stock_movements';
}
protected function select(): string
{
return '*,products(code,name)';
}
protected function searchableColumns(): array
{
return ['notes', 'type'];
}
protected function sortableColumns(): array
{
return ['created_at', 'quantity', 'type'];
}
/** @param array<string, mixed> $filters */
public function paginate(
?string $search = null,
?string $sortColumn = null,
?string $sortDirection = null,
int $page = 1,
int $perPage = 25,
array $filters = [],
): LengthAwarePaginator {
$extra = array_intersect_key($filters, array_flip(['type', 'product_id']));
return parent::paginate($search, $sortColumn, $sortDirection, $page, $perPage, $extra);
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\InsForge\InsForgeClient;
use App\Services\InsForge\InsForgeTableService;
class StockService extends InsForgeTableService
{
public function __construct(
InsForgeClient $client,
private readonly ProductService $products,
private readonly ActivityLogger $activity,
) {
parent::__construct($client);
}
protected function table(): string
{
return 'stocks';
}
protected function select(): string
{
return '*,products(code,name,stock_minimum,is_active)';
}
protected function searchableColumns(): array
{
return [];
}
protected function sortableColumns(): array
{
return ['quantity', 'updated_at'];
}
protected function defaultSortColumn(): string
{
return 'updated_at';
}
/**
* Tambah stok (restok).
*/
public function restock(string $productId, int $quantity, ?string $notes = null, ?User $actor = null): void
{
$quantity > 0 || throw new \InvalidArgumentException('Jumlah restok harus lebih dari nol.');
$newBalance = $this->applyMutation($productId, fn (int $current): int => $current + $quantity, $quantity, 'restock', $notes, $actor);
$this->activity->log(
'stock_restocked',
'stocks',
$productId,
sprintf('Restok %d untuk produk %s (saldo menjadi %d).', $quantity, $this->productLabel($productId), $newBalance),
$actor,
);
}
/**
* Koreksi saldo ke nilai absolut baru.
*/
public function adjust(string $productId, int $newQuantity, ?string $notes = null, ?User $actor = null): void
{
$delta = $newQuantity - $this->currentQuantity($productId);
if ($delta === 0) {
return;
}
$this->applyMutation($productId, fn (): int => $newQuantity, $delta, 'adjustment', $notes, $actor);
$this->activity->log(
'stock_adjusted',
'stocks',
$productId,
sprintf('Koreksi stok produk %s menjadi %d (selisih %+d).', $this->productLabel($productId), $newQuantity, $delta),
$actor,
);
}
private function applyMutation(string $productId, callable $resolveNewBalance, int $movementQuantity, string $type, ?string $notes, ?User $actor): int
{
[$client, $asUser] = $this->scoped();
$stock = $client->listRecords('stocks', ['product_id' => 'eq.'.$productId, 'limit' => 1], asUser: $asUser)[0] ?? null;
$current = (int) ($stock['quantity'] ?? 0);
$newBalance = $resolveNewBalance($current);
if ($stock === null) {
$client->insertRecord('stocks', [[
'product_id' => $productId,
'quantity' => max($newBalance, 0),
]], asUser: false);
} else {
$client->updateRecords('stocks', ['id' => $stock['id']], [
'quantity' => $newBalance,
], asUser: false);
}
$mutation = array_filter([
'product_id' => $productId,
'type' => $type,
'quantity' => $movementQuantity,
'notes' => $notes,
'created_by' => $actor?->id,
], fn ($value) => $value !== null && $value !== '');
$client->insertRecord('stock_movements', [$mutation], asUser: false);
return $newBalance;
}
private function currentQuantity(string $productId): int
{
[$client, $asUser] = $this->scoped();
$stock = $client->listRecords('stocks', ['product_id' => 'eq.'.$productId, 'limit' => 1], asUser: $asUser)[0] ?? null;
return (int) ($stock['quantity'] ?? 0);
}
private function productLabel(string $productId): string
{
$product = $this->products->find($productId);
return trim(($product['code'] ?? '').' — '.($product['name'] ?? '?'), ' —') ?: '?';
}
}