commit pertama

This commit is contained in:
iblfzi 2026-07-28 13:00:53 +07:00
commit 0451bbf721
207 changed files with 23370 additions and 0 deletions

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

58
.env.example Normal file
View File

@ -0,0 +1,58 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

11
.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

18
.gitignore vendored Normal file
View File

@ -0,0 +1,18 @@
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode

11
.htaccess Normal file
View File

@ -0,0 +1,11 @@
DirectoryIndex public/index.php
<IfModule mod_rewrite.c>
RewriteEngine On
# Arahkan request ke folder public agar Laravel bisa berjalan dari root hosting.
RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

66
README.md Normal file
View File

@ -0,0 +1,66 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 2000 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Cubet Techno Labs](https://cubettech.com)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[Many](https://www.many.co.uk)**
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
- **[DevSquad](https://devsquad.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
- **[OP.GG](https://op.gg)**
- **[WebReinvent](https://webreinvent.com/?utm_source=laravel&utm_medium=github&utm_campaign=patreon-sponsors)**
- **[Lendio](https://lendio.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

32
app/Console/Kernel.php Normal file
View File

@ -0,0 +1,32 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AccountController extends Controller
{
public function index()
{
// Fetch all users including admins
$accounts = User::all();
// Fetch all branches
$allBranches = \App\Models\Branch::all();
// Get names of branches that already have an account
$usedBranchNames = User::whereNotNull('branch')->pluck('branch')->toArray();
return view('manajemen_akun', compact('accounts', 'allBranches', 'usedBranchNames'));
}
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255', 'regex:/^[a-zA-Z0-9\s]+$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users', 'regex:/^[a-z0-9._%+-]+@gmail\.com$/'],
'password' => 'required|string|min:8|max:12',
'branch' => 'required|string|unique:users,branch',
], [
'name.regex' => 'Nama lengkap hanya boleh berisi huruf, angka, dan spasi.',
'email.regex' => 'Email harus menggunakan huruf kecil dan diakhiri dengan @gmail.com',
'password.min' => 'Password minimal 8 karakter.',
'password.max' => 'Password maksimal 12 karakter.',
'branch.unique' => 'Cabang ini sudah memiliki akun terdaftar.',
]);
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => 'karyawan',
'branch' => $request->branch,
]);
return back()->with('success', 'Akun karyawan berhasil ditambahkan!');
}
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$request->validate([
'name' => ['required', 'string', 'max:255', 'regex:/^[a-zA-Z0-9\s]+$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$id, 'regex:/^[a-z0-9._%+-]+@gmail\.com$/'],
'branch' => 'required|string|unique:users,branch,'.$id,
], [
'name.regex' => 'Nama lengkap hanya boleh berisi huruf, angka, dan spasi.',
'email.regex' => 'Email harus menggunakan huruf kecil dan diakhiri dengan @gmail.com',
'branch.unique' => 'Cabang ini sudah memiliki akun terdaftar.',
]);
$data = [
'name' => $request->name,
'email' => strtolower($request->email),
'branch' => $request->branch,
];
if ($request->filled('password')) {
$request->validate([
'password' => 'string|min:8|max:12'
], [
'password.min' => 'Password minimal 8 karakter.',
'password.max' => 'Password maksimal 12 karakter.',
]);
$data['password'] = Hash::make($request->password);
}
$user->update($data);
return back()->with('success', 'Akun karyawan berhasil diperbarui!');
}
public function destroy($id)
{
$user = User::findOrFail($id);
// Prevent deleting the main admin if accidentally reached
if ($user->role === 'admin') {
return back()->with('error', 'Tidak dapat menghapus akun admin!');
}
$user->delete();
return back()->with('success', 'Akun karyawan berhasil dihapus!');
}
}

View File

View File

@ -0,0 +1,48 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function showLoginForm()
{
return view('login');
}
public function authenticate(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::attempt($credentials)) {
$user = Auth::user();
// Store in session for UI logic (matching previous behavior)
session(['role' => $user->role]);
session(['branch' => $user->branch]);
$request->session()->regenerate();
return redirect()->intended('/dashboard');
}
return back()->withErrors([
'email' => 'Email atau password salah.',
]);
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Branch;
class BranchController extends Controller
{
public function index()
{
$branches = Branch::orderBy('name')->get();
return view('branches', compact('branches'));
}
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|regex:/^[a-zA-Z0-9\s]+$/|unique:branches|max:255',
], [
'name.regex' => 'Nama cabang hanya boleh berisi huruf, angka, dan spasi.',
'name.unique' => 'Nama cabang ini sudah terdaftar.',
]);
Branch::create([
'name' => $request->name,
]);
return back()->with('success', 'Cabang baru berhasil ditambahkan!');
}
public function destroy($id)
{
$branch = Branch::findOrFail($id);
$branch->delete();
return back()->with('success', 'Cabang berhasil dihapus!');
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

View File

@ -0,0 +1,135 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Sale;
use App\Models\Purchase;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
class DashboardController extends Controller
{
public function index()
{
if (Auth::user()->role === 'admin') {
return redirect('/admin/dashboard');
}
$branch = Auth::user()->branch ?? 'Cabang 1';
$today = Carbon::today()->toDateString();
// 1. Total Penjualan Hari Ini (IDR)
$totalSalesToday = Sale::where('branch', $branch)
->whereDate('date', $today)
->sum('total_price');
// 2. Total Transaksi Hari Ini (Count)
$transactionCountToday = Sale::where('branch', $branch)
->whereDate('date', $today)
->count();
// 3. Total Pengeluaran Hari Ini (IDR) - From Purchases
$totalPurchasesToday = Purchase::where('branch', $branch)
->whereDate('date', $today)
->sum('total_price');
// 4. Aktivitas Terbaru
$recentSales = Sale::where('branch', $branch)
->latest()
->take(5)
->get()
->map(function ($item) {
$item->type = 'Penjualan';
$item->badge = 'badge-success';
return $item;
});
$recentPurchases = Purchase::where('branch', $branch)
->latest()
->take(5)
->get()
->map(function ($item) {
$item->type = 'Pembelian'; // Fixed from 'Pengeluaran' for consistency
$item->badge = 'badge-danger';
return $item;
});
$activities = $recentSales->concat($recentPurchases)
->sortByDesc('created_at')
->take(5);
return view('dashboard', compact(
'totalSalesToday',
'transactionCountToday',
'totalPurchasesToday',
'activities'
));
}
public function adminIndex()
{
if (Auth::user()->role !== 'admin') {
return redirect('/dashboard');
}
$today = Carbon::today()->toDateString();
// 1. Total Omzet Semua Cabang
$totalOmzetAll = Sale::whereDate('date', $today)->sum('total_price');
// 2. Total Pengeluaran Semua Cabang
$totalExpensesAll = Purchase::whereDate('date', $today)->sum('total_price');
// 3. Laba Bersih
$netProfit = $totalOmzetAll - $totalExpensesAll;
// 4. Cabang Aktif
$branchCount = 3; // Static as per current design or count unique branches
// 5. Rata-rata per Cabang
$averageSales = $branchCount > 0 ? $totalOmzetAll / $branchCount : 0;
// 6. Data Grafik Mingguan (7 hari terakhir)
$weeklyLabels = [];
$branch1Data = [];
$branch2Data = [];
$branch3Data = [];
for ($i = 6; $i >= 0; $i--) {
$date = Carbon::today()->subDays($i);
$weeklyLabels[] = $date->translatedFormat('D');
$branch1Data[] = Sale::where('branch', 'Cabang 1')->whereDate('date', $date->toDateString())->sum('total_price');
$branch2Data[] = Sale::where('branch', 'Cabang 2')->whereDate('date', $date->toDateString())->sum('total_price');
$branch3Data[] = Sale::where('branch', 'Cabang 3')->whereDate('date', $date->toDateString())->sum('total_price');
}
// 7. Omzet per Cabang (Untuk Bar Chart)
$branchOmzet = [
Sale::where('branch', 'Cabang 1')->sum('total_price'),
Sale::where('branch', 'Cabang 2')->sum('total_price'),
Sale::where('branch', 'Cabang 3')->sum('total_price'),
];
$branchProfit = [
$branchOmzet[0] - Purchase::where('branch', 'Cabang 1')->sum('total_price'),
$branchOmzet[1] - Purchase::where('branch', 'Cabang 2')->sum('total_price'),
$branchOmzet[2] - Purchase::where('branch', 'Cabang 3')->sum('total_price'),
];
return view('admin.dashboard', compact(
'totalOmzetAll',
'totalExpensesAll',
'netProfit',
'branchCount',
'averageSales',
'weeklyLabels',
'branch1Data',
'branch2Data',
'branch3Data',
'branchOmzet',
'branchProfit'
));
}
}

View File

@ -0,0 +1,429 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Sale;
use App\Models\Purchase;
use App\Models\Branch;
use App\Models\JournalEntry;
use App\Models\JournalDetail;
use App\Models\Stock;
class FinancialReportController extends Controller
{
public function profitAndLoss(Request $request)
{
// Define branches dynamically
$branches = Branch::pluck('name')->toArray();
if (empty($branches)) {
$branches = ['Cabang 1', 'Cabang 2', 'Cabang 3']; // Fallback
}
$month = $request->get('month');
$year = $request->get('year');
// 1. Data Gabungan
$jQuery = JournalDetail::with('journalEntry', 'account')
->whereHas('journalEntry', function($q) use ($month, $year) {
if ($month) $q->whereMonth('date', $month);
if ($year) $q->whereYear('date', $year);
});
$penjualan = (clone $jQuery)->whereHas('account', function($q) { $q->where('code', '401'); })->sum('credit');
$hpp = (clone $jQuery)->whereHas('account', function($q) { $q->where('code', '501'); })->sum('debit');
$labaKotor = $penjualan - $hpp;
$opCostsDetails = (clone $jQuery)->whereHas('account', function($q) { $q->where('code', '502'); })->get();
// Format to match existing view
$opCostsTotal = $opCostsDetails->map(function($d) {
$desc = str_replace('Biaya Operasional: ', '', $d->journalEntry->description);
return (object)[
'label' => $desc,
'branch' => $d->journalEntry->branch,
'amount' => $d->debit
];
});
$totalOpAmount = $opCostsTotal->sum('amount');
$labaBersih = $labaKotor - $totalOpAmount;
$dataTotal = [
'penjualan' => $penjualan,
'pembelian' => $hpp,
'laba_kotor' => $labaKotor,
'operational' => $opCostsTotal,
'total_operational' => $totalOpAmount,
'laba_bersih' => $labaBersih
];
// 2. Per Branch Data
$branchData = [];
foreach ($branches as $branch) {
$bJQuery = JournalDetail::with('journalEntry', 'account')
->whereHas('journalEntry', function($q) use ($month, $year, $branch) {
$q->where('branch', $branch);
if ($month) $q->whereMonth('date', $month);
if ($year) $q->whereYear('date', $year);
});
$bPenjualan = (clone $bJQuery)->whereHas('account', function($q) { $q->where('code', '401'); })->sum('credit');
$bHpp = (clone $bJQuery)->whereHas('account', function($q) { $q->where('code', '501'); })->sum('debit');
$bLabaKotor = $bPenjualan - $bHpp;
$bOpCostsDetails = (clone $bJQuery)->whereHas('account', function($q) { $q->where('code', '502'); })->get();
$bOpCostsTotal = $bOpCostsDetails->map(function($d) {
$desc = str_replace('Biaya Operasional: ', '', $d->journalEntry->description);
return (object)[
'label' => $desc,
'branch' => $d->journalEntry->branch,
'amount' => $d->debit
];
});
$bTotalOpAmount = $bOpCostsTotal->sum('amount');
$bLabaBersih = $bLabaKotor - $bTotalOpAmount;
$branchData[$branch] = [
'penjualan' => $bPenjualan,
'pembelian' => $bHpp,
'laba_kotor' => $bLabaKotor,
'operational' => $bOpCostsTotal,
'total_operational' => $bTotalOpAmount,
'laba_bersih' => $bLabaBersih
];
}
return view('neraca_laba_rugi', compact('dataTotal', 'branchData', 'branches'));
}
public function exportProfitAndLossPdf(Request $request)
{
$branches = Branch::pluck('name')->toArray();
if (empty($branches)) {
$branches = ['Cabang 1', 'Cabang 2', 'Cabang 3']; // Fallback
}
$month = $request->get('month');
$year = $request->get('year');
$branchFilter = $request->get('branch');
// Target branch calculation
$targetBranch = $branchFilter ?: 'Total Gabungan';
$jQuery = JournalDetail::with('journalEntry', 'account')
->whereHas('journalEntry', function($q) use ($month, $year, $branchFilter) {
if ($branchFilter && $branchFilter !== 'Total Gabungan') {
$q->where('branch', $branchFilter);
}
if ($month) $q->whereMonth('date', $month);
if ($year) $q->whereYear('date', $year);
});
$penjualan = (clone $jQuery)->whereHas('account', function($q) { $q->where('code', '401'); })->sum('credit');
$hpp = (clone $jQuery)->whereHas('account', function($q) { $q->where('code', '501'); })->sum('debit');
$labaKotor = $penjualan - $hpp;
$opCostsDetails = (clone $jQuery)->whereHas('account', function($q) { $q->where('code', '502'); })->get();
// Format to match existing view expectation
$opCostsTotalData = $opCostsDetails->map(function($d) {
$desc = str_replace('Biaya Operasional: ', '', $d->journalEntry->description);
return (object)[
'label' => $desc,
'branch' => $d->journalEntry->branch,
'amount' => $d->debit
];
});
$totalOpAmount = $opCostsTotalData->sum('amount');
$labaBersih = $labaKotor - $totalOpAmount;
$data = [
'penjualan' => $penjualan,
'pembelian' => $hpp,
'laba_kotor' => $labaKotor,
'operational' => $opCostsTotalData,
'total_operational' => $totalOpAmount,
'laba_bersih' => $labaBersih,
'branch' => $targetBranch,
'month' => $month,
'year' => $year
];
$pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('reports.neraca_laba_rugi_pdf', $data);
return $pdf->download('laporan_neraca_laba_rugi_' . date('Y-m-d') . '.pdf');
}
public function generalLedger()
{
$branches = Branch::pluck('name')->toArray();
if (empty($branches)) {
$branches = ['Cabang 1', 'Cabang 2', 'Cabang 3']; // Fallback
}
// 1. Total Gabungan
// Filter only 'Kas' account (101) to match existing simplified Ledger layout
$kasDetails = JournalDetail::whereHas('account', function($q) {
$q->where('code', '101');
})->with('journalEntry')->get();
$transactionsTotal = $kasDetails->map(function($d) {
return [
'date' => $d->journalEntry->date,
'account' => 'Kas',
'desc' => $d->journalEntry->description,
'debit' => $d->debit,
'credit' => $d->credit
];
});
// Initial Balance dari nilai stok saat ini
$initialBalance = $this->calculateModalFromStock();
$ledgerTotal = $this->processLedger($transactionsTotal, $initialBalance, 'Modal dari Stok');
// 2. Per Branch
$branchLedgers = [];
foreach ($branches as $branch) {
$initialBranchBalance = $this->calculateModalFromStock($branch);
$bKasDetails = JournalDetail::whereHas('account', function($q) {
$q->where('code', '101');
})->whereHas('journalEntry', function($q) use ($branch) {
$q->where('branch', $branch);
})->with('journalEntry')->get();
$bTransactions = $bKasDetails->map(function($d) {
return [
'date' => $d->journalEntry->date,
'account' => 'Kas',
'desc' => $d->journalEntry->description,
'debit' => $d->debit,
'credit' => $d->credit
];
});
$branchLedgers[$branch] = $this->processLedger($bTransactions, $initialBranchBalance, 'Modal dari Stok ' . $branch);
}
return view('buku_besar', compact('ledgerTotal', 'branchLedgers', 'branches'));
}
private function processLedger($transactions, $initialBalance, $initialDesc)
{
$ledger = collect();
// Add Initial Transaction
$ledger->push([
'date' => '2025-09-01', // Example date matching mockup
'account' => 'Kas',
'desc' => $initialDesc,
'debit' => $initialBalance,
'credit' => 0,
'balance' => $initialBalance
]);
$sortedTrans = $transactions->sortBy('date');
$currentBalance = $initialBalance;
foreach ($sortedTrans as $t) {
$currentBalance += $t['debit'];
$currentBalance -= $t['credit'];
$ledger->push([
'date' => $t['date'],
'account' => $t['account'],
'desc' => $t['desc'],
'debit' => $t['debit'],
'credit' => $t['credit'],
'balance' => $currentBalance
]);
}
return $ledger;
}
public function generalJournal()
{
$branches = Branch::pluck('name')->toArray();
if (empty($branches)) {
$branches = ['Cabang 1', 'Cabang 2', 'Cabang 3']; // Fallback
}
// 1. Total Gabungan
$journalTotal = collect();
$details = JournalDetail::with('journalEntry', 'account')
->join('journal_entries', 'journal_details.journal_entry_id', '=', 'journal_entries.id')
->orderBy('journal_entries.date')
->orderBy('journal_entries.id')
->orderBy('journal_details.credit') // debit first
->select('journal_details.*')
->get();
foreach($details as $d) {
$journalTotal->push([
'date' => $d->journalEntry->date,
'desc' => $d->credit > 0 ? ' ' . $d->account->name : $d->account->name,
'reff' => $d->account->code,
'debit' => $d->debit,
'credit' => $d->credit
]);
}
// 2. Per Branch Data
$branchJournals = [];
foreach ($branches as $branch) {
$journal = collect();
$bDetails = JournalDetail::with('journalEntry', 'account')
->join('journal_entries', 'journal_details.journal_entry_id', '=', 'journal_entries.id')
->where('journal_entries.branch', $branch)
->orderBy('journal_entries.date')
->orderBy('journal_entries.id')
->orderBy('journal_details.credit') // debit first
->select('journal_details.*')
->get();
foreach($bDetails as $d) {
$journal->push([
'date' => $d->journalEntry->date,
'desc' => $d->credit > 0 ? ' ' . $d->account->name : $d->account->name,
'reff' => $d->account->code,
'debit' => $d->debit,
'credit' => $d->credit
]);
}
$branchJournals[$branch] = $journal;
}
return view('jurnal_umum', compact('journalTotal', 'branchJournals', 'branches'));
}
public function equityStatement(Request $request)
{
$branches = Branch::pluck('name')->toArray();
if (empty($branches)) $branches = ['Cabang 1', 'Cabang 2', 'Cabang 3'];
// Laba Bersih = Penjualan (401) - HPP (501) - Biaya (502)
$penjualan = JournalDetail::whereHas('account', function($q) { $q->where('code', '401'); })->sum('credit');
$hpp = JournalDetail::whereHas('account', function($q) { $q->where('code', '501'); })->sum('debit');
$biaya = JournalDetail::whereHas('account', function($q) { $q->where('code', '502'); })->sum('debit');
$labaBersih = $penjualan - $hpp - $biaya;
// Modal berasal dari nilai stok saat ini berdasarkan biaya perolehan (harga beli),
// karena sistem belum punya akun modal nyata.
$modalAwal = $this->calculateModalFromStock();
$modalAkhir = $modalAwal + $labaBersih;
$data = [
'modal_awal' => $modalAwal,
'laba_bersih' => $labaBersih,
'prive' => 0,
'modal_akhir' => $modalAkhir
];
return view('perubahan_modal', compact('data', 'branches'));
}
public function balanceSheet(Request $request)
{
$branches = Branch::pluck('name')->toArray();
if (empty($branches)) $branches = ['Cabang 1', 'Cabang 2', 'Cabang 3'];
// Assets
$kas = JournalDetail::whereHas('account', function($q) { $q->where('code', '101'); })->sum('debit') - JournalDetail::whereHas('account', function($q) { $q->where('code', '101'); })->sum('credit');
// Persediaan dari journal (Debit = Awal Persediaan, Credit = Penjualan HPP)
$persediaan = JournalDetail::whereHas('account', function($q) { $q->where('code', '102'); })->sum('debit') - JournalDetail::whereHas('account', function($q) { $q->where('code', '102'); })->sum('credit');
$totalAset = $kas + $persediaan;
// Liabilities
$hutang = 0; // We don't have liability accounts seeded yet
// Equity
$penjualan = JournalDetail::whereHas('account', function($q) { $q->where('code', '401'); })->sum('credit');
$hpp = JournalDetail::whereHas('account', function($q) { $q->where('code', '501'); })->sum('debit');
$biaya = JournalDetail::whereHas('account', function($q) { $q->where('code', '502'); })->sum('debit');
$labaBersih = $penjualan - $hpp - $biaya;
// Modal berasal dari nilai stok saat ini berdasarkan biaya perolehan (harga beli),
// karena sistem belum punya akun modal nyata.
$modalAwal = $this->calculateModalFromStock();
$modalAkhir = $modalAwal + $labaBersih;
$totalPasiva = $hutang + $modalAkhir;
$data = [
'kas' => $kas,
'persediaan' => $persediaan,
'total_aset' => $totalAset,
'hutang' => $hutang,
'modal_akhir' => $modalAkhir,
'total_pasiva' => $totalPasiva
];
return view('neraca_keuangan', compact('data', 'branches'));
}
private function calculateModalFromStock($branch = null)
{
$query = Stock::query()->with('product');
if ($branch) {
$query->where('branch', $branch);
}
return (float) $query->get()->sum(function ($stock) {
$product = $stock->product;
if (!$product) {
return 0;
}
$quantity = (float) $stock->quantity;
$purchasePrice = (float) $product->purchase_price;
return $quantity > 0 ? $quantity * $purchasePrice : 0;
});
}
public function cashFlow(Request $request)
{
$branches = Branch::pluck('name')->toArray();
if (empty($branches)) $branches = ['Cabang 1', 'Cabang 2', 'Cabang 3'];
// Penerimaan dari Penjualan (Debit Kas dari Jurnal Penjualan)
$penerimaanPenjualan = JournalDetail::whereHas('account', function($q) { $q->where('code', '101'); })
->whereHas('journalEntry', function($q) { $q->where('reference_type', 'Sale'); })->sum('debit');
// Pengeluaran Pembelian (Kredit Kas dari Pembelian)
$pengeluaranPembelian = JournalDetail::whereHas('account', function($q) { $q->where('code', '101'); })
->whereHas('journalEntry', function($q) { $q->where('reference_type', 'Purchase'); })->sum('credit');
// Pengeluaran Biaya Operasional (Kredit Kas dari Biaya Operasional)
$pengeluaranOperasional = JournalDetail::whereHas('account', function($q) { $q->where('code', '101'); })
->whereHas('journalEntry', function($q) { $q->where('reference_type', 'OperationalCost'); })->sum('credit');
// Modal berasal dari stok, sehingga tidak ada setoran modal terpisah dalam arus kas
$setoranModal = 0;
$arusKasOperasi = $penerimaanPenjualan - $pengeluaranPembelian - $pengeluaranOperasional;
$arusKasPendanaan = $setoranModal;
$kenaikanKas = $arusKasOperasi + $arusKasPendanaan;
// Saldo Kas Akhir
$saldoKas = JournalDetail::whereHas('account', function($q) { $q->where('code', '101'); })->sum('debit') - JournalDetail::whereHas('account', function($q) { $q->where('code', '101'); })->sum('credit');
$data = [
'penerimaan_penjualan' => $penerimaanPenjualan,
'pengeluaran_pembelian' => $pengeluaranPembelian,
'pengeluaran_operasional' => $pengeluaranOperasional,
'arus_kas_operasi' => $arusKasOperasi,
'setoran_modal' => $setoranModal,
'arus_kas_pendanaan' => $arusKasPendanaan,
'kenaikan_kas' => $kenaikanKas,
'saldo_kas' => $saldoKas
];
return view('arus_kas', compact('data', 'branches'));
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\OperationalCost;
use App\Models\Branch;
use App\Models\JournalEntry;
use App\Models\JournalDetail;
use App\Models\Account;
class OperationalCostController extends Controller
{
public function index(Request $request)
{
$query = OperationalCost::orderBy('date', 'desc');
if ($request->filled('month')) {
$query->whereMonth('date', $request->month);
}
if ($request->filled('year')) {
$query->whereYear('date', $request->year);
}
if ($request->filled('branch') && $request->branch != 'Semua Cabang') {
$query->where('branch', $request->branch);
}
$costs = $query->get();
$branches = Branch::all();
$labels = OperationalCost::select('label')->distinct()->pluck('label');
return view('biaya_operasional', compact('costs', 'branches', 'labels'));
}
public function store(Request $request)
{
$request->validate([
'date' => 'required|date',
'branch' => 'required|string|max:255',
'label' => 'required|string|max:255',
'amount' => 'required|numeric|min:0',
]);
$cleanAmount = str_replace('.', '', $request->amount);
\Illuminate\Support\Facades\DB::transaction(function () use ($request, $cleanAmount) {
$cost = OperationalCost::create([
'date' => $request->date,
'branch' => $request->branch,
'label' => $request->label,
'amount' => (int) $cleanAmount,
]);
$kasAccount = Account::where('code', '101')->first();
$bebanAccount = Account::where('code', '502')->first();
if ($kasAccount && $bebanAccount) {
$journal = JournalEntry::create([
'date' => $cost->date,
'description' => 'Biaya Operasional: ' . $cost->label,
'reference_type' => 'OperationalCost',
'reference_id' => $cost->id,
'branch' => $cost->branch,
]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $bebanAccount->id, 'debit' => $cost->amount, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => 0, 'credit' => $cost->amount]);
}
});
return back()->with('success', 'Biaya operasional berhasil ditambahkan!');
}
public function update(Request $request, $id)
{
$request->validate([
'date' => 'required|date',
'branch' => 'required|string|max:255',
'label' => 'required|string|max:255',
'amount' => 'required|numeric|min:0',
]);
$cleanAmount = str_replace('.', '', $request->amount);
\Illuminate\Support\Facades\DB::transaction(function () use ($request, $id, $cleanAmount) {
$cost = OperationalCost::findOrFail($id);
$cost->update([
'date' => $request->date,
'branch' => $request->branch,
'label' => $request->label,
'amount' => (int) $cleanAmount,
]);
JournalEntry::where('reference_type', 'OperationalCost')->where('reference_id', $cost->id)->delete();
$kasAccount = Account::where('code', '101')->first();
$bebanAccount = Account::where('code', '502')->first();
if ($kasAccount && $bebanAccount) {
$journal = JournalEntry::create([
'date' => $cost->date,
'description' => 'Biaya Operasional: ' . $cost->label,
'reference_type' => 'OperationalCost',
'reference_id' => $cost->id,
'branch' => $cost->branch,
]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $bebanAccount->id, 'debit' => $cost->amount, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => 0, 'credit' => $cost->amount]);
}
});
return back()->with('success', 'Biaya operasional berhasil diperbarui!');
}
public function destroy($id)
{
$cost = OperationalCost::findOrFail($id);
JournalEntry::where('reference_type', 'OperationalCost')->where('reference_id', $cost->id)->delete();
$cost->delete();
return back()->with('success', 'Biaya operasional berhasil dihapus!');
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Carbon\Carbon;
class PasswordResetController extends Controller
{
public function showLinkRequestForm()
{
return view('auth.forgot-password');
}
public function sendResetLinkEmail(Request $request)
{
$request->validate(['email' => 'required|email']);
$user = User::where('email', $request->email)->first();
// Cek jika akun ada
if (!$user) {
return back()->withErrors(['email' => 'Email tidak ditemukan']);
}
// Syarat utama: HANYA Admin yang boleh melakukan reset
if ($user->role !== 'admin') {
return back()->withErrors(['email' => 'Fitur Lupa Password HANYA tersedia untuk Admin. Karyawan harap menghubungi Admin.']);
}
// Generate token
$token = Str::random(60);
// Hapus token lama jika ada, lalu insert yang baru (menyederhanakan karena kita bisa pakai insert)
DB::table('password_resets')->where('email', $user->email)->delete();
DB::table('password_resets')->insert([
'email' => $user->email,
'token' => Hash::make($token),
'created_at' => Carbon::now()
]);
// Buat link reset
$resetUrl = url('/reset-password/' . $token . '?email=' . urlencode($user->email));
// Mengirim Email
// Pastikan driver mail di-set ke 'log' pada .env agar bisa dilihat di storage/logs/laravel.log pada local environment.
Mail::raw("Halo Admin,\n\nSilakan klik tautan di bawah ini untuk mereset kata sandi akun Anda:\n{$resetUrl}\n\nJika Anda tidak merasa mengajukan permintaan ini, mohon abaikan pesan ini.", function ($message) use ($user) {
$message->to($user->email)
->subject('Reset Password Sistem Akuntansi Cak Imin');
});
return back()->with('status', 'Link reset password telah dikirim ke email Anda. Silakan cek inbox/spam Anda.');
}
public function showResetForm($token, Request $request)
{
return view('auth.reset-password', ['token' => $token, 'email' => $request->email]);
}
public function reset(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required|min:6|confirmed',
'token' => 'required'
]);
// Verifikasi token
$resetRecord = DB::table('password_resets')->where('email', $request->email)->first();
if (!$resetRecord || !Hash::check($request->token, $resetRecord->token)) {
return back()->withErrors(['token' => 'Token reset kadaluarsa atau tidak valid. Harap minta kembali link reset.']);
}
// Verifikasi User Admin
$user = User::where('email', $request->email)->first();
if (!$user || $user->role !== 'admin') {
return back()->withErrors(['email' => 'Akses ditolak. Fitur reset hanya dapat diakses oleh Admin.']);
}
// Update Password
$user->password = Hash::make($request->password);
$user->save();
// Hapus Token Reset
DB::table('password_resets')->where('email', $request->email)->delete();
return redirect('/login')->with('success', 'Berhasil! Kata sandi telah diubah. Silakan masuk menggunakan kata sandi baru.');
}
}

View File

@ -0,0 +1,435 @@
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Stock;
use App\Models\Sale;
class ProductController extends Controller
{
public function index(Request $request)
{
// If user is karyawan, use karyawanIndex logic
if (auth()->user()->role !== 'admin') {
return $this->karyawanIndex($request);
}
$branches = \App\Models\Branch::all();
$selectedBranch = $request->input('branch', 'Total Gabungan');
$query = Product::with(['stocks', 'recipes.rawMaterial']);
if (auth()->user()->role !== 'admin') {
$query->where('branch', auth()->user()->branch ?? 'Cabang 1');
} elseif ($selectedBranch && $selectedBranch !== 'Total Gabungan') {
$query->where('branch', $selectedBranch);
}
if ($request->filled('search')) {
$query->where(function($q) use ($request) {
$q->where('name', 'like', '%' . $request->search . '%')
->orWhere('category', 'like', '%' . $request->search . '%');
});
}
$products = $query->get();
$selectedRawMaterialBranch = $request->input('raw_material_branch', 'Total Gabungan');
$rawMaterialsQuery = \App\Models\RawMaterial::query();
if ($selectedRawMaterialBranch && $selectedRawMaterialBranch !== 'Total Gabungan') {
$rawMaterialsQuery->where('branch', $selectedRawMaterialBranch);
}
$rawMaterials = $rawMaterialsQuery->get();
return view('produk', compact('products', 'branches', 'selectedBranch', 'rawMaterials', 'selectedRawMaterialBranch'));
}
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'category' => 'required|in:makanan,minuman,snack',
'purchase_price' => 'required|integer',
'selling_price' => 'required|integer',
'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$data = $request->all();
$branch = auth()->user()->branch ?? 'Cabang 1';
$data['branch'] = $branch;
// Unique name check per branch
$exists = Product::whereRaw('LOWER(name) = ?', [strtolower($request->name)])
->where('branch', $branch)
->exists();
if ($exists) {
return back()->withInput()->withErrors(['duplicate_error' => 'Produk dengan nama "' . $request->name . '" sudah ada di ' . $branch . '.']);
}
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $file->getClientOriginalName());
$destination = public_path('images/produk');
if (!file_exists($destination)) {
mkdir($destination, 0775, true);
}
$file->move($destination, $filename);
$data['image'] = '/images/produk/' . $filename;
}
$product = Product::create($data);
// Save Recipes if any
if ($request->has('recipes') && is_array($request->recipes)) {
foreach ($request->recipes as $recipeData) {
if (isset($recipeData['raw_material_id']) && isset($recipeData['quantity_needed']) && $recipeData['quantity_needed'] !== '') {
// Parse quantity string to allow '300 ml', '0.5', '300'
$parsed = $this->parseQuantity($recipeData['quantity_needed']);
$rm = \App\Models\RawMaterial::find($recipeData['raw_material_id']);
$quantityToStore = $parsed['value'];
// If unit provided and differs from raw material unit, try to convert
if ($parsed['unit'] && $rm) {
$quantityToStore = $this->convertRecipeToRawMaterialUnit($parsed['value'], $parsed['unit'], $rm->unit);
}
\App\Models\ProductRecipe::create([
'product_id' => $product->id,
'raw_material_id' => $recipeData['raw_material_id'],
'quantity_needed' => $quantityToStore,
]);
}
}
// Recalculate stock based on raw materials
$this->recalculateProductsFromRawMaterials($product->id, $branch);
}
// Create initial stock for THIS branch only
\App\Models\Stock::create([
'product_id' => $product->id,
'branch' => $branch,
'quantity' => 0,
'unit' => 'Pcs',
]);
return back()->with('success', 'Produk Master berhasil ditambahkan!');
}
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required|string|max:255',
'category' => 'required|in:makanan,minuman,snack',
'purchase_price' => 'required|integer',
'selling_price' => 'required|integer',
'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$product = Product::findOrFail($id);
$branch = auth()->user()->branch ?? 'Cabang 1';
// Only allow update if product belongs to user's branch
if ($product->branch !== $branch) {
return back()->with('error', 'Anda tidak memiliki akses untuk mengubah produk dari cabang lain.');
}
// Unique name check for update per branch
$exists = Product::whereRaw('LOWER(name) = ?', [strtolower($request->name)])
->where('branch', $branch)
->where('id', '!=', $id)
->exists();
if ($exists) {
return back()->withInput()->withErrors(['duplicate_error' => 'Produk dengan nama "' . $request->name . '" sudah ada di ' . $branch . '.']);
}
$data = $request->only(['name', 'category', 'purchase_price', 'selling_price']);
if ($request->hasFile('image')) {
// Delete old image if it exists in our public/images/produk directory
if ($product->image && str_contains($product->image, '/images/produk/')) {
$oldFile = public_path($product->image);
if (file_exists($oldFile)) {
unlink($oldFile);
}
}
// Also handle old images stored via storage symlink
if ($product->image && str_contains($product->image, '/storage/produk/')) {
$oldPath = str_replace('/storage/', '', $product->image);
Storage::disk('public')->delete($oldPath);
}
$file = $request->file('image');
$filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $file->getClientOriginalName());
$destination = public_path('images/produk');
if (!file_exists($destination)) {
mkdir($destination, 0775, true);
}
$file->move($destination, $filename);
$data['image'] = '/images/produk/' . $filename;
}
$product->update($data);
// Update Recipes
\App\Models\ProductRecipe::where('product_id', $product->id)->delete();
if ($request->has('recipes') && is_array($request->recipes)) {
foreach ($request->recipes as $recipeData) {
if (isset($recipeData['raw_material_id']) && isset($recipeData['quantity_needed']) && $recipeData['quantity_needed'] !== '') {
$parsed = $this->parseQuantity($recipeData['quantity_needed']);
$rm = \App\Models\RawMaterial::find($recipeData['raw_material_id']);
$quantityToStore = $parsed['value'];
if ($parsed['unit'] && $rm) {
$quantityToStore = $this->convertRecipeToRawMaterialUnit($parsed['value'], $parsed['unit'], $rm->unit);
}
\App\Models\ProductRecipe::create([
'product_id' => $product->id,
'raw_material_id' => $recipeData['raw_material_id'],
'quantity_needed' => $quantityToStore,
]);
}
}
// Recalculate stock based on raw materials
$this->recalculateProductsFromRawMaterials($product->id, $branch);
}
return back()->with('success', 'Produk berhasil diperbarui!');
}
public function destroy($id)
{
$product = Product::findOrFail($id);
$branch = auth()->user()->branch ?? 'Cabang 1';
// Only allow deletion if product belongs to user's branch
if ($product->branch !== $branch) {
return back()->with('error', 'Anda tidak memiliki akses untuk menghapus produk dari cabang lain.');
}
$product->delete();
return back()->with('success', 'Produk berhasil dihapus!');
}
// Karyawan: lihat produk dengan stok per cabang dan catat penjualan sederhana
public function karyawanIndex(Request $request)
{
$branch = auth()->user()->branch ?? 'Cabang 1';
$query = Product::with(['stocks' => function($q) use ($branch) {
$q->where('branch', $branch);
}, 'recipes.rawMaterial'])->where('branch', $branch);
if ($request->filled('search')) {
$query->where('name', 'like', '%' . $request->search . '%')
->orWhere('category', 'like', '%' . $request->search . '%');
}
$products = $query->get();
$rawMaterials = \App\Models\RawMaterial::where('branch', $branch)->get();
return view('produk_karyawan', compact('products', 'branch', 'rawMaterials'));
}
public function sell(Request $request, $id)
{
$request->validate([
'quantity' => 'required|integer|min:1'
]);
$branch = auth()->user()->branch ?? 'Cabang 1';
$qty = (int) $request->input('quantity');
$product = Product::with('recipes.rawMaterial')->findOrFail($id);
if ($product->recipes->count() > 0) {
// Check raw material stock first
foreach ($product->recipes as $recipe) {
$rm = $recipe->rawMaterial;
if (!$rm) continue;
$needed = $recipe->quantity_needed * $qty;
if ($rm->stock_quantity < $needed) {
return back()->withErrors(['stock' => 'Bahan baku tidak cukup untuk membuat ' . $qty . ' porsi.']);
}
}
// Deduct raw materials
foreach ($product->recipes as $recipe) {
$rm = $recipe->rawMaterial;
if ($rm) {
$rm->stock_quantity -= ($recipe->quantity_needed * $qty);
$rm->save();
// Optional: recalculate other products that depend on this raw material
$this->recalculateProductsFromRawMaterial($rm->id, $branch);
}
}
} else {
// Deduct from regular stock
$stock = Stock::where('product_id', $id)->where('branch', $branch)->first();
if (!$stock) {
return back()->withErrors(['stock' => 'Stok untuk produk ini tidak ditemukan pada cabang Anda.']);
}
if ($stock->quantity < $qty) {
return back()->withErrors(['stock' => 'Stok tidak cukup. Tersedia: ' . $stock->quantity]);
}
// Kurangi stok
$stock->quantity = $stock->quantity - $qty;
$stock->save();
}
// Catat penjualan sederhana
Sale::create([
'date' => now()->toDateString(),
'branch' => $branch,
'product_id' => $product->id,
'item' => $product->name,
'quantity' => $qty,
'total_price' => ($product->selling_price ?? 0) * $qty,
]);
return back()->with('success', 'Penjualan berhasil dicatat dan stok diperbarui.');
}
private function recalculateProductsFromRawMaterials($productId, $branch)
{
$product = \App\Models\Product::with('recipes.rawMaterial')->find($productId);
if (!$product || $product->recipes->isEmpty()) {
return;
}
$minStock = null;
foreach ($product->recipes as $recipe) {
$rm = $recipe->rawMaterial;
if (!$rm || $recipe->quantity_needed <= 0) {
continue;
}
$possibleAmount = floor($rm->stock_quantity / $recipe->quantity_needed);
if ($minStock === null || $possibleAmount < $minStock) {
$minStock = $possibleAmount;
}
}
if ($minStock !== null && $minStock >= 0) {
$stock = \App\Models\Stock::firstOrCreate(
['product_id' => $productId, 'branch' => $branch],
['quantity' => 0, 'unit' => 'Pcs']
);
$stock->quantity = $minStock;
$stock->save();
}
}
// Parse quantity strings used in recipe inputs (e.g. '300 ml', '0.5', '300')
private function parseQuantity($quantityStr)
{
$quantityStr = trim((string)$quantityStr);
if (preg_match('/^([\d.,]+)\s*(.*)$/', $quantityStr, $m)) {
$value = floatval(str_replace(',', '.', $m[1]));
$unit = strtolower(trim($m[2]));
return ['value' => $value, 'unit' => $unit];
}
return ['value' => floatval($quantityStr), 'unit' => ''];
}
// Convert a recipe quantity with unit into the raw material's unit if possible
private function convertRecipeToRawMaterialUnit($value, $fromUnit, $toUnit)
{
$from = strtolower(trim($fromUnit));
$to = strtolower(trim($toUnit));
// If same unit or no fromUnit, return value as-is
if (!$from || $from === $to) return $value;
// Basic conversions: liters <-> ml, kilogram <-> gram
$mapping = [
'l' => ['ml' => 1000, 'liter' => 1000],
'liter' => ['ml' => 1000, 'l' => 1],
'ml' => ['l' => 1/1000, 'liter' => 1/1000],
'kg' => ['g' => 1000, 'kilogram' => 1000],
'kilogram' => ['g' => 1000, 'kg' => 1],
'g' => ['kg' => 1/1000, 'gram' => 1/1000],
'gram' => ['kg' => 1/1000, 'g' => 1],
];
// Normalize tokens
$aliases = [
'grams' => 'g', 'gram' => 'g', 'gr' => 'g',
'milliliter' => 'ml', 'mililiter' => 'ml',
'litre' => 'l', 'liters' => 'l', 'liter' => 'l',
'kilograms' => 'kg', 'kilogram' => 'kg',
'pcs' => 'pcs', 'piece' => 'pcs', 'pc' => 'pcs',
'botol' => 'botol'
];
$fromNorm = $aliases[$from] ?? $from;
$toNorm = $aliases[$to] ?? $to;
// If one is pcs and other is numeric unit, do not convert automatically
if (($fromNorm === 'pcs' && $toNorm !== 'pcs') || ($toNorm === 'pcs' && $fromNorm !== 'pcs')) {
return $value;
}
if (isset($mapping[$fromNorm]) && isset($mapping[$fromNorm][$toNorm])) {
return $value * $mapping[$fromNorm][$toNorm];
}
// If direct mapping not found, try inverse
if (isset($mapping[$toNorm]) && isset($mapping[$toNorm][$fromNorm])) {
return $value / $mapping[$toNorm][$fromNorm];
}
return $value;
}
private function recalculateProductsFromRawMaterial($rawMaterialId, $branch)
{
$recipes = \App\Models\ProductRecipe::where('raw_material_id', $rawMaterialId)
->whereHas('product', function($q) use ($branch) {
$q->where('branch', $branch);
})->get();
foreach ($recipes as $recipe) {
$product = clone $recipe->product;
$minStock = null;
foreach ($product->recipes as $prodRecipe) {
$rm = $prodRecipe->rawMaterial;
$possibleAmount = floor($rm->stock_quantity / $prodRecipe->quantity_needed);
if ($minStock === null || $possibleAmount < $minStock) {
$minStock = $possibleAmount;
}
}
if ($minStock !== null) {
$stock = \App\Models\Stock::firstOrCreate(
['product_id' => $product->id, 'branch' => $branch],
['quantity' => 0, 'unit' => 'Pcs']
);
$stock->quantity = $minStock;
$stock->save();
}
}
}
public function updateStock(Request $request, $id)
{
$request->validate([
'quantity' => 'required|integer'
]);
$branch = auth()->user()->branch ?? 'Cabang 1';
$stock = Stock::where('product_id', $id)->where('branch', $branch)->first();
if (!$stock) {
return back()->withErrors(['stock' => 'Stok untuk produk ini tidak ditemukan pada cabang Anda.']);
}
$stock->quantity += (int)$request->input('quantity');
if ($stock->quantity < 0) $stock->quantity = 0;
$stock->save();
return back()->with('success', 'Stok berhasil diperbarui.');
}
}

View File

@ -0,0 +1,473 @@
<?php
namespace App\Http\Controllers;
use App\Models\Purchase;
use App\Models\JournalEntry;
use App\Models\JournalDetail;
use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PurchaseController extends Controller
{
public function index(Request $request)
{
$user = Auth::user();
$branches = \App\Models\Branch::all();
$branch = $user->branch ?? 'Cabang 1';
$query = Purchase::with('product')->orderBy('date', 'desc');
if ($request->filled('year')) {
$query->whereYear('date', $request->year);
}
if ($request->filled('month')) {
$query->whereMonth('date', $request->month);
}
if ($request->filled('day')) {
$query->whereDay('date', $request->day);
}
if ($request->filled('search')) {
$query->where('item', 'like', '%' . $request->search . '%');
}
// Apply "today" filter by default only when the page is first loaded
// (i.e. there are no query parameters). If the user submitted the filter
// form with "Semua Tahun" (empty values), we treat that as an explicit
// request and do not force today's data.
if (count($request->query()) === 0) {
$query->whereDate('date', \Carbon\Carbon::today());
}
// Filter raw materials by branch for karyawan, show all for admin
if ($user->role === 'admin') {
$rawMaterials = \App\Models\RawMaterial::all();
$purchases = $query->get();
return view('laporan_pembelian', compact('purchases', 'branches', 'rawMaterials'));
} else {
$rawMaterials = \App\Models\RawMaterial::where('branch', $branch)->get();
$purchases = $query->where('branch', $user->branch)->get();
return view('laporan_pembelian', compact('purchases', 'branches', 'rawMaterials'));
}
}
public function create()
{
$user = Auth::user();
if ($user->role === 'admin') {
return redirect('/laporan/pembelian')->with('error', 'Fitur tambah pembelian hanya tersedia untuk karyawan.');
}
$branches = \App\Models\Branch::all();
$branch = $user->branch ?? 'Cabang 1';
$rawMaterials = \App\Models\RawMaterial::where('branch', $branch)->get();
return view('transaksi.pembelian', compact('branches', 'rawMaterials'));
}
public function exportPdf(Request $request)
{
$user = Auth::user();
if ($user->role !== 'admin') {
abort(403);
}
$query = Purchase::with('product')->orderBy('date', 'desc');
if ($request->filled('year')) {
$query->whereYear('date', $request->year);
}
if ($request->filled('month')) {
$query->whereMonth('date', $request->month);
}
if ($request->filled('day')) {
$query->whereDay('date', $request->day);
}
if ($request->filled('search')) {
$query->where('item', 'like', '%' . $request->search . '%');
}
// Apply default today filter for export only when there are no query params
if (count($request->query()) === 0) {
$query->whereDate('date', \Carbon\Carbon::today());
}
$purchases = $query->get();
$branches = \App\Models\Branch::all();
$pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('reports.purchase_pdf', compact('purchases', 'branches'));
return $pdf->download('laporan_pembelian.pdf');
}
public function store(Request $request)
{
$rules = [
'date' => 'required|date',
'item' => 'required|string|max:255',
'quantity' => 'required|string|max:255',
'total_price' => 'required|numeric|min:0',
'type' => 'nullable|in:product,raw_material',
'raw_material_id' => 'required_if:type,raw_material|not_in:0',
];
// Hanya require field bahan baku baru jika raw_material_id = 'new'
if ($request->input('type') === 'raw_material' && $request->input('raw_material_id') === 'new') {
$rules['new_raw_material_name'] = 'required|string|max:255';
$rules['new_raw_material_unit'] = 'required|string|max:50';
}
$request->validate($rules);
// Debug log
\Illuminate\Support\Facades\Log::info('Purchase store - Request data:', [
'type' => $request->type,
'raw_material_id' => $request->raw_material_id,
'new_raw_material_name' => $request->new_raw_material_name,
'new_raw_material_unit' => $request->new_raw_material_unit,
'item' => $request->item,
'quantity' => $request->quantity
]);
try {
\Illuminate\Support\Facades\DB::transaction(function () use ($request) {
$branch = Auth::user()->branch ?? 'Cabang 1';
if (Auth::user()->role === 'admin' && $request->has('branch')) {
$branch = $request->branch;
}
// Bersihkan format angka (hapus titik pemisah ribuan jika ada)
$cleanPrice = str_replace('.', '', $request->total_price);
// Handle raw material creation if new raw material is provided
$rawMaterialId = $request->raw_material_id;
if ($request->type === 'raw_material' && $request->raw_material_id === 'new') {
if ($request->filled('new_raw_material_name') && $request->filled('new_raw_material_unit')) {
// Create new raw material
$newRm = \App\Models\RawMaterial::create([
'name' => $request->new_raw_material_name,
'unit' => $request->new_raw_material_unit,
'stock_quantity' => 0,
'branch' => $branch
]);
$rawMaterialId = $newRm->id;
} else {
throw new \Exception('Nama dan satuan bahan baku baru harus diisi.');
}
}
$purchase = Purchase::create([
'date' => $request->date,
'branch' => $branch,
'item' => $request->item,
'quantity' => $request->quantity,
'total_price' => (int) $cleanPrice,
'product_id' => null,
'raw_material_id' => $request->type === 'raw_material' ? $rawMaterialId : null,
'type' => $request->type ?? 'product',
]);
if ($purchase->type === 'raw_material' && $purchase->raw_material_id) {
$rm = \App\Models\RawMaterial::find($purchase->raw_material_id);
if ($rm) {
// Only update stock if raw material belongs to user's branch
if ($rm->branch !== $branch) {
throw new \Exception('Bahan baku ini tidak terdaftar di cabang Anda.');
}
// Parse quantity string, e.g. "10 Kilogram" → value=10, unit=kilogram
$parsed = $this->parseQuantity($purchase->quantity);
$qtyValue = $parsed['value'];
$qtyUnit = $parsed['unit'] ?: strtolower($rm->unit);
// Konversi ke satuan dasar bahan baku
$qtyInBase = $this->convertToBaseUnit($qtyValue, $qtyUnit);
$rm->stock_quantity += $qtyInBase;
$rm->save();
$this->recalculateProductsFromRawMaterial($rm->id, $branch);
}
}
// Create Journal Entry
$kasAccount = Account::where('code', '101')->first();
$persediaanAccount = Account::where('code', '102')->first();
if ($kasAccount && $persediaanAccount) {
$journal = JournalEntry::create([
'date' => $purchase->date,
'description' => 'Pembelian ' . $purchase->item,
'reference_type' => 'Purchase',
'reference_id' => $purchase->id,
'branch' => $branch,
]);
// Debit Persediaan, Kredit Kas
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $persediaanAccount->id, 'debit' => $purchase->total_price, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => 0, 'credit' => $purchase->total_price]);
}
});
return back()->with('success', 'Transaksi pembelian berhasil ditambahkan!');
} catch (\Exception $e) {
\Illuminate\Support\Facades\Log::error('Purchase store error: ' . $e->getMessage());
return back()->withInput()->withErrors(['db_error' => 'Gagal menyimpan transaksi: ' . $e->getMessage()]);
}
}
/**
* Konversi nilai ke satuan stok yang dipakai aplikasi.
* Untuk bisnis sederhana, pembelian liter dan unit lain disimpan apa adanya
* agar stok tetap sesuai dengan satuan yang dimasukkan.
*/
private function convertToBaseUnit($value, $unit)
{
$unit = strtolower(trim($unit));
$conversions = [
'kilogram' => 1000,
'kg' => 1000,
'gram' => 1,
'gr' => 1,
'g' => 1,
'liter' => 1,
'l' => 1,
'mililiter'=> 1,
'ml' => 1,
'pcs' => 1,
'dus' => 1,
'pack' => 1,
'karung' => 1,
'ikat' => 1,
'botol' => 1,
'kaleng' => 1,
'lembar' => 1,
'sendok makan' => 1,
'sendok teh' => 1,
];
$multiplier = $conversions[$unit] ?? 1;
return $value * $multiplier;
}
/**
* Parse quantity string seperti "10 Kilogram" returns ['value' => 10, 'unit' => 'kilogram']
*/
private function parseQuantity($quantityStr)
{
$quantityStr = trim($quantityStr);
// Coba pisahkan angka dan satuan
if (preg_match('/^([\d.,]+)\s*(.*)$/', $quantityStr, $matches)) {
$value = floatval(str_replace(',', '.', $matches[1]));
$unit = strtolower(trim($matches[2]));
return ['value' => $value, 'unit' => $unit];
}
return ['value' => floatval($quantityStr), 'unit' => ''];
}
private function recalculateProductsFromRawMaterial($rawMaterialId, $branch)
{
// Ambil semua resep yang menggunakan bahan baku ini, eager load product & semua resep produk tsb
$recipes = \App\Models\ProductRecipe::where('raw_material_id', $rawMaterialId)
->with(['product.recipes.rawMaterial'])
->get();
foreach ($recipes as $recipe) {
$product = $recipe->product;
if (!$product) continue;
$minStock = null;
foreach ($product->recipes as $prodRecipe) {
$rm = $prodRecipe->rawMaterial;
if (!$rm || $prodRecipe->quantity_needed <= 0) continue;
// Stok bahan baku sudah dalam satuan dasar (disimpan apa adanya)
$rmStock = $rm->stock_quantity;
// quantity_needed di resep dalam satuan apa? Anggap sama dengan satuan bahan baku
$needed = $prodRecipe->quantity_needed;
$possibleAmount = floor($rmStock / $needed);
if ($minStock === null || $possibleAmount < $minStock) {
$minStock = $possibleAmount;
}
}
if ($minStock !== null && $minStock >= 0) {
// Update semua cabang (atau hanya cabang ini)
$allBranches = \App\Models\Branch::all();
foreach ($allBranches as $b) {
$stock = \App\Models\Stock::firstOrCreate(
['product_id' => $product->id, 'branch' => $b->name],
['quantity' => 0, 'unit' => 'Pcs']
);
$stock->quantity = $minStock;
$stock->save();
}
}
}
}
public function update(Request $request, $id)
{
$rules = [
'date' => 'required|date',
'item' => 'required|string|max:255',
'quantity' => 'required|string|max:255',
'total_price' => 'required|numeric|min:0',
'type' => 'nullable|in:product,raw_material',
'raw_material_id' => 'required_if:type,raw_material|not_in:0',
];
// Hanya require field bahan baku baru jika raw_material_id = 'new'
if ($request->input('type') === 'raw_material' && $request->input('raw_material_id') === 'new') {
$rules['new_raw_material_name'] = 'required|string|max:255';
$rules['new_raw_material_unit'] = 'required|string|max:50';
}
$request->validate($rules);
try {
\Illuminate\Support\Facades\DB::transaction(function () use ($request, $id) {
$purchase = Purchase::findOrFail($id);
$oldType = $purchase->type;
$oldRawMaterialId = $purchase->raw_material_id;
$branch = $purchase->branch;
// Jika pembelian lama adalah bahan baku, hapus stok lama dulu
if ($oldType === 'raw_material' && $oldRawMaterialId) {
$oldRm = \App\Models\RawMaterial::find($oldRawMaterialId);
if ($oldRm) {
$oldParsed = $this->parseQuantity($purchase->quantity);
$oldQty = $this->convertToBaseUnit($oldParsed['value'], $oldParsed['unit'] ?: strtolower($oldRm->unit));
$oldRm->stock_quantity -= $oldQty;
if ($oldRm->stock_quantity < 0) {
$oldRm->stock_quantity = 0;
}
$oldRm->save();
}
}
$newRawMaterialId = null;
if ($request->type === 'raw_material') {
$newRawMaterialId = $request->raw_material_id;
if ($newRawMaterialId === 'new') {
$newRm = \App\Models\RawMaterial::create([
'name' => $request->new_raw_material_name,
'unit' => $request->new_raw_material_unit,
'stock_quantity' => 0,
'branch' => Auth::user()->branch ?? 'Cabang 1',
]);
$newRawMaterialId = $newRm->id;
}
$rm = \App\Models\RawMaterial::find($newRawMaterialId);
if ($rm) {
$parsed = $this->parseQuantity($request->quantity);
$qty = $this->convertToBaseUnit($parsed['value'], $parsed['unit'] ?: strtolower($rm->unit));
$rm->stock_quantity += $qty;
$rm->save();
}
}
// Perbarui data pembelian
$cleanPrice = str_replace('.', '', $request->total_price);
$data = $request->all();
$data['total_price'] = (int) $cleanPrice;
$data['product_id'] = null;
if (Auth::user()->role === 'admin' && $request->has('branch')) {
$data['branch'] = $request->branch;
}
$purchase->update($data);
// Recalculate product stock from raw materials if needed
if ($oldType === 'raw_material' && $oldRawMaterialId) {
$this->recalculateProductsFromRawMaterial($oldRawMaterialId, $branch);
}
if ($request->type === 'raw_material' && $newRawMaterialId) {
$this->recalculateProductsFromRawMaterial($newRawMaterialId, $branch);
}
// Recreate Journal Entry
JournalEntry::where('reference_type', 'Purchase')->where('reference_id', $purchase->id)->delete();
$kasAccount = Account::where('code', '101')->first();
$persediaanAccount = Account::where('code', '102')->first();
if ($kasAccount && $persediaanAccount) {
$journal = JournalEntry::create([
'date' => $purchase->date,
'description' => 'Pembelian ' . $purchase->item,
'reference_type' => 'Purchase',
'reference_id' => $purchase->id,
'branch' => $purchase->branch,
]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $persediaanAccount->id, 'debit' => $purchase->total_price, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => 0, 'credit' => $purchase->total_price]);
}
});
return back()->with('success', 'Transaksi pembelian berhasil diperbarui!');
} catch (\Exception $e) {
\Illuminate\Support\Facades\Log::error('Purchase update error: ' . $e->getMessage());
return back()->withInput()->withErrors(['db_error' => 'Gagal memperbarui transaksi: ' . $e->getMessage()]);
}
}
public function destroy($id)
{
try {
\Illuminate\Support\Facades\DB::transaction(function () use ($id) {
$purchase = Purchase::findOrFail($id);
// If this is a raw material purchase, update stock and potentially delete raw material
if ($purchase->type === 'raw_material' && $purchase->raw_material_id) {
$rm = \App\Models\RawMaterial::find($purchase->raw_material_id);
if ($rm) {
// Parse quantity to subtract from stock
$parsed = $this->parseQuantity($purchase->quantity);
$qtyValue = $parsed['value'];
$qtyUnit = $parsed['unit'] ?: strtolower($rm->unit);
$qtyInBase = $this->convertToBaseUnit($qtyValue, $qtyUnit);
// Subtract from stock
$rm->stock_quantity -= $qtyInBase;
if ($rm->stock_quantity < 0) $rm->stock_quantity = 0;
$rm->save();
// Recalculate products
$this->recalculateProductsFromRawMaterial($rm->id, $purchase->branch);
// Check if this is the only purchase for this raw material
$otherPurchases = Purchase::where('raw_material_id', $rm->id)
->where('id', '!=', $purchase->id)
->count();
if ($otherPurchases === 0) {
// No other purchases, delete the raw material
$rm->delete();
}
}
}
// Delete journal entries
JournalEntry::where('reference_type', 'Purchase')->where('reference_id', $purchase->id)->delete();
// Delete purchase
$purchase->delete();
});
return back()->with('success', 'Transaksi pembelian berhasil dihapus!');
} catch (\Exception $e) {
\Illuminate\Support\Facades\Log::error('Purchase destroy error: ' . $e->getMessage());
return back()->with('error', 'Gagal menghapus transaksi: ' . $e->getMessage());
}
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\RawMaterial;
class RawMaterialController extends Controller
{
public function index()
{
// Redirect to produk page with bahan-baku tab
return redirect('/produk?tab=bahan-baku');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'unit' => 'required|string|max:50',
]);
$branch = auth()->user()->branch ?? 'Cabang 1';
RawMaterial::create([
'name' => $request->name,
'unit' => $request->unit,
'stock_quantity' => 0,
'branch' => $branch
]);
return redirect('/produk?tab=bahan-baku')->with('success', 'Bahan Baku berhasil ditambahkan.');
}
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required|string|max:255',
'unit' => 'required|string|max:50',
]);
$rawMaterial = RawMaterial::findOrFail($id);
$branch = auth()->user()->branch ?? 'Cabang 1';
// Only allow update if raw material belongs to user's branch
if ($rawMaterial->branch !== $branch) {
return back()->with('error', 'Anda tidak memiliki akses untuk mengubah bahan baku dari cabang lain.');
}
$rawMaterial->update([
'name' => $request->name,
'unit' => $request->unit,
]);
return redirect('/produk?tab=bahan-baku')->with('success', 'Bahan Baku berhasil diperbarui.');
}
public function destroy($id)
{
$rawMaterial = RawMaterial::findOrFail($id);
$branch = auth()->user()->branch ?? 'Cabang 1';
// Only allow deletion if raw material belongs to user's branch
if ($rawMaterial->branch !== $branch) {
return back()->with('error', 'Anda tidak memiliki akses untuk menghapus bahan baku dari cabang lain.');
}
$rawMaterial->delete();
return redirect('/produk?tab=bahan-baku')->with('success', 'Bahan Baku berhasil dihapus.');
}
}

View File

@ -0,0 +1,356 @@
<?php
namespace App\Http\Controllers;
use App\Models\Sale;
use App\Models\Stock;
use App\Models\JournalEntry;
use App\Models\JournalDetail;
use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class SaleController extends Controller
{
public function index(Request $request)
{
$user = Auth::user();
$branches = \App\Models\Branch::all();
$query = Sale::with('product')->orderBy('date', 'desc');
if ($request->filled('year')) {
$query->whereYear('date', $request->year);
}
if ($request->filled('month')) {
$query->whereMonth('date', $request->month);
}
if ($request->filled('day')) {
$query->whereDay('date', $request->day);
}
if ($request->filled('search')) {
$query->where('item', 'like', '%' . $request->search . '%');
}
// Apply "today" filter by default only when the page is first loaded
// (i.e. there are no query parameters). If the user submitted the filter
// form with "Semua Tahun" (empty values), we treat that as an explicit
// request and do not force today's data.
if (count($request->query()) === 0) {
$query->whereDate('date', \Carbon\Carbon::today());
}
if ($user->role === 'admin') {
$products = \App\Models\Product::all();
$sales = $query->get();
// We no longer need salesByBranch as we use a single consolidated view
return view('laporan_penjualan', compact('sales', 'products', 'branches'));
} else {
$products = \App\Models\Product::all();
$sales = $query->where('branch', $user->branch)->get();
return view('laporan_penjualan', compact('sales', 'products', 'branches'));
}
}
public function create()
{
$user = Auth::user();
if ($user->role === 'admin') {
return redirect('/laporan/penjualan')->with('error', 'Fitur tambah penjualan hanya tersedia untuk karyawan.');
}
$branches = \App\Models\Branch::all();
$branch = $user->branch ?? 'Cabang 1';
$products = \App\Models\Product::where('branch', $branch)->get();
return view('transaksi.penjualan', compact('branches', 'products'));
}
public function exportPdf(Request $request)
{
$user = Auth::user();
if ($user->role !== 'admin') {
abort(403);
}
$query = Sale::with('product')->orderBy('date', 'desc');
if ($request->filled('year')) {
$query->whereYear('date', $request->year);
}
if ($request->filled('month')) {
$query->whereMonth('date', $request->month);
}
if ($request->filled('day')) {
$query->whereDay('date', $request->day);
}
if ($request->filled('search')) {
$query->where('item', 'like', '%' . $request->search . '%');
}
// Apply "today" filter by default only when the page is first loaded
// (i.e. there are no query parameters). If the admin submits the filter
// form with empty values intentionally, return the full dataset.
if (count($request->query()) === 0) {
$query->whereDate('date', \Carbon\Carbon::today());
}
$sales = $query->get();
$branches = \App\Models\Branch::all();
$pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('reports.sale_pdf', compact('sales', 'branches'));
return $pdf->download('laporan_penjualan.pdf');
}
public function store(Request $request)
{
$request->validate([
'date' => 'required|date',
'product_id' => 'required|exists:products,id',
'quantity' => 'required|integer|min:1',
'total_price' => 'required|numeric|min:0',
]);
try {
\Illuminate\Support\Facades\DB::transaction(function () use ($request) {
$product = \App\Models\Product::findOrFail($request->product_id);
$branch = Auth::user()->branch ?? 'Cabang 1';
if (Auth::user()->role === 'admin' && $request->has('branch')) {
$branch = $request->branch;
}
// Bersihkan format angka (hapus titik pemisah ribuan jika ada)
$cleanPrice = str_replace('.', '', $request->total_price);
// First, adjust stocks: either raw materials (if product has recipes)
// or product stock per branch
$product = \App\Models\Product::with('recipes.rawMaterial')->findOrFail($request->product_id);
if ($product->recipes->count() > 0) {
// Check and deduct raw materials
foreach ($product->recipes as $recipe) {
$rm = $recipe->rawMaterial;
if (!$rm) continue;
$needed = $recipe->quantity_needed * $request->quantity;
if ($rm->stock_quantity < $needed) {
throw new \Exception('Bahan baku tidak cukup untuk membuat ' . $request->quantity . ' porsi.');
}
}
foreach ($product->recipes as $recipe) {
$rm = $recipe->rawMaterial;
if ($rm) {
$needed = $recipe->quantity_needed * $request->quantity;
$rm->stock_quantity -= $needed;
if ($rm->stock_quantity < 0) $rm->stock_quantity = 0;
$rm->save();
}
}
// Recalculate finished product stock once after all raw materials are updated
$this->recalculateProductsFromRawMaterials($product->id, $branch);
} else {
// Deduct from regular stock
$stock = \App\Models\Stock::where('product_id', $request->product_id)->where('branch', $branch)->first();
if (!$stock) {
throw new \Exception('Stok untuk produk ini tidak ditemukan pada cabang Anda.');
}
if ($stock->quantity < $request->quantity) {
throw new \Exception('Stok tidak cukup. Tersedia: ' . $stock->quantity);
}
$stock->quantity = $stock->quantity - $request->quantity;
if ($stock->quantity < 0) $stock->quantity = 0;
$stock->save();
}
// Now create sale record
$sale = Sale::create([
'date' => $request->date,
'branch' => $branch,
'product_id' => $request->product_id,
'item' => $product->name,
'quantity' => $request->quantity,
'total_price' => (int) $cleanPrice,
]);
// Create Journal Entry
$kasAccount = $this->ensureAccount('101', 'Kas', 'Asset');
$penjualanAccount = $this->ensureAccount('401', 'Penjualan', 'Revenue');
$hppAccount = $this->ensureAccount('501', 'Harga Pokok Penjualan', 'Expense');
$persediaanAccount = $this->ensureAccount('102', 'Persediaan Barang Dagang', 'Asset');
$journal = JournalEntry::create([
'date' => $sale->date,
'description' => 'Penjualan ' . $sale->item,
'reference_type' => 'Sale',
'reference_id' => $sale->id,
'branch' => $branch,
]);
// Debit Kas, Kredit Penjualan
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => $sale->total_price, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $penjualanAccount->id, 'debit' => 0, 'credit' => $sale->total_price]);
// Debit HPP, Kredit Persediaan
$hppTotal = $sale->quantity * $product->purchase_price;
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $hppAccount->id, 'debit' => $hppTotal, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $persediaanAccount->id, 'debit' => 0, 'credit' => $hppTotal]);
});
return back()->with('success', 'Transaksi penjualan berhasil ditambahkan!');
} catch (\Exception $e) {
\Illuminate\Support\Facades\Log::error('Sale store error: ' . $e->getMessage());
return back()->withInput()->withErrors(['db_error' => 'Gagal menyimpan transaksi: ' . $e->getMessage()]);
}
}
private function ensureAccount($code, $name, $type)
{
return Account::updateOrCreate(
['code' => $code],
['name' => $name, 'type' => $type]
);
}
public function update(Request $request, $id)
{
$request->validate([
'date' => 'required|date',
'product_id' => 'required|exists:products,id',
'quantity' => 'required|integer|min:1',
'total_price' => 'required|numeric|min:0',
]);
try {
\Illuminate\Support\Facades\DB::transaction(function () use ($request, $id) {
$sale = Sale::findOrFail($id);
$product = \App\Models\Product::findOrFail($request->product_id);
// Bersihkan format angka (hapus titik pemisah ribuan jika ada)
$cleanPrice = str_replace('.', '', $request->total_price);
$data = $request->all();
$data['item'] = $product->name;
$data['total_price'] = (int) $cleanPrice;
if (Auth::user()->role === 'admin' && $request->has('branch')) {
$data['branch'] = $request->branch;
}
$sale->update($data);
// Recreate Journal Entry
JournalEntry::where('reference_type', 'Sale')->where('reference_id', $sale->id)->delete();
$kasAccount = Account::where('code', '101')->first();
$penjualanAccount = Account::where('code', '401')->first();
$hppAccount = Account::where('code', '501')->first();
$persediaanAccount = Account::where('code', '102')->first();
if ($kasAccount && $penjualanAccount && $hppAccount && $persediaanAccount) {
$journal = JournalEntry::create([
'date' => $sale->date,
'description' => 'Penjualan ' . $sale->item,
'reference_type' => 'Sale',
'reference_id' => $sale->id,
'branch' => $sale->branch,
]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => $sale->total_price, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $penjualanAccount->id, 'debit' => 0, 'credit' => $sale->total_price]);
$hppTotal = $sale->quantity * $product->purchase_price;
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $hppAccount->id, 'debit' => $hppTotal, 'credit' => 0]);
JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $persediaanAccount->id, 'debit' => 0, 'credit' => $hppTotal]);
}
});
return back()->with('success', 'Transaksi penjualan berhasil diperbarui!');
} catch (\Exception $e) {
\Illuminate\Support\Facades\Log::error('Sale update error: ' . $e->getMessage());
return back()->withInput()->withErrors(['db_error' => 'Gagal memperbarui transaksi: ' . $e->getMessage()]);
}
}
public function destroy($id)
{
$sale = Sale::findOrFail($id);
JournalEntry::where('reference_type', 'Sale')->where('reference_id', $sale->id)->delete();
$sale->delete();
return back()->with('success', 'Transaksi penjualan berhasil dihapus!');
}
private function recalculateProductsFromRawMaterials($productId, $branch)
{
$product = \App\Models\Product::with('recipes.rawMaterial')->find($productId);
if (!$product || $product->recipes->isEmpty()) {
return;
}
$minStock = null;
foreach ($product->recipes as $recipe) {
$rm = $recipe->rawMaterial;
if (!$rm || $recipe->quantity_needed <= 0) {
continue;
}
$possibleAmount = floor($rm->stock_quantity / $recipe->quantity_needed);
if ($minStock === null || $possibleAmount < $minStock) {
$minStock = $possibleAmount;
}
}
if ($minStock !== null && $minStock >= 0) {
$stock = \App\Models\Stock::firstOrCreate(
['product_id' => $productId, 'branch' => $branch],
['quantity' => 0, 'unit' => 'Pcs']
);
$stock->quantity = $minStock;
$stock->save();
}
}
private function recalculateProductsFromRawMaterial($rawMaterialId, $branch)
{
$recipes = \App\Models\ProductRecipe::where('raw_material_id', $rawMaterialId)
->with(['product.recipes.rawMaterial'])
->get();
foreach ($recipes as $recipe) {
$product = $recipe->product;
if (!$product) continue;
$minStock = null;
foreach ($product->recipes as $prodRecipe) {
$rm = $prodRecipe->rawMaterial;
if (!$rm || $prodRecipe->quantity_needed <= 0) continue;
$rmStock = $rm->stock_quantity;
$needed = $prodRecipe->quantity_needed;
$possibleAmount = floor($rmStock / $needed);
if ($minStock === null || $possibleAmount < $minStock) {
$minStock = $possibleAmount;
}
}
if ($minStock !== null && $minStock >= 0) {
$allBranches = \App\Models\Branch::all();
foreach ($allBranches as $b) {
$stock = \App\Models\Stock::firstOrCreate(
['product_id' => $product->id, 'branch' => $b->name],
['quantity' => 0, 'unit' => 'Pcs']
);
$stock->quantity = $minStock;
$stock->save();
}
}
}
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class SendEmailController extends Controller
{
public function showForm()
{
return view('test-email');
}
public function sendEmail(Request $request)
{
$request->validate([
'email' => 'required|email'
]);
$email = $request->email;
// Mengirim email sederhana menggunakan raw () langsung, bisa juga dengan Mailable Class jika format lebih kompleks
Mail::raw("Halo!\n\nIni adalah email testing dari sistem Akuntansi SIA menggunakan SMTP.\nPengujian ini memastikan bahwa konfigurasi email berjalan dengan baik.\n\nSalam,\nSistem Admin", function ($message) use ($email) {
$message->to($email)
->subject('Testing Email SMTP Laravel');
});
return back()->with('success', 'Email berhasil dikirim ke ' . $email . '. Silakan cek kotak masuk atau folder spam Anda.');
}
}

67
app/Http/Kernel.php Normal file
View File

@ -0,0 +1,67 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @param string|null ...$guards
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

18
app/Models/Account.php Normal file
View File

@ -0,0 +1,18 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Account extends Model
{
use HasFactory;
protected $fillable = ['code', 'name', 'type'];
public function journalDetails()
{
return $this->hasMany(JournalDetail::class);
}
}

13
app/Models/Branch.php Normal file
View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Branch extends Model
{
use HasFactory;
protected $fillable = ['name'];
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class JournalDetail extends Model
{
use HasFactory;
protected $fillable = ['journal_entry_id', 'account_id', 'debit', 'credit'];
public function journalEntry()
{
return $this->belongsTo(JournalEntry::class);
}
public function account()
{
return $this->belongsTo(Account::class);
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class JournalEntry extends Model
{
use HasFactory;
protected $fillable = ['date', 'description', 'reference_type', 'reference_id', 'branch'];
public function details()
{
return $this->hasMany(JournalDetail::class);
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class OperationalCost extends Model
{
use HasFactory;
protected $fillable = [
'branch',
'date',
'label',
'amount',
];
}

34
app/Models/Product.php Normal file
View File

@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'category', 'purchase_price', 'selling_price', 'image', 'branch'
];
public function stocks()
{
return $this->hasMany(Stock::class);
}
public function sales()
{
return $this->hasMany(Sale::class);
}
public function recipes()
{
return $this->hasMany(ProductRecipe::class);
}
public function purchases()
{
return $this->hasMany(Purchase::class);
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProductRecipe extends Model
{
use HasFactory;
protected $guarded = [];
public function product()
{
return $this->belongsTo(Product::class);
}
public function rawMaterial()
{
return $this->belongsTo(RawMaterial::class);
}
}

27
app/Models/Purchase.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
use HasFactory;
protected $fillable = [
'date',
'branch',
'product_id',
'item',
'quantity',
'total_price',
'raw_material_id',
'type',
];
public function product()
{
return $this->belongsTo(Product::class);
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class RawMaterial extends Model
{
use HasFactory;
protected $guarded = [];
public function productRecipes()
{
return $this->hasMany(ProductRecipe::class);
}
}

25
app/Models/Sale.php Normal file
View File

@ -0,0 +1,25 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Sale extends Model
{
use HasFactory;
protected $fillable = [
'date',
'branch',
'product_id',
'item',
'quantity',
'total_price',
];
public function product()
{
return $this->belongsTo(Product::class);
}
}

20
app/Models/Stock.php Normal file
View File

@ -0,0 +1,20 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model
{
use HasFactory;
protected $fillable = [
'product_id', 'manual_item_name', 'branch', 'quantity', 'unit'
];
public function product()
{
return $this->belongsTo(Product::class);
}
}

46
app/Models/User.php Normal file
View File

@ -0,0 +1,46 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'role',
'branch',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
\Illuminate\Support\Facades\Gate::define('admin-access', function ($user) {
return $user->role === 'admin';
});
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}

53
artisan Normal file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any of our classes manually. It's great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php Normal file
View File

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

35
check_stock_modal.php Normal file
View File

@ -0,0 +1,35 @@
<?php
require __DIR__ . '/vendor/autoload.php';
$app = require __DIR__ . '/bootstrap/app.php';
use App\Models\Stock;
$stocks = Stock::with('product')->get();
echo "Total Stock Details:\n";
$total = 0;
$byBranch = [];
foreach ($stocks as $s) {
$v = ($s->quantity ?? 0) * ($s->product->selling_price ?? 0);
echo sprintf(" - %s (%s): %d × %d = %s\n",
$s->product->name,
$s->branch,
$s->quantity,
$s->product->selling_price,
number_format($v, 0, ',', '.')
);
$total += $v;
if (!isset($byBranch[$s->branch])) {
$byBranch[$s->branch] = 0;
}
$byBranch[$s->branch] += $v;
}
echo "\nBy Branch:\n";
foreach ($byBranch as $branch => $value) {
echo " $branch: Rp" . number_format($value, 0, ',', '.') . "\n";
}
echo "\nGrand Total Modal: Rp" . number_format($total, 0, ',', '.') . "\n";
?>

67
composer.json Normal file
View File

@ -0,0 +1,67 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"php": "^8.0.2",
"barryvdh/laravel-dompdf": "^2.2",
"doctrine/dbal": "^3.10",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.19",
"laravel/sanctum": "^3.0",
"laravel/tinker": "^2.7"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8823
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

215
config/app.php Normal file
View File

@ -0,0 +1,215 @@
<?php
use Illuminate\Support\Facades\Facade;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'ExampleClass' => App\Example\ExampleClass::class,
])->toArray(),
];

111
config/auth.php Normal file
View File

@ -0,0 +1,111 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

70
config/broadcasting.php Normal file
View File

@ -0,0 +1,70 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

110
config/cache.php Normal file
View File

@ -0,0 +1,110 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
| stores there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

34
config/cors.php Normal file
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

151
config/database.php Normal file
View File

@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

76
config/filesystems.php Normal file
View File

@ -0,0 +1,76 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been set up for each driver as an example of the required values.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

52
config/hashing.php Normal file
View File

@ -0,0 +1,52 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 10),
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 65536,
'threads' => 1,
'time' => 4,
],
];

122
config/logging.php Normal file
View File

@ -0,0 +1,122 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => env('LOG_LEVEL', 'critical'),
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

118
config/mail.php Normal file
View File

@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array", "failover"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
],
'postmark' => [
'transport' => 'postmark',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

93
config/queue.php Normal file
View File

@ -0,0 +1,93 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

67
config/sanctum.php Normal file
View File

@ -0,0 +1,67 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. If this value is null, personal access tokens do
| not expire. This won't tweak the lifetime of first-party sessions.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],
];

34
config/services.php Normal file
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
'scheme' => 'https',
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

201
config/session.php Normal file
View File

@ -0,0 +1,201 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
];

36
config/view.php Normal file
View File

@ -0,0 +1,36 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];

70
create_es_teh.php Normal file
View File

@ -0,0 +1,70 @@
<?php
require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();
// Create product
$product = \App\Models\Product::create([
'name' => 'es teh',
'category' => 'minuman',
'purchase_price' => 4000,
'selling_price' => 5000,
'branch' => 'Cabang 2'
]);
echo "Product created with ID: " . $product->id . "\n";
// Create recipes
\App\Models\ProductRecipe::create([
'product_id' => $product->id,
'raw_material_id' => 3, // Es Batu
'quantity_needed' => 15
]);
echo "Recipe added: Es Batu 15 Gram\n";
\App\Models\ProductRecipe::create([
'product_id' => $product->id,
'raw_material_id' => 2, // Gula
'quantity_needed' => 20
]);
echo "Recipe added: Gula 20 Gram\n";
\App\Models\ProductRecipe::create([
'product_id' => $product->id,
'raw_material_id' => 4, // Teh Kotak
'quantity_needed' => 0.5 // 1 pcs untuk 2 es teh
]);
echo "Recipe added: Teh Kotak 0.5 Pcs\n";
// Create initial stock
\App\Models\Stock::create([
'product_id' => $product->id,
'branch' => 'Cabang 2',
'quantity' => 0,
'unit' => 'Pcs'
]);
echo "Initial stock created\n";
// Recalculate stock
$product = \App\Models\Product::with('recipes.rawMaterial')->find($product->id);
$minStock = null;
foreach ($product->recipes as $recipe) {
$rm = $recipe->rawMaterial;
if (!$rm || $recipe->quantity_needed <= 0) continue;
$possibleAmount = floor($rm->stock_quantity / $recipe->quantity_needed);
if ($minStock === null || $possibleAmount < $minStock) {
$minStock = $possibleAmount;
}
}
if ($minStock !== null && $minStock >= 0) {
$stock = \App\Models\Stock::where('product_id', $product->id)->where('branch', 'Cabang 2')->first();
$stock->quantity = $minStock;
$stock->save();
echo "Stock recalculated: " . $minStock . " Pcs\n";
} else {
echo "Stock could not be calculated (insufficient raw materials)\n";
}
echo "Done!\n";

1
database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite*

90
database/ERD.md Normal file
View File

@ -0,0 +1,90 @@
# ERD
```mermaid
erDiagram
USERS {
bigint id PK
string name
string email
timestamp email_verified_at
string password
timestamp created_at
timestamp updated_at
string role
string branch
}
BRANCHES {
bigint id PK
string name
timestamp created_at
timestamp updated_at
}
PRODUCTS {
bigint id PK
string name
enum category
integer purchase_price
integer selling_price
string image
string branch
timestamp created_at
timestamp updated_at
}
STOCKS {
bigint id PK
bigint product_id FK
string branch
integer quantity
string unit
timestamp created_at
timestamp updated_at
}
PURCHASES {
bigint id PK
date date
string branch
string item
string quantity
integer total_price
bigint product_id FK
timestamp created_at
timestamp updated_at
}
SALES {
bigint id PK
date date
string branch
string item
integer quantity
integer total_price
bigint product_id FK
timestamp created_at
timestamp updated_at
}
OPERATIONAL_COSTS {
bigint id PK
string branch
date date
string label
integer amount
timestamp created_at
timestamp updated_at
}
USERS ||--o{ BRANCHES : "belongs_to (via branch name)"
PRODUCTS ||--o{ BRANCHES : "belongs_to (via branch name)"
STOCKS }o--|| PRODUCTS : "product_id"
PURCHASES }o--|| PRODUCTS : "product_id"
SALES }o--|| PRODUCTS : "product_id"
BRANCHES ||--o{ STOCKS : "has"
BRANCHES ||--o{ PURCHASES : "has"
BRANCHES ||--o{ SALES : "has"
BRANCHES ||--o{ OPERATIONAL_COSTS : "has"
```

View File

@ -0,0 +1,40 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* @return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,36 @@
f<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('password_resets');
}
};

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->enum('category', ['makanan', 'minuman', 'snack']);
$table->integer('purchase_price');
$table->integer('selling_price');
$table->string('image')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('products');
}
}

View File

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->enum('role', ['admin', 'employee'])->default('employee')->after('email');
$table->string('branch')->nullable()->after('role');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['role', 'branch']);
});
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('stocks', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->string('branch');
$table->integer('quantity')->default(0);
$table->string('unit')->nullable(); // Added unit to stock for flexibility
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('stocks');
}
};

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('purchases', function (Blueprint $table) {
$table->id();
$table->date('date');
$table->string('branch');
$table->string('item');
$table->string('quantity');
$table->integer('total_price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('purchases');
}
};

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sales', function (Blueprint $table) {
$table->id();
$table->date('date');
$table->string('branch');
$table->string('item');
$table->integer('quantity');
$table->integer('total_price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sales');
}
};

View File

@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('purchases', function (Blueprint $table) {
$table->foreignId('product_id')->nullable()->after('branch')->constrained()->onDelete('set null');
});
Schema::table('sales', function (Blueprint $table) {
$table->foreignId('product_id')->nullable()->after('branch')->constrained()->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('purchases', function (Blueprint $table) {
$table->dropForeign(['product_id']);
$table->dropColumn('product_id');
});
Schema::table('sales', function (Blueprint $table) {
$table->dropForeign(['product_id']);
$table->dropColumn('product_id');
});
}
};

View File

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('stocks', function (Blueprint $table) {
$table->foreignId('product_id')->nullable()->change();
$table->string('manual_item_name')->nullable()->after('product_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('stocks', function (Blueprint $table) {
$table->foreignId('product_id')->nullable(false)->change();
$table->dropColumn('manual_item_name');
});
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->string('branch')->default('Cabang 1')->after('image');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('branch');
});
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('branches', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('branches');
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('role')->change();
});
// Update existing data for consistency
\DB::table('users')->where('role', 'employee')->update(['role' => 'karyawan']);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->enum('role', ['admin', 'employee'])->default('employee')->change();
});
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
//
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
//
});
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
//
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
//
});
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
//
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
//
});
}
};

View File

@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
// 1. Clean up duplicate products (keep only the first one based on ID for each lowercase name)
$duplicates = DB::select("
SELECT id FROM products p1
WHERE EXISTS (
SELECT 1 FROM products p2
WHERE LOWER(p1.name) = LOWER(p2.name)
AND p1.id > p2.id
)
");
$duplicateIds = array_column($duplicates, 'id');
if (!empty($duplicateIds)) {
// Optional: Reassign purchase/sales references if necessary, or just delete.
// Since this is a hard shift, we will just delete the duplicates.
DB::table('products')->whereIn('id', $duplicateIds)->delete();
}
// 2. Modify the table schema
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('branch');
// Adding unique constraint to name to prevent future duplicates at database level
// Note: because collation might differ, we'll keep the application-level validation too,
// but this adds a hard layer of protection.
$table->unique('name');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropUnique(['name']);
$table->string('branch')->nullable();
});
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('operational_costs', function (Blueprint $table) {
$table->id();
$table->string('branch');
$table->date('date');
$table->string('label');
$table->integer('amount');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('operational_costs');
}
};

View File

@ -0,0 +1,64 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->foreign('branch')->references('name')->on('branches')->onUpdate('cascade')->onDelete('cascade');
});
Schema::table('sales', function (Blueprint $table) {
$table->foreign('branch')->references('name')->on('branches')->onUpdate('cascade')->onDelete('cascade');
});
Schema::table('purchases', function (Blueprint $table) {
$table->foreign('branch')->references('name')->on('branches')->onUpdate('cascade')->onDelete('cascade');
});
Schema::table('stocks', function (Blueprint $table) {
$table->foreign('branch')->references('name')->on('branches')->onUpdate('cascade')->onDelete('cascade');
});
Schema::table('operational_costs', function (Blueprint $table) {
$table->foreign('branch')->references('name')->on('branches')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropForeign(['branch']);
});
Schema::table('sales', function (Blueprint $table) {
$table->dropForeign(['branch']);
});
Schema::table('purchases', function (Blueprint $table) {
$table->dropForeign(['branch']);
});
Schema::table('stocks', function (Blueprint $table) {
$table->dropForeign(['branch']);
});
Schema::table('operational_costs', function (Blueprint $table) {
$table->dropForeign(['branch']);
});
}
};

View File

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('name');
$table->enum('type', ['Asset', 'Liability', 'Equity', 'Revenue', 'Expense']);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('accounts');
}
};

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('journal_entries', function (Blueprint $table) {
$table->id();
$table->date('date');
$table->string('description');
$table->string('reference_type')->nullable(); // e.g. Sale, Purchase, OperationalCost
$table->unsignedBigInteger('reference_id')->nullable();
$table->string('branch')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('journal_entries');
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('journal_details', function (Blueprint $table) {
$table->id();
$table->foreignId('journal_entry_id')->constrained('journal_entries')->onDelete('cascade');
$table->foreignId('account_id')->constrained('accounts')->onDelete('cascade');
$table->bigInteger('debit')->default(0);
$table->bigInteger('credit')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('journal_details');
}
};

View File

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('raw_materials', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('unit');
$table->float('stock_quantity')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('raw_materials');
}
};

View File

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_recipes', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained('products')->onDelete('cascade');
$table->foreignId('raw_material_id')->constrained('raw_materials')->onDelete('cascade');
$table->float('quantity_needed');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('product_recipes');
}
};

Some files were not shown because too many files have changed in this diff Show More