This commit is contained in:
ashok 2026-03-11 11:03:12 +05:30
commit b4f05d31cd
171 changed files with 30273 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
[compose.yaml]
indent_size = 4

65
.env.example Normal file
View File

@ -0,0 +1,65 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=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
VITE_APP_NAME="${APP_NAME}"

11
.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.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

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

59
README.md Normal file
View File

@ -0,0 +1,59 @@
<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 can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of 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 Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.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).

55
ai-context.md Normal file
View File

@ -0,0 +1,55 @@
GymPro - Gym Management System Context
1. Project Overview
GymPro is a comprehensive, multi-branch Gym Management System. It features a responsive web dashboard for Owners and Receptionists, and mobile-optimized views for Owners, Trainers, and Members. The frontend is built with React, Vite, Tailwind CSS, and Framer Motion. It currently relies on mock data and needs a robust backend to handle relational data, authentication, and complex business logic.
2. User Roles & Access
Owner (Super Admin): Full access to all branches. Can view global reports, manage investors, process branch-wise payrolls, and configure system masters.
Receptionist: Branch-specific access. Can handle POS/billing, record collections/expenses, manage local inventory, register members, and view branch-specific reports.
Trainer: Mobile-first access. Can view assigned clients, manage their schedule/bookings, mark attendance, and view their commission/earnings.
Member: Mobile-first access. Can view their active plans, remaining sessions, book PT/Group sessions, and view their access/payment history.
3. Core Entities & Required Database Schema
The backend needs to support the following relational entities:
A. Users & Authentication (users table)
Fields: id, name, email, phone, role (Owner, Receptionist, Trainer, Member), branch_id, status (Active, Inactive, Blocked), avatar_url, joining_date.
Staff Specific: designation, member_count (for trainers).
Member Specific: dob, gender, address, emergency_contact.
Related Tables:
user_documents: type, number, expiry_date, auto_notify, reminder_days.
user_family: name, relationship, contact.
user_plans (Plan History): plan_id, start_date, end_date, status, used_sessions, total_sessions.
B. Branches (branches table)
Fields: id, name, location, manager_name, status, start_date, salary_release_date.
C. Payroll & Salaries (salaries & salary_history tables)
Salary Config: user_id, type (Monthly/Daily), amount, frequency, cycle_start_date.
Salary Advance: total_amount, months, monthly_deduction, remaining_amount, repay_mode (full/divide).
Commission: amount_per_member (Flat rate per assigned member/session).
Salary Release History: Tracks bulk salary releases per branch (date, total_amount, staff_count, releasor_name).
D. Inventory & POS (products & stock_history tables)
Products: id, name, category, branch_id, cost_price, selling_price, stock, reorder_level, sku, status.
Stock History: Tracks every addition, deduction, or POS sale (product_id, qty_change, new_stock, action_type, date).
E. Financials (collections & expenses tables)
Collections (Income): id, date, branch_id, type (Product sale, Gym fee, PT fee), amount, method (Cash/Card/Online), items (JSON array of products sold if applicable).
Expenses: id, date, branch_id, category, amount, type (Internal, Petty cash, ROI Payout), remarks.
F. Investors & ROI (investors & investor_payouts tables)
Investors: id, name, investment_date, amount, roi_percent, roi_period (Monthly/Yearly), profit_sharing_percent, branch_ids (Array or 'All'), status (Active/Closed).
Payouts: investor_id, due_date, paid_date, expected_amount, paid_amount, adjustment (carry-over from previous under/over payments), status (Pending/Paid).
G. CRM / Enquiries (enquiries table)
Fields: id, name, contact, email, programs (Array), goal, source, assigned_trainer_id, status (New, Follow-up, Converted), next_follow_up_date.
H. Scheduling & Calendar (sessions table)
Fields: id, member_id, trainer_id, date_time, session_type (Personal/Group), status (Confirmed, Completed, Cancelled), cancellation_reason.
4. Key Business Logic & Backend Processes
The backend API must handle the following complex logic:
Salary Calculation Engine:
Formula: Net Payable = Base Salary + (Assigned Members * Commission Rate) - Monthly Advance Deduction.
When a bulk "Salary Release" is triggered, the backend must generate individual payslips, deduct the monthly_deduction from the staff's remaining_advance, and log the total in expenses.
Inventory Management:
When a POS Collection is created (type: 'Product sale'), the backend must automatically deduct the sold quantities from the products table and log the changes in stock_history.
Investor Payout Carry-over:
If an investor is paid less or more than their expected_amount for a given month, the difference (adjustment) must automatically be added/subtracted from their next scheduled payout.
Session Deductions:
When a session is marked as "Completed" (or cancelled late), it must decrement the used_sessions count on the Member's currently active user_plan.
Automated Cron Jobs / Background Tasks:
Document Expiry: Daily check. If expiry_date - reminder_days is reached, trigger a notification.
Plan Expiry: Automatically change user_plans status to 'Expired' when end_date passes.

View File

@ -0,0 +1,14 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Account;
class AccountController extends Controller
{
public function index()
{
return response()->json(Account::with(['accountable', 'branch'])->orderBy('date', 'desc')->orderBy('time', 'desc')->get());
}
}

View File

@ -0,0 +1,136 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
/**
* Show the owner login page.
*/
public function showLogin()
{
return view('welcome');
}
/**
* Show the receptionist login page.
*/
public function showReceptionistLogin()
{
return view('welcome');
}
/**
* Handle owner login request.
*/
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::guard('web')->attempt($credentials, $request->boolean('remember'))) {
$request->session()->regenerate();
$user = Auth::guard('web')->user();
return response()->json([
'user' => $user,
'redirect' => '/owner/dashboard'
]);
}
return response()->json([
'message' => 'The provided credentials do not match our records.',
], 401);
}
/**
* Handle receptionist login request.
*/
public function receptionistLogin(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::guard('receptionist')->attempt($credentials, $request->boolean('remember'))) {
$request->session()->regenerate();
$user = Auth::guard('receptionist')->user();
return response()->json([
'user' => $user,
'redirect' => '/receptionist/dashboard'
]);
}
return response()->json([
'message' => 'The provided credentials do not match our records.',
], 401);
}
/**
* Get the authenticated user's profile.
*/
public function profile(Request $request)
{
$context = $request->query('context', 'owner');
if ($context === 'receptionist') {
if ($user = Auth::guard('receptionist')->user()) {
$user->load('branch');
return response()->json([
'user' => $user,
'role' => 'receptionist',
'branch' => $user->branch ? $user->branch->name : 'N/A'
]);
}
// fallback
if ($user = Auth::guard('web')->user()) {
return response()->json([
'user' => $user,
'role' => 'owner',
'branch' => 'Management'
]);
}
} else {
// Check Owner Guard
if ($user = Auth::guard('web')->user()) {
return response()->json([
'user' => $user,
'role' => 'owner',
'branch' => 'Management'
]);
}
// Check Receptionist Guard fallback
if ($user = Auth::guard('receptionist')->user()) {
$user->load('branch');
return response()->json([
'user' => $user,
'role' => 'receptionist',
'branch' => $user->branch ? $user->branch->name : 'N/A'
]);
}
}
return response()->json(['message' => 'Unauthenticated'], 401);
}
/**
* Handle logout request.
*/
public function logout(Request $request)
{
Auth::guard('web')->logout();
Auth::guard('receptionist')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

View File

@ -0,0 +1,122 @@
<?php
namespace App\Http\Controllers;
use App\Models\Branch;
use App\Models\BranchDocument;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class BranchController extends Controller
{
public function index()
{
return response()->json(Branch::with('documents')->get());
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string',
'location' => 'required|string',
'manager_name' => 'required|string',
'operational_start_date' => 'required|date',
'payroll_from_day' => 'required|integer|min:1|max:31',
'payroll_to_day' => 'required|integer|min:1|max:31',
'salary_generation_day' => 'required|integer|min:1|max:31',
'docs' => 'required|array|min:1',
'docs.*.file' => 'required|file',
'docs.*.name' => 'required|string',
'docs.*.document_number' => 'nullable|string',
'docs.*.expiry_date' => 'required|date',
'docs.*.reminder_days' => 'nullable|integer|min:0',
]);
$branch = Branch::create([
'name' => $validated['name'],
'location' => $validated['location'],
'manager_name' => $validated['manager_name'],
'operational_start_date' => $validated['operational_start_date'],
'payroll_from_day' => $validated['payroll_from_day'],
'payroll_to_day' => $validated['payroll_to_day'],
'salary_generation_day' => $validated['salary_generation_day'],
'status' => 'Active'
]);
foreach ($validated['docs'] as $doc) {
$path = $doc['file']->store('branch_documents', 'public');
BranchDocument::create([
'branch_id' => $branch->id,
'name' => $doc['name'],
'document_number' => $doc['document_number'] ?? null,
'path' => $path,
'expiry_date' => $doc['expiry_date'],
'reminder_days' => $doc['reminder_days'] ?? 30
]);
}
return response()->json(['message' => 'Branch created successfully', 'branch' => $branch]);
}
public function update(Request $request, $id)
{
$branch = Branch::findOrFail($id);
$validated = $request->validate([
'name' => 'required|string',
'location' => 'required|string',
'manager_name' => 'required|string',
'operational_start_date' => 'required|date',
'payroll_from_day' => 'required|integer|min:1|max:31',
'payroll_to_day' => 'required|integer|min:1|max:31',
'salary_generation_day' => 'required|integer|min:1|max:31',
'status' => 'required|string',
'new_docs' => 'nullable|array',
'new_docs.*.file' => 'required|file',
'new_docs.*.name' => 'required|string',
'new_docs.*.document_number' => 'nullable|string',
'new_docs.*.expiry_date' => 'required|date',
'new_docs.*.reminder_days' => 'nullable|integer|min:0',
]);
$branch->update([
'name' => $validated['name'],
'location' => $validated['location'],
'manager_name' => $validated['manager_name'],
'operational_start_date' => $validated['operational_start_date'],
'payroll_from_day' => $validated['payroll_from_day'],
'payroll_to_day' => $validated['payroll_to_day'],
'salary_generation_day' => $validated['salary_generation_day'],
'status' => $validated['status'],
]);
if (isset($validated['new_docs'])) {
foreach ($validated['new_docs'] as $doc) {
$path = $doc['file']->store('branch_documents', 'public');
BranchDocument::create([
'branch_id' => $branch->id,
'name' => $doc['name'],
'document_number' => $doc['document_number'] ?? null,
'path' => $path,
'expiry_date' => $doc['expiry_date'],
'reminder_days' => $doc['reminder_days'] ?? 30
]);
}
}
return response()->json(['message' => 'Branch updated successfully', 'branch' => $branch->load('documents')]);
}
public function show($id)
{
return response()->json(Branch::with('documents')->findOrFail($id));
}
public function destroy($id)
{
$branch = Branch::findOrFail($id);
// Documents will be auto-deleted via cascade constraint in migration
$branch->delete();
return response()->json(['message' => 'Branch deleted successfully']);
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace App\Http\Controllers;
use App\Models\Receptionist;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
class BranchReceptionistController extends Controller
{
/**
* Get all receptionists for a branch.
*/
public function show($branchId)
{
$receptionists = Receptionist::where('branch_id', $branchId)->get();
return response()->json($receptionists);
}
/**
* Create or update a receptionist.
*/
public function store(Request $request, $branchId)
{
$validated = $request->validate([
'id' => 'nullable|exists:receptionists,id',
'name' => 'required|string|max:255',
'email' => [
'required',
'email',
Rule::unique('receptionists')->ignore($request->id),
],
'password' => $request->id ? 'nullable|min:6|confirmed' : 'required|min:6|confirmed',
]);
if ($request->id) {
$receptionist = Receptionist::findOrFail($request->id);
$receptionist->name = $validated['name'];
$receptionist->email = $validated['email'];
if (!empty($validated['password'])) {
$receptionist->password = $validated['password'];
}
$receptionist->save();
return response()->json($receptionist);
} else {
$new = Receptionist::create([
'branch_id' => $branchId,
'name' => $validated['name'],
'email' => $validated['email'],
'password' => $validated['password'],
]);
return response()->json($new, 201);
}
}
/**
* Delete a receptionist account.
*/
public function destroy($branchId, $receptionistId = null)
{
$id = $receptionistId ?: request()->receptionist_id;
if ($id) {
Receptionist::where('branch_id', $branchId)->where('id', $id)->delete();
}
return response()->json(['message' => 'Receptionist account deleted.']);
}
}

View File

@ -0,0 +1,153 @@
<?php
namespace App\Http\Controllers;
use App\Models\Collection;
use App\Models\CollectionItem;
use App\Models\CollectionType;
use App\Models\Product;
use App\Models\StockAdjustment;
use App\Models\Account;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class CollectionController extends Controller
{
public function index(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$branchId = $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$startDate = $request->query('start_date');
$endDate = $request->query('end_date');
$paymentMethod = $request->query('payment_method');
$query = Collection::with(['branch', 'type', 'items.product']);
if ($branchId) {
$query->where('branch_id', $branchId);
}
if ($startDate) {
$query->where('date', '>=', $startDate);
}
if ($endDate) {
$query->where('date', '<=', $endDate);
}
if ($paymentMethod) {
$query->where('payment_method', $paymentMethod);
}
return response()->json($query->orderBy('date', 'desc')->get()->map(function($c) {
$originalAmount = $c->items->sum('subtotal');
$c->is_adjusted = $originalAmount > 0 && abs($c->amount - $originalAmount) > 0.01;
$c->original_amount = $originalAmount;
return $c;
}));
}
public function store(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$data = $request->all();
if ($user->isReceptionist()) {
$data['branch_id'] = $user->branch_id;
}
$validated = \Illuminate\Support\Facades\Validator::make($data, [
'date' => 'required|date',
'branch_id' => 'required|exists:branches,id',
'collection_type_id' => 'required|exists:collection_types,id',
'payment_method' => 'required|string',
'amount' => 'required|numeric|min:0',
'remarks' => 'nullable|string',
'items' => 'nullable|array',
'items.*.product_id' => 'required_with:items|exists:products,id',
'items.*.quantity' => 'required_with:items|integer|min:1',
'items.*.unit_price' => 'required_with:items|numeric|min:0',
])->validate();
return DB::transaction(function () use ($validated) {
$count = Collection::count() + 1;
$transactionId = "COL-" . (1000 + $count);
$collection = Collection::create([
'date' => $validated['date'],
'branch_id' => $validated['branch_id'],
'collection_type_id' => $validated['collection_type_id'],
'payment_method' => $validated['payment_method'],
'amount' => $validated['amount'],
'remarks' => $validated['remarks'],
'transaction_id' => $transactionId
]);
$type = CollectionType::find($validated['collection_type_id']);
if (isset($validated['items']) && !empty($validated['items'])) {
foreach ($validated['items'] as $item) {
CollectionItem::create([
'collection_id' => $collection->id,
'product_id' => $item['product_id'],
'quantity' => $item['quantity'],
'unit_price' => $item['unit_price'],
'subtotal' => $item['quantity'] * $item['unit_price']
]);
// If it's a "Product sale" type, we should also track inventory
// Checking if the type name is "Product sale"
if (strtolower($type->name) === 'product sale' || strtolower($type->name) === 'product saled') {
$product = Product::find($item['product_id']);
$newStock = $product->current_stock - $item['quantity'];
$status = 'In Stock';
if ($newStock <= 0) $status = 'Out of Stock';
else if ($newStock <= $product->reorder_level) $status = 'Low Stock';
$product->update([
'current_stock' => $newStock,
'status' => $status
]);
StockAdjustment::create([
'product_id' => $product->id,
'adjustment_qty' => -$item['quantity'],
'new_stock' => $newStock,
'adjustment_date' => $validated['date'],
'reason' => 'Sale',
'remarks' => "Collection #{$transactionId}"
]);
}
}
}
// Record to Ledger
Account::create([
'date' => $validated['date'],
'time' => Carbon::parse($validated['date'])->isToday() ? Carbon::now()->toTimeString() : '00:00:00',
'credit' => $validated['amount'],
'debit' => 0,
'type' => 'income',
'branch_id' => $validated['branch_id'],
'accountable_id' => $collection->id,
'accountable_type' => Collection::class,
'description' => "Collection [{$type->name}] #{$transactionId}"
]);
return response()->json($collection->load(['branch', 'type', 'items.product']), 201);
});
}
public function show($id)
{
$collection = Collection::with(['branch', 'type', 'items.product'])->findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $collection->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
return response()->json($collection);
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@ -0,0 +1,134 @@
<?php
namespace App\Http\Controllers;
use App\Models\Expense;
use App\Models\Account;
use App\Models\ExpenseCategory;
use App\Models\Branch;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
class ExpenseController extends Controller
{
public function index(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$query = Expense::with(['branch', 'category']);
$branchId = $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$startDate = $request->query('start_date');
$endDate = $request->query('end_date');
if ($branchId) {
$query->where('branch_id', $branchId);
}
if ($startDate) {
$query->where('date', '>=', $startDate);
}
if ($endDate) {
$query->where('date', '<=', $endDate);
}
return response()->json($query->orderBy('date', 'desc')->get());
}
public function store(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$data = $request->all();
if ($user->isReceptionist()) {
$data['branch_id'] = $user->branch_id;
}
$validated = \Illuminate\Support\Facades\Validator::make($data, [
'date' => 'required|date',
'branch_id' => 'required|exists:branches,id',
'expense_category_id' => 'required|exists:expense_categories,id',
'expense_type' => 'required|string|in:Account,Petty Cash',
'amount' => 'required|numeric|min:0',
'remarks' => 'nullable|string'
])->validate();
// Security check for branch_id if receptionist
if ($user->isReceptionist() && $validated['branch_id'] != $user->branch_id) {
return response()->json(['message' => 'Unauthorized branch assignment'], 403);
}
$expense = Expense::create($validated);
// Auto-ledgering: Debit from Accounts
Account::create([
'date' => $expense->date,
'time' => Carbon::now()->toTimeString(),
'credit' => 0,
'debit' => $expense->amount,
'type' => 'expense',
'branch_id' => $expense->branch_id,
'accountable_id' => $expense->id,
'accountable_type' => Expense::class,
'description' => "Expense: {$expense->category->name} - {$expense->remarks}"
]);
return response()->json($expense->load(['branch', 'category']), 201);
}
public function getCategories()
{
return response()->json(ExpenseCategory::where('status', 'Active')->get());
}
public function getBranches()
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
$query = Branch::where('status', 'Active');
if ($user && $user->isReceptionist()) {
$query->where('id', $user->branch_id);
}
return response()->json($query->get());
}
public function getSalaryHistory(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$salaryCategory = ExpenseCategory::where('name', 'Salary')->first();
if (!$salaryCategory) return response()->json([]);
$query = Expense::with(['branch'])
->where('expense_category_id', $salaryCategory->id);
if ($user->isReceptionist()) {
$query->where('branch_id', $user->branch_id);
}
$expenses = $query->orderBy('date', 'desc')->get();
// Group by batch_id
$grouped = $expenses->groupBy(function ($item) {
return $item->batch_id ?? 'INDIVIDUAL-' . $item->id;
})->map(function ($items, $batchId) {
$first = $items->first();
$isBulk = strpos($batchId, 'BATCH-') === 0;
return [
'batch_id' => $isBulk ? $batchId : null,
'is_bulk' => $isBulk,
'date' => $first->date,
'branch' => $first->branch?->name ?? 'Mixed',
'amount' => $items->sum('amount'),
'remarks' => $isBulk ? "Bulk Salary Release" : $first->remarks,
'count' => $items->count(),
'items' => $items // Optional: for detail view
];
})->values();
return response()->json($grouped);
}
}

View File

@ -0,0 +1,304 @@
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Models\StockAdjustment;
use App\Models\ProductSale;
use App\Models\ProductSaleItem;
use App\Models\Account;
use App\Models\Branch;
use App\Models\ProductCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class InventoryController extends Controller
{
public function getProducts(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$branchId = $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$status = $request->query('status'); // In Stock, Low Stock, Out of Stock
$query = Product::with(['branch', 'category']);
if ($branchId) {
$query->where('branch_id', $branchId);
}
if ($status) {
$query->where('status', $status);
}
return response()->json($query->orderBy('name')->get());
}
public function storeProduct(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'sku' => 'nullable|string|unique:products,sku',
'product_category_id' => 'required|exists:product_categories,id',
'branch_id' => 'required|exists:branches,id',
'cost_price' => 'required|numeric|min:0',
'selling_price' => 'required|numeric|min:0',
'current_stock' => 'required|integer|min:0',
'reorder_level' => 'required|integer|min:0',
]);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $validated['branch_id'] != $user->branch_id) {
return response()->json(['message' => 'Unauthorized branch assignment'], 403);
}
$status = 'In Stock';
if ($validated['current_stock'] <= 0) $status = 'Out of Stock';
else if ($validated['current_stock'] <= $validated['reorder_level']) $status = 'Low Stock';
$product = Product::create(array_merge($validated, ['status' => $status]));
// Record Initial Stock Adjustment
StockAdjustment::create([
'product_id' => $product->id,
'adjustment_qty' => $product->current_stock,
'new_stock' => $product->current_stock,
'adjustment_date' => Carbon::now()->toDateString(),
'reason' => 'Initial',
'remarks' => 'System initialization'
]);
return response()->json($product->load(['branch', 'category']), 201);
}
public function adjustStock(Request $request, $id)
{
$product = Product::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $product->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$validated = $request->validate([
'adjustment_qty' => 'required|integer', // Positive for add, negative for remove
'adjustment_date' => 'required|date',
'reason' => 'required|string',
'remarks' => 'nullable|string'
]);
DB::transaction(function () use ($product, $validated) {
$newStock = $product->current_stock + $validated['adjustment_qty'];
$status = 'In Stock';
if ($newStock <= 0) $status = 'Out of Stock';
else if ($newStock <= $product->reorder_level) $status = 'Low Stock';
$product->update([
'current_stock' => $newStock,
'status' => $status
]);
StockAdjustment::create(array_merge($validated, [
'product_id' => $product->id,
'new_stock' => $newStock
]));
});
return response()->json($product->fresh(['branch', 'category']));
}
public function getStockHistory($id)
{
$product = Product::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $product->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$history = StockAdjustment::where('product_id', $id)
->orderBy('adjustment_date', 'desc')
->orderBy('created_at', 'desc')
->get();
return response()->json($history);
}
public function getSales(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
$branchId = $user && $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$startDate = $request->query('start_date');
$endDate = $request->query('end_date');
$query = ProductSale::with(['branch', 'items.product']);
if ($branchId) {
$query->where('branch_id', $branchId);
}
if ($startDate) {
$query->where('date', '>=', $startDate);
}
if ($endDate) {
$query->where('date', '<=', $endDate);
}
return response()->json($query->orderBy('date', 'desc')->get());
}
public function storeSale(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$data = $request->all();
if ($user->isReceptionist()) {
$data['branch_id'] = $user->branch_id;
}
$validated = \Illuminate\Support\Facades\Validator::make($data, [
'branch_id' => 'required|exists:branches,id',
'payment_method' => 'required|string',
'items' => 'required|array|min:1',
'items.*.product_id' => 'required|exists:products,id',
'items.*.quantity' => 'required|integer|min:1',
'items.*.unit_price' => 'nullable|numeric|min:0',
'items.*.price' => 'nullable|numeric|min:0',
'total_amount' => 'nullable|numeric|min:0',
'remarks' => 'nullable|string'
])->validate();
// Security check for branch_id if receptionist
if ($user->isReceptionist() && $validated['branch_id'] != $user->branch_id) {
return response()->json(['message' => 'Unauthorized branch assignment'], 403);
}
return DB::transaction(function () use ($validated) {
$subtotal = 0;
$items = $validated['items'];
foreach ($items as &$item) {
$price = $item['unit_price'] ?? $item['price'] ?? 0;
$item['final_price'] = $price;
$subtotal += $item['quantity'] * $price;
}
$vatPercentage = 0.05;
$vatAmount = round($subtotal * $vatPercentage, 2);
$totalWithVat = $subtotal + $vatAmount;
// If a manual total_amount was provided, we use it, otherwise use calculated total
$totalAmount = $validated['total_amount'] ?? $totalWithVat;
$count = ProductSale::count() + 1;
$transactionId = "COL-" . (1000 + $count);
$sale = ProductSale::create([
'transaction_id' => $transactionId,
'branch_id' => $validated['branch_id'],
'subtotal_amount' => $subtotal,
'vat_amount' => $vatAmount,
'total_amount' => $totalAmount,
'payment_method' => $validated['payment_method'],
'date' => Carbon::now()->toDateString(),
'remarks' => $validated['remarks'] ?? null
]);
foreach ($items as $item) {
ProductSaleItem::create([
'product_sale_id' => $sale->id,
'product_id' => $item['product_id'],
'quantity' => $item['quantity'],
'unit_price' => $item['final_price'],
'subtotal' => $item['quantity'] * $item['final_price']
]);
// Update Stock
$product = Product::find($item['product_id']);
$newStock = $product->current_stock - $item['quantity'];
$status = 'In Stock';
if ($newStock <= 0) $status = 'Out of Stock';
else if ($newStock <= $product->reorder_level) $status = 'Low Stock';
$product->update([
'current_stock' => $newStock,
'status' => $status
]);
// Record Adjustment
StockAdjustment::create([
'product_id' => $product->id,
'adjustment_qty' => -$item['quantity'],
'new_stock' => $newStock,
'adjustment_date' => Carbon::now()->toDateString(),
'reason' => 'Sale',
'remarks' => "Sale #{$transactionId}"
]);
}
// Record to Accounts (Credit)
Account::create([
'date' => Carbon::now()->toDateString(),
'time' => Carbon::now()->toTimeString(),
'credit' => $totalAmount,
'debit' => 0,
'type' => 'sale',
'branch_id' => $validated['branch_id'],
'accountable_id' => $sale->id,
'accountable_type' => ProductSale::class,
'description' => "Product Sale #{$transactionId}"
]);
return response()->json($sale->load('items.product'), 201);
});
}
public function getCategories()
{
return response()->json(ProductCategory::where('status', 'Active')->get());
}
public function getAllMovements(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
$query = StockAdjustment::with(['product.branch']);
$branchId = $user && $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$startDate = $request->query('start_date');
$endDate = $request->query('end_date');
if ($branchId) {
$query->whereHas('product', function($q) use ($branchId) {
$q->where('branch_id', $branchId);
});
}
if ($startDate) {
$query->where('adjustment_date', '>=', $startDate);
}
if ($endDate) {
$query->where('adjustment_date', '<=', $endDate);
}
$movements = $query->orderBy('adjustment_date', 'desc')
->orderBy('created_at', 'desc')
->get()
->map(function ($adj) {
return [
'id' => $adj->id,
'date' => $adj->adjustment_date,
'product_name' => $adj->product->name,
'sku' => $adj->product->sku,
'branch' => $adj->product->branch->name,
'reason' => $adj->reason,
'change' => $adj->adjustment_qty,
'new_stock' => $adj->new_stock,
'remarks' => $adj->remarks
];
});
return response()->json($movements);
}
}

View File

@ -0,0 +1,394 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Investor;
use App\Models\Account;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
class InvestorController extends Controller
{
public function index()
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
$query = Investor::with('branches');
if ($user && $user->isReceptionist()) {
$query->where(function($q) use ($user) {
$q->where('applicable_to_all_branches', true)
->orWhereHas('branches', function($bq) use ($user) {
$bq->where('branches.id', $user->branch_id);
});
});
}
return response()->json($query->get());
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'investment_date' => 'required|date',
'investment_amount' => 'required|numeric',
'applicable_to_all_branches' => 'required|boolean',
'roi_type' => 'required|string|in:Percentage,Fixed Amount',
'roi_value' => 'nullable|numeric',
'roi_period' => 'nullable|string',
'branch_ids' => 'nullable|array',
'branch_ids.*' => 'exists:branches,id',
'security_proof_document' => 'nullable|file|mimes:pdf,png,jpg,jpeg|max:10240',
]);
if ($request->hasFile('security_proof_document')) {
$path = $request->file('security_proof_document')->store('investor_docs', 'public');
$validated['security_proof_document'] = $path;
}
$investor = Investor::create($validated);
// Log to Accounts
Account::create([
'date' => Carbon::now()->toDateString(),
'time' => Carbon::now()->toTimeString(),
'branch_id' => $investor->applicable_to_all_branches ? null : $investor->branches->first()?->id,
'credit' => $investor->investment_amount,
'debit' => 0,
'type' => 'investor',
'accountable_id' => $investor->id,
'accountable_type' => Investor::class,
'description' => "Initial investment from {$investor->name}"
]);
if (!$validated['applicable_to_all_branches'] && isset($validated['branch_ids'])) {
$investor->branches()->attach($validated['branch_ids']);
}
return response()->json($investor->load('branches'), 201);
}
public function show($id)
{
$investor = Investor::with('branches')->findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist()) {
$isLinked = $investor->applicable_to_all_branches || $investor->branches->contains($user->branch_id);
if (!$isLinked) {
return response()->json(['message' => 'Unauthorized'], 403);
}
}
return response()->json($investor);
}
public function update(Request $request, $id)
{
$investor = Investor::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist()) {
$isLinked = $investor->applicable_to_all_branches || $investor->branches->contains($user->branch_id);
if (!$isLinked) {
return response()->json(['message' => 'Unauthorized'], 403);
}
}
$validated = $request->validate([
'name' => 'required|string|max:255',
'investment_date' => 'required|date',
'investment_amount' => 'required|numeric',
'applicable_to_all_branches' => 'required|boolean',
'roi_type' => 'required|string|in:Percentage,Fixed Amount',
'roi_value' => 'nullable|numeric',
'roi_period' => 'nullable|string',
'branch_ids' => 'nullable|array',
'branch_ids.*' => 'exists:branches,id',
'security_proof_document' => 'nullable|file|mimes:pdf,png,jpg,jpeg|max:10240',
]);
if ($request->hasFile('security_proof_document')) {
if ($investor->security_proof_document) {
Storage::disk('public')->delete($investor->security_proof_document);
}
$path = $request->file('security_proof_document')->store('investor_docs', 'public');
$validated['security_proof_document'] = $path;
}
$investor->update($validated);
if ($validated['applicable_to_all_branches']) {
$investor->branches()->detach();
} elseif (isset($validated['branch_ids'])) {
$investor->branches()->sync($validated['branch_ids']);
}
return response()->json($investor->load('branches'));
}
public function destroy($id)
{
$investor = Investor::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist()) {
return response()->json(['message' => 'Unauthorized'], 403);
}
// Delete associated Account records (investments)
Account::where('accountable_id', $investor->id)
->where('accountable_type', Investor::class)
->delete();
// Also delete associated payouts and their account entries
$payouts = \App\Models\InvestorPayout::where('investor_id', $id)->get();
foreach ($payouts as $payout) {
Account::where('accountable_id', $payout->id)
->where('accountable_type', \App\Models\InvestorPayout::class)
->delete();
$payout->delete();
}
// Detach branches first to avoid foreign key issues
$investor->branches()->detach();
if ($investor->security_proof_document) {
Storage::disk('public')->delete($investor->security_proof_document);
}
$investor->delete();
return response()->json(['message' => 'Investor and associated financial records deleted successfully']);
}
public function getPayouts($id)
{
$investor = Investor::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist()) {
$isLinked = $investor->applicable_to_all_branches || $investor->branches->contains($user->branch_id);
if (!$isLinked) {
return response()->json(['message' => 'Unauthorized'], 403);
}
}
$payouts = \App\Models\InvestorPayout::where('investor_id', $id)->orderBy('payout_date', 'desc')->get();
return response()->json($payouts);
}
public function getROIPayoutStatus($id)
{
$investor = Investor::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist()) {
$isLinked = $investor->applicable_to_all_branches || $investor->branches->contains($user->branch_id);
if (!$isLinked) {
return response()->json(['message' => 'Unauthorized'], 403);
}
}
$investmentDate = Carbon::parse($investor->investment_date)->startOfMonth();
$currentMonth = Carbon::now()->startOfMonth();
// Fetch all payouts for this investor
$payouts = \App\Models\InvestorPayout::where('investor_id', $id)->get();
$status = [];
$tempMonth = $investmentDate->copy();
$periodMonths = 1;
if ($investor->roi_period === 'Quarterly') $periodMonths = 3;
if ($investor->roi_period === 'Yearly') $periodMonths = 12;
$carryOver = 0;
$canSettleFound = false;
while ($tempMonth->lessThanOrEqualTo($currentMonth)) {
$monthKey = $tempMonth->format('F Y');
$baseROI = round($investor->roi_type === 'Percentage'
? ($investor->investment_amount * ($investor->roi_value / 100))
: ($investor->roi_value ?? 0), 2);
$targetAmount = $baseROI + $carryOver;
// Check if there is a payout recorded for this specific month
$monthPayouts = $payouts->filter(function($p) use ($monthKey) {
return $p->payout_month === $monthKey;
});
if ($monthPayouts->isNotEmpty()) {
$paidForThisMonth = $monthPayouts->sum('amount');
$status[] = [
'month' => $monthKey,
'status' => 'Paid',
'base_amount' => $baseROI,
'carry_from_previous' => $carryOver,
'target_amount' => $targetAmount,
'paid' => $paidForThisMonth,
'amount' => 0,
'can_settle' => false
];
// Carry forward the difference
$carryOver = round($targetAmount - $paidForThisMonth, 2);
} else {
$canSettle = false;
if (!$canSettleFound) {
$canSettle = true;
$canSettleFound = true;
}
$status[] = [
'month' => $monthKey,
'status' => 'Pending',
'base_amount' => $baseROI,
'carry_from_previous' => $carryOver,
'target_amount' => $targetAmount,
'paid' => 0,
'amount' => $targetAmount,
'can_settle' => $canSettle
];
// No carry over update here, it stays until this month is settled
// Actually, if we don't settle Jan, Feb's target should eventually include Jan's?
// The user says "Older months must be settled first", so we don't need to accumulate carry automatically
// across pending months, because you can't skip.
}
$tempMonth->addMonths($periodMonths);
}
return response()->json(array_reverse($status));
}
public function settleROIPayout(Request $request, $id)
{
$investor = Investor::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist()) {
$isLinked = $investor->applicable_to_all_branches || $investor->branches->contains($user->branch_id);
if (!$isLinked) {
return response()->json(['message' => 'Unauthorized'], 403);
}
}
$validated = $request->validate([
'payout_month' => 'required|string',
'amount' => 'required|numeric',
'payout_date' => 'required|date',
'payment_method' => 'nullable|string',
'remarks' => 'nullable|string'
]);
$payout = \App\Models\InvestorPayout::create(array_merge($validated, [
'investor_id' => $id,
'status' => 'Paid'
]));
// Log to Accounts
Account::create([
'date' => $validated['payout_date'],
'time' => Carbon::now()->toTimeString(),
'branch_id' => $investor->applicable_to_all_branches ? null : $investor->branches->first()?->id,
'credit' => 0,
'debit' => $validated['amount'],
'type' => 'payout',
'accountable_id' => $payout->id,
'accountable_type' => \App\Models\InvestorPayout::class,
'description' => "ROI Payout for {$investor->name} - {$validated['payout_month']}"
]);
// Log to Expenses
$roiCategory = \App\Models\ExpenseCategory::where('name', 'ROI Payout')->first();
\App\Models\Expense::create([
'date' => $validated['payout_date'],
'branch_id' => $investor->applicable_to_all_branches ? null : $investor->branches->first()?->id,
'expense_category_id' => $roiCategory ? $roiCategory->id : 1,
'expense_type' => 'Account',
'amount' => $validated['amount'],
'remarks' => "ROI Payout to {$investor->name} for {$validated['payout_month']}"
]);
return response()->json(['message' => 'ROI settled successfully', 'payout' => $payout]);
}
public function getAllPendingROIs(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
$branchId = $user && $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$query = Investor::with('branches');
if ($branchId) {
$query->where(function($q) use ($branchId) {
$q->where('applicable_to_all_branches', true)
->orWhereHas('branches', function($bq) use ($branchId) {
$bq->where('branches.id', $branchId);
});
});
}
$investors = $query->get();
$pending = [];
$currentMonth = Carbon::now()->startOfMonth();
foreach ($investors as $investor) {
$investmentDate = Carbon::parse($investor->investment_date)->startOfMonth();
$payouts = \App\Models\InvestorPayout::where('investor_id', $investor->id)->get();
$tempMonth = $investmentDate->copy();
$periodMonths = 1;
if ($investor->roi_period === 'Quarterly') $periodMonths = 3;
if ($investor->roi_period === 'Yearly') $periodMonths = 12;
$investorPendingMonths = [];
$carryOver = 0;
while ($tempMonth->lessThanOrEqualTo($currentMonth)) {
$monthKey = $tempMonth->format('F Y');
$baseROI = round($investor->roi_type === 'Percentage'
? ($investor->investment_amount * ($investor->roi_value / 100))
: ($investor->roi_value ?? 0), 2);
$targetAmount = $baseROI + $carryOver;
$monthPayouts = $payouts->filter(function($p) use ($monthKey) {
return $p->payout_month === $monthKey;
});
if ($monthPayouts->isNotEmpty()) {
$paidForThisMonth = $monthPayouts->sum('amount');
$carryOver = round($targetAmount - $paidForThisMonth, 2);
} else {
$investorPendingMonths[] = [
'payout_month' => $monthKey,
'base_amount' => $baseROI,
'carry_from_previous' => $carryOver,
'amount' => $targetAmount
];
// If a month is missing, we stop accumulating carry for the global view
// until that month is settled, to avoid confusing numbers.
// Or should we? Let's stay consistent with getROIPayoutStatus.
$carryOver = 0;
}
$tempMonth->addMonths($periodMonths);
}
if (!empty($investorPendingMonths)) {
$totalPending = array_sum(array_column($investorPendingMonths, 'amount'));
$pending[] = [
'investor_id' => $investor->id,
'investor_name' => $investor->name,
'investment_amount' => $investor->investment_amount,
'roi_percentage' => $investor->roi_value,
'roi_type' => $investor->roi_type,
'roi_period' => $investor->roi_period,
'pending_count' => count($investorPendingMonths),
'total_pending' => $totalPending,
'pending_months' => $investorPendingMonths
];
}
}
return response()->json($pending);
}
public function storePayout(Request $request, $id)
{
// ... (keep existing storePayout or just use settleROI if we want unity)
// I'll keep it for now but settleROI is more complete with accounts/expenses
return $this->settleROIPayout($request, $id);
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\CollectionType;
use App\Models\ExpenseCategory;
use App\Models\ProductCategory;
use App\Models\PaymentMethod;
use Illuminate\Support\Facades\Log;
class MasterController extends Controller
{
private function getModel($type)
{
switch ($type) {
case 'collection': return new CollectionType();
case 'expense': return new ExpenseCategory();
case 'product': return new ProductCategory();
case 'payment_method': return new PaymentMethod();
default: return null;
}
}
public function index($type)
{
$model = $this->getModel($type);
if (!$model) return response()->json(['message' => 'Invalid master type'], 400);
return response()->json($model::all());
}
public function store(Request $request, $type)
{
$model = $this->getModel($type);
if (!$model) return response()->json(['message' => 'Invalid master type'], 400);
$validated = $request->validate([
'name' => 'required|string|max:255',
'status' => 'required|string|in:Active,Inactive'
]);
$item = $model::create($validated);
return response()->json($item, 201);
}
public function update(Request $request, $type, $id)
{
$model = $this->getModel($type);
if (!$model) return response()->json(['message' => 'Invalid master type'], 400);
$item = $model::findOrFail($id);
$validated = $request->validate([
'name' => 'required|string|max:255',
'status' => 'required|string|in:Active,Inactive'
]);
$item->update($validated);
return response()->json($item);
}
public function destroy($type, $id)
{
$model = $this->getModel($type);
if (!$model) return response()->json(['message' => 'Invalid master type'], 400);
$item = $model::findOrFail($id);
if ($type === 'collection' && (
strtolower($item->name) === 'product sale' ||
strtolower($item->name) === 'product saled'
)) {
return response()->json(['message' => 'System required item cannot be deleted'], 422);
}
$item->delete();
return response()->json(['message' => 'Deleted successfully']);
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class OwnerController extends Controller
{
public function index()
{
return view('welcome'); // Since we're using React, we'll use welcome as the entry point
}
}

View File

@ -0,0 +1,294 @@
<?php
namespace App\Http\Controllers;
use App\Models\Account;
use App\Models\Expense;
use App\Models\Staff;
use App\Models\Branch;
use App\Models\BranchDocument;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class ReportController extends Controller
{
public function getProfitReport(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$branchId = $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$startDate = $request->query('start_date');
$endDate = $request->query('end_date');
$query = Account::with('accountable');
if ($branchId) {
$query->where('branch_id', $branchId);
}
if ($startDate) {
$query->where('date', '>=', $startDate);
}
if ($endDate) {
$query->where('date', '<=', $endDate);
}
$totalCredits = $query->sum('credit');
$totalDebits = (clone $query)->sum('debit');
// Note: We use Account table for both to ensure consistency with the "Total Received" and "Total Debited" requirement.
// If Expenses are also tracked in Accounts as debits (which they should be), this is correct.
// Fetch Transactions for the breakdown
$accounts = Account::select('date', 'credit as amount', 'type', 'description')
->where('credit', '>', 0);
if ($branchId) {
$accounts->where('branch_id', $branchId);
}
if ($startDate) {
$accounts->where('date', '>=', $startDate);
}
if ($endDate) {
$accounts->where('date', '<=', $endDate);
}
$accounts = $accounts->get()
->map(function($a) {
$isAdjusted = false;
$originalAmount = $a->amount;
$remarks = '';
if ($a->accountable_type === \App\Models\ProductSale::class && $a->accountable) {
$originalAmount = $a->accountable->subtotal_amount + $a->accountable->vat_amount;
$isAdjusted = abs($a->amount - $originalAmount) > 0.01;
$remarks = $a->accountable->remarks;
} elseif ($a->accountable_type === \App\Models\Collection::class && $a->accountable) {
$originalAmount = $a->accountable->items()->sum('subtotal');
$isAdjusted = $originalAmount > 0 && abs($a->amount - $originalAmount) > 0.01;
$remarks = $a->accountable->remarks;
}
return [
'date' => $a->date,
'type' => 'Income',
'category' => $a->type,
'description' => $a->description,
'amount' => $a->amount,
'branch' => 'N/A',
'is_adjusted' => $isAdjusted,
'original_amount' => $originalAmount,
'remarks' => $remarks
];
});
$expensesQuery = Expense::with('category', 'branch');
if ($branchId) {
$expensesQuery->where('branch_id', $branchId);
}
if ($startDate) {
$expensesQuery->where('date', '>=', $startDate);
}
if ($endDate) {
$expensesQuery->where('date', '<=', $endDate);
}
$expenses = $expensesQuery->get()->map(function($e) {
return [
'date' => $e->date,
'type' => 'Expense',
'category' => $e->category->name ?? 'Other',
'description' => $e->remarks,
'amount' => $e->amount,
'branch' => $e->branch->name ?? 'Global'
];
});
$transactions = $accounts->concat($expenses)->sortByDesc('date')->values();
$lowStockCount = \App\Models\Product::query();
if ($branchId) {
$lowStockCount->where('branch_id', $branchId);
}
$lowStockCount = $lowStockCount->whereRaw('current_stock <= reorder_level')->count();
return response()->json([
'total_income' => $totalCredits,
'total_expense' => $totalDebits,
'net_profit' => $totalCredits - $totalDebits,
'low_stock_count' => $lowStockCount,
'transactions' => $transactions
]);
}
public function getExpiryReminders(Request $request)
{
$today = Carbon::today();
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$branchId = $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$staffDocsQuery = \App\Models\StaffDocument::with('staff.branch')
->whereNotNull('expiry_date');
if ($branchId) {
$staffDocsQuery->whereHas('staff', function($q) use ($branchId) {
$q->where('branch_id', $branchId);
});
}
$staffDocs = $staffDocsQuery->get()
->filter(function($doc) use ($today) {
$expiryDate = Carbon::parse($doc->expiry_date)->startOfDay();
$reminderDays = (int)($doc->reminder_days ?? 30);
return $today->startOfDay()->greaterThanOrEqualTo($expiryDate->copy()->subDays($reminderDays));
})
->map(function($doc) use ($today) {
$expiryDate = Carbon::parse($doc->expiry_date);
$reminderDays = (int)($doc->reminder_days ?? 30);
$reminderStartedOn = $expiryDate->copy()->subDays($reminderDays);
return [
'type' => 'Staff',
'entity_name' => $doc->staff->full_name ?? 'N/A',
'branch_name' => $doc->staff->branch->name ?? 'Global',
'document_name' => $doc->name,
'document_number' => $doc->document_number,
'reminder_started_on' => $reminderStartedOn->format('d/m/Y'),
'expiry_date' => $doc->expiry_date,
'days_left' => (int)$today->diffInDays($expiryDate, false)
];
});
// Branch Document Reminders
$branchDocsQuery = BranchDocument::with('branch')
->whereNotNull('expiry_date');
if ($branchId) {
$branchDocsQuery->where('branch_id', $branchId);
}
$branchReminders = $branchDocsQuery->get()
->filter(function($doc) use ($today) {
$expiryDate = Carbon::parse($doc->expiry_date);
$reminderDays = (int)($doc->reminder_days ?? 30);
return $today->greaterThanOrEqualTo($expiryDate->copy()->subDays($reminderDays));
})
->map(function($doc) use ($today) {
$expiryDate = Carbon::parse($doc->expiry_date);
$reminderDays = (int)($doc->reminder_days ?? 30);
$reminderStartedOn = $expiryDate->copy()->subDays($reminderDays);
return [
'type' => 'Branch',
'entity_name' => $doc->branch->name ?? 'N/A',
'branch_name' => $doc->branch->name ?? 'Global',
'document_name' => $doc->name,
'document_number' => $doc->document_number,
'reminder_started_on' => $reminderStartedOn->format('d/m/Y'),
'expiry_date' => $doc->expiry_date,
'days_left' => (int)$today->diffInDays($expiryDate, false)
];
});
return response()->json([
'reminders' => $staffDocs->concat($branchReminders)->values()
]);
}
public function getInvestmentReport(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if (!$user) return response()->json(['message' => 'Unauthenticated'], 401);
$branchId = $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$startDate = $request->query('start_date');
$endDate = $request->query('end_date');
$query = \App\Models\Investor::with('branches');
if ($branchId) {
$query->where(function($q) use ($branchId) {
$q->where('applicable_to_all_branches', true)
->orWhereHas('branches', function($bq) use ($branchId) {
$bq->where('branches.id', $branchId);
});
});
}
if ($startDate) {
$query->where('investment_date', '>=', $startDate);
}
if ($endDate) {
$query->where('investment_date', '<=', $endDate);
}
$investors = $query->get();
$reportData = [];
$currentMonth = Carbon::now()->startOfMonth();
$totalInvested = 0;
$totalROIReturned = 0;
foreach ($investors as $investor) {
$investmentDate = Carbon::parse($investor->investment_date)->startOfMonth();
// Get all actual payouts made to this investor
$totalPaid = \App\Models\InvestorPayout::where('investor_id', $investor->id)->sum('amount');
$returnsEarned = $totalPaid;
$tempMonth = $investmentDate->copy();
$periodMonths = 1;
if ($investor->roi_period === 'Quarterly') $periodMonths = 3;
if ($investor->roi_period === 'Yearly') $periodMonths = 12;
$totalPending = 0;
$carryOver = 0;
// Calculate how much should have been paid up to now
while ($tempMonth->lessThan($currentMonth)) {
$monthKey = $tempMonth->format('F Y');
$baseAmount = round($investor->roi_type === 'Percentage'
? ($investor->investment_amount * ($investor->roi_value / 100))
: ($investor->roi_value ?? 0), 2);
$expected = $baseAmount + $carryOver;
if ($totalPaid >= $expected && $expected > 0) {
$totalPaid -= $expected;
$carryOver = 0;
} else {
$paidTowardsThis = $totalPaid;
$remains = $expected - $paidTowardsThis;
$totalPaid = 0;
$carryOver = $remains;
}
$tempMonth->addMonths($periodMonths);
}
$totalPending = $carryOver; // The leftover carryover is the net pending amount
$totalInvested += $investor->investment_amount;
$totalROIReturned += $returnsEarned;
$reportData[] = [
'investor_id' => $investor->id,
'investor_name' => $investor->name,
'investment_date' => $investor->investment_date,
'investment_amount' => $investor->investment_amount,
'roi_type' => $investor->roi_type,
'roi_value' => $investor->roi_value,
'roi_period' => $investor->roi_period,
'returns_earned' => $returnsEarned,
'total_pending' => $totalPending
];
}
return response()->json([
'total_invested' => $totalInvested,
'total_roi_returned' => $totalROIReturned,
'investors' => $reportData
]);
}
}

View File

@ -0,0 +1,827 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Staff;
use App\Models\TrainerCommission;
use App\Models\SalaryAdvanceDeduction;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
class StaffController extends Controller
{
public function index(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
$query = Staff::with(['branch', 'documents']);
if ($user && $user->isReceptionist()) {
$query->where('branch_id', $user->branch_id);
} else if ($branchId = $request->query('branch_id')) {
$query->where('branch_id', $branchId);
}
return response()->json($query->get());
}
public function show($id)
{
$staff = Staff::with(['branch', 'documents'])->findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
return response()->json($staff);
}
public function store(Request $request)
{
Log::info('Creating standalone staff record', $request->all());
$validated = $request->validate([
'full_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:staff,email',
'phone' => ['required', 'string', 'max:20', 'regex:/^(\+91|91|0)?[6-9]\d{9}$|^(\+971|971|0)?5[024568]\d{7}$/'],
'role' => 'required|string',
'branch_id' => 'required|exists:branches,id',
'joining_date' => 'required|date',
'status' => 'required|string',
'salary_type' => 'required|string',
'salary_amount' => 'required|numeric',
'advance_enabled' => 'nullable|boolean',
'advance_amount' => 'nullable|numeric',
'advance_repayment_mode' => 'nullable|string',
'advance_months' => 'nullable|integer',
'commission_enabled' => 'nullable|boolean',
'commission_amount' => 'nullable|numeric',
'commission_member_count' => 'nullable|integer',
'emirates_id' => 'nullable|string|max:255',
'emirates_id_expiry' => 'nullable|date',
'family_member_name' => 'nullable|string|max:255',
'family_member_relation' => 'nullable|string|max:255',
'family_member_contact' => ['nullable', 'string', 'max:255', 'regex:/^(\+91|91|0)?[6-9]\d{9}$|^(\+971|971|0)?5[024568]\d{7}$/'],
'salary_reminder_enabled' => 'nullable|boolean',
'document_expiry_enabled' => 'nullable|boolean',
'family_members' => 'nullable|array',
'family_members.*.name' => 'required|string|max:255',
'family_members.*.relation' => 'required|string|max:255',
'family_members.*.contact' => ['required', 'string', 'max:255', 'regex:/^(\+91|91|0)?[6-9]\d{9}$|^(\+971|971|0)?5[024568]\d{7}$/'],
'documents' => 'nullable|array',
'documents.*.name' => 'required|string|max:255',
'documents.*.document_number' => 'nullable|string|max:255',
'documents.*.expiry_date' => 'nullable|date',
'documents.*.reminder_days' => 'nullable|integer',
]);
// Branch Start Date Validation - REMOVED AS PER USER REQUEST
/*
$branch = \App\Models\Branch::find($validated['branch_id']);
if ($branch && $validated['joining_date'] < $branch->operational_start_date) {
return response()->json([
'errors' => ['joining_date' => ["Joining date cannot be before branch start date ({$branch->operational_start_date})"]]
], 422);
}
*/
if (empty($validated['staff_id_code'])) {
$role = strtoupper($validated['role'] ?? 'STAFF');
$count = Staff::count() + 1;
$validated['staff_id_code'] = "USR-{$role}-" . str_pad($count, 3, '0', STR_PAD_LEFT);
}
$status = $validated['status'] ?? 'Active';
$validated['status'] = $status;
$staff = Staff::create($validated);
// Handle Salary Advance Deductions
if ($staff->advance_enabled) {
if ($staff->advance_repayment_mode === 'Divide by Months') {
$months = $staff->advance_months ?: 1;
$monthlyDeduction = $staff->advance_amount / $months;
SalaryAdvanceDeduction::create([
'staff_id' => $staff->id,
'advance_amount' => $staff->advance_amount,
'total_months' => $months,
'monthly_deduction' => $monthlyDeduction,
'remaining_amount' => $staff->advance_amount,
'paid_amount' => 0,
'status' => 'Pending'
]);
}
// Record immediate account debit and expense for the advance
$this->recordFinancialsForAdvance($staff, $staff->advance_amount);
}
// Handle Documents
if ($request->has('documents')) {
foreach ($request->input('documents') as $index => $doc) {
$path = null;
if ($request->hasFile("documents.{$index}.file")) {
$path = $request->file("documents.{$index}.file")->store('staff_documents', 'public');
}
$staff->documents()->create([
'name' => $doc['name'],
'document_number' => $doc['document_number'] ?? null,
'expiry_date' => $doc['expiry_date'] ?? null,
'reminder_days' => $doc['reminder_days'] ?? 30,
'path' => $path,
]);
}
}
return response()->json(['message' => 'Staff created successfully', 'staff' => $staff], 201);
}
public function update(Request $request, $id)
{
$staff = Staff::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
Log::info('Updating standalone staff record', $request->all());
$validated = $request->validate([
'full_name' => 'nullable|string|max:255',
'email' => 'nullable|string|max:255',
'phone' => ['nullable', 'string', 'max:20', 'regex:/^(\+91|91|0)?[6-9]\d{9}$|^(\+971|971|0)?5[024568]\d{7}$/'],
'designation' => 'nullable|string|max:255',
'role' => 'nullable|string',
'branch_id' => 'nullable|exists:branches,id',
'joining_date' => 'nullable|date',
'status' => 'nullable|string',
'salary_type' => 'nullable|string',
'salary_amount' => 'nullable|numeric',
'salary_cycle' => 'nullable|string',
'advance_enabled' => 'nullable|boolean',
'advance_amount' => 'nullable|numeric',
'advance_repayment_mode' => 'nullable|string',
'advance_months' => 'nullable|integer',
'commission_enabled' => 'nullable|boolean',
'commission_amount' => 'nullable|numeric',
'commission_member_count' => 'nullable|integer',
'apply_from' => 'nullable|string',
'emirates_id' => 'nullable|string|max:255',
'emirates_id_expiry' => 'nullable|date',
'family_member_name' => 'nullable|string|max:255',
'family_member_relation' => 'nullable|string|max:255',
'family_member_contact' => ['nullable', 'string', 'max:255', 'regex:/^(\+91|91|0)?[6-9]\d{9}$|^(\+971|971|0)?5[024568]\d{7}$/'],
'salary_reminder_enabled' => 'nullable|boolean',
'document_expiry_enabled' => 'nullable|boolean',
'family_members' => 'nullable|array',
'family_members.*.name' => 'required|string|max:255',
'family_members.*.relation' => 'required|string|max:255',
'family_members.*.contact' => ['required', 'string', 'max:255', 'regex:/^(\+91|91|0)?[6-9]\d{9}$|^(\+971|971|0)?5[024568]\d{7}$/'],
'documents' => 'nullable|array',
'documents.*.id' => 'nullable|exists:staff_documents,id',
'documents.*.name' => 'required|string|max:255',
'documents.*.document_number' => 'nullable|string|max:255',
'documents.*.expiry_date' => 'nullable|date',
'documents.*.reminder_days' => 'nullable|integer',
]);
$status = $validated['status'] ?? 'Active';
$validated['status'] = $status;
$staff->update($validated);
// Handle Documents Update
if ($request->has('documents')) {
$existingDocIds = [];
foreach ($request->input('documents') as $index => $doc) {
$path = null;
if ($request->hasFile("documents.{$index}.file")) {
$path = $request->file("documents.{$index}.file")->store('staff_documents', 'public');
}
if (isset($doc['id'])) {
$staffDoc = \App\Models\StaffDocument::find($doc['id']);
if ($staffDoc && $staffDoc->staff_id == $staff->id) {
$updateData = [
'name' => $doc['name'],
'document_number' => $doc['document_number'] ?? null,
'expiry_date' => $doc['expiry_date'] ?? null,
'reminder_days' => $doc['reminder_days'] ?? 30,
];
if ($path) $updateData['path'] = $path;
$staffDoc->update($updateData);
$existingDocIds[] = $staffDoc->id;
}
} else {
$newDoc = $staff->documents()->create([
'name' => $doc['name'],
'document_number' => $doc['document_number'] ?? null,
'expiry_date' => $doc['expiry_date'] ?? null,
'reminder_days' => $doc['reminder_days'] ?? 30,
'path' => $path,
]);
$existingDocIds[] = $newDoc->id;
}
}
// Delete removed documents
$staff->documents()->whereNotIn('id', $existingDocIds)->get()->each(function($doc) {
if ($doc->path) Storage::disk('public')->delete($doc->path);
$doc->delete();
});
}
// Handle Salary Advance Deductions
if ($staff->advance_enabled) {
// Only record financials if advance amount has increased
if ($request->has('advance_amount')) {
$oldAdvance = $staff->getOriginal('advance_amount') ?: 0;
$newAdvance = $staff->advance_amount;
if ($newAdvance > $oldAdvance) {
$additionalAmount = $newAdvance - $oldAdvance;
$this->recordFinancialsForAdvance($staff, $additionalAmount);
}
}
if ($staff->advance_repayment_mode === 'Divide by Months') {
$existing = SalaryAdvanceDeduction::where('staff_id', $staff->id)->where('status', 'Pending')->first();
$months = $staff->advance_months ?: 1;
$monthlyDeduction = $staff->advance_amount / $months;
if ($existing) {
$existing->update([
'advance_amount' => $staff->advance_amount,
'total_months' => $months,
'monthly_deduction' => $monthlyDeduction,
'remaining_amount' => $staff->advance_amount,
]);
} else {
SalaryAdvanceDeduction::create([
'staff_id' => $staff->id,
'advance_amount' => $staff->advance_amount,
'total_months' => $months,
'monthly_deduction' => $monthlyDeduction,
'remaining_amount' => $staff->advance_amount,
'paid_amount' => 0,
'status' => 'Pending'
]);
}
}
} else {
// If advance was enabled but now disabled, mark active deduction as Closed
if ($staff->getOriginal('advance_enabled')) {
SalaryAdvanceDeduction::where('staff_id', $staff->id)
->where('status', 'Pending')
->update(['status' => 'Closed']);
}
}
// Handle Trainer Commission History
if ($staff->commission_enabled && $request->has('commission_member_count')) {
$effectiveMonth = $request->input('apply_from') === 'next_month'
? Carbon::now()->addMonth()->format('Y-m')
: Carbon::now()->format('Y-m');
TrainerCommission::updateOrCreate(
[
'staff_id' => $staff->id,
'effective_month' => $effectiveMonth
],
[
'member_count' => $request->input('commission_member_count'),
'amount_per_head' => $request->input('commission_amount'),
'total_amount' => $request->input('commission_member_count') * $request->input('commission_amount')
]
);
}
return response()->json(['message' => 'Staff updated successfully', 'staff' => $staff]);
}
public function destroy($id)
{
$staff = Staff::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$staff->delete();
return response()->json(['message' => 'Staff deleted successfully']);
}
public function getPayments($id)
{
$staff = Staff::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$payments = \App\Models\StaffPayment::where('staff_id', $id)->orderBy('payment_date', 'desc')->get();
return response()->json($payments);
}
public function storePayment(Request $request, $id)
{
$staff = Staff::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$validated = $request->validate([
'amount' => 'required|numeric',
'payment_date' => 'required|date',
'payment_type' => 'required|string',
'status' => 'required|string',
'remarks' => 'nullable|string'
]);
$payment = \App\Models\StaffPayment::create(array_merge($validated, ['staff_id' => $id]));
// Log to Accounts as Debit
\App\Models\Account::create([
'date' => $validated['payment_date'],
'time' => \Carbon\Carbon::now()->toTimeString(),
'credit' => 0,
'debit' => $validated['amount'],
'type' => 'salary',
'accountable_id' => $payment->id,
'accountable_type' => \App\Models\StaffPayment::class,
'description' => "{$validated['payment_type']} for {$staff->full_name}"
]);
return response()->json($payment, 201);
}
public function getSettlementDetails(Request $request, $id)
{
$staff = Staff::with('branch')->findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$targetMonthKey = $request->query('month');
$branch = $staff->branch;
if ($targetMonthKey) {
$nextSettlementMonth = Carbon::parse($targetMonthKey . '-01');
// Verify if already paid
$existing = \App\Models\StaffPayment::where('staff_id', $id)
->where('payment_type', 'Salary Settlement')
->where('settlement_month', $targetMonthKey)
->first();
if ($existing) {
return response()->json([
'can_settle' => false,
'message' => "Salary for {$nextSettlementMonth->format('F Y')} is already settled.",
]);
}
} else {
// Find the next unpaid month logically
$lastPayment = \App\Models\StaffPayment::where('staff_id', $id)
->where('payment_type', 'Salary Settlement')
->orderBy('settlement_month', 'desc')
->first();
$joiningDate = Carbon::parse($staff->joining_date);
$currentMonth = Carbon::now()->startOfMonth();
if ($lastPayment) {
$nextSettlementMonth = Carbon::parse($lastPayment->settlement_month . '-01')->addMonth();
} else {
$nextSettlementMonth = $joiningDate->copy()->startOfMonth();
}
// Only allow settlement if the generation date for the month has arrived
$genDay = $branch->salary_generation_day ?? 2;
$generationDate = $nextSettlementMonth->copy()->addMonth()->day(min($genDay, $nextSettlementMonth->copy()->addMonth()->daysInMonth));
if (Carbon::now()->lessThan($generationDate)) {
return response()->json([
'can_settle' => false,
'message' => "Salary for {$nextSettlementMonth->format('F Y')} will be available for settlement on " . $generationDate->format('jS F Y'),
]);
}
}
// Calculate Cycle and Pro-rata
$monthKey = $nextSettlementMonth->format('Y-m');
[$start, $end] = $this->getSalaryCycleRange($monthKey, $branch);
$baseSalary = $staff->salary_amount ?: 0;
$proratedBase = $this->calculateProRatedSalary($baseSalary, $start, $end, $staff->joining_date);
$commissionCount = $staff->commission_member_count ?: 0;
$commissionAmount = $staff->commission_amount ?: 0;
$totalCommission = $commissionCount * $commissionAmount;
// Commission pro-rata logic (optional? User didn't specify, but usually commission is per head so no pro-rata)
$advanceDeduction = 0;
$remainingAdvance = 0;
// Find any pending deduction regardless of staff->advance_enabled
// This ensures repayments continue even if the feature toggle is flipped
$deduction = SalaryAdvanceDeduction::where('staff_id', $id)
->where('status', 'Pending')
->first();
if ($deduction) {
if ($staff->advance_repayment_mode === 'Full Next Month') {
$advanceDeduction = $deduction->remaining_amount;
$remainingAdvance = 0;
} else {
$advanceDeduction = min($deduction->monthly_deduction, $deduction->remaining_amount);
$remainingAdvance = $deduction->remaining_amount - $advanceDeduction;
}
}
$netPayable = $proratedBase + $totalCommission - $advanceDeduction;
return response()->json([
'can_settle' => true,
'staff_name' => $staff->full_name,
'period' => $nextSettlementMonth->format('F Y'),
'settlement_month' => $monthKey,
'cycle_range' => $start->format('j M') . ' - ' . $end->format('j M Y'),
'base_salary' => $baseSalary,
'prorated_base' => round($proratedBase, 2),
'is_prorated' => round($proratedBase, 2) < round($baseSalary, 2),
'salary_type' => $staff->salary_type,
'commission_count' => $commissionCount,
'commission_amount' => $commissionAmount,
'total_commission' => $totalCommission,
'advance_deduction' => $advanceDeduction,
'remaining_advance' => $remainingAdvance,
'net_payable' => round($netPayable, 2)
]);
}
public function settleSalary(Request $request, $id)
{
$staff = Staff::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$details = $this->getSettlementDetails($request, $id)->getData(true);
if (!($details['can_settle'] ?? false)) {
return response()->json(['message' => $details['message'] ?? 'Cannot settle at this time'], 400);
}
$settlementMonth = $details['settlement_month'];
$batchId = $request->input('batch_id');
// Double check for existing record
$exists = \App\Models\StaffPayment::where('staff_id', $id)
->where('payment_type', 'Salary Settlement')
->where('settlement_month', $settlementMonth)
->exists();
if ($exists) {
return response()->json(['message' => 'Salary for this period is already settled'], 400);
}
$payment = \App\Models\StaffPayment::create([
'staff_id' => $id,
'amount' => $details['net_payable'],
'payment_date' => Carbon::now()->toDateString(),
'payment_type' => 'Salary Settlement',
'settlement_month' => $settlementMonth,
'status' => 'Paid',
'remarks' => $request->input('remarks') ?? "Salary settlement for {$details['period']}",
'batch_id' => $batchId
]);
// Log to Accounts (Debit)
\App\Models\Account::create([
'date' => Carbon::now()->toDateString(),
'time' => Carbon::now()->toTimeString(),
'credit' => 0,
'debit' => $details['net_payable'],
'type' => 'salary',
'accountable_id' => $payment->id,
'accountable_type' => \App\Models\StaffPayment::class,
'description' => "Salary settlement for {$staff->full_name} ({$details['period']})"
]);
// Log to General Expenses
$salaryCategory = \App\Models\ExpenseCategory::where('name', 'Salary')->first();
\App\Models\Expense::create([
'date' => Carbon::now()->toDateString(),
'branch_id' => $staff->branch_id,
'expense_category_id' => $salaryCategory ? $salaryCategory->id : 1,
'expense_type' => 'Account',
'amount' => $details['net_payable'],
'remarks' => "Salary payout for {$staff->full_name} ({$details['period']})" . ($batchId ? " (Batch: {$batchId})" : ""),
'batch_id' => $batchId
]);
// Update Advance Deduction if applicable
$deduction = SalaryAdvanceDeduction::where('staff_id', $id)
->where('status', 'Pending')
->first();
if ($deduction) {
$newRemaining = $deduction->remaining_amount - $details['advance_deduction'];
$newPaid = ($deduction->paid_amount ?: 0) + $details['advance_deduction'];
$deduction->update([
'remaining_amount' => max(0, $newRemaining),
'paid_amount' => $newPaid,
'status' => $newRemaining <= 0.01 ? 'Closed' : 'Pending'
]);
if ($newRemaining <= 0.01) {
$staff->update(['advance_enabled' => false]);
}
}
return response()->json(['message' => 'Salary settled successfully', 'payment' => $payment]);
}
private function recordFinancialsForAdvance($staff, $amount)
{
if ($amount <= 0) return;
// Create a payment record for the advance
$payment = \App\Models\StaffPayment::create([
'staff_id' => $staff->id,
'amount' => $amount,
'payment_date' => Carbon::now()->toDateString(),
'payment_type' => 'Advance',
'status' => 'Paid',
'remarks' => "Salary advance issued"
]);
// Log to Accounts (Debit)
\App\Models\Account::create([
'date' => Carbon::now()->toDateString(),
'time' => Carbon::now()->toTimeString(),
'credit' => 0,
'debit' => $amount,
'type' => 'salary',
'accountable_id' => $payment->id,
'accountable_type' => \App\Models\StaffPayment::class,
'description' => "Salary advance for {$staff->full_name}"
]);
// Log to General Expenses
$advanceCategory = \App\Models\ExpenseCategory::where('name', 'Salary Advance')->first();
\App\Models\Expense::create([
'date' => Carbon::now()->toDateString(),
'branch_id' => $staff->branch_id,
'expense_category_id' => $advanceCategory ? $advanceCategory->id : 1,
'expense_type' => 'Account',
'amount' => $amount,
'remarks' => "Salary advance issued to {$staff->full_name}"
]);
}
public function getPayrollStatus($id)
{
$staff = Staff::findOrFail($id);
$joiningDate = Carbon::parse($staff->joining_date)->startOfMonth();
$currentMonth = Carbon::now()->startOfMonth();
$payroll = [];
$tempMonth = $joiningDate->copy();
// Get all settlements for this staff
$settlements = \App\Models\StaffPayment::where('staff_id', $id)
->where('payment_type', 'Salary Settlement')
->pluck('amount', 'settlement_month')
->toArray();
while ($tempMonth->lessThan($currentMonth)) {
$monthKey = $tempMonth->format('Y-m');
$isPaid = isset($settlements[$monthKey]);
if (!$isPaid) {
$payroll[] = [
'month' => $tempMonth->format('F Y'),
'month_key' => $monthKey,
'status' => 'Unpaid',
'amount' => null,
'can_settle' => true
];
}
$tempMonth->addMonth();
}
return response()->json(array_reverse($payroll));
}
public function getCommissionHistory($id)
{
$staff = Staff::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$history = TrainerCommission::where('staff_id', $id)
->orderBy('effective_month', 'desc')
->get();
return response()->json($history);
}
public function getAdvanceHistory($id)
{
$staff = Staff::findOrFail($id);
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
if ($user && $user->isReceptionist() && $staff->branch_id != $user->branch_id) {
return response()->json(['message' => 'Unauthorized'], 403);
}
$history = SalaryAdvanceDeduction::where('staff_id', $id)
->orderBy('created_at', 'desc')
->get();
return response()->json($history);
}
public function getAllPendingSalaries(Request $request)
{
$user = Auth::guard('web')->user() ?? Auth::guard('receptionist')->user();
$branchId = $user && $user->isReceptionist() ? $user->branch_id : $request->query('branch_id');
$query = Staff::with('branch');
if ($branchId) {
$query->where('branch_id', $branchId);
}
$staffMembers = $query->get();
$pending = [];
foreach ($staffMembers as $staff) {
$branch = $staff->branch;
$joiningDate = Carbon::parse($staff->joining_date)->startOfMonth();
$tempMonth = $joiningDate->copy();
// Get all settlements for this staff
$settlements = \App\Models\StaffPayment::where('staff_id', $staff->id)
->where('payment_type', 'Salary Settlement')
->pluck('amount', 'settlement_month')
->toArray();
$staffMonths = [];
// Loop while generation date for the month has passed
while (true) {
$monthKey = $tempMonth->format('Y-m');
// Calculate generation date for this month
$genDay = $branch->salary_generation_day ?? 2;
$generationDate = $tempMonth->copy()->addMonth()->day(min($genDay, $tempMonth->copy()->addMonth()->daysInMonth));
if (Carbon::now()->lessThan($generationDate)) {
break;
}
if (!isset($settlements[$monthKey])) {
// Calculate details for this month
[$start, $end] = $this->getSalaryCycleRange($monthKey, $branch);
$baseSalary = $staff->salary_amount ?: 0;
$proratedBase = $this->calculateProRatedSalary($baseSalary, $start, $end, $staff->joining_date);
// Commission for this month
$commission = TrainerCommission::where('staff_id', $staff->id)
->where('effective_month', '<=', $monthKey)
->orderBy('effective_month', 'desc')
->first();
$commissionAmount = $commission ? $commission->total_amount : 0;
// Advance deduction
$advanceDed = 0;
if ($staff->advance_enabled) {
if ($staff->advance_repayment_mode === 'Full Next Month') {
$advanceDed = $staff->advance_amount;
} else {
$deduction = SalaryAdvanceDeduction::where('staff_id', $staff->id)->where('status', 'Pending')->first();
$advanceDed = $deduction ? $deduction->monthly_deduction : 0;
}
}
$netPayable = $proratedBase + $commissionAmount - $advanceDed;
$staffMonths[] = [
'month_key' => $monthKey,
'month_name' => $tempMonth->format('F Y'),
'cycle_range' => $start->format('j M') . ' - ' . $end->format('j M'),
'base_salary' => $baseSalary,
'prorated_base' => round($proratedBase, 2),
'commission' => $commissionAmount,
'advance_deduction' => $advanceDed,
'net_payable' => round($netPayable, 2),
];
}
$tempMonth->addMonth();
}
if (!empty($staffMonths)) {
$totalNet = array_sum(array_column($staffMonths, 'net_payable'));
$totalBase = array_sum(array_column($staffMonths, 'prorated_base'));
$totalComm = array_sum(array_column($staffMonths, 'commission'));
$totalAdv = array_sum(array_column($staffMonths, 'advance_deduction'));
$pending[] = [
'staff_id' => $staff->id,
'staff_name' => $staff->full_name,
'branch' => $staff->branch?->name ?? 'N/A',
'role' => $staff->designation ?? 'Staff',
'base_salary' => $totalBase,
'commission' => $totalComm,
'advance_ded' => $totalAdv,
'net_payable' => $totalNet,
'status' => 'Pending',
'pending_months' => $staffMonths
];
}
}
return response()->json($pending);
}
public function bulkSettleSalaries(Request $request)
{
$payload = $request->validate([
'settlements' => 'required|array',
'settlements.*.staff_id' => 'required|exists:staff,id',
'settlements.*.month_key' => 'required|string',
'remarks' => 'nullable|string'
]);
$batchId = 'BATCH-' . strtoupper(bin2hex(random_bytes(4)));
$results = [];
foreach ($payload['settlements'] as $item) {
$settleReq = new Request();
$settleReq->merge([
'month' => $item['month_key'],
'batch_id' => $batchId,
'remarks' => $payload['remarks'] ?? 'Bulk salary release'
]);
try {
$resp = $this->settleSalary($settleReq, $item['staff_id']);
$results[] = [
'staff_id' => $item['staff_id'],
'month' => $item['month_key'],
'status' => 'success'
];
} catch (\Exception $e) {
Log::error("Bulk settle error for staff {$item['staff_id']}: " . $e->getMessage());
$results[] = [
'staff_id' => $item['staff_id'],
'month' => $item['month_key'],
'status' => 'error',
'message' => $e->getMessage()
];
}
}
return response()->json(['results' => $results, 'batch_id' => $batchId]);
}
private function getSalaryCycleRange($monthKey, $branch)
{
$fromDay = $branch->payroll_from_day ?? 1;
$toDay = $branch->payroll_to_day ?? 28;
$month = Carbon::parse($monthKey . '-01');
if ($fromDay <= $toDay) {
// Same month cycle (e.g., 1st to 28th)
$start = $month->copy()->day($fromDay)->startOfDay();
$end = $month->copy()->day($toDay)->endOfDay();
} else {
// Cross-month cycle (e.g., 25th to 24th next month)
// If monthKey is Feb, cycle is Jan 25 to Feb 24
$end = $month->copy()->day($toDay)->endOfDay();
$start = $month->copy()->subMonth()->day($fromDay)->startOfDay();
}
return [$start, $end];
}
private function calculateProRatedSalary($monthlySalary, $start, $end, $joiningDate)
{
$joining = Carbon::parse($joiningDate)->startOfDay();
// If joined after the cycle ended, salary is 0
if ($joining->greaterThan($end)) return 0;
// If joined before or on the start day, full salary
if ($joining->lessThanOrEqualTo($start)) return $monthlySalary;
// Prorated calculation
$totalDaysInCycle = $start->diffInDays($end) + 1;
$workDays = $joining->diffInDays($end) + 1;
return ($monthlySalary / $totalDaysInCycle) * $workDays;
}
}

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

@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Account extends Model
{
protected $fillable = [
'date', 'time', 'credit', 'debit', 'type',
'branch_id', 'accountable_id', 'accountable_type', 'description'
];
public function branch()
{
return $this->belongsTo(Branch::class);
}
public function accountable()
{
return $this->morphTo();
}
}

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

@ -0,0 +1,30 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Branch extends Model
{
protected $fillable = [
'name', 'location', 'manager_name', 'total_members', 'revenue', 'status', 'operational_start_date', 'next_salary_release',
'payroll_from_day', 'payroll_to_day', 'salary_generation_day'
];
public function documents()
{
return $this->hasMany(BranchDocument::class);
}
}
class BranchDocument extends Model
{
protected $fillable = [
'branch_id', 'name', 'document_number', 'path', 'expiry_date', 'reminder_days'
];
public function branch()
{
return $this->belongsTo(Branch::class);
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BranchDocument extends Model
{
protected $fillable = [
'branch_id',
'name',
'path',
'document_number',
'expiry_date',
'reminder_days'
];
}

35
app/Models/Collection.php Normal file
View File

@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Collection extends Model
{
protected $fillable = [
'date',
'branch_id',
'collection_type_id',
'payment_method',
'amount',
'remarks',
'transaction_id'
];
public function branch(): BelongsTo
{
return $this->belongsTo(Branch::class);
}
public function type(): BelongsTo
{
return $this->belongsTo(CollectionType::class, 'collection_type_id');
}
public function items(): HasMany
{
return $this->hasMany(CollectionItem::class);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CollectionItem extends Model
{
protected $fillable = [
'collection_id',
'product_id',
'quantity',
'unit_price',
'subtotal'
];
public function collection(): BelongsTo
{
return $this->belongsTo(Collection::class);
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

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

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

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Expense extends Model
{
protected $fillable = [
'date', 'branch_id', 'expense_category_id', 'expense_type', 'amount', 'remarks', 'batch_id'
];
public function branch()
{
return $this->belongsTo(Branch::class);
}
public function category()
{
return $this->belongsTo(ExpenseCategory::class, 'expense_category_id');
}
public function account()
{
return $this->morphOne(Account::class, 'accountable');
}
}

View File

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

24
app/Models/Investor.php Normal file
View File

@ -0,0 +1,24 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Investor extends Model
{
protected $fillable = [
'name',
'investment_date',
'investment_amount',
'applicable_to_all_branches',
'roi_type',
'roi_value',
'roi_period',
'security_proof_document'
];
public function branches()
{
return $this->belongsToMany(Branch::class, 'investor_branch');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class InvestorPayout extends Model
{
protected $fillable = [
'investor_id', 'amount', 'payout_date', 'payout_month', 'status', 'payment_method', 'remarks'
];
public function investor()
{
return $this->belongsTo(Investor::class);
}
}

View File

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

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

@ -0,0 +1,43 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Product extends Model
{
protected $fillable = [
'name',
'sku',
'product_category_id',
'branch_id',
'cost_price',
'selling_price',
'current_stock',
'reorder_level',
'status',
'image'
];
public function category(): BelongsTo
{
return $this->belongsTo(ProductCategory::class, 'product_category_id');
}
public function branch(): BelongsTo
{
return $this->belongsTo(Branch::class);
}
public function adjustments(): HasMany
{
return $this->hasMany(StockAdjustment::class);
}
public function saleItems(): HasMany
{
return $this->hasMany(ProductSaleItem::class);
}
}

View File

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

View File

@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ProductSale extends Model
{
protected $fillable = [
'transaction_id',
'branch_id',
'subtotal_amount',
'vat_amount',
'total_amount',
'payment_method',
'date',
'remarks'
];
public function branch(): BelongsTo
{
return $this->belongsTo(Branch::class);
}
public function items(): HasMany
{
return $this->hasMany(ProductSaleItem::class);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ProductSaleItem extends Model
{
protected $fillable = [
'product_sale_id',
'product_id',
'quantity',
'unit_price',
'subtotal'
];
public function sale(): BelongsTo
{
return $this->belongsTo(ProductSale::class, 'product_sale_id');
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Receptionist extends Authenticatable
{
use HasFactory, Notifiable;
/**
* Check if the user is a receptionist.
*/
public function isReceptionist(): bool
{
return true;
}
/**
* Check if the user is an owner.
*/
public function isOwner(): bool
{
return false;
}
protected $fillable = [
'name',
'email',
'password',
'branch_id',
];
protected $hidden = [
'password',
'remember_token',
];
protected function casts(): array
{
return [
'password' => 'hashed',
];
}
public function branch()
{
return $this->belongsTo(Branch::class);
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SalaryAdvanceDeduction extends Model
{
use \Illuminate\Database\Eloquent\Factories\HasFactory;
protected $fillable = [
'staff_id',
'advance_amount',
'total_months',
'monthly_deduction',
'remaining_amount',
'paid_amount',
'status'
];
public function staff()
{
return $this->belongsTo(Staff::class);
}
}

60
app/Models/Staff.php Normal file
View File

@ -0,0 +1,60 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Staff extends Model
{
protected $table = 'staff';
protected $fillable = [
'full_name',
'email',
'phone',
'designation',
'role',
'branch_id',
'joining_date',
'status',
'salary_type',
'salary_amount',
'salary_cycle',
'cycle_effective_date',
'advance_enabled',
'advance_amount',
'advance_repayment_mode',
'commission_enabled',
'commission_amount',
'commission_member_count',
'apply_from',
'advance_months',
'staff_id_code',
'emirates_id',
'emirates_id_expiry',
'family_member_name',
'family_member_relation',
'family_member_contact',
'salary_reminder_enabled',
'document_expiry_enabled',
'family_members',
];
protected $casts = [
'family_members' => 'array',
'advance_enabled' => 'boolean',
'commission_enabled' => 'boolean',
'salary_reminder_enabled' => 'boolean',
'document_expiry_enabled' => 'boolean',
];
public function branch()
{
return $this->belongsTo(Branch::class);
}
public function documents()
{
return $this->hasMany(StaffDocument::class);
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class StaffDocument extends Model
{
protected $table = 'staff_documents';
protected $fillable = [
'staff_id',
'name',
'document_number',
'expiry_date',
'path',
'reminder_days',
];
public function staff()
{
return $this->belongsTo(Staff::class);
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class StaffPayment extends Model
{
protected $fillable = [
'staff_id', 'amount', 'payment_date', 'payment_type', 'status', 'remarks', 'settlement_month', 'batch_id'
];
public function staff()
{
return $this->belongsTo(Staff::class);
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class StockAdjustment extends Model
{
protected $fillable = [
'product_id',
'adjustment_qty',
'new_stock',
'adjustment_date',
'reason',
'remarks'
];
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TrainerCommission extends Model
{
protected $fillable = [
'staff_id',
'member_count',
'amount_per_head',
'total_amount',
'effective_month'
];
public function staff()
{
return $this->belongsTo(Staff::class);
}
}

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

@ -0,0 +1,62 @@
<?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;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
'role',
];
public function isOwner(): bool
{
return true;
}
/**
* Check if the user is a receptionist.
*/
public function isReceptionist(): bool
{
return false;
}
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View File

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

18
artisan Normal file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

18
bootstrap/app.php Normal file
View File

@ -0,0 +1,18 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();

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

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

5
bootstrap/providers.php Normal file
View File

@ -0,0 +1,5 @@
<?php
return [
App\Providers\AppServiceProvider::class,
];

86
composer.json Normal file
View File

@ -0,0 +1,86 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/tinker": "^2.10.1"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.3"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
],
"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",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8400
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

126
config/app.php Normal file
View File

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'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
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| 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' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

123
config/auth.php Normal file
View File

@ -0,0 +1,123 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'receptionist' => [
'driver' => 'session',
'provider' => 'receptionists',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
'receptionists' => [
'driver' => 'eloquent',
'model' => App\Models\Receptionist::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry 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.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

117
config/cache.php Normal file
View File

@ -0,0 +1,117 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| 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: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_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' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_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',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and 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((string) env('APP_NAME', 'laravel')).'-cache-'),
];

183
config/database.php Normal file
View File

@ -0,0 +1,183 @@
<?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 database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_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 on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| 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 Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'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'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'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'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];

80
config/filesystems.php Normal file
View File

@ -0,0 +1,80 @@
<?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 for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => 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,
'report' => 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'),
],
];

132
config/logging.php Normal file
View File

@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'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' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'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'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'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 all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| 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 that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'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',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails 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 emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];

129
config/queue.php Normal file
View File

@ -0,0 +1,129 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_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' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

38
config/services.php Normal file
View File

@ -0,0 +1,38 @@
<?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.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

217
config/session.php Normal file
View File

@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| 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 expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'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 to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "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 session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) 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're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'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. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_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" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

1
database/.gitignore vendored Normal file
View File

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

View File

@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
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();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

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.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
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.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

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

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.
*/
public function up(): void
{
Schema::create('branches', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('location');
$table->string('manager_name');
$table->integer('total_members')->default(0);
$table->decimal('revenue', 15, 2)->default(0);
$table->string('status')->default('Active');
$table->date('operational_start_date');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('branches');
}
};

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('branch_documents', function (Blueprint $table) {
$table->id();
$table->foreignId('branch_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('path');
$table->date('expiry_date');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('branch_documents');
}
};

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.
*/
public function up(): void
{
Schema::create('staff', function (Blueprint $table) {
$table->id();
$table->string('full_name');
$table->string('email')->unique();
$table->string('phone')->nullable();
$table->string('designation')->nullable();
$table->string('role');
$table->foreignId('branch_id')->nullable()->constrained('branches')->nullOnDelete();
$table->date('joining_date');
$table->string('status')->default('Active');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('staff');
}
};

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.
*/
public function up(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->string('salary_type')->nullable()->after('status');
$table->decimal('salary_amount', 10, 2)->nullable()->after('salary_type');
$table->string('salary_cycle')->nullable()->after('salary_amount');
$table->date('cycle_effective_date')->nullable()->after('salary_cycle');
$table->boolean('advance_enabled')->default(false)->after('cycle_effective_date');
$table->decimal('advance_amount', 10, 2)->nullable()->after('advance_enabled');
$table->string('advance_repayment_mode')->nullable()->after('advance_amount');
$table->boolean('commission_enabled')->default(false)->after('advance_repayment_mode');
$table->decimal('commission_amount', 10, 2)->nullable()->after('commission_enabled');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->dropColumn([
'salary_type', 'salary_amount', 'salary_cycle', 'cycle_effective_date',
'advance_enabled', 'advance_amount', 'advance_repayment_mode',
'commission_enabled', 'commission_amount'
]);
});
}
};

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.
*/
public function up(): void
{
Schema::create('investors', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->date('investment_date');
$table->decimal('investment_amount', 15, 2);
$table->boolean('applicable_to_all_branches')->default(false);
$table->string('roi_type')->default('Percentage'); // 'Percentage', 'Fixed Amount'
$table->decimal('roi_value', 15, 2)->nullable();
$table->string('roi_period')->nullable(); // Monthly, Yearly, etc.
$table->string('security_proof_document')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('investors');
}
};

View File

@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('investor_branch', function (Blueprint $table) {
$table->id();
$table->foreignId('investor_id')->constrained()->onDelete('cascade');
$table->foreignId('branch_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('investor_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.
*/
public function up(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->string('full_name')->nullable()->change();
$table->string('email')->nullable()->change();
$table->string('role')->nullable()->change();
$table->date('joining_date')->nullable()->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->string('full_name')->nullable(false)->change();
$table->string('email')->nullable(false)->change();
$table->string('role')->nullable(false)->change();
$table->date('joining_date')->nullable(false)->change();
});
}
};

View File

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

View File

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

View File

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

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.
*/
public function up(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->string('staff_id_code')->nullable()->after('id');
$table->string('emirates_id')->nullable()->after('phone');
$table->date('emirates_id_expiry')->nullable()->after('emirates_id');
$table->string('family_member_name')->nullable();
$table->string('family_member_relation')->nullable();
$table->string('family_member_contact')->nullable();
$table->boolean('salary_reminder_enabled')->default(true);
$table->boolean('document_expiry_enabled')->default(true);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('staff', function (Blueprint $table) {
//
});
}
};

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.
*/
public function up(): void
{
Schema::create('accounts', function (Blueprint $table) {
$table->id();
$table->date('date');
$table->time('time');
$table->decimal('credit', 15, 2)->default(0);
$table->decimal('debit', 15, 2)->default(0);
$table->string('type'); // investor, salary, expense, etc.
$table->nullableMorphs('accountable'); // Link to Investor, Staff, etc.
$table->text('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('accounts');
}
};

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.
*/
public function up(): void
{
Schema::create('staff_payments', function (Blueprint $table) {
$table->id();
$table->foreignId('staff_id')->constrained('staff')->onDelete('cascade');
$table->decimal('amount', 15, 2);
$table->date('payment_date');
$table->string('payment_type'); // Salary, Advance, Commission
$table->string('status')->default('Paid');
$table->text('remarks')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('staff_payments');
}
};

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.
*/
public function up(): void
{
Schema::create('investor_payouts', function (Blueprint $table) {
$table->id();
$table->foreignId('investor_id')->constrained('investors')->onDelete('cascade');
$table->decimal('amount', 15, 2);
$table->date('payout_date');
$table->string('payout_month'); // e.g. "March 2026"
$table->string('status')->default('Paid');
$table->string('payment_method')->nullable();
$table->text('remarks')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('investor_payouts');
}
};

View File

@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('expenses', function (Blueprint $row) {
$row->id();
$row->date('date');
$row->foreignId('branch_id')->constrained()->onDelete('cascade');
$row->foreignId('expense_category_id')->constrained()->onDelete('cascade');
$row->string('expense_type'); // Account, Petty Cash
$row->decimal('amount', 15, 2);
$row->text('remarks')->nullable();
$row->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('expenses');
}
};

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.
*/
public function up(): void
{
Schema::create('trainer_commissions', function (Blueprint $table) {
$table->id();
$table->foreignId('staff_id')->constrained('staff')->onDelete('cascade');
$table->integer('member_count');
$table->decimal('amount_per_head', 10, 2);
$table->decimal('total_amount', 10, 2);
$table->string('effective_month'); // Format: YYYY-MM
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('trainer_commissions');
}
};

View File

@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->integer('commission_member_count')->nullable()->after('commission_amount');
$table->string('apply_from')->nullable()->after('commission_member_count');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('staff', function (Blueprint $table) {
//
});
}
};

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.
*/
public function up(): void
{
Schema::create('salary_advance_deductions', function (Blueprint $table) {
$table->id();
$table->foreignId('staff_id')->constrained()->onDelete('cascade');
$table->decimal('advance_amount', 10, 2);
$table->integer('total_months');
$table->decimal('monthly_deduction', 10, 2);
$table->decimal('remaining_amount', 10, 2);
$table->string('status')->default('Pending'); // Pending, Paid
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('salary_advance_deductions');
}
};

View File

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

View File

@ -0,0 +1,45 @@
<?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
{
// Add settlement_month to staff_payments
if (!Schema::hasColumn('staff_payments', 'settlement_month')) {
Schema::table('staff_payments', function (Blueprint $table) {
$table->string('settlement_month', 7)->nullable()->after('payment_type'); // YYYY-MM
$table->unique(['staff_id', 'settlement_month', 'payment_type'], 'staff_payment_month_unique');
});
}
// Ensure "Salary" expense category exists (Global)
DB::table('expense_categories')->updateOrInsert(
['name' => 'Salary'],
['created_at' => now(), 'updated_at' => now()]
);
DB::table('expense_categories')->updateOrInsert(
['name' => 'Salary Advance'],
['created_at' => now(), 'updated_at' => now()]
);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('staff_payments', function (Blueprint $table) {
$table->dropUnique('staff_payment_month_unique');
$table->dropColumn('settlement_month');
});
}
};

View File

@ -0,0 +1,72 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
// Ensure owner exists
DB::table('users')->updateOrInsert(
['email' => 'owner@gympro.com'],
[
'name' => 'Gym Owner',
'password' => \Illuminate\Support\Facades\Hash::make('password'),
'role' => 'owner',
'created_at' => now(),
'updated_at' => now()
]
);
// Add a sample branch if none exists
$branchId = DB::table('branches')->first()?->id;
if (!$branchId) {
$branchId = DB::table('branches')->insertGetId([
'name' => 'Test Branch',
'location' => '123 Test Street',
'manager_name' => 'Test Manager',
'total_members' => 0,
'revenue' => 0.00,
'status' => 'Active',
'operational_start_date' => now()->format('Y-m-d'),
'created_at' => now(),
'updated_at' => now()
]);
}
// Add a sample staff joined 1 month ago
DB::table('staff')->insert([
'staff_id_code' => 'TEST001',
'full_name' => 'John Test Doe',
'email' => 'john.test@example.com',
'phone' => '0501234567',
'joining_date' => Carbon::now()->subMonth()->startOfMonth()->toDateString(),
'role' => 'Trainer',
'status' => 'Active',
'salary_type' => 'Monthly',
'salary_amount' => 5000,
'salary_cycle' => 'Monthly',
'commission_enabled' => true,
'commission_amount' => 50,
'commission_member_count' => 10,
'branch_id' => $branchId,
'created_at' => now(),
'updated_at' => now()
]);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
DB::table('staff')->where('staff_id_code', 'TEST001')->delete();
}
};

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.
*/
public function up(): void
{
Schema::table('staff_payments', function (Blueprint $table) {
$table->string('batch_id')->nullable()->after('settlement_month');
});
Schema::table('expenses', function (Blueprint $table) {
$table->string('batch_id')->nullable()->after('remarks');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('staff_payments', function (Blueprint $table) {
$table->dropColumn('batch_id');
});
Schema::table('expenses', function (Blueprint $table) {
$table->dropColumn('batch_id');
});
}
};

View File

@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('branches', function (Blueprint $table) {
$table->integer('payroll_from_day')->default(1);
$table->integer('payroll_to_day')->default(28);
$table->integer('salary_generation_day')->default(2);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('branches', function (Blueprint $table) {
$table->dropColumn(['payroll_from_day', 'payroll_to_day', 'salary_generation_day']);
});
}
};

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.
*/
public function up(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->integer('emirates_id_reminder_days')->default(30)->after('emirates_id_expiry');
});
Schema::table('branch_documents', function (Blueprint $table) {
$table->integer('reminder_days')->default(30)->after('expiry_date');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('staff', function (Blueprint $table) {
$table->dropColumn('emirates_id_reminder_days');
});
Schema::table('branch_documents', function (Blueprint $table) {
$table->dropColumn('reminder_days');
});
}
};

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.
*/
public function up(): void
{
Schema::create('staff_documents', function (Blueprint $table) {
$table->id();
$table->foreignId('staff_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('document_number')->nullable();
$table->date('expiry_date');
$table->string('path');
$table->integer('reminder_days')->default(30);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('staff_documents');
}
};

View File

@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('branch_documents', function (Blueprint $table) {
if (!Schema::hasColumn('branch_documents', 'document_number')) {
$table->string('document_number')->nullable()->after('name');
}
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('branch_documents', function (Blueprint $table) {
$table->dropColumn('document_number');
});
}
};

View File

@ -0,0 +1,66 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('sku')->unique()->nullable();
$table->foreignId('product_category_id')->constrained()->onDelete('cascade');
$table->foreignId('branch_id')->constrained()->onDelete('cascade');
$table->decimal('cost_price', 15, 2)->default(0);
$table->decimal('selling_price', 15, 2)->default(0);
$table->integer('current_stock')->default(0);
$table->integer('reorder_level')->default(10);
$table->string('status')->default('In Stock'); // In Stock, Low Stock, Out of Stock
$table->string('image')->nullable();
$table->timestamps();
});
Schema::create('stock_adjustments', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->integer('adjustment_qty');
$table->integer('new_stock');
$table->date('adjustment_date');
$table->string('reason'); // Purchase, Sale, Adjustment, Initial
$table->text('remarks')->nullable();
$table->timestamps();
});
Schema::create('product_sales', function (Blueprint $table) {
$table->id();
$table->string('transaction_id')->unique();
$table->foreignId('branch_id')->constrained()->onDelete('cascade');
$table->decimal('total_amount', 15, 2);
$table->string('payment_method'); // Cash, Online, Card
$table->date('date');
$table->text('remarks')->nullable();
$table->timestamps();
});
Schema::create('product_sale_items', function (Blueprint $table) {
$table->id();
$table->foreignId('product_sale_id')->constrained()->onDelete('cascade');
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->integer('quantity');
$table->decimal('unit_price', 15, 2);
$table->decimal('subtotal', 15, 2);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('product_sale_items');
Schema::dropIfExists('product_sales');
Schema::dropIfExists('stock_adjustments');
Schema::dropIfExists('products');
}
};

View File

@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('collections', function (Blueprint $table) {
$table->id();
$table->date('date');
$table->foreignId('branch_id')->constrained()->onDelete('cascade');
$table->foreignId('collection_type_id')->constrained('collection_types')->onDelete('cascade');
$table->string('payment_method');
$table->decimal('amount', 15, 2);
$table->text('remarks')->nullable();
$table->string('transaction_id')->unique();
$table->timestamps();
});
Schema::create('collection_items', function (Blueprint $table) {
$table->id();
$table->foreignId('collection_id')->constrained()->onDelete('cascade');
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->integer('quantity');
$table->decimal('unit_price', 15, 2);
$table->decimal('subtotal', 15, 2);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('collection_items');
Schema::dropIfExists('collections');
}
};

View File

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

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.
*/
public function up(): void
{
Schema::create('receptionists', function (Blueprint $バランス) {
$バランス->id();
$バランス->string('name');
$バランス->string('email')->unique();
$バランス->string('password');
$バランス->foreignId('branch_id')->constrained()->onDelete('cascade');
$バランス->rememberToken();
$バランス->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('receptionists');
}
};

View File

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

View File

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('salary_advance_deductions', function (Blueprint $table) {
$table->decimal('paid_amount', 10, 2)->default(0)->after('remaining_amount');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('salary_advance_deductions', function (Blueprint $table) {
$table->dropColumn('paid_amount');
});
}
};

View File

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

View File

@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('product_sales', function (Blueprint $table) {
$table->decimal('subtotal_amount', 15, 2)->after('branch_id')->default(0);
$table->decimal('vat_amount', 15, 2)->after('subtotal_amount')->default(0);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('product_sales', function (Blueprint $table) {
//
});
}
};

View File

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

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