feat: phase 6 — dashboard widgets, sales & stock reports, user management, activity log

This commit is contained in:
sean
2026-08-25 19:25:40 +07:00
parent 28937a786e
commit feba1ec839
18 changed files with 1011 additions and 5 deletions
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Services;
use App\Services\InsForge\InsForgeTableService;
class ActivityLogService extends InsForgeTableService
{
protected function table(): string
{
return 'activity_logs';
}
protected function select(): string
{
return '*,users(name)';
}
protected function searchableColumns(): array
{
return ['description', 'action', 'entity_type'];
}
protected function sortableColumns(): array
{
return ['created_at'];
}
}
+38 -3
View File
@@ -72,10 +72,45 @@ class InsForgeClient
public function countRecords(string $table, array $filters = []): int
{
$query = $this->buildFilters($filters);
$response = $this->request('HEAD', "/api/database/records/{$table}", query: array_merge($query, ['limit' => 1]));
$response = $this->send(
'GET',
"/api/database/records/{$table}",
query: array_merge($this->buildFilters($filters), ['limit' => 0]),
headers: ['Prefer' => 'count=exact'],
);
return (int) ($response->header('Content-Range') ? explode('/', explode('-', $response->header('Content-Range'))[1])[0] : 0);
return $this->parseTotalFromRange($response->header('Content-Range'));
}
/**
* Jalankan SQL read-only/administratif via management API (admin key).
*
* @return list<array<string, mixed>>
*/
public function rawSql(string $query): array
{
$response = Http::baseUrl(rtrim($this->baseUrl, '/'))
->timeout($this->timeout)
->withToken($this->apiKey)
->post('/api/database/advance/rawsql', ['query' => $query]);
throw_unless($response->successful(), fn () => InsForgeException::fromResponse(
$response->status(),
$response->json() ?? $response->body(),
));
return $response->json('rows') ?? [];
}
private function parseTotalFromRange(?string $contentRange): int
{
if (! filled($contentRange)) {
return 0;
}
$total = explode('/', $contentRange)[1] ?? '';
return ctype_digit($total) ? (int) $total : 0;
}
public function rpc(string $function, array $args = [], bool $asUser = true): mixed
+66
View File
@@ -272,6 +272,72 @@ class OrderService extends InsForgeTableService
return $actor !== null && ($actor->isAdmin() || $actor->id === ($record['created_by'] ?? null));
}
/** @return array<string, int> status => jumlah order aktif */
public function countByStatus(): array
{
[$client] = $this->scoped();
$counts = [];
foreach (array_keys(self::TRANSITIONS) as $status) {
$counts[$status] = $client->countRecords($this->table(), [
'order_status' => $status,
'deleted_at' => 'null',
]);
}
return $counts;
}
public function recent(int $limit = 8): array
{
[$client] = $this->scoped();
return $client->listRecords($this->table(), [
'select' => 'id,order_number,order_date,order_status,customers(name)',
'deleted_at' => 'eq.null',
'order' => 'created_at.desc',
'limit' => $limit,
]);
}
/**
* Agregasi penjualan per produk dari order completed dalam periode (UTC).
*
* @return list<array{code: string, name: string, qty: int, revenue: int}>
*/
public function salesPerProduct(string $fromDate, string $toDate): array
{
[$client, $asUser] = $this->scoped();
$orders = $client->listRecords($this->table(), [
'select' => 'order_items(quantity,subtotal,products(code,name))',
'and' => sprintf(
'(order_status.eq.completed,completed_at.gte.%sT00:00:00+00:00,completed_at.lte.%sT23:59:59+00:00)',
$fromDate,
$toDate,
),
'limit' => 1000,
], asUser: $asUser);
$aggregated = [];
foreach ($orders as $order) {
foreach ($order['order_items'] ?? [] as $item) {
$code = data_get($item, 'products.code', '?');
$key = $code;
$aggregated[$key] ??= ['code' => $code, 'name' => data_get($item, 'products.name', ''), 'qty' => 0, 'revenue' => 0];
$aggregated[$key]['qty'] += (int) ($item['quantity'] ?? 0);
$aggregated[$key]['revenue'] += (int) ($item['subtotal'] ?? 0);
}
}
usort($aggregated, fn (array $a, array $b): int => $b['revenue'] <=> $a['revenue']);
return array_values($aggregated);
}
public function deliveryNoteData(string $orderId): array
{
[$client, $asUser] = $this->scoped();
+1 -1
View File
@@ -23,7 +23,7 @@ class StockService extends InsForgeTableService
protected function select(): string
{
return '*,products(code,name,stock_minimum,is_active)';
return '*,products(code,name,stock_minimum,is_active,cost_price)';
}
protected function searchableColumns(): array
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\InsForge\InsForgeClient;
use App\Services\InsForge\InsForgeException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class UserAdminService
{
public function __construct(
private readonly InsForgeClient $client,
private readonly ActivityLogger $activity,
) {}
/**
* Buat user InsForge (auth) + mirror public.users, langsung terverifikasi.
*
* @return array{id: string, email: string}
*/
public function createUser(array $attributes, ?User $actor = null): array
{
$email = strtolower(trim((string) ($attributes['email'] ?? '')));
$password = (string) ($attributes['password'] ?? '');
$role = in_array($attributes['role'] ?? '', ['admin', 'operator'], true) ? $attributes['role'] : 'operator';
if ($email === '' || strlen($password) < 8) {
throw ValidationException::withMessages(['password' => 'Password minimal 8 karakter.']);
}
try {
$this->client->createUserAsAdmin([
'email' => $email,
'password' => $password,
'name' => $attributes['name'] ?? $email,
]);
} catch (InsForgeException $exception) {
if ($exception->getCode() === 409 || str_contains($exception->getMessage(), 'exist')) {
throw ValidationException::withMessages(['email' => 'Email sudah terdaftar.']);
}
throw $exception;
}
[$authId] = $this->client->rawSql(sprintf(
"SELECT id::text FROM auth.users WHERE email = '%s' LIMIT 1",
str_replace("'", "''", $email),
)) ?: [null];
$authId = $authId['id'] ?? null;
if ($authId === null) {
throw new \RuntimeException('Gagal menemukan user auth yang baru dibuat.');
}
$this->client->rawSql(sprintf(
"UPDATE auth.users SET email_verified = true WHERE id = '%s'",
$authId,
));
$this->client->insertRecord('users', [[
'id' => $authId,
'name' => $attributes['name'] ?? $email,
'email' => $email,
'password' => Hash::make($password),
'role' => $role,
'is_active' => true,
]], asUser: false);
$this->activity->log('user_created', 'users', $authId, "User {$email} dibuat dengan role {$role}.", $actor);
return ['id' => $authId, 'email' => $email];
}
public function setActive(string $userId, bool $active, ?User $actor = null): void
{
$this->client->updateRecords('users', ['id' => $userId], [
'is_active' => $active,
], asUser: false);
$this->activity->log(
$active ? 'user_activated' : 'user_deactivated',
'users',
$userId,
sprintf('User %s.', $active ? 'diaktifkan' : 'dinonaktifkan'),
$actor,
);
}
public function setRole(string $userId, string $role, ?User $actor = null): void
{
in_array($role, ['admin', 'operator'], true) || throw ValidationException::withMessages(['role' => 'Role tidak valid.']);
$this->client->updateRecords('users', ['id' => $userId], [
'role' => $role,
], asUser: false);
$this->activity->log('user_role_changed', 'users', $userId, "Role diubah menjadi {$role}.", $actor);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Services;
use App\Services\InsForge\InsForgeTableService;
class UserService extends InsForgeTableService
{
protected function table(): string
{
return 'users';
}
protected function searchableColumns(): array
{
return ['name', 'email'];
}
protected function sortableColumns(): array
{
return ['name', 'email', 'created_at'];
}
}