Compare commits

...

12 Commits

Author SHA1 Message Date
Yoga Pangestu
bc02af2a66 feat: enhance attendance management with employee-specific data and location tracking 2026-08-06 23:43:49 +07:00
Yoga Pangestu
9bbb00c69f feat: refactor column definitions to conditionally include action buttons based on user permissions 2026-08-06 22:48:00 +07:00
Yoga Pangestu
5ec0e9ff3b feat: add view payments permission for employee advances and update related checks 2026-08-06 22:41:40 +07:00
Yoga Pangestu
d2d10ea63a feat: add transfer stock and view stock mutations permissions for products 2026-08-06 22:19:58 +07:00
Yoga Pangestu
a10a1700b0 feat: add visibility check for leave requests based on user roles 2026-08-06 17:39:56 +07:00
Yoga Pangestu
c11962cda1 feat: rename attendanceDate method to formattedAttendanceDate for clarity 2026-08-06 17:31:08 +07:00
Yoga Pangestu
66d6c843c3 feat: add base64 media registration method with support for multiple image formats and S3 storage 2026-08-06 17:29:56 +07:00
Yoga Pangestu
78965e9728 feat: update RolePermissionSeeder to include additional permissions for analysis, attendance, employee advances, and payroll 2026-08-06 17:26:34 +07:00
Yoga Pangestu
8aa4e83cd8 feat: enhance role selection in Employee edit page; add conditional rendering based on view permissions and update role filtering in EmployeeService 2026-08-06 17:18:53 +07:00
Yoga Pangestu
ab217a8d79 feat: enhance Attendance model date formatting; add restricted roles check in EmployeeService; update RolePermissionSeeder with new payroll permissions 2026-08-06 17:16:50 +07:00
Yoga Pangestu
8df17601ea feat: enhance EmployeeAdvanceService and ExpenseService with validation and transaction handling; update transaction columns for improved display 2026-08-06 17:12:22 +07:00
Yoga Pangestu
42e04673c6 feat: update CashTransactionType enum and improve transaction labels; refactor EmployeeAdvanceService and PayrollPeriodService for consistency 2026-08-06 15:26:46 +07:00
41 changed files with 1119 additions and 791 deletions

View File

@ -10,16 +10,16 @@ enum CashTransactionType: string
case DEPOSIT = 'deposit'; case DEPOSIT = 'deposit';
case EXPENSE = 'expense'; case EXPENSE = 'expense';
case TRANSFER = 'transfer';
case WITHDRAWAL = 'withdrawal'; case WITHDRAWAL = 'withdrawal';
case EMPLOYEE_ADVANCE = 'employee_advance';
public function label(): string public function label(): string
{ {
return match ($this) { return match ($this) {
self::DEPOSIT => 'Setoran', self::DEPOSIT => 'Deposit',
self::EXPENSE => 'Pengeluaran', self::EXPENSE => 'Pengeluaran',
self::TRANSFER => 'Transfer', self::WITHDRAWAL => 'Withdrawal',
self::WITHDRAWAL => 'Penarikan', self::EMPLOYEE_ADVANCE => 'Kasbon',
}; };
} }
} }

View File

@ -71,9 +71,8 @@ enum Permission: string
case PRODUCTS_UPDATE = 'products.update'; case PRODUCTS_UPDATE = 'products.update';
case PRODUCTS_DELETE = 'products.delete'; case PRODUCTS_DELETE = 'products.delete';
case PRODUCTS_TOGGLE_STATUS = 'products.toggle_status'; case PRODUCTS_TOGGLE_STATUS = 'products.toggle_status';
case PRODUCTS_TRANSFER_STOCK = 'products.transfer_stock';
// Stocks case PRODUCTS_VIEW_STOCK_MUTATIONS = 'products.view_stock_mutations';
case STOCKS_VIEW = 'stocks.view';
// Orders // Orders
case ORDERS_VIEW = 'orders.view'; case ORDERS_VIEW = 'orders.view';
@ -113,6 +112,7 @@ enum Permission: string
case EMPLOYEE_ADVANCES_UPDATE = 'employee_advances.update'; case EMPLOYEE_ADVANCES_UPDATE = 'employee_advances.update';
case EMPLOYEE_ADVANCES_DELETE = 'employee_advances.delete'; case EMPLOYEE_ADVANCES_DELETE = 'employee_advances.delete';
case EMPLOYEE_ADVANCES_PAY = 'employee_advances.pay'; case EMPLOYEE_ADVANCES_PAY = 'employee_advances.pay';
case EMPLOYEE_ADVANCES_VIEW_PAYMENTS = 'employee_advances.view_payments';
case EMPLOYEE_ADVANCES_VERIFY = 'employee_advances.verify'; case EMPLOYEE_ADVANCES_VERIFY = 'employee_advances.verify';
// Payroll // Payroll

View File

@ -22,12 +22,14 @@ public function index(Request $request): Response
{ {
$year = $request->integer('year', now()->year); $year = $request->integer('year', now()->year);
$month = $request->integer('month', now()->month); $month = $request->integer('month', now()->month);
$hrSettings = app(HRSettings::class); $hrSettings = app(HRSettings::class);
$user = auth()->user();
$isAdmin = $user->hasAnyRole(['developer', 'owner', 'direktur']);
if ($isAdmin) {
return Inertia::render('admin/hr/attendance/index', [ return Inertia::render('admin/hr/attendance/index', [
'attendances' => $this->service->getByMonth($year, $month), 'attendances' => $this->service->getByMonth($year, $month),
'todayAttendance' => $this->service->getToday(), 'todayAttendance' => null,
'currentYear' => $year, 'currentYear' => $year,
'currentMonth' => $month, 'currentMonth' => $month,
'monthStats' => $this->service->getMonthStats($year, $month), 'monthStats' => $this->service->getMonthStats($year, $month),
@ -35,6 +37,23 @@ public function index(Request $request): Response
'scheduled_check_in_time' => $hrSettings->scheduled_check_in_time, 'scheduled_check_in_time' => $hrSettings->scheduled_check_in_time,
'scheduled_check_out_time' => $hrSettings->scheduled_check_out_time, 'scheduled_check_out_time' => $hrSettings->scheduled_check_out_time,
], ],
'isAdmin' => true,
]);
}
$employeeId = $user->employee?->id;
return Inertia::render('admin/hr/attendance/index', [
'attendances' => $this->service->getByMonth($year, $month, $employeeId),
'todayAttendance' => $this->service->getToday(),
'currentYear' => $year,
'currentMonth' => $month,
'monthStats' => $this->service->getMonthStats($year, $month, $employeeId),
'hrSettings' => [
'scheduled_check_in_time' => $hrSettings->scheduled_check_in_time,
'scheduled_check_out_time' => $hrSettings->scheduled_check_out_time,
],
'isAdmin' => false,
]); ]);
} }

View File

@ -36,7 +36,9 @@ public function create(): Response
return Inertia::render('admin/hr/employee/create', [ return Inertia::render('admin/hr/employee/create', [
'roles' => $this->service->canViewAll() 'roles' => $this->service->canViewAll()
? Role::where('name', '!=', 'Developer')->get(['id', 'name']) ? Role::where('name', '!=', 'Developer')
->when($this->service->shouldHideAdminBahanBaku(), fn ($q) => $q->where('name', '!=', 'admin-bahan-baku'))
->get(['id', 'name'])
: Role::where('name', '=', $user->roles->first()?->name)->get(['id', 'name']), : Role::where('name', '=', $user->roles->first()?->name)->get(['id', 'name']),
'canViewAll' => $this->service->canViewAll(), 'canViewAll' => $this->service->canViewAll(),
]); ]);
@ -57,7 +59,10 @@ public function edit(User $user): Response
return Inertia::render('admin/hr/employee/edit', [ return Inertia::render('admin/hr/employee/edit', [
'employee' => $user, 'employee' => $user,
'roles' => Role::where('name', '!=', 'Developer')->get(['id', 'name']), 'roles' => Role::where('name', '!=', 'Developer')
->when($this->service->shouldHideAdminBahanBaku(), fn ($q) => $q->where('name', '!=', 'admin-bahan-baku'))
->get(['id', 'name']),
'canViewAll' => $this->service->canViewAll(),
]); ]);
} }

View File

@ -30,10 +30,10 @@ protected function casts(): array
]; ];
} }
protected function attendanceDate(): Attribute protected function formattedAttendanceDate(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: fn ($value) => $value?->translatedFormat('l, d F Y'), get: fn ($value) => $value ? \Carbon\Carbon::parse($value)->translatedFormat('l, d F Y') : null,
); );
} }

View File

@ -2,6 +2,7 @@
namespace App\Services\Admin\Finance; namespace App\Services\Admin\Finance;
use App\Enums\CashTransactionType;
use App\Enums\EmployeeAdvanceStatus; use App\Enums\EmployeeAdvanceStatus;
use App\Models\EmployeeAdvance; use App\Models\EmployeeAdvance;
use App\Models\EmployeeAdvancePayment; use App\Models\EmployeeAdvancePayment;
@ -47,7 +48,9 @@ public function create(array $data): EmployeeAdvance
$employee = auth()->user()->employee; $employee = auth()->user()->employee;
if (! $employee) { if (! $employee) {
throw new \Exception('Anda tidak terdaftar sebagai karyawan.'); throw ValidationException::withMessages([
'amount' => 'Anda tidak terdaftar sebagai karyawan.',
]);
} }
$employeeAdvance = EmployeeAdvance::create([ $employeeAdvance = EmployeeAdvance::create([
@ -73,6 +76,44 @@ public function create(array $data): EmployeeAdvance
public function update(EmployeeAdvance $employeeAdvance, array $data): EmployeeAdvance public function update(EmployeeAdvance $employeeAdvance, array $data): EmployeeAdvance
{ {
if ($employeeAdvance->status === EmployeeAdvanceStatus::PAID) {
throw ValidationException::withMessages([
'amount' => 'Kasbon yang sudah dibayar tidak dapat diedit.',
]);
}
if ($employeeAdvance->status === EmployeeAdvanceStatus::APPROVED && $employeeAdvance->cash_transaction_id) {
$oldAmount = $employeeAdvance->amount;
$newAmount = $data['amount'];
if ($oldAmount !== $newAmount) {
$employeeAdvance = DB::transaction(function () use ($employeeAdvance, $data, $oldAmount, $newAmount) {
$this->creditCash(
$oldAmount,
'Pembatalan kasbon: '.$employeeAdvance->description,
CashTransactionType::DEPOSIT,
);
$cashTransaction = $this->debitCash(
$newAmount,
'Kasbon: '.$data['description'],
CashTransactionType::EMPLOYEE_ADVANCE,
);
$employeeAdvance->update([
'amount' => $newAmount,
'description' => $data['description'],
'due_date' => $data['due_date'],
'cash_transaction_id' => $cashTransaction->id,
]);
return $employeeAdvance;
});
return $employeeAdvance;
}
}
$employeeAdvance->update([ $employeeAdvance->update([
'amount' => $data['amount'], 'amount' => $data['amount'],
'description' => $data['description'], 'description' => $data['description'],
@ -84,21 +125,49 @@ public function update(EmployeeAdvance $employeeAdvance, array $data): EmployeeA
public function delete(EmployeeAdvance $employeeAdvance): bool public function delete(EmployeeAdvance $employeeAdvance): bool
{ {
return DB::transaction(function () use ($employeeAdvance) {
if ($employeeAdvance->status === EmployeeAdvanceStatus::APPROVED && $employeeAdvance->cash_transaction_id) { if ($employeeAdvance->status === EmployeeAdvanceStatus::APPROVED && $employeeAdvance->cash_transaction_id) {
$cashAccount = $this->getCashAccount(); $this->creditCash(
$newBalance = $cashAccount->balance + $employeeAdvance->amount; $employeeAdvance->amount,
$cashAccount->update(['balance' => $newBalance]); 'Pembatalan kasbon: '.$employeeAdvance->description,
CashTransactionType::DEPOSIT,
);
$employeeAdvance->cashTransaction()->delete(); $employeeAdvance->cashTransaction()->delete();
} }
if ($employeeAdvance->status === EmployeeAdvanceStatus::PAID) {
$this->creditCash(
$employeeAdvance->amount,
'Pembatalan kasbon: '.$employeeAdvance->description,
CashTransactionType::DEPOSIT,
);
$employeeAdvance->load('payments');
foreach ($employeeAdvance->payments as $payment) {
if ($payment->cash_transaction_id) {
$this->debitCash(
$payment->amount,
'Pembatalan pembayaran kasbon: '.$employeeAdvance->description,
CashTransactionType::EXPENSE,
);
$payment->cashTransaction()->delete();
}
}
$employeeAdvance->payments()->delete();
}
return $employeeAdvance->delete(); return $employeeAdvance->delete();
});
} }
public function approve(EmployeeAdvance $employeeAdvance): EmployeeAdvance public function approve(EmployeeAdvance $employeeAdvance): EmployeeAdvance
{ {
$employeeAdvance = DB::transaction(function () use ($employeeAdvance) {
$cashTransaction = $this->debitCash( $cashTransaction = $this->debitCash(
amount: $employeeAdvance->amount, $employeeAdvance->amount,
description: 'Kasbon: '.$employeeAdvance->description, 'Kasbon: '.$employeeAdvance->description,
CashTransactionType::EMPLOYEE_ADVANCE
); );
$employeeAdvance->update([ $employeeAdvance->update([
@ -108,6 +177,9 @@ public function approve(EmployeeAdvance $employeeAdvance): EmployeeAdvance
'verified_at' => now(), 'verified_at' => now(),
]); ]);
return $employeeAdvance;
});
NotificationService::notify( NotificationService::notify(
roles: ['Owner', 'Developer', 'Direktur', 'Admin Toko'], roles: ['Owner', 'Developer', 'Direktur', 'Admin Toko'],
title: 'Kasbon Disetujui', title: 'Kasbon Disetujui',
@ -131,8 +203,9 @@ public function pay(EmployeeAdvance $employeeAdvance, int $amount): EmployeeAdva
$employeeAdvance = DB::transaction(function () use ($employeeAdvance, $amount) { $employeeAdvance = DB::transaction(function () use ($employeeAdvance, $amount) {
$cashTransaction = $this->creditCash( $cashTransaction = $this->creditCash(
amount: $amount, $amount,
description: 'Pembayaran kasbon: '.$employeeAdvance->description, 'Pembayaran kasbon: '.$employeeAdvance->description,
CashTransactionType::DEPOSIT
); );
EmployeeAdvancePayment::create([ EmployeeAdvancePayment::create([

View File

@ -2,6 +2,7 @@
namespace App\Services\Admin\Finance; namespace App\Services\Admin\Finance;
use App\Enums\CashTransactionType;
use App\Models\CashAccount; use App\Models\CashAccount;
use App\Models\Expense; use App\Models\Expense;
use App\Services\Concerns\HandlesCashTransactions; use App\Services\Concerns\HandlesCashTransactions;
@ -175,10 +176,11 @@ public function update(Expense $expense, array $data): Expense
public function delete(Expense $expense): bool public function delete(Expense $expense): bool
{ {
return DB::transaction(function () use ($expense) { return DB::transaction(function () use ($expense) {
$cashAccount = CashAccount::firstOrFail(); $this->creditCash(
amount: $expense->amount,
$newBalance = $cashAccount->balance + $expense->amount; description: 'Pembatalan pengeluaran: '.$expense->description,
$cashAccount->update(['balance' => $newBalance]); type: CashTransactionType::DEPOSIT,
);
// Invalidate receipt cache // Invalidate receipt cache
$media = $expense->getFirstMedia('receipts'); $media = $expense->getFirstMedia('receipts');

View File

@ -2,6 +2,7 @@
namespace App\Services\Admin\Finance; namespace App\Services\Admin\Finance;
use App\Enums\CashTransactionType;
use App\Enums\PayrollPeriodStatus; use App\Enums\PayrollPeriodStatus;
use App\Enums\PayrollStatus; use App\Enums\PayrollStatus;
use App\Models\Payroll; use App\Models\Payroll;
@ -141,9 +142,10 @@ public function pay(Payroll $payroll): Payroll
} }
$payroll = DB::transaction(function () use ($payroll) { $payroll = DB::transaction(function () use ($payroll) {
$cashTransaction = $this->creditCash( $cashTransaction = $this->debitCash(
amount: $payroll->total_amount, amount: $payroll->total_amount,
description: 'Pembayaran gaji karyawan', description: 'Pembayaran gaji karyawan',
type: CashTransactionType::EXPENSE,
); );
$payroll->update([ $payroll->update([

View File

@ -3,6 +3,7 @@
namespace App\Services\Admin\HR; namespace App\Services\Admin\HR;
use App\Models\Attendance; use App\Models\Attendance;
use App\Models\Employee;
use App\Models\LeaveRequest; use App\Models\LeaveRequest;
use App\Services\Concerns\RegistersMedia; use App\Services\Concerns\RegistersMedia;
use App\Services\NotificationService; use App\Services\NotificationService;
@ -27,11 +28,12 @@ public function getAll(): Collection
->map(fn (Attendance $attendance) => $this->formatAttendance($attendance)); ->map(fn (Attendance $attendance) => $this->formatAttendance($attendance));
} }
public function getByMonth(int $year, int $month): Collection public function getByMonth(int $year, int $month, ?int $employeeId = null): Collection
{ {
return Attendance::with(['employee.user.userProfile', 'media']) return Attendance::with(['employee.user.userProfile', 'media'])
->whereYear('attendance_date', $year) ->whereYear('attendance_date', $year)
->whereMonth('attendance_date', $month) ->whereMonth('attendance_date', $month)
->when($employeeId, fn ($q) => $q->where('employee_id', $employeeId))
->get() ->get()
->map(fn (Attendance $attendance) => $this->formatAttendance($attendance)); ->map(fn (Attendance $attendance) => $this->formatAttendance($attendance));
} }
@ -51,7 +53,14 @@ public function getToday(): ?array
return $this->getByDate(now()->toDateString()); return $this->getByDate(now()->toDateString());
} }
public function getMonthStats(int $year, int $month): array public function getAllEmployees(): Collection
{
return Employee::with(['user.userProfile', 'user.roles'])
->whereHas('user', fn ($q) => $q->where('is_active', true))
->get();
}
public function getMonthStats(int $year, int $month, ?int $employeeId = null): array
{ {
$startOfMonth = Carbon::createFromDate($year, $month, 1)->startOfMonth(); $startOfMonth = Carbon::createFromDate($year, $month, 1)->startOfMonth();
$endOfMonth = $startOfMonth->copy()->endOfMonth(); $endOfMonth = $startOfMonth->copy()->endOfMonth();
@ -65,14 +74,20 @@ public function getMonthStats(int $year, int $month): array
$current->addDay(); $current->addDay();
} }
$attendanceCount = Attendance::whereYear('attendance_date', $year) $attendanceQuery = Attendance::whereYear('attendance_date', $year)
->whereMonth('attendance_date', $month) ->whereMonth('attendance_date', $month);
->count(); if ($employeeId) {
$attendanceQuery->where('employee_id', $employeeId);
}
$attendanceCount = $attendanceQuery->count();
$leaveDays = LeaveRequest::approved() $leaveQuery = LeaveRequest::approved()
->where('start_date', '<=', $endOfMonth) ->where('start_date', '<=', $endOfMonth)
->where('end_date', '>=', $startOfMonth) ->where('end_date', '>=', $startOfMonth);
->get() if ($employeeId) {
$leaveQuery->where('employee_id', $employeeId);
}
$leaveDays = $leaveQuery->get()
->reduce(function ($carry, $leave) use ($startOfMonth, $endOfMonth) { ->reduce(function ($carry, $leave) use ($startOfMonth, $endOfMonth) {
$leaveStart = max($leave->start_date->timestamp, $startOfMonth->timestamp); $leaveStart = max($leave->start_date->timestamp, $startOfMonth->timestamp);
$leaveEnd = min($leave->end_date->timestamp, $endOfMonth->timestamp); $leaveEnd = min($leave->end_date->timestamp, $endOfMonth->timestamp);
@ -154,6 +169,7 @@ public function checkOut(Attendance $attendance, array $data): Attendance
private function formatAttendance(Attendance $attendance): array private function formatAttendance(Attendance $attendance): array
{ {
$toArray = $attendance->toArray(); $toArray = $attendance->toArray();
$toArray['employee_name'] = $attendance->employee?->user?->userProfile?->full_name ?? '-';
if (is_null($toArray['work_duration_minutes']) && $attendance->check_in_at) { if (is_null($toArray['work_duration_minutes']) && $attendance->check_in_at) {
$checkIn = Carbon::parse($attendance->check_in_at); $checkIn = Carbon::parse($attendance->check_in_at);

View File

@ -10,12 +10,18 @@
class EmployeeService class EmployeeService
{ {
private const ADMIN_ROLES = ['developer', 'owner', 'direktur', 'admin-toko']; private const ADMIN_ROLES = ['developer', 'owner', 'direktur', 'admin-toko'];
private const RESTRICTED_ROLES = ['admin-toko', 'direktur'];
public function canViewAll(): bool public function canViewAll(): bool
{ {
return auth()->user()->hasAnyRole(self::ADMIN_ROLES); return auth()->user()->hasAnyRole(self::ADMIN_ROLES);
} }
public function shouldHideAdminBahanBaku(): bool
{
return auth()->user()->hasAnyRole(self::RESTRICTED_ROLES);
}
public function getAll(array $filters = []): Collection public function getAll(array $filters = []): Collection
{ {
return User::select(['id', 'email', 'username', 'is_active']) return User::select(['id', 'email', 'username', 'is_active'])
@ -29,6 +35,7 @@ public function getAll(array $filters = []): Collection
$userRoles = auth()->user()->roles->pluck('name'); $userRoles = auth()->user()->roles->pluck('name');
$q->whereHas('roles', fn ($rq) => $rq->whereIn('name', $userRoles)); $q->whereHas('roles', fn ($rq) => $rq->whereIn('name', $userRoles));
}) })
->when($this->shouldHideAdminBahanBaku(), fn ($q) => $q->whereDoesntHave('roles', fn ($rq) => $rq->where('name', 'admin-bahan-baku')))
->when($filters['employment_status'] ?? null, fn ($q, $status) => $q->whereHas('employee', fn ($eq) => $eq->where('employment_status', $status))) ->when($filters['employment_status'] ?? null, fn ($q, $status) => $q->whereHas('employee', fn ($eq) => $eq->where('employment_status', $status)))
->when(isset($filters['is_active']) && $filters['is_active'] !== '', fn ($q) => $q->where('is_active', filter_var($filters['is_active'], FILTER_VALIDATE_BOOLEAN))) ->when(isset($filters['is_active']) && $filters['is_active'] !== '', fn ($q) => $q->where('is_active', filter_var($filters['is_active'], FILTER_VALIDATE_BOOLEAN)))
->when($filters['gender'] ?? null, fn ($q, $gender) => $q->whereHas('userProfile', fn ($uq) => $uq->where('gender', $gender))) ->when($filters['gender'] ?? null, fn ($q, $gender) => $q->whereHas('userProfile', fn ($uq) => $uq->where('gender', $gender)))
@ -50,6 +57,7 @@ public function paginated(int $perPage = 25, string $search = '', string $sort =
$userRoles = auth()->user()->roles->pluck('name'); $userRoles = auth()->user()->roles->pluck('name');
$q->whereHas('roles', fn ($rq) => $rq->whereIn('name', $userRoles)); $q->whereHas('roles', fn ($rq) => $rq->whereIn('name', $userRoles));
}) })
->when($this->shouldHideAdminBahanBaku(), fn ($q) => $q->whereDoesntHave('roles', fn ($rq) => $rq->where('name', 'admin-bahan-baku')))
->when($search, fn ($q) => $q->whereHas('userProfile', fn ($uq) => $uq->where('full_name', 'like', "%{$search}%"))) ->when($search, fn ($q) => $q->whereHas('userProfile', fn ($uq) => $uq->where('full_name', 'like', "%{$search}%")))
->when($filters['employment_status'] ?? null, fn ($q, $status) => $q->whereHas('employee', fn ($eq) => $eq->where('employment_status', $status))) ->when($filters['employment_status'] ?? null, fn ($q, $status) => $q->whereHas('employee', fn ($eq) => $eq->where('employment_status', $status)))
->when(isset($filters['is_active']) && $filters['is_active'] !== '', fn ($q) => $q->where('is_active', filter_var($filters['is_active'], FILTER_VALIDATE_BOOLEAN))) ->when(isset($filters['is_active']) && $filters['is_active'] !== '', fn ($q) => $q->where('is_active', filter_var($filters['is_active'], FILTER_VALIDATE_BOOLEAN)))

View File

@ -12,10 +12,16 @@
class LeaveRequestService class LeaveRequestService
{ {
private function canViewAll(): bool
{
return auth()->user()->hasAnyRole(['developer', 'owner', 'direktur', 'admin-toko']);
}
public function getAll(array $filters = []): Collection public function getAll(array $filters = []): Collection
{ {
return LeaveRequest::select(['id', 'employee_id', 'start_date', 'end_date', 'total_days', 'status', 'created_at']) return LeaveRequest::select(['id', 'employee_id', 'start_date', 'end_date', 'total_days', 'status', 'created_at'])
->with(['employee.user.userProfile']) ->with(['employee.user.userProfile'])
->when(! $this->canViewAll(), fn ($q) => $q->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id())))
->when($filters['status'] ?? null, function ($query, $status) { ->when($filters['status'] ?? null, function ($query, $status) {
$query->where('status', $status); $query->where('status', $status);
}) })
@ -28,6 +34,7 @@ public function paginated(int $perPage = 25, string $search = '', string $sort =
return LeaveRequest::query() return LeaveRequest::query()
->select(['id', 'employee_id', 'start_date', 'end_date', 'total_days', 'status', 'created_at']) ->select(['id', 'employee_id', 'start_date', 'end_date', 'total_days', 'status', 'created_at'])
->with(['employee.user.userProfile']) ->with(['employee.user.userProfile'])
->when(! $this->canViewAll(), fn ($q) => $q->whereHas('employee', fn ($eq) => $eq->where('user_id', auth()->id())))
->when($search, fn ($q) => $q->whereHas('employee.user.userProfile', fn ($uq) => $uq->where('full_name', 'like', "%{$search}%"))) ->when($search, fn ($q) => $q->whereHas('employee.user.userProfile', fn ($uq) => $uq->where('full_name', 'like', "%{$search}%")))
->when($filters['status'] ?? null, function ($query, $status) { ->when($filters['status'] ?? null, function ($query, $status) {
$query->where('status', $status); $query->where('status', $status);

View File

@ -3,11 +3,58 @@
namespace App\Services\Concerns; namespace App\Services\Concerns;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Spatie\MediaLibrary\MediaCollections\Models\Media; use Spatie\MediaLibrary\MediaCollections\Models\Media;
trait RegistersMedia trait RegistersMedia
{ {
private function registerMediaFromBase64(
Model $model,
string $base64Data,
string $collectionName,
string $folder,
): void {
$dataUrl = $base64Data;
$mime = 'image/jpeg';
if (preg_match('/^data:(.+?);base64,/', $dataUrl, $matches)) {
$mime = $matches[1];
$dataUrl = preg_replace('/^data:.+?;base64,/', '', $dataUrl);
}
$binary = base64_decode($dataUrl, true);
if ($binary === false) {
return;
}
$extension = match ($mime) {
'image/png' => 'png',
'image/webp' => 'webp',
'image/gif' => 'gif',
default => 'jpg',
};
$date = now()->format('Y/m/d');
$uuid = Str::uuid();
$key = "{$folder}/{$date}/{$uuid}/photo.{$extension}";
Storage::disk('s3')->put($key, $binary, [
'ContentType' => $mime,
'ACL' => 'public-read',
]);
$this->registerMedia(
model: $model,
s3Key: $key,
collectionName: $collectionName,
mimeType: $mime,
fileSize: strlen($binary),
orderColumn: 1,
);
}
private function registerMedia( private function registerMedia(
Model $model, Model $model,
string $s3Key, string $s3Key,

View File

@ -21,14 +21,14 @@ public function run(): void
'leave_requests' => ['view', 'create', 'update', 'delete', 'verify'], 'leave_requests' => ['view', 'create', 'update', 'delete', 'verify'],
'categories' => ['view', 'create', 'update', 'delete'], 'categories' => ['view', 'create', 'update', 'delete'],
'customers' => ['view', 'create', 'update', 'delete'], 'customers' => ['view', 'create', 'update', 'delete'],
'products' => ['view', 'create', 'update', 'delete', 'toggle_status'], 'products' => ['view', 'create', 'update', 'delete', 'toggle_status', 'transfer_stock', 'view_stock_mutations'],
'stocks' => ['view'], 'stocks' => ['view'],
'orders' => ['view', 'create', 'update', 'delete', 'send', 'complete', 'cancel'], 'orders' => ['view', 'create', 'update', 'delete', 'send', 'complete', 'cancel'],
'cuttings' => ['view', 'create', 'update', 'delete', 'complete'], 'cuttings' => ['view', 'create', 'update', 'delete', 'complete'],
'cash' => ['view', 'deposit', 'withdraw', 'update', 'delete'], 'cash' => ['view', 'deposit', 'withdraw', 'update', 'delete'],
'expenses' => ['view', 'create', 'update', 'delete'], 'expenses' => ['view', 'create', 'update', 'delete'],
'activity_logs' => ['view'], 'activity_logs' => ['view'],
'employee_advances' => ['view', 'create', 'update', 'delete', 'pay', 'verify'], 'employee_advances' => ['view', 'create', 'update', 'delete', 'pay', 'view_payments', 'verify'],
'payroll' => ['view', 'pay', 'cancel', 'adjust'], 'payroll' => ['view', 'pay', 'cancel', 'adjust'],
'owner_verifications' => ['view', 'verify', 'reject'], 'owner_verifications' => ['view', 'verify', 'reject'],
'restocks' => ['view', 'create', 'update', 'delete'], 'restocks' => ['view', 'create', 'update', 'delete'],
@ -92,7 +92,6 @@ public function run(): void
'analysis.top_products', 'analysis.top_products',
'analysis.marketing_sales', 'analysis.marketing_sales',
'stocks.view',
'stok_opnames.view', 'stok_opnames.view',
'attendances.view', 'attendances.view',
@ -124,6 +123,8 @@ public function run(): void
'products.update', 'products.update',
'products.delete', 'products.delete',
'products.toggle_status', 'products.toggle_status',
'products.transfer_stock',
'products.view_stock_mutations',
'owner_verifications.view', 'owner_verifications.view',
@ -153,9 +154,12 @@ public function run(): void
'employee_advances.update', 'employee_advances.update',
'employee_advances.delete', 'employee_advances.delete',
'employee_advances.pay', 'employee_advances.pay',
'employee_advances.view_payments',
'payroll.view', 'payroll.view',
'payroll.adjust', 'payroll.adjust',
'payroll.pay',
'payroll.cancel',
'settings.view_system', 'settings.view_system',
'settings.update_system', 'settings.update_system',
@ -220,9 +224,9 @@ public function run(): void
'employee_advances.update', 'employee_advances.update',
'employee_advances.delete', 'employee_advances.delete',
'employee_advances.pay', 'employee_advances.pay',
'employee_advances.view_payments',
'payroll.view', 'payroll.view',
'payroll.adjust',
], true); ], true);
})), })),
@ -250,7 +254,6 @@ public function run(): void
'raw_materials.create', 'raw_materials.create',
'raw_materials.update', 'raw_materials.update',
'raw_materials.toggle_status', 'raw_materials.toggle_status',
'stocks.view',
'owner_verifications.view', 'owner_verifications.view',
@ -308,6 +311,7 @@ public function run(): void
'employee_advances.update', 'employee_advances.update',
'employee_advances.delete', 'employee_advances.delete',
'employee_advances.pay', 'employee_advances.pay',
'employee_advances.view_payments',
'payroll.view', 'payroll.view',
], true); ], true);
@ -346,6 +350,7 @@ public function run(): void
'employee_advances.update', 'employee_advances.update',
'employee_advances.delete', 'employee_advances.delete',
'employee_advances.pay', 'employee_advances.pay',
'employee_advances.view_payments',
'payroll.view', 'payroll.view',
], true); ], true);
@ -361,6 +366,7 @@ public function run(): void
'dashboard.orders_payment', 'dashboard.orders_payment',
'dashboard.orders_marketing', 'dashboard.orders_marketing',
'dashboard.orders_status', 'dashboard.orders_status',
'analysis.view', 'analysis.view',
'analysis.attendance', 'analysis.attendance',
'analysis.cash', 'analysis.cash',
@ -375,29 +381,38 @@ public function run(): void
'analysis.top_customers', 'analysis.top_customers',
'analysis.top_products', 'analysis.top_products',
'analysis.marketing_sales', 'analysis.marketing_sales',
'employees.view', 'employees.view',
'attendances.view', 'attendances.view',
'attendances.create', 'attendances.create',
'attendances.delete', 'attendances.delete',
'attendances.manage', 'attendances.manage',
'leave_requests.view', 'leave_requests.view',
'leave_requests.create', 'leave_requests.create',
'leave_requests.update', 'leave_requests.update',
'leave_requests.delete', 'leave_requests.delete',
'categories.view', 'categories.view',
'customers.view', 'customers.view',
'products.view', 'products.view',
'stocks.view',
'orders.view', 'orders.view',
'cuttings.view',
'cash.view', 'cash.view',
'expenses.view', 'expenses.view',
'activity_logs.view', 'activity_logs.view',
'employee_advances.view', 'employee_advances.view',
'employee_advances.create', 'employee_advances.create',
'employee_advances.update', 'employee_advances.update',
'employee_advances.delete', 'employee_advances.delete',
'employee_advances.pay',
'payroll.view', 'payroll.view',
], true); ], true);
})), })),
@ -405,19 +420,23 @@ public function run(): void
'non-operator' => array_values(array_filter($allPermissions, function ($p) { 'non-operator' => array_values(array_filter($allPermissions, function ($p) {
return in_array($p, [ return in_array($p, [
'dashboard.view', 'dashboard.view',
'analysis.view', 'analysis.view',
'analysis.attendance', 'analysis.attendance',
'attendances.view', 'attendances.view',
'attendances.create', 'attendances.create',
'leave_requests.view', 'leave_requests.view',
'leave_requests.create', 'leave_requests.create',
'leave_requests.update', 'leave_requests.update',
'leave_requests.delete', 'leave_requests.delete',
'employee_advances.view', 'employee_advances.view',
'employee_advances.create', 'employee_advances.create',
'employee_advances.update', 'employee_advances.update',
'employee_advances.delete', 'employee_advances.delete',
'employee_advances.pay',
'payroll.view', 'payroll.view',
], true); ], true);
})), })),
@ -425,24 +444,28 @@ public function run(): void
'stok-opname' => array_values(array_filter($allPermissions, function ($p) { 'stok-opname' => array_values(array_filter($allPermissions, function ($p) {
return in_array($p, [ return in_array($p, [
'dashboard.view', 'dashboard.view',
'attendances.view', 'attendances.view',
'attendances.create', 'attendances.create',
'leave_requests.view', 'leave_requests.view',
'leave_requests.create', 'leave_requests.create',
'leave_requests.update', 'leave_requests.update',
'leave_requests.delete', 'leave_requests.delete',
'products.view', 'products.view',
'stocks.view',
'stok_opnames.view', 'stok_opnames.view',
'stok_opnames.create', 'stok_opnames.create',
'stok_opnames.update', 'stok_opnames.update',
'stok_opnames.delete', 'stok_opnames.delete',
'stok_opnames.submit', 'stok_opnames.submit',
'employee_advances.view', 'employee_advances.view',
'employee_advances.create', 'employee_advances.create',
'employee_advances.update', 'employee_advances.update',
'employee_advances.delete', 'employee_advances.delete',
'employee_advances.pay',
'payroll.view', 'payroll.view',
], true); ], true);
})), })),

View File

@ -1,7 +1,3 @@
import L from 'leaflet';
import { useEffect, useRef } from 'react';
import 'leaflet/dist/leaflet.css';
interface LocationMapProps { interface LocationMapProps {
latitude: number; latitude: number;
longitude: number; longitude: number;
@ -13,52 +9,18 @@ export function LocationMap({
latitude, latitude,
longitude, longitude,
height = '250px', height = '250px',
zoom = 15, zoom = 17,
}: LocationMapProps) { }: LocationMapProps) {
const mapRef = useRef<HTMLDivElement>(null); const src = `https://maps.google.com/maps?q=${latitude},${longitude}&z=${zoom}&t=k&output=embed`;
const mapInstanceRef = useRef<L.Map | null>(null);
useEffect(() => {
if (!mapRef.current || mapInstanceRef.current) {
return;
}
const map = L.map(mapRef.current, {
center: [latitude, longitude],
zoom,
zoomControl: false,
attributionControl: true,
});
L.control.zoom({ position: 'topright' }).addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);
const icon = L.divIcon({
html: `<div style="background: #ef4444; width: 24px; height: 24px; border-radius: 50%; border: 3px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.3);"></div>`,
className: '',
iconSize: [24, 24],
iconAnchor: [12, 12],
});
L.marker([latitude, longitude], { icon }).addTo(map);
mapInstanceRef.current = map;
return () => {
map.remove();
mapInstanceRef.current = null;
};
}, [latitude, longitude, zoom]);
return ( return (
<div <iframe
ref={mapRef} src={src}
style={{ height, width: '100%' }} style={{ height, width: '100%', border: 0 }}
className="rounded-lg" className="rounded-lg"
loading="lazy"
referrerPolicy="no-referrer-when-downgrade"
title="Lokasi Presensi"
/> />
); );
} }

View File

@ -20,7 +20,7 @@ export function createCashAccountColumns(
): ColumnDef<CashAccount>[] { ): ColumnDef<CashAccount>[] {
const { handleEdit, handleDeleteClick, can } = params; const { handleEdit, handleDeleteClick, can } = params;
return [ const columns: ColumnDef<CashAccount>[] = [
{ {
accessorKey: 'name', accessorKey: 'name',
header: () => <span>Nama</span>, header: () => <span>Nama</span>,
@ -39,7 +39,10 @@ export function createCashAccountColumns(
</span> </span>
), ),
}, },
{ ];
if (can('cash.update') || can('cash.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -70,6 +73,8 @@ export function createCashAccountColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -1,7 +1,7 @@
import type { ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2 } from 'lucide-react';
import { ImagePreviewButton } from '@/components/image-preview-button'; import { ImagePreviewButton } from '@/components/image-preview-button';
import { RowActions } from '@/components/row-actions'; import { RowActions } from '@/components/row-actions';
import type { ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2 } from 'lucide-react';
export type CashTransaction = { export type CashTransaction = {
id: number; id: number;
@ -30,23 +30,12 @@ function getTypeLabel(type: string): string {
deposit: 'Deposit', deposit: 'Deposit',
withdrawal: 'Withdrawal', withdrawal: 'Withdrawal',
expense: 'Pengeluaran', expense: 'Pengeluaran',
transfer: 'Transfer', employee_advance: 'Kasbon',
}; };
return labels[type] ?? type; return labels[type] ?? type;
} }
function getReferenceLabel(type: string): string {
const labels: Record<string, string> = {
'App\\Models\\Expense': 'Pengeluaran',
'App\\Models\\Order': 'Penjualan Tunai',
'App\\Models\\Purchase': 'Belanja',
'App\\Models\\CashAccount': 'Transfer Kas',
};
return labels[type] ?? '-';
}
type CreateColumnsParams = { type CreateColumnsParams = {
handleEdit: (transaction: CashTransaction) => void; handleEdit: (transaction: CashTransaction) => void;
handleDeleteClick: (transaction: CashTransaction) => void; handleDeleteClick: (transaction: CashTransaction) => void;
@ -58,7 +47,7 @@ export function createTransactionColumns(
): ColumnDef<CashTransaction>[] { ): ColumnDef<CashTransaction>[] {
const { handleEdit, handleDeleteClick, can } = params; const { handleEdit, handleDeleteClick, can } = params;
return [ const columns: ColumnDef<CashTransaction>[] = [
{ {
accessorKey: 'formatted_created_at', accessorKey: 'formatted_created_at',
header: () => <span>Tanggal</span>, header: () => <span>Tanggal</span>,
@ -77,11 +66,6 @@ export function createTransactionColumns(
<span className="font-medium"> <span className="font-medium">
{getTypeLabel(transaction.type)} {getTypeLabel(transaction.type)}
</span> </span>
<span className="text-xs text-muted-foreground">
{getReferenceLabel(
transaction.reference?.type ?? '',
)}
</span>
</div> </div>
); );
}, },
@ -152,7 +136,10 @@ export function createTransactionColumns(
return <span>{createdBy?.user_profile?.full_name ?? '-'}</span>; return <span>{createdBy?.user_profile?.full_name ?? '-'}</span>;
}, },
}, },
{ ];
if (can('cash.update') || can('cash.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -190,6 +177,8 @@ export function createTransactionColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -91,7 +91,7 @@ export function createEmployeeAdvanceColumns(
const { handleEdit, handleDeleteClick, handleApprove, handlePay, handleShowPayments, can, authUserId } = const { handleEdit, handleDeleteClick, handleApprove, handlePay, handleShowPayments, can, authUserId } =
params; params;
return [ const columns: ColumnDef<EmployeeAdvance>[] = [
{ {
accessorKey: 'formatted_created_at', accessorKey: 'formatted_created_at',
header: () => <span>Tanggal</span>, header: () => <span>Tanggal</span>,
@ -162,7 +162,16 @@ export function createEmployeeAdvanceColumns(
<span>{getStatusBadge(row.getValue('status') as string)}</span> <span>{getStatusBadge(row.getValue('status') as string)}</span>
), ),
}, },
{ ];
if (
can('employee_advances.verify') ||
can('employee_advances.pay') ||
can('employee_advances.view_payments') ||
can('employee_advances.update') ||
can('employee_advances.delete')
) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -198,7 +207,7 @@ export function createEmployeeAdvanceColumns(
{ {
label: 'Riwayat', label: 'Riwayat',
icon: <History className="h-4 w-4" />, icon: <History className="h-4 w-4" />,
show: employeeAdvance.payments.length > 0, show: can('employee_advances.view_payments') && employeeAdvance.payments.length > 0,
onClick: () => handleShowPayments(employeeAdvance), onClick: () => handleShowPayments(employeeAdvance),
}, },
{ {
@ -226,6 +235,8 @@ export function createEmployeeAdvanceColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -30,7 +30,7 @@ export function createExpenseColumns(
): ColumnDef<Expense>[] { ): ColumnDef<Expense>[] {
const { handleEdit, handleDeleteClick, can } = params; const { handleEdit, handleDeleteClick, can } = params;
return [ const columns: ColumnDef<Expense>[] = [
{ {
accessorKey: 'formatted_created_at', accessorKey: 'formatted_created_at',
header: () => <span>Tanggal</span>, header: () => <span>Tanggal</span>,
@ -69,8 +69,8 @@ export function createExpenseColumns(
accessorKey: 'formatted_amount', accessorKey: 'formatted_amount',
header: () => <span>Jumlah</span>, header: () => <span>Jumlah</span>,
cell: ({ row }) => ( cell: ({ row }) => (
<span className="font-medium text-red-600"> <span className="font-medium">
- {row.getValue('formatted_amount') as string} {row.getValue('formatted_amount') as string}
</span> </span>
), ),
}, },
@ -83,7 +83,10 @@ export function createExpenseColumns(
return <span>{createdBy?.user_profile?.full_name ?? '-'}</span>; return <span>{createdBy?.user_profile?.full_name ?? '-'}</span>;
}, },
}, },
{ ];
if (can('expenses.update') || can('expenses.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -114,6 +117,8 @@ export function createExpenseColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -174,15 +174,15 @@ export function createPayrollPeriodColumns(
}); });
} }
columns.push( columns.push({
{
accessorKey: 'status', accessorKey: 'status',
header: () => <span>Status</span>, header: () => <span>Status</span>,
cell: ({ row }) => ( cell: ({ row }) => (
<span>{getStatusBadge(row.getValue('status') as string)}</span> <span>{getStatusBadge(row.getValue('status') as string)}</span>
), ),
}, });
{
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -224,8 +224,7 @@ export function createPayrollPeriodColumns(
/> />
); );
}, },
}, });
);
return columns; return columns;
} }

View File

@ -18,6 +18,7 @@ import { toast } from 'sonner';
import { CameraCapture } from '@/components/camera-capture'; import { CameraCapture } from '@/components/camera-capture';
import { LocationMap } from '@/components/location-map'; import { LocationMap } from '@/components/location-map';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card'; import { Card, CardContent } from '@/components/ui/card';
import { import {
@ -44,6 +45,7 @@ type Attendance = {
check_out_latitude: number | null; check_out_latitude: number | null;
check_out_longitude: number | null; check_out_longitude: number | null;
work_duration_minutes: number | null; work_duration_minutes: number | null;
employee_name: string;
}; };
type MonthStats = { type MonthStats = {
@ -58,11 +60,12 @@ type Props = {
todayAttendance: Attendance | null; todayAttendance: Attendance | null;
currentYear: number; currentYear: number;
currentMonth: number; currentMonth: number;
monthStats: MonthStats; monthStats: MonthStats | null;
hrSettings: { hrSettings: {
scheduled_check_in_time: string; scheduled_check_in_time: string;
scheduled_check_out_time: string; scheduled_check_out_time: string;
}; };
isAdmin: boolean;
}; };
const WEEKDAYS = ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab']; const WEEKDAYS = ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'];
@ -83,16 +86,6 @@ function isSameDay(d1: Date, d2: Date): boolean {
); );
} }
function checkIsToday(date: Date): boolean {
const t = new Date();
return (
date.getDate() === t.getDate() &&
date.getMonth() === t.getMonth() &&
date.getFullYear() === t.getFullYear()
);
}
function isWeekend(date: Date): boolean { function isWeekend(date: Date): boolean {
const day = date.getDay(); const day = date.getDay();
@ -153,6 +146,7 @@ export default function AttendanceIndex({
currentMonth, currentMonth,
monthStats, monthStats,
hrSettings, hrSettings,
isAdmin,
}: Props) { }: Props) {
const [officeHour, officeMinute] = hrSettings.scheduled_check_in_time const [officeHour, officeMinute] = hrSettings.scheduled_check_in_time
.split(':') .split(':')
@ -173,21 +167,17 @@ export default function AttendanceIndex({
const viewYear = viewDate.getFullYear(); const viewYear = viewDate.getFullYear();
const viewMonth = viewDate.getMonth() + 1; const viewMonth = viewDate.getMonth() + 1;
const attendanceDates = useMemo(() => { const attendanceByDate = useMemo(() => {
const dates = new Map<string, Attendance>(); const map = new Map<string, Attendance[]>();
attendances.forEach((att) => { attendances.forEach((att) => {
dates.set(att.attendance_date, att); const existing = map.get(att.attendance_date) ?? [];
existing.push(att);
map.set(att.attendance_date, existing);
}); });
return dates; return map;
}, [attendances]); }, [attendances]);
const selectedAttendance = useMemo(() => {
const dateStr = format(selectedDate, 'yyyy-MM-dd');
return attendanceDates.get(dateStr) ?? null;
}, [selectedDate, attendanceDates]);
const calendarDays = useMemo(() => { const calendarDays = useMemo(() => {
const daysInMonth = getDaysInMonth(viewYear, viewMonth); const daysInMonth = getDaysInMonth(viewYear, viewMonth);
const firstDay = getFirstDayOfMonth(viewYear, viewMonth); const firstDay = getFirstDayOfMonth(viewYear, viewMonth);
@ -232,8 +222,51 @@ export default function AttendanceIndex({
return days; return days;
}, [viewYear, viewMonth]); }, [viewYear, viewMonth]);
const handlePrevMonth = () => setViewDate((d) => subMonths(d, 1)); const handlePrevMonth = () => {
const handleNextMonth = () => setViewDate((d) => addMonths(d, 1)); const newDate = subMonths(viewDate, 1);
setViewDate(newDate);
if (!isAdmin) {
router.get(
attendanceIndex.url(),
{
year: newDate.getFullYear(),
month: newDate.getMonth() + 1,
},
{ preserveState: true, preserveScroll: true },
);
}
};
const handleNextMonth = () => {
const newDate = addMonths(viewDate, 1);
setViewDate(newDate);
if (!isAdmin) {
router.get(
attendanceIndex.url(),
{
year: newDate.getFullYear(),
month: newDate.getMonth() + 1,
},
{ preserveState: true, preserveScroll: true },
);
}
};
const handleGoToToday = () => {
const now = new Date();
setViewDate(now);
setSelectedDate(now);
if (!isAdmin) {
router.get(
attendanceIndex.url(),
{ year: now.getFullYear(), month: now.getMonth() + 1 },
{ preserveState: true, preserveScroll: true },
);
}
};
const handleCameraCapture = (dataUrl: string) => { const handleCameraCapture = (dataUrl: string) => {
setShowCamera(false); setShowCamera(false);
@ -305,14 +338,14 @@ return '-';
<> <>
<Head title="Presensi" /> <Head title="Presensi" />
<div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6"> <div className="flex min-h-full flex-1 flex-col gap-6 overflow-auto p-4 md:p-6">
<div> <div>
<h2 className="text-2xl font-semibold tracking-tight"> <h2 className="text-2xl font-semibold tracking-tight">
Presensi Presensi
</h2> </h2>
</div> </div>
{/* Alert Status Presensi */} {!isAdmin && (
<Alert> <Alert>
<CalendarCheck className="h-4 w-4" /> <CalendarCheck className="h-4 w-4" />
<AlertTitle>Presensi Hari Ini</AlertTitle> <AlertTitle>Presensi Hari Ini</AlertTitle>
@ -396,8 +429,9 @@ return '-';
</div> </div>
</AlertDescription> </AlertDescription>
</Alert> </Alert>
)}
{/* Summary Stats */} {monthStats && (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4"> <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<Card> <Card>
<CardContent className="flex items-center gap-3 py-3"> <CardContent className="flex items-center gap-3 py-3">
@ -460,12 +494,12 @@ return '-';
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
)}
<Card <Card
className="overflow-hidden" className="overflow-hidden"
style={{ '--card-spacing': '0px' } as React.CSSProperties} style={{ '--card-spacing': '0px' } as React.CSSProperties}
> >
{/* Calendar Header */}
<div className="flex items-center justify-between border-b px-6 py-4"> <div className="flex items-center justify-between border-b px-6 py-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="flex flex-col items-center overflow-hidden rounded-lg ring-1 ring-border"> <div className="flex flex-col items-center overflow-hidden rounded-lg ring-1 ring-border">
@ -503,10 +537,7 @@ return '-';
variant="ghost" variant="ghost"
size="sm" size="sm"
className="h-8 px-3 text-xs font-medium" className="h-8 px-3 text-xs font-medium"
onClick={() => { onClick={handleGoToToday}
setViewDate(new Date());
setSelectedDate(new Date());
}}
> >
Hari ini Hari ini
</Button> </Button>
@ -521,7 +552,6 @@ return '-';
</div> </div>
</div> </div>
{/* Weekday Headers */}
<div className="grid grid-cols-7 border-b"> <div className="grid grid-cols-7 border-b">
{WEEKDAYS.map((day) => ( {WEEKDAYS.map((day) => (
<div <div
@ -533,11 +563,10 @@ return '-';
))} ))}
</div> </div>
{/* Calendar Grid */}
<div className="grid grid-cols-7"> <div className="grid grid-cols-7">
{calendarDays.map((cell, idx) => { {calendarDays.map((cell, idx) => {
const dateStr = format(cell.date, 'yyyy-MM-dd'); const dateStr = format(cell.date, 'yyyy-MM-dd');
const attendance = attendanceDates.get(dateStr); const dayAttendances = attendanceByDate.get(dateStr) ?? [];
const isSelected = isSameDay( const isSelected = isSameDay(
cell.date, cell.date,
selectedDate, selectedDate,
@ -547,47 +576,33 @@ return '-';
new Date(), new Date(),
); );
const today = new Date(); const todayMidnight = new Date();
today.setHours(0, 0, 0, 0); todayMidnight.setHours(0, 0, 0, 0);
const cellDate = new Date(cell.date); const cellDate = new Date(cell.date);
cellDate.setHours(0, 0, 0, 0); cellDate.setHours(0, 0, 0, 0);
const isPastDate = cellDate < today; const isPastDate = cellDate < todayMidnight;
const showAbsent = const showAbsent =
cell.isCurrentMonth && cell.isCurrentMonth &&
isPastDate && isPastDate &&
!isWeekend(cell.date) && !isWeekend(cell.date) &&
!attendance; dayAttendances.length === 0;
const late = attendance
? isLate(
attendance.check_in_at,
officeHour,
officeMinute,
)
: false;
const lateMins = attendance
? getLateMinutes(
attendance.check_in_at,
officeHour,
officeMinute,
)
: 0;
return ( return (
<button <div
key={idx} key={idx}
onClick={() => { onClick={() => {
setSelectedDate(cell.date); setSelectedDate(cell.date);
if (!isAdmin && dayAttendances.length > 0) {
if (attendance) { setDetailAttendance(dayAttendances[0]);
setDetailAttendance(attendance);
} }
}} }}
className={`group relative flex min-h-[100px] flex-col p-2 text-left transition-colors hover:bg-muted/50 ${ className={`group relative flex min-h-[100px] flex-col p-2 text-left transition-colors hover:bg-muted/50 ${
!cell.isCurrentMonth !cell.isCurrentMonth
? 'bg-muted/30 text-muted-foreground/50' ? 'bg-muted/30 text-muted-foreground/50'
: '' : ''
} ${isSelected ? 'bg-muted/50' : ''} ${
!isAdmin && dayAttendances.length > 0 ? 'cursor-pointer' : ''
}`} }`}
style={{ style={{
borderRight: '1px solid var(--border)', borderRight: '1px solid var(--border)',
@ -607,8 +622,51 @@ setDetailAttendance(attendance);
{cell.day} {cell.day}
</span> </span>
</div> </div>
<div className="mt-1 flex flex-col gap-0.5"> <div className="mt-1 flex flex-col gap-0.5 overflow-hidden">
{attendance && ( {isAdmin ? (
<>
{dayAttendances.map((att) => {
const late = isLate(
att.check_in_at,
officeHour,
officeMinute,
);
return (
<button
key={att.id}
onClick={(e) => {
e.stopPropagation();
setDetailAttendance(att);
}}
className="w-full"
>
<Badge
variant={late ? 'destructive' : 'default'}
className="w-full justify-center cursor-pointer truncate"
>
{att.employee_name}
</Badge>
</button>
);
})}
</>
) : (
<>
{dayAttendances.length > 0 && (() => {
const att = dayAttendances[0];
const late = isLate(
att.check_in_at,
officeHour,
officeMinute,
);
const lateMins = getLateMinutes(
att.check_in_at,
officeHour,
officeMinute,
);
return (
<> <>
<span <span
className={`inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-[10px] font-semibold ${late ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700'}`} className={`inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-[10px] font-semibold ${late ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700'}`}
@ -620,13 +678,13 @@ setDetailAttendance(attendance);
<span className="text-[10px] text-muted-foreground"> <span className="text-[10px] text-muted-foreground">
Masuk :{' '} Masuk :{' '}
{formatTime( {formatTime(
attendance.check_in_at, att.check_in_at,
)} )}
</span> </span>
<span className="text-[10px] text-muted-foreground"> <span className="text-[10px] text-muted-foreground">
Pulang :{' '} Pulang :{' '}
{formatTime( {formatTime(
attendance.check_out_at, att.check_out_at,
)} )}
</span> </span>
{late && ( {late && (
@ -641,10 +699,13 @@ setDetailAttendance(attendance);
<span className="text-[10px] text-muted-foreground"> <span className="text-[10px] text-muted-foreground">
Jam Kerja :{' '} Jam Kerja :{' '}
{formatMinutes( {formatMinutes(
attendance.work_duration_minutes, att.work_duration_minutes,
)} )}
</span> </span>
</> </>
);
})()}
</>
)} )}
{showAbsent && ( {showAbsent && (
<span className="inline-flex items-center justify-center rounded-full bg-red-100 px-1.5 py-0.5 text-[10px] font-semibold text-red-700"> <span className="inline-flex items-center justify-center rounded-full bg-red-100 px-1.5 py-0.5 text-[10px] font-semibold text-red-700">
@ -652,7 +713,7 @@ setDetailAttendance(attendance);
</span> </span>
)} )}
</div> </div>
</button> </div>
); );
})} })}
</div> </div>
@ -673,6 +734,9 @@ setDetailAttendance(attendance);
<DialogContent className="sm:max-w-2xl"> <DialogContent className="sm:max-w-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
{isAdmin && detailAttendance?.employee_name
? `${detailAttendance.employee_name} - `
: ''}
Detail Presensi -{' '} Detail Presensi -{' '}
{detailAttendance && {detailAttendance &&
format( format(
@ -749,9 +813,10 @@ setDetailAttendance(attendance);
</div> </div>
</div> </div>
</div> </div>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<span className="text-sm font-medium text-muted-foreground"> <span className="text-sm font-medium text-muted-foreground">
Lokasi Presensi Lokasi Masuk
</span> </span>
<LocationMap <LocationMap
latitude={ latitude={
@ -763,6 +828,23 @@ setDetailAttendance(attendance);
height="200px" height="200px"
/> />
</div> </div>
{detailAttendance.check_out_latitude && detailAttendance.check_out_longitude && (
<div className="flex flex-col gap-2">
<span className="text-sm font-medium text-muted-foreground">
Lokasi Pulang
</span>
<LocationMap
latitude={
detailAttendance.check_out_latitude
}
longitude={
detailAttendance.check_out_longitude
}
height="200px"
/>
</div>
)}
</div>
</div> </div>
)} )}
</DialogContent> </DialogContent>

View File

@ -54,7 +54,7 @@ export function createEmployeeColumns(
canViewAll, canViewAll,
} = params; } = params;
return [ const columns: ColumnDef<Employee>[] = [
{ {
accessorKey: 'user_profile.full_name', accessorKey: 'user_profile.full_name',
id: 'full_name', id: 'full_name',
@ -154,7 +154,14 @@ export function createEmployeeColumns(
); );
}, },
}, },
{ ];
if (
can('employees.update') ||
can('employees.reset_password') ||
can('employees.delete')
) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -193,6 +200,8 @@ export function createEmployeeColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -161,6 +161,7 @@ export default function EmployeeEdit({ employee, roles, canViewAll }: Props) {
* *
</span> </span>
</Label> </Label>
{canViewAll ? (
<Combobox <Combobox
items={roles} items={roles}
itemToStringLabel={(r) => r.name} itemToStringLabel={(r) => r.name}
@ -190,6 +191,11 @@ export default function EmployeeEdit({ employee, roles, canViewAll }: Props) {
</ComboboxList> </ComboboxList>
</ComboboxContent> </ComboboxContent>
</Combobox> </Combobox>
) : (
<div className="flex h-10 w-full items-center rounded-md border border-input bg-muted px-3 py-2 text-sm">
{selectedRole?.name ?? '-'}
</div>
)}
<InputError <InputError
message={errors.role} message={errors.role}
/> />

View File

@ -64,7 +64,7 @@ export function createLeaveRequestColumns(
const { handleEdit, handleDeleteClick, handleApprove, handleReject, can } = const { handleEdit, handleDeleteClick, handleApprove, handleReject, can } =
params; params;
return [ const columns: ColumnDef<LeaveRequest>[] = [
{ {
id: 'employee_name', id: 'employee_name',
header: () => <span>Oleh</span>, header: () => <span>Oleh</span>,
@ -112,7 +112,14 @@ export function createLeaveRequestColumns(
<span>{getStatusBadge(row.getValue('status') as string)}</span> <span>{getStatusBadge(row.getValue('status') as string)}</span>
), ),
}, },
{ ];
if (
can('leave_requests.verify') ||
can('leave_requests.update') ||
can('leave_requests.delete')
) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -167,6 +174,8 @@ export function createLeaveRequestColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -139,6 +139,7 @@ export function CuttingCardRow({
)} )}
</div> </div>
{(can('cuttings.update') || can('cuttings.delete')) && (
<RowActions <RowActions
actions={[ actions={[
{ {
@ -158,6 +159,7 @@ export function CuttingCardRow({
]} ]}
wrapperClassName="flex shrink-0 items-center gap-1" wrapperClassName="flex shrink-0 items-center gap-1"
/> />
)}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@ -126,6 +126,7 @@ export function PurchaseCardRow({
)} )}
</div> </div>
{(can('purchases.update') || can('purchases.delete')) && (
<RowActions <RowActions
actions={[ actions={[
{ {
@ -145,6 +146,7 @@ export function PurchaseCardRow({
]} ]}
wrapperClassName="flex shrink-0 items-center gap-1" wrapperClassName="flex shrink-0 items-center gap-1"
/> />
)}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@ -135,6 +135,7 @@ export function RestockCardRow({
</div> </div>
</div> </div>
{(can('restocks.update') || can('restocks.delete')) && (
<RowActions <RowActions
actions={[ actions={[
{ {
@ -154,6 +155,7 @@ export function RestockCardRow({
]} ]}
wrapperClassName="flex shrink-0 items-center gap-1" wrapperClassName="flex shrink-0 items-center gap-1"
/> />
)}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@ -183,6 +183,7 @@ export function TransactionCardRow({
</div> </div>
</div> </div>
{(can('orders.update') || can('orders.delete')) && (
<RowActions <RowActions
actions={[ actions={[
...(transaction.status === 'pending' && can('orders.update') ...(transaction.status === 'pending' && can('orders.update')
@ -234,6 +235,7 @@ export function TransactionCardRow({
]} ]}
wrapperClassName="flex shrink-0 items-center gap-1" wrapperClassName="flex shrink-0 items-center gap-1"
/> />
)}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@ -18,7 +18,7 @@ export function createCategoryColumns(
): ColumnDef<Category>[] { ): ColumnDef<Category>[] {
const { handleEdit, handleDeleteClick, can } = params; const { handleEdit, handleDeleteClick, can } = params;
return [ const columns: ColumnDef<Category>[] = [
{ {
accessorKey: 'name', accessorKey: 'name',
header: () => <span>Nama</span>, header: () => <span>Nama</span>,
@ -28,7 +28,10 @@ export function createCategoryColumns(
</span> </span>
), ),
}, },
{ ];
if (can('categories.update') || can('categories.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -59,6 +62,8 @@ export function createCategoryColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -20,7 +20,7 @@ export function createCustomerColumns(
): ColumnDef<Customer>[] { ): ColumnDef<Customer>[] {
const { handleEdit, handleDeleteClick, can } = params; const { handleEdit, handleDeleteClick, can } = params;
return [ const columns: ColumnDef<Customer>[] = [
{ {
accessorKey: 'name', accessorKey: 'name',
header: () => <span>Nama</span>, header: () => <span>Nama</span>,
@ -46,7 +46,10 @@ export function createCustomerColumns(
</span> </span>
), ),
}, },
{ ];
if (can('customers.update') || can('customers.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -77,6 +80,8 @@ export function createCustomerColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -90,7 +90,7 @@ export function createProductColumns(
can, can,
} = params; } = params;
return [ const columns: ColumnDef<Product>[] = [
{ {
id: 'expand', id: 'expand',
header: '', header: '',
@ -338,7 +338,10 @@ export function createProductColumns(
); );
}, },
}, },
{ ];
if (can('products.update') || can('products.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -369,6 +372,8 @@ export function createProductColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -144,6 +144,7 @@ export function ProductCardRow({
</div> </div>
</div> </div>
{(can('products.update') || can('products.delete')) && (
<RowActions <RowActions
actions={[ actions={[
{ {
@ -163,6 +164,7 @@ export function ProductCardRow({
]} ]}
wrapperClassName="flex shrink-0 items-center gap-1" wrapperClassName="flex shrink-0 items-center gap-1"
/> />
)}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@ -34,6 +34,8 @@ export function VariantSubRow({
variant: ProductVariant; variant: ProductVariant;
} | null>(null); } | null>(null);
const canAnyAction = can('products.transfer_stock') || can('products.view_stock_mutations') || can('products.update') || can('products.delete');
return ( return (
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<Table> <Table>
@ -52,16 +54,18 @@ export function VariantSubRow({
</TableHead> </TableHead>
<TableHead className="text-center">Stok Ecer</TableHead> <TableHead className="text-center">Stok Ecer</TableHead>
<TableHead>Harga</TableHead> <TableHead>Harga</TableHead>
{canAnyAction && (
<TableHead className="w-[120px] text-center"> <TableHead className="w-[120px] text-center">
Aksi Aksi
</TableHead> </TableHead>
)}
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{variants.length === 0 ? ( {variants.length === 0 ? (
<TableRow> <TableRow>
<TableCell <TableCell
colSpan={8} colSpan={canAnyAction ? 8 : 7}
className="text-center text-muted-foreground" className="text-center text-muted-foreground"
> >
Tidak ada varian. Tidak ada varian.
@ -116,6 +120,7 @@ export function VariantSubRow({
'-' '-'
)} )}
</TableCell> </TableCell>
{canAnyAction && (
<TableCell> <TableCell>
<RowActions <RowActions
actions={[ actions={[
@ -124,7 +129,7 @@ export function VariantSubRow({
icon: ( icon: (
<ArrowRightLeft className="h-4 w-4" /> <ArrowRightLeft className="h-4 w-4" />
), ),
show: can('stocks.view'), show: can('products.transfer_stock'),
onClick: () => onClick: () =>
setTransferVariant({ setTransferVariant({
product, product,
@ -136,7 +141,7 @@ export function VariantSubRow({
icon: ( icon: (
<ScrollText className="h-4 w-4" /> <ScrollText className="h-4 w-4" />
), ),
show: can('stocks.view'), show: can('products.view_stock_mutations'),
onClick: () => { onClick: () => {
router.visit( router.visit(
stockMutations.url({ stockMutations.url({
@ -173,6 +178,7 @@ export function VariantSubRow({
]} ]}
/> />
</TableCell> </TableCell>
)}
</TableRow> </TableRow>
)) ))
)} )}

View File

@ -94,6 +94,7 @@ export function RawMaterialCardRow({
</div> </div>
</div> </div>
{(can('raw_materials.update') || can('raw_materials.delete')) && (
<RowActions <RowActions
actions={[ actions={[
{ {
@ -113,6 +114,7 @@ export function RawMaterialCardRow({
]} ]}
wrapperClassName="flex shrink-0 items-center gap-1" wrapperClassName="flex shrink-0 items-center gap-1"
/> />
)}
</div> </div>
</CardContent> </CardContent>
</Card> </Card>

View File

@ -47,6 +47,8 @@ export function RawMaterialVariantSubRow({
); );
} }
const canAnyAction = can('raw_materials.update') || can('raw_materials.delete');
return ( return (
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<Table> <Table>
@ -59,16 +61,18 @@ export function RawMaterialVariantSubRow({
<TableHead>Nama Varian</TableHead> <TableHead>Nama Varian</TableHead>
<TableHead>Harga</TableHead> <TableHead>Harga</TableHead>
<TableHead className="text-center">Stok</TableHead> <TableHead className="text-center">Stok</TableHead>
{canAnyAction && (
<TableHead className="w-[100px] text-center"> <TableHead className="w-[100px] text-center">
Aksi Aksi
</TableHead> </TableHead>
)}
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{variants.length === 0 ? ( {variants.length === 0 ? (
<TableRow> <TableRow>
<TableCell <TableCell
colSpan={6} colSpan={canAnyAction ? 6 : 5}
className="text-center text-muted-foreground" className="text-center text-muted-foreground"
> >
Tidak ada varian. Tidak ada varian.
@ -101,6 +105,7 @@ export function RawMaterialVariantSubRow({
<TableCell className="text-center"> <TableCell className="text-center">
{formatNumber(variant.stock)} {formatNumber(variant.stock)}
</TableCell> </TableCell>
{canAnyAction && (
<TableCell> <TableCell>
<RowActions <RowActions
actions={[ actions={[
@ -132,6 +137,7 @@ export function RawMaterialVariantSubRow({
]} ]}
/> />
</TableCell> </TableCell>
)}
</TableRow> </TableRow>
)) ))
)} )}

View File

@ -20,7 +20,7 @@ export function createSupplierColumns(
): ColumnDef<Supplier>[] { ): ColumnDef<Supplier>[] {
const { handleEdit, handleDeleteClick, can } = params; const { handleEdit, handleDeleteClick, can } = params;
return [ const columns: ColumnDef<Supplier>[] = [
{ {
accessorKey: 'name', accessorKey: 'name',
header: () => <span>Nama</span>, header: () => <span>Nama</span>,
@ -46,7 +46,10 @@ export function createSupplierColumns(
</span> </span>
), ),
}, },
{ ];
if (can('suppliers.update') || can('suppliers.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -77,6 +80,8 @@ export function createSupplierColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -19,7 +19,7 @@ export function createRoleColumns(
): ColumnDef<Role>[] { ): ColumnDef<Role>[] {
const { handleEdit, handleDeleteClick, can } = params; const { handleEdit, handleDeleteClick, can } = params;
return [ const columns: ColumnDef<Role>[] = [
{ {
accessorKey: 'name', accessorKey: 'name',
header: () => <span>Nama Role</span>, header: () => <span>Nama Role</span>,
@ -44,7 +44,10 @@ export function createRoleColumns(
</span> </span>
), ),
}, },
{ ];
if (can('roles.update') || can('roles.delete')) {
columns.push({
id: 'actions', id: 'actions',
header: () => <span className="block text-center">Aksi</span>, header: () => <span className="block text-center">Aksi</span>,
meta: { meta: {
@ -75,6 +78,8 @@ export function createRoleColumns(
/> />
); );
}, },
}, });
]; }
return columns;
} }

View File

@ -45,8 +45,8 @@
Route::delete('products/{product}/variants/{variant}', [ProductVariantController::class, 'destroy'])->name('products.variants.destroy')->middleware('permission:products.delete'); Route::delete('products/{product}/variants/{variant}', [ProductVariantController::class, 'destroy'])->name('products.variants.destroy')->middleware('permission:products.delete');
Route::get('products/{product}/variants/{variant}/edit', [ProductVariantController::class, 'edit'])->name('products.variants.edit')->middleware('permission:products.update'); Route::get('products/{product}/variants/{variant}/edit', [ProductVariantController::class, 'edit'])->name('products.variants.edit')->middleware('permission:products.update');
Route::put('products/{product}/variants/{variant}', [ProductVariantController::class, 'update'])->name('products.variants.update')->middleware('permission:products.update'); Route::put('products/{product}/variants/{variant}', [ProductVariantController::class, 'update'])->name('products.variants.update')->middleware('permission:products.update');
Route::post('products/{product}/variants/{variant}/transfer-stock', [ProductVariantController::class, 'transferStock'])->name('products.variants.transfer-stock')->middleware('permission:products.update'); Route::post('products/{product}/variants/{variant}/transfer-stock', [ProductVariantController::class, 'transferStock'])->name('products.variants.transfer-stock')->middleware('permission:products.transfer_stock');
Route::get('products/{product}/variants/{variant}/stock-mutations', [StockMutationController::class, 'index'])->name('products.variants.stock-mutations')->middleware('permission:products.view'); Route::get('products/{product}/variants/{variant}/stock-mutations', [StockMutationController::class, 'index'])->name('products.variants.stock-mutations')->middleware('permission:products.view_stock_mutations');
Route::resource('raw-materials', RawMaterialController::class)->except(['show'])->middleware('permission:raw_materials.view|raw_materials.create|raw_materials.update|raw_materials.delete'); Route::resource('raw-materials', RawMaterialController::class)->except(['show'])->middleware('permission:raw_materials.view|raw_materials.create|raw_materials.update|raw_materials.delete');
Route::post('raw-materials/{rawMaterial}/toggle-status', [RawMaterialController::class, 'toggleStatus'])->name('raw-materials.toggle-status')->middleware('permission:raw_materials.toggle_status'); Route::post('raw-materials/{rawMaterial}/toggle-status', [RawMaterialController::class, 'toggleStatus'])->name('raw-materials.toggle-status')->middleware('permission:raw_materials.toggle_status');
@ -101,8 +101,8 @@
Route::post('employees/{user}/reset-password', [EmployeeController::class, 'resetPassword'])->name('employees.reset-password')->middleware('permission:employees.reset_password'); Route::post('employees/{user}/reset-password', [EmployeeController::class, 'resetPassword'])->name('employees.reset-password')->middleware('permission:employees.reset_password');
Route::get('attendances', [AttendanceController::class, 'index'])->name('attendances.index')->middleware('permission:attendances.view'); Route::get('attendances', [AttendanceController::class, 'index'])->name('attendances.index')->middleware('permission:attendances.view');
Route::post('attendances', [AttendanceController::class, 'store'])->name('attendances.store')->middleware('permission:attendances.manage'); Route::post('attendances', [AttendanceController::class, 'store'])->name('attendances.store')->middleware('permission:attendances.create');
Route::put('attendances/{attendance}', [AttendanceController::class, 'update'])->name('attendances.update')->middleware('permission:attendances.manage'); Route::put('attendances/{attendance}', [AttendanceController::class, 'update'])->name('attendances.update')->middleware('permission:attendances.create');
Route::get('attendances/by-date', [AttendanceController::class, 'byDate'])->name('attendances.by-date')->middleware('permission:attendances.view'); Route::get('attendances/by-date', [AttendanceController::class, 'byDate'])->name('attendances.by-date')->middleware('permission:attendances.view');
Route::resource('leave-requests', LeaveRequestController::class)->except(['show', 'create', 'edit'])->middleware('permission:leave_requests.view|leave_requests.create|leave_requests.update|leave_requests.delete'); Route::resource('leave-requests', LeaveRequestController::class)->except(['show', 'create', 'edit'])->middleware('permission:leave_requests.view|leave_requests.create|leave_requests.update|leave_requests.delete');