Skip to content

Latest commit

 

History

History
448 lines (386 loc) · 17.1 KB

06.md

File metadata and controls

448 lines (386 loc) · 17.1 KB

Pembuatan Laravel Inventory Management System 06 - manajemen stok menipis

mari kita implementasikan sistem notifikasi untuk stok menipis. Kita akan menggunakan Laravel Notifications.

Buat Notification Class

// app\Notifications\LowStockNotification.php
<?php

namespace App\Notifications;

use App\Models\Product;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\DatabaseMessage;

class LowStockNotification extends Notification
{
    use Queueable;

    protected $product;

    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    public function via($notifiable)
    {
        return ['database'];  // Simpan ke database
    }

    public function toDatabase($notifiable)
    {
        return [
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
            'current_stock' => $this->product->stock->quantity,
            'minimum_stock' => $this->product->stock->minimum_stock,
            'message' => "Stok {$this->product->name} sudah mencapai batas minimum"
        ];
    }
} 

Buat Migration untuk Notifications Table

// database\migrations\2024_01_01_000005_create_notifications_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('notifications', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('type');
            $table->morphs('notifiable');
            $table->text('data');
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('notifications');
    }
}; 

migrate

php artisan migrate:fresh --seed

Update StockController untuk Mengirim Notifikasi

// app\Http\Controllers\Inventory\StockController.php
<?php

namespace App\Http\Controllers\Inventory;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Notifications\LowStockNotification;
use App\Models\User;

class StockController extends Controller
{
    public function index()
    {
        $products = Product::with(['category', 'stock'])->paginate(10);
        return view('inventory.stock.index', compact('products'));
    }

    public function adjust(Product $product)
    {
        return view('inventory.stock.adjust', compact('product'));
    }

    public function update(Request $request, Product $product)
    {
        $request->validate([
            'type' => 'required|in:in,out',
            'quantity' => 'required|integer|min:1',
            'description' => 'required|string'
        ]);

        try {
            DB::beginTransaction();

            // Cek stok cukup jika pengurangan
            if ($request->type === 'out') {
                if ($product->stock->quantity < $request->quantity) {
                    return back()->with('error', 'Stok tidak mencukupi!');
                }
            }

            // Buat record stock movement
            StockMovement::create([
                'product_id' => $product->id,
                'type' => $request->type,
                'quantity' => $request->quantity,
                'description' => $request->description,
                'user_id' => auth()->id()
            ]);

            // Update stok produk
            $newQuantity = $request->type === 'in' 
                ? $product->stock->quantity + $request->quantity
                : $product->stock->quantity - $request->quantity;

            $product->stock->update(['quantity' => $newQuantity]);

            // Cek apakah stok sudah mencapai batas minimum
            if ($newQuantity <= $product->stock->minimum_stock) {
                // Kirim notifikasi ke semua admin
                User::role('admin')->each(function ($admin) use ($product) {
                    $admin->notify(new LowStockNotification($product));
                });
            }

            DB::commit();

            return redirect()->route('stock.index')
                ->with('success', 'Stok berhasil diperbarui');

        } catch (\Exception $e) {
            DB::rollback();
            return back()->with('error', 'Terjadi kesalahan saat memperbarui stok');
        }
    }

    public function history(Product $product)
    {
        $movements = StockMovement::with(['user'])
            ->where('product_id', $product->id)
            ->latest()
            ->paginate(10);

        return view('inventory.stock.history', compact('product', 'movements'));
    }
} 

Buat Controller untuk Notifikasi

// app\Http\Controllers\NotificationController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index()
    {
        $notifications = auth()->user()->notifications()->paginate(10);
        return view('notifications.index', compact('notifications'));
    }

    public function markAsRead($id)
    {
        $notification = auth()->user()->notifications()->findOrFail($id);
        $notification->markAsRead();
        
        return back()->with('success', 'Notifikasi ditandai sebagai telah dibaca');
    }

    public function markAllAsRead()
    {
        auth()->user()->unreadNotifications->markAsRead();
        
        return back()->with('success', 'Semua notifikasi ditandai sebagai telah dibaca');
    }
} 

Tambahkan Route untuk Notifikasi

// routes\web.php
<?php

use App\Http\Controllers\Dashboard\DashboardController;
use App\Http\Controllers\Inventory\StockController;
use App\Http\Controllers\NotificationController;

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return redirect()->route('dashboard');
});

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    
    // Tambahkan route untuk kategori
    Route::resource('categories', \App\Http\Controllers\Inventory\CategoryController::class);
    Route::resource('products', \App\Http\Controllers\Inventory\ProductController::class);
    
    // Stock Management Routes
    Route::get('/stock', [StockController::class, 'index'])->name('stock.index');
    Route::get('/stock/{product}/adjust', [StockController::class, 'adjust'])->name('stock.adjust');
    Route::post('/stock/{product}/update', [StockController::class, 'update'])->name('stock.update');
    Route::get('/stock/{product}/history', [StockController::class, 'history'])->name('stock.history');
    
    // Notification Routes
    Route::get('/notifications', [NotificationController::class, 'index'])->name('notifications.index');
    Route::post('/notifications/{id}/read', [NotificationController::class, 'markAsRead'])->name('notifications.markAsRead');
    Route::post('/notifications/read-all', [NotificationController::class, 'markAllAsRead'])->name('notifications.markAllAsRead');
});

Buat View untuk Notifikasi

// resources\views\notifications\index.blade.php
<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                {{ __('Notifikasi') }}
            </h2>
            @if(auth()->user()->unreadNotifications->count() > 0)
                <form action="{{ route('notifications.markAllAsRead') }}" method="POST">
                    @csrf
                    <button type="submit" class="bg-blue-500 hover:bg-blue-700 text-black font-bold py-2 px-4 rounded">
                        Tandai Semua Dibaca
                    </button>
                </form>
            @endif
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg p-6">
                @if($notifications->isEmpty())
                    <p class="text-gray-500 text-center py-4">Tidak ada notifikasi</p>
                @else
                    <div class="space-y-4">
                        @foreach($notifications as $notification)
                            <div class="flex items-center justify-between p-4 {{ $notification->read_at ? 'bg-gray-50' : 'bg-yellow-50' }} rounded-lg">
                                <div class="flex-1">
                                    <p class="text-gray-800">{{ $notification->data['message'] }}</p>
                                    <p class="text-sm text-gray-500">
                                        {{ $notification->created_at->diffForHumans() }}
                                    </p>
                                </div>
                                @if(!$notification->read_at)
                                    <form action="{{ route('notifications.markAsRead', $notification->id) }}" method="POST">
                                        @csrf
                                        <button type="submit" class="text-blue-600 hover:text-blue-800">
                                            Tandai Dibaca
                                        </button>
                                    </form>
                                @endif
                            </div>
                        @endforeach
                    </div>

                    <div class="mt-4">
                        {{ $notifications->links() }}
                    </div>
                @endif
            </div>
        </div>
    </div>
</x-app-layout> 

Update Navigation Menu untuk Menampilkan Jumlah Notifikasi

// resources\views\navigation-menu.blade.php
<nav x-data="{ open: false }" class="bg-white border-b border-gray-100">
    <!-- Primary Navigation Menu -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
            <div class="flex">
                <!-- Logo -->
                <div class="shrink-0 flex items-center">
                    <a href="{{ route('dashboard') }}">
                        <x-application-mark class="block h-9 w-auto" />
                    </a>
                </div>

                <!-- Navigation Links -->
                <div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
                    <x-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                        {{ __('Dashboard') }}
                    </x-nav-link>

                    <!-- Tambahkan Menu Kategori -->
                    <x-nav-link href="{{ route('categories.index') }}" :active="request()->routeIs('categories.*')">
                        {{ __('Kategori') }}
                    </x-nav-link>

                    <!-- Tambahkan Menu Produk -->
                    <x-nav-link href="{{ route('products.index') }}" :active="request()->routeIs('products.*')">
                        {{ __('Produk') }}
                    </x-nav-link>

                    <!-- Tambahkan Menu Stok -->
                    <x-nav-link href="{{ route('stock.index') }}" :active="request()->routeIs('stock.*')">
                        {{ __('Stok') }}
                    </x-nav-link>

                    <!-- Tambahkan Menu Notifikasi -->
                    <x-nav-link href="{{ route('notifications.index') }}" :active="request()->routeIs('notifications.*')" class="relative">
                        {{ __('Notifikasi') }}
                        @if(auth()->user()->unreadNotifications->count() > 0)
                            <span class="absolute -top-2 -right-2 bg-red-500 text-black text-xs rounded-full h-5 w-5 flex items-center justify-center">
                                {{ auth()->user()->unreadNotifications->count() }}
                            </span>
                        @endif
                    </x-nav-link>
                </div>
            </div>

            <!-- Settings Dropdown -->
            <div class="hidden sm:flex sm:items-center sm:ml-6">
                <x-dropdown align="right" width="48">
                    <x-slot name="trigger">
                        <button class="flex text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-gray-300 transition">
                            <img class="h-8 w-8 rounded-full object-cover" src="{{ Auth::user()->profile_photo_url }}" alt="{{ Auth::user()->name }}" />
                        </button>
                    </x-slot>

                    <x-slot name="content">
                        <!-- Account Management -->
                        <div class="block px-4 py-2 text-xs text-gray-400">
                            {{ __('Manage Account') }}
                        </div>

                        <x-dropdown-link href="{{ route('profile.show') }}">
                            {{ __('Profile') }}
                        </x-dropdown-link>

                        <!-- Authentication -->
                        <form method="POST" action="{{ route('logout') }}" x-data>
                            @csrf
                            <x-dropdown-link href="{{ route('logout') }}"
                                     @click.prevent="$root.submit();">
                                {{ __('Log Out') }}
                            </x-dropdown-link>
                        </form>
                    </x-slot>
                </x-dropdown>
            </div>

            <!-- Hamburger -->
            <div class="-mr-2 flex items-center sm:hidden">
                <button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition">
                    <svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
                        <path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                        <path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div>
        </div>
    </div>

    <!-- Responsive Navigation Menu -->
    <div :class="{'block': open, 'hidden': ! open}" class="hidden sm:hidden">
        <div class="pt-2 pb-3 space-y-1">
            <x-responsive-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                {{ __('Dashboard') }}
            </x-responsive-nav-link>

            <!-- Responsive Menu Kategori -->
            <x-responsive-nav-link href="{{ route('categories.index') }}" :active="request()->routeIs('categories.*')">
                {{ __('Kategori') }}
            </x-responsive-nav-link>

            <!-- Responsive Menu Produk -->
            <x-responsive-nav-link href="{{ route('products.index') }}" :active="request()->routeIs('products.*')">
                {{ __('Produk') }}
            </x-responsive-nav-link>

            <!-- Responsive Menu Stok -->
            <x-responsive-nav-link href="{{ route('stock.index') }}" :active="request()->routeIs('stock.*')">
                {{ __('Stok') }}
            </x-responsive-nav-link>

            <!-- Responsive Menu Notifikasi -->
            <x-responsive-nav-link href="{{ route('notifications.index') }}" :active="request()->routeIs('notifications.*')">
                {{ __('Notifikasi') }}
                @if(auth()->user()->unreadNotifications->count() > 0)
                    <span class="text-red-500">
                        {{ auth()->user()->unreadNotifications->count() }}
                    </span>
                @endif
            </x-responsive-nav-link>
        </div>

        <!-- Responsive Settings Options -->
        <div class="pt-4 pb-1 border-t border-gray-200">
            <div class="flex items-center px-4">
                <div class="shrink-0">
                    <img class="h-10 w-10 rounded-full" src="{{ Auth::user()->profile_photo_url }}" alt="{{ Auth::user()->name }}" />
                </div>

                <div class="ml-3">
                    <div class="font-medium text-base text-gray-800">{{ Auth::user()->name }}</div>
                    <div class="font-medium text-sm text-gray-500">{{ Auth::user()->email }}</div>
                </div>
            </div>

            <div class="mt-3 space-y-1">
                <!-- Account Management -->
                <x-responsive-nav-link href="{{ route('profile.show') }}" :active="request()->routeIs('profile.show')">
                    {{ __('Profile') }}
                </x-responsive-nav-link>

                <!-- Authentication -->
                <form method="POST" action="{{ route('logout') }}" x-data>
                    @csrf
                    <x-responsive-nav-link href="{{ route('logout') }}"
                                   @click.prevent="$root.submit();">
                        {{ __('Log Out') }}
                    </x-responsive-nav-link>
                </form>
            </div>
        </div>
    </div>
</nav>