Initial commit - Physiotherapy Clinic Management System
This commit is contained in:
commit
dbb326f2cc
300 files changed
+144285
No files matched your search
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console;
|
||||
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
|
||||
|
||||
class Kernel extends ConsoleKernel
|
||||
{
|
||||
/**
|
||||
* Define the application's command schedule.
|
||||
*/
|
||||
protected function schedule(Schedule $schedule): void
|
||||
{
|
||||
// $schedule->command('inspire')->hourly();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the commands for the application.
|
||||
*/
|
||||
protected function commands(): void
|
||||
{
|
||||
$this->load(__DIR__.'/Commands');
|
||||
|
||||
require base_path('routes/console.php');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* The list of the inputs that are never flashed to the session on validation exceptions.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register the exception handling callbacks for the application.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->reportable(function (Throwable $e) {
|
||||
//
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StoreAppointmentRequest;
|
||||
use App\Http\Requests\UpdateAppointmentRequest;
|
||||
use App\Http\Resources\AppointmentResource;
|
||||
use App\Models\Appointment;
|
||||
use App\Services\AppointmentService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class AppointmentController extends Controller
|
||||
{
|
||||
protected $appointmentService;
|
||||
|
||||
public function __construct(AppointmentService $appointmentService)
|
||||
{
|
||||
$this->appointmentService = $appointmentService;
|
||||
}
|
||||
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = Appointment::with(['patient', 'user']);
|
||||
|
||||
if ($request->has('patient_id')) {
|
||||
$query->where('patient_id', $request->patient_id);
|
||||
}
|
||||
|
||||
if ($request->has('therapist_id')) {
|
||||
$query->where('user_id', $request->therapist_id);
|
||||
}
|
||||
|
||||
if ($request->has('status')) {
|
||||
$query->where('status', $request->status);
|
||||
}
|
||||
|
||||
if ($request->has('date_from')) {
|
||||
$query->whereDate('appointment_date', '>=', $request->date_from);
|
||||
}
|
||||
|
||||
if ($request->has('date_to')) {
|
||||
$query->whereDate('appointment_date', '<=', $request->date_to);
|
||||
}
|
||||
|
||||
if ($request->has('date')) {
|
||||
$query->whereDate('appointment_date', $request->date);
|
||||
}
|
||||
|
||||
$appointments = $query->orderBy('appointment_date')->paginate($request->per_page ?? 20);
|
||||
|
||||
return AppointmentResource::collection($appointments);
|
||||
}
|
||||
|
||||
public function store(StoreAppointmentRequest $request)
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
// Check for conflicts
|
||||
$appointmentDate = \Carbon\Carbon::parse($data['appointment_date']);
|
||||
|
||||
if ($this->appointmentService->hasConflict($data['therapist_id'], $appointmentDate, $data['duration_minutes'])) {
|
||||
return response()->json([
|
||||
'message' => 'Therapist has a conflicting appointment at this time',
|
||||
], 422);
|
||||
}
|
||||
|
||||
if ($this->appointmentService->hasPatientConflict($data['patient_id'], $appointmentDate, $data['duration_minutes'])) {
|
||||
return response()->json([
|
||||
'message' => 'Patient has a conflicting appointment at this time',
|
||||
], 422);
|
||||
}
|
||||
|
||||
$appointment = Appointment::create([
|
||||
'patient_id' => $data['patient_id'],
|
||||
'user_id' => $data['therapist_id'],
|
||||
'appointment_date' => $data['appointment_date'],
|
||||
'duration_minutes' => $data['duration_minutes'],
|
||||
'notes' => $data['notes'] ?? null,
|
||||
]);
|
||||
|
||||
// Generate reminders
|
||||
$reminderService = new \App\Services\ReminderService();
|
||||
$reminderService->generateReminders($appointment);
|
||||
|
||||
return new AppointmentResource($appointment);
|
||||
}
|
||||
|
||||
public function show(Appointment $appointment)
|
||||
{
|
||||
return new AppointmentResource($appointment);
|
||||
}
|
||||
|
||||
public function update(UpdateAppointmentRequest $request, Appointment $appointment)
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
// Check for conflicts if date/therapist changed
|
||||
if (isset($data['appointment_date']) || isset($data['therapist_id'])) {
|
||||
$newDate = isset($data['appointment_date'])
|
||||
? \Carbon\Carbon::parse($data['appointment_date'])
|
||||
: $appointment->appointment_date;
|
||||
$newTherapistId = $data['therapist_id'] ?? $appointment->user_id;
|
||||
$duration = $data['duration_minutes'] ?? $appointment->duration_minutes;
|
||||
|
||||
if ($this->appointmentService->hasConflict($newTherapistId, $newDate, $duration, $appointment->id)) {
|
||||
return response()->json([
|
||||
'message' => 'Therapist has a conflicting appointment at this time',
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
|
||||
$appointment->update([
|
||||
'patient_id' => $data['patient_id'],
|
||||
'user_id' => $data['therapist_id'],
|
||||
'appointment_date' => $data['appointment_date'],
|
||||
'duration_minutes' => $data['duration_minutes'],
|
||||
'status' => $data['status'],
|
||||
'notes' => $data['notes'] ?? null,
|
||||
'cancellation_reason' => $data['cancellation_reason'] ?? null,
|
||||
]);
|
||||
|
||||
if ($data['status'] === 'cancelled') {
|
||||
$appointment->cancelled_by = auth()->id();
|
||||
$appointment->cancelled_at = now();
|
||||
$appointment->save();
|
||||
}
|
||||
|
||||
return new AppointmentResource($appointment);
|
||||
}
|
||||
|
||||
public function destroy(Appointment $appointment)
|
||||
{
|
||||
$appointment->delete();
|
||||
return response()->json(['message' => 'Appointment deleted successfully']);
|
||||
}
|
||||
|
||||
public function calendar(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'start' => 'required|date',
|
||||
'end' => 'required|date|after_or_equal:start',
|
||||
]);
|
||||
|
||||
$feed = $this->appointmentService->getCalendarFeed(
|
||||
$request->start,
|
||||
$request->end,
|
||||
$request->therapist_id
|
||||
);
|
||||
|
||||
return response()->json($feed);
|
||||
}
|
||||
|
||||
public function availableSlots(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'therapist_id' => 'required|exists:users,id',
|
||||
'date' => 'required|date',
|
||||
'duration' => 'nullable|integer|min:15',
|
||||
]);
|
||||
|
||||
$slots = $this->appointmentService->getAvailableSlots(
|
||||
$request->therapist_id,
|
||||
$request->date,
|
||||
$request->duration ?? 60
|
||||
);
|
||||
|
||||
return response()->json(['slots' => $slots]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
public function register(Request $request)
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
|
||||
'password' => ['required', 'confirmed', Password::defaults()],
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return response()->json(['errors' => $validator->errors()], 422);
|
||||
}
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'password' => Hash::make($request->password),
|
||||
]);
|
||||
|
||||
$token = $user->createToken('auth_token')->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'message' => __('auth.registered'),
|
||||
'user' => $user,
|
||||
'token' => $token,
|
||||
], 201);
|
||||
}
|
||||
|
||||
public function login(Request $request)
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return response()->json(['errors' => $validator->errors()], 422);
|
||||
}
|
||||
|
||||
$user = User::where('email', $request->email)->first();
|
||||
|
||||
if (!$user || !Hash::check($request->password, $user->password)) {
|
||||
return response()->json([
|
||||
'message' => __('auth.failed'),
|
||||
], 401);
|
||||
}
|
||||
|
||||
// Check if 2FA is enabled
|
||||
if ($user->isTwoFactorEnabled()) {
|
||||
return response()->json([
|
||||
'requires_2fa' => true,
|
||||
'user_id' => $user->id,
|
||||
'message' => __('auth.2fa_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
$token = $user->createToken('auth_token')->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'message' => __('auth.logged_in'),
|
||||
'user' => $user,
|
||||
'token' => $token,
|
||||
]);
|
||||
}
|
||||
|
||||
public function verify2FA(Request $request)
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'user_id' => ['required', 'integer', 'exists:users,id'],
|
||||
'code' => ['required', 'string', 'size:6'],
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return response()->json(['errors' => $validator->errors()], 422);
|
||||
}
|
||||
|
||||
$user = User::find($request->user_id);
|
||||
|
||||
if (!$user || !$user->isTwoFactorEnabled()) {
|
||||
return response()->json(['message' => __('auth.2fa_not_enabled')], 400);
|
||||
}
|
||||
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
$secret = $user->getTwoFactorSecret();
|
||||
|
||||
$valid = $google2fa->verifyKey($secret, $request->code);
|
||||
|
||||
if (!$valid) {
|
||||
// Check recovery codes
|
||||
$recoveryCodes = $user->two_factor_recovery_codes ?? [];
|
||||
if (in_array($request->code, $recoveryCodes)) {
|
||||
// Remove used recovery code
|
||||
$user->two_factor_recovery_codes = array_diff($recoveryCodes, [$request->code]);
|
||||
$user->save();
|
||||
$valid = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$valid) {
|
||||
return response()->json(['message' => __('auth.2fa_invalid')], 401);
|
||||
}
|
||||
|
||||
$token = $user->createToken('auth_token')->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'message' => __('auth.logged_in'),
|
||||
'user' => $user,
|
||||
'token' => $token,
|
||||
]);
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
$request->user()->currentAccessToken()->delete();
|
||||
|
||||
return response()->json([
|
||||
'message' => __('auth.logged_out'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function user(Request $request)
|
||||
{
|
||||
return response()->json([
|
||||
'user' => $request->user(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Patient;
|
||||
use App\Models\Appointment;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Payment;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$today = Carbon::today();
|
||||
$monthStart = $today->copy()->startOfMonth();
|
||||
$monthEnd = $today->copy()->endOfMonth();
|
||||
|
||||
return response()->json([
|
||||
'stats' => [
|
||||
'total_patients' => Patient::count(),
|
||||
'active_patients' => Patient::where('status', 'active')->count(),
|
||||
'today_appointments' => Appointment::whereDate('appointment_date', $today)->count(),
|
||||
'pending_appointments' => Appointment::whereIn('status', ['scheduled', 'confirmed'])
|
||||
->whereDate('appointment_date', '>=', $today)
|
||||
->count(),
|
||||
'month_invoices' => Invoice::whereBetween('invoice_date', [$monthStart, $monthEnd])->count(),
|
||||
'month_revenue' => Payment::whereBetween('payment_date', [$monthStart, $monthEnd])->sum('amount'),
|
||||
'outstanding_balance' => Invoice::sum('balance'),
|
||||
],
|
||||
'recent_appointments' => Appointment::with(['patient', 'user'])
|
||||
->whereDate('appointment_date', '>=', $today)
|
||||
->orderBy('appointment_date')
|
||||
->limit(5)
|
||||
->get()
|
||||
->map(fn($a) => [
|
||||
'id' => $a->id,
|
||||
'patient_name' => $a->patient->fullName(),
|
||||
'therapist_name' => $a->user->name,
|
||||
'date' => $a->appointment_date->format('Y-m-d'),
|
||||
'time' => $a->appointment_date->format('H:i'),
|
||||
'status' => $a->status,
|
||||
]),
|
||||
'appointments_by_status' => Appointment::selectRaw('status, count(*) as count')
|
||||
->whereDate('appointment_date', '>=', $today->copy()->subDays(30))
|
||||
->groupBy('status')
|
||||
->get(),
|
||||
'invoices_by_status' => Invoice::selectRaw('status, count(*) as count, sum(total_amount) as total')
|
||||
->groupBy('status')
|
||||
->get(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\InvoiceResource;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Payment;
|
||||
use App\Services\LedgerService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class InvoiceController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = Invoice::with(['patient', 'currency']);
|
||||
|
||||
if ($request->has('patient_id')) {
|
||||
$query->where('patient_id', $request->patient_id);
|
||||
}
|
||||
|
||||
if ($request->has('status')) {
|
||||
$query->where('status', $request->status);
|
||||
}
|
||||
|
||||
if ($request->has('date_from')) {
|
||||
$query->whereDate('invoice_date', '>=', $request->date_from);
|
||||
}
|
||||
|
||||
if ($request->has('date_to')) {
|
||||
$query->whereDate('invoice_date', '<=', $request->date_to);
|
||||
}
|
||||
|
||||
$invoices = $query->orderByDesc('invoice_date')->paginate($request->per_page ?? 20);
|
||||
|
||||
return InvoiceResource::collection($invoices);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'patient_id' => 'required|exists:patients,id',
|
||||
'invoice_date' => 'required|date',
|
||||
'due_date' => 'required|date|after_or_equal:invoice_date',
|
||||
'subtotal' => 'required|numeric|min:0',
|
||||
'tax_amount' => 'nullable|numeric|min:0',
|
||||
'discount_amount' => 'nullable|numeric|min:0',
|
||||
'currency_id' => 'required|exists:currencies,id',
|
||||
'notes' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$data['created_by'] = auth()->id();
|
||||
|
||||
// Calculate total
|
||||
$data['total_amount'] = $data['subtotal']
|
||||
+ ($data['tax_amount'] ?? 0)
|
||||
- ($data['discount_amount'] ?? 0);
|
||||
$data['paid_amount'] = 0;
|
||||
|
||||
// Generate invoice number
|
||||
$lastId = Invoice::max('id') ?? 0;
|
||||
$data['invoice_number'] = 'INV-' . date('Y') . '-' . str_pad($lastId + 1, 6, '0', STR_PAD_LEFT);
|
||||
|
||||
$invoice = Invoice::create($data);
|
||||
|
||||
return new InvoiceResource($invoice);
|
||||
}
|
||||
|
||||
public function show(Invoice $invoice)
|
||||
{
|
||||
return new InvoiceResource($invoice);
|
||||
}
|
||||
|
||||
public function update(Request $request, Invoice $invoice)
|
||||
{
|
||||
if (in_array($invoice->status, ['paid', 'cancelled'])) {
|
||||
return response()->json(['message' => 'Cannot update paid or cancelled invoice'], 422);
|
||||
}
|
||||
|
||||
$data = $request->validate([
|
||||
'invoice_date' => 'sometimes|date',
|
||||
'due_date' => 'sometimes|date',
|
||||
'subtotal' => 'sometimes|numeric|min:0',
|
||||
'tax_amount' => 'nullable|numeric|min:0',
|
||||
'discount_amount' => 'nullable|numeric|min:0',
|
||||
'notes' => 'nullable|string',
|
||||
'status' => ['sometimes', Rule::in(['draft', 'sent', 'paid', 'partial', 'overdue', 'cancelled'])],
|
||||
]);
|
||||
|
||||
if (isset($data['subtotal'])) {
|
||||
$data['total_amount'] = $data['subtotal']
|
||||
+ ($data['tax_amount'] ?? $invoice->tax_amount)
|
||||
- ($data['discount_amount'] ?? $invoice->discount_amount);
|
||||
}
|
||||
|
||||
$invoice->update($data);
|
||||
|
||||
return new InvoiceResource($invoice);
|
||||
}
|
||||
|
||||
public function destroy(Invoice $invoice)
|
||||
{
|
||||
if ($invoice->payments()->exists()) {
|
||||
return response()->json(['message' => 'Cannot delete invoice with payments'], 422);
|
||||
}
|
||||
|
||||
$invoice->delete();
|
||||
return response()->json(['message' => 'Invoice deleted successfully']);
|
||||
}
|
||||
|
||||
public function summary(Request $request)
|
||||
{
|
||||
$query = Invoice::query();
|
||||
|
||||
if ($request->has('date_from')) {
|
||||
$query->whereDate('invoice_date', '>=', $request->date_from);
|
||||
}
|
||||
|
||||
if ($request->has('date_to')) {
|
||||
$query->whereDate('invoice_date', '<=', $request->date_to);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'total_invoices' => $query->count(),
|
||||
'total_amount' => $query->sum('total_amount'),
|
||||
'total_paid' => $query->sum('paid_amount'),
|
||||
'total_outstanding' => $query->sum('balance'),
|
||||
'by_status' => $query->selectRaw('status, count(*) as count, sum(total_amount) as amount')
|
||||
->groupBy('status')
|
||||
->get(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\LedgerEntryResource;
|
||||
use App\Models\LedgerEntry;
|
||||
use App\Services\LedgerService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class LedgerController extends Controller
|
||||
{
|
||||
protected $ledgerService;
|
||||
|
||||
public function __construct(LedgerService $ledgerService)
|
||||
{
|
||||
$this->ledgerService = $ledgerService;
|
||||
}
|
||||
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = LedgerEntry::with(['chartOfAccount', 'currency', 'creator']);
|
||||
|
||||
if ($request->has('account_id')) {
|
||||
$query->where('chart_of_account_id', $request->account_id);
|
||||
}
|
||||
|
||||
if ($request->has('type')) {
|
||||
$query->whereHas('chartOfAccount', function ($q) use ($request) {
|
||||
$q->where('type', $request->type);
|
||||
});
|
||||
}
|
||||
|
||||
if ($request->has('date_from')) {
|
||||
$query->whereDate('entry_date', '>=', $request->date_from);
|
||||
}
|
||||
|
||||
if ($request->has('date_to')) {
|
||||
$query->whereDate('entry_date', '<=', $request->date_to);
|
||||
}
|
||||
|
||||
$entries = $query->orderByDesc('entry_date')->paginate($request->per_page ?? 20);
|
||||
|
||||
return LedgerEntryResource::collection($entries);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'entry_date' => 'required|date',
|
||||
'chart_of_account_id' => 'required|exists:chart_of_accounts,id',
|
||||
'currency_id' => 'required|exists:currencies,id',
|
||||
'amount' => 'required|numeric',
|
||||
'description' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$data['created_by'] = auth()->id();
|
||||
$data['source_type'] = 'manual';
|
||||
|
||||
$entry = LedgerEntry::create($data);
|
||||
|
||||
return new LedgerEntryResource($entry);
|
||||
}
|
||||
|
||||
public function summary(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'date_from' => 'required|date',
|
||||
'date_to' => 'required|date|after_or_equal:date_from',
|
||||
]);
|
||||
|
||||
$report = $this->ledgerService->getProfitLossReport(
|
||||
$request->date_from,
|
||||
$request->date_to
|
||||
);
|
||||
|
||||
return response()->json($report);
|
||||
}
|
||||
|
||||
public function incomeSummary(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'date_from' => 'required|date',
|
||||
'date_to' => 'required|date|after_or_equal:date_from',
|
||||
]);
|
||||
|
||||
$summary = $this->ledgerService->getIncomeSummary(
|
||||
$request->date_from,
|
||||
$request->date_to
|
||||
);
|
||||
|
||||
return response()->json($summary);
|
||||
}
|
||||
|
||||
public function expenseSummary(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'date_from' => 'required|date',
|
||||
'date_to' => 'required|date|after_or_equal:date_from',
|
||||
]);
|
||||
|
||||
$summary = $this->ledgerService->getExpenseSummary(
|
||||
$request->date_from,
|
||||
$request->date_to
|
||||
);
|
||||
|
||||
return response()->json($summary);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\PackageResource;
|
||||
use App\Http\Resources\PatientPackageResource;
|
||||
use App\Models\Package;
|
||||
use App\Models\PatientPackage;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PackageController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = Package::with('currency')->where('is_active', true);
|
||||
|
||||
if ($request->has('search')) {
|
||||
$query->where('name', 'like', "%{$request->search}%");
|
||||
}
|
||||
|
||||
$packages = $query->orderBy('name')->paginate($request->per_page ?? 20);
|
||||
|
||||
return PackageResource::collection($packages);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'number_of_sessions' => 'required|integer|min:1',
|
||||
'price' => 'required|numeric|min:0',
|
||||
'currency_id' => 'required|exists:currencies,id',
|
||||
'validity_days' => 'required|integer|min:1',
|
||||
'description' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$package = Package::create($data);
|
||||
|
||||
return new PackageResource($package);
|
||||
}
|
||||
|
||||
public function show(Package $package)
|
||||
{
|
||||
return new PackageResource($package);
|
||||
}
|
||||
|
||||
public function update(Request $request, Package $package)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'name' => 'sometimes|string|max:255',
|
||||
'number_of_sessions' => 'sometimes|integer|min:1',
|
||||
'price' => 'sometimes|numeric|min:0',
|
||||
'currency_id' => 'sometimes|exists:currencies,id',
|
||||
'validity_days' => 'sometimes|integer|min:1',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'sometimes|boolean',
|
||||
]);
|
||||
|
||||
$package->update($data);
|
||||
|
||||
return new PackageResource($package);
|
||||
}
|
||||
|
||||
public function destroy(Package $package)
|
||||
{
|
||||
$package->delete();
|
||||
return response()->json(['message' => 'Package deleted successfully']);
|
||||
}
|
||||
|
||||
// Patient Package Assignment
|
||||
public function assignToPatient(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'patient_id' => 'required|exists:patients,id',
|
||||
'package_id' => 'required|exists:packages,id',
|
||||
'start_date' => 'required|date',
|
||||
]);
|
||||
|
||||
$package = Package::findOrFail($data['package_id']);
|
||||
|
||||
$patientPackage = PatientPackage::create([
|
||||
'patient_id' => $data['patient_id'],
|
||||
'package_id' => $data['package_id'],
|
||||
'total_sessions' => $package->number_of_sessions,
|
||||
'remaining_sessions' => $package->number_of_sessions,
|
||||
'start_date' => $data['start_date'],
|
||||
'end_date' => \Carbon\Carbon::parse($data['start_date'])->addDays($package->validity_days),
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
return new PatientPackageResource($patientPackage);
|
||||
}
|
||||
|
||||
public function patientPackages(Request $request)
|
||||
{
|
||||
$query = PatientPackage::with(['patient', 'package']);
|
||||
|
||||
if ($request->has('patient_id')) {
|
||||
$query->where('patient_id', $request->patient_id);
|
||||
}
|
||||
|
||||
if ($request->has('status')) {
|
||||
$query->where('status', $request->status);
|
||||
}
|
||||
|
||||
$packages = $query->orderByDesc('created_at')->paginate($request->per_page ?? 20);
|
||||
|
||||
return PatientPackageResource::collection($packages);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StorePatientRequest;
|
||||
use App\Http\Requests\UpdatePatientRequest;
|
||||
use App\Http\Resources\PatientResource;
|
||||
use App\Http\Resources\PatientProfileResource;
|
||||
use App\Models\Patient;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PatientController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = Patient::query();
|
||||
|
||||
if ($request->has('search')) {
|
||||
$search = $request->search;
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('first_name', 'like', "%{$search}%")
|
||||
->orWhere('last_name', 'like', "%{$search}%")
|
||||
->orWhere('email', 'like', "%{$search}%")
|
||||
->orWhere('phone', 'like', "%{$search}%")
|
||||
->orWhere('patient_code', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
if ($request->has('status')) {
|
||||
$query->where('status', $request->status);
|
||||
}
|
||||
|
||||
$patients = $query->orderBy('created_at', 'desc')->paginate($request->per_page ?? 20);
|
||||
|
||||
return PatientResource::collection($patients);
|
||||
}
|
||||
|
||||
public function store(StorePatientRequest $request)
|
||||
{
|
||||
$data = $request->validated();
|
||||
$data['created_by'] = auth()->id();
|
||||
|
||||
// Generate patient code
|
||||
$lastId = Patient::max('id') ?? 0;
|
||||
$data['patient_code'] = 'P' . str_pad($lastId + 1, 6, '0', STR_PAD_LEFT);
|
||||
|
||||
$patient = Patient::create($data);
|
||||
|
||||
return new PatientResource($patient);
|
||||
}
|
||||
|
||||
public function show(Patient $patient)
|
||||
{
|
||||
return new PatientResource($patient);
|
||||
}
|
||||
|
||||
public function profile(Patient $patient)
|
||||
{
|
||||
return new PatientProfileResource($patient);
|
||||
}
|
||||
|
||||
public function update(UpdatePatientRequest $request, Patient $patient)
|
||||
{
|
||||
$patient->update($request->validated());
|
||||
return new PatientResource($patient);
|
||||
}
|
||||
|
||||
public function destroy(Patient $patient)
|
||||
{
|
||||
$patient->delete();
|
||||
return response()->json(['message' => 'Patient deleted successfully']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\PaymentResource;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Payment;
|
||||
use App\Services\LedgerService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PaymentController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = Payment::with(['invoice.patient', 'receivedBy']);
|
||||
|
||||
if ($request->has('invoice_id')) {
|
||||
$query->where('invoice_id', $request->invoice_id);
|
||||
}
|
||||
|
||||
if ($request->has('patient_id')) {
|
||||
$query->whereHas('invoice', function ($q) use ($request) {
|
||||
$q->where('patient_id', $request->patient_id);
|
||||
});
|
||||
}
|
||||
|
||||
if ($request->has('date_from')) {
|
||||
$query->whereDate('payment_date', '>=', $request->date_from);
|
||||
}
|
||||
|
||||
if ($request->has('date_to')) {
|
||||
$query->whereDate('payment_date', '<=', $request->date_to);
|
||||
}
|
||||
|
||||
$payments = $query->orderByDesc('payment_date')->paginate($request->per_page ?? 20);
|
||||
|
||||
return PaymentResource::collection($payments);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'invoice_id' => 'required|exists:invoices,id',
|
||||
'payment_date' => 'required|date',
|
||||
'amount' => 'required|numeric|min:0.01',
|
||||
'payment_method' => 'required|in:cash,card,bank_transfer,check,insurance,other',
|
||||
'reference_number' => 'nullable|string|max:255',
|
||||
'notes' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$invoice = Invoice::findOrFail($data['invoice_id']);
|
||||
|
||||
// Check if payment exceeds balance
|
||||
if ($data['amount'] > $invoice->balance) {
|
||||
return response()->json([
|
||||
'message' => 'Payment amount exceeds invoice balance',
|
||||
'balance' => $invoice->balance,
|
||||
], 422);
|
||||
}
|
||||
|
||||
$data['received_by'] = auth()->id();
|
||||
|
||||
// Generate payment number
|
||||
$lastId = Payment::max('id') ?? 0;
|
||||
$data['payment_number'] = 'PAY-' . date('Y') . '-' . str_pad($lastId + 1, 6, '0', STR_PAD_LEFT);
|
||||
|
||||
$payment = Payment::create($data);
|
||||
|
||||
// Update invoice
|
||||
$invoice->paid_amount += $data['amount'];
|
||||
$invoice->status = $invoice->paid_amount >= $invoice->total_amount ? 'paid' : 'partial';
|
||||
$invoice->save();
|
||||
|
||||
// Create ledger entry
|
||||
$ledgerService = new LedgerService();
|
||||
$ledgerService->recordPayment($payment);
|
||||
|
||||
return new PaymentResource($payment);
|
||||
}
|
||||
|
||||
public function show(Payment $payment)
|
||||
{
|
||||
return new PaymentResource($payment);
|
||||
}
|
||||
|
||||
public function destroy(Payment $payment)
|
||||
{
|
||||
// Revert invoice payment
|
||||
$invoice = $payment->invoice;
|
||||
$invoice->paid_amount -= $payment->amount;
|
||||
$invoice->status = $invoice->paid_amount <= 0 ? 'sent' : 'partial';
|
||||
$invoice->save();
|
||||
|
||||
$payment->delete();
|
||||
|
||||
return response()->json(['message' => 'Payment deleted successfully']);
|
||||
}
|
||||
|
||||
public function summary(Request $request)
|
||||
{
|
||||
$query = Payment::query();
|
||||
|
||||
if ($request->has('date_from')) {
|
||||
$query->whereDate('payment_date', '>=', $request->date_from);
|
||||
}
|
||||
|
||||
if ($request->has('date_to')) {
|
||||
$query->whereDate('payment_date', '<=', $request->date_to);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'total_payments' => $query->count(),
|
||||
'total_amount' => $query->sum('amount'),
|
||||
'by_method' => $query->selectRaw('payment_method, count(*) as count, sum(amount) as amount')
|
||||
->groupBy('payment_method')
|
||||
->get(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\LedgerEntryResource;
|
||||
use App\Http\Resources\TherapistResource;
|
||||
use App\Models\User;
|
||||
use App\Services\LedgerService;
|
||||
use App\Services\WageService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TherapistController extends Controller
|
||||
{
|
||||
protected $ledgerService;
|
||||
protected $wageService;
|
||||
|
||||
public function __construct(LedgerService $ledgerService, WageService $wageService)
|
||||
{
|
||||
$this->ledgerService = $ledgerService;
|
||||
$this->wageService = $wageService;
|
||||
}
|
||||
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = User::whereIn('role', ['therapist', 'admin', 'manager']);
|
||||
|
||||
if ($request->has('search')) {
|
||||
$search = $request->search;
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('name', 'like', "%{$search}%")
|
||||
->orWhere('email', 'like', "%{$search}%")
|
||||
->orWhere('specialization', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
$therapists = $query->orderBy('name')->paginate($request->per_page ?? 20);
|
||||
|
||||
return TherapistResource::collection($therapists);
|
||||
}
|
||||
|
||||
public function show(User $user)
|
||||
{
|
||||
return new TherapistResource($user);
|
||||
}
|
||||
|
||||
public function update(Request $request, User $user)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'name' => 'sometimes|string|max:255',
|
||||
'specialization' => 'nullable|string|max:255',
|
||||
'hourly_rate' => 'nullable|numeric|min:0',
|
||||
'session_rate' => 'nullable|numeric|min:0',
|
||||
'target_sessions_per_day' => 'nullable|integer|min:0',
|
||||
'target_sessions_per_month' => 'nullable|integer|min:0',
|
||||
'working_schedule' => 'nullable|array',
|
||||
]);
|
||||
|
||||
$user->update($data);
|
||||
|
||||
return new TherapistResource($user);
|
||||
}
|
||||
|
||||
public function performance(Request $request, User $user)
|
||||
{
|
||||
$request->validate([
|
||||
'period_start' => 'required|date',
|
||||
'period_end' => 'required|date|after_or_equal:period_start',
|
||||
]);
|
||||
|
||||
$metrics = $this->wageService->getPerformanceMetrics(
|
||||
$user->id,
|
||||
$request->period_start,
|
||||
$request->period_end
|
||||
);
|
||||
|
||||
return response()->json($metrics);
|
||||
}
|
||||
|
||||
public function calculateWage(Request $request, User $user)
|
||||
{
|
||||
$request->validate([
|
||||
'period_start' => 'required|date',
|
||||
'period_end' => 'required|date|after_or_equal:period_start',
|
||||
]);
|
||||
|
||||
$wage = $this->wageService->calculateWage(
|
||||
$user->id,
|
||||
$request->period_start,
|
||||
$request->period_end
|
||||
);
|
||||
|
||||
return response()->json($wage);
|
||||
}
|
||||
|
||||
public function storeWage(Request $request, User $user)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'period_start' => 'required|date',
|
||||
'period_end' => 'required|date|after_or_equal:period_start',
|
||||
'sessions_count' => 'required|integer|min:0',
|
||||
'hours_worked' => 'required|numeric|min:0',
|
||||
'base_amount' => 'required|numeric|min:0',
|
||||
'bonus' => 'nullable|numeric|min:0',
|
||||
'deductions' => 'nullable|numeric|min:0',
|
||||
'total_amount' => 'required|numeric|min:0',
|
||||
'currency_id' => 'required|exists:currencies,id',
|
||||
'notes' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$data['user_id'] = $user->id;
|
||||
|
||||
$wage = $this->wageService->createWage($data, auth()->id());
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Wage record created successfully',
|
||||
'wage' => $wage,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class TwoFactorController extends Controller
|
||||
{
|
||||
public function status(Request $request)
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
return response()->json([
|
||||
'enabled' => $user->isTwoFactorEnabled(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function enable(Request $request)
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if ($user->isTwoFactorEnabled()) {
|
||||
return response()->json([
|
||||
'message' => __('auth.2fa_already_enabled'),
|
||||
], 400);
|
||||
}
|
||||
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
$secret = $google2fa->generateSecretKey();
|
||||
|
||||
// Generate QR code URL
|
||||
$qrCodeUrl = $google2fa->getQRCodeUrl(
|
||||
config('app.name'),
|
||||
$user->email,
|
||||
$secret
|
||||
);
|
||||
|
||||
// Store secret temporarily (not enabled until confirmed)
|
||||
session(['2fa_secret' => $secret]);
|
||||
|
||||
return response()->json([
|
||||
'secret' => $secret,
|
||||
'qr_code_url' => $qrCodeUrl,
|
||||
]);
|
||||
}
|
||||
|
||||
public function confirm(Request $request)
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'code' => ['required', 'string', 'size:6'],
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return response()->json(['errors' => $validator->errors()], 422);
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
$secret = session('2fa_secret');
|
||||
|
||||
if (!$secret) {
|
||||
return response()->json([
|
||||
'message' => __('auth.2fa_session_expired'),
|
||||
], 400);
|
||||
}
|
||||
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
|
||||
if (!$google2fa->verifyKey($secret, $request->code)) {
|
||||
return response()->json([
|
||||
'message' => __('auth.2fa_invalid'),
|
||||
], 401);
|
||||
}
|
||||
|
||||
// Enable 2FA
|
||||
$recoveryCodes = $user->generateRecoveryCodes();
|
||||
$user->setTwoFactorSecret($secret);
|
||||
$user->two_factor_recovery_codes = $recoveryCodes;
|
||||
$user->two_factor_enabled = true;
|
||||
$user->save();
|
||||
|
||||
session()->forget('2fa_secret');
|
||||
|
||||
return response()->json([
|
||||
'message' => __('auth.2fa_enabled'),
|
||||
'recovery_codes' => $recoveryCodes,
|
||||
]);
|
||||
}
|
||||
|
||||
public function disable(Request $request)
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'password' => ['required', 'string'],
|
||||
'code' => ['nullable', 'string'],
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return response()->json(['errors' => $validator->errors()], 422);
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
// Verify password
|
||||
if (!\Hash::check($request->password, $user->password)) {
|
||||
return response()->json([
|
||||
'message' => __('auth.password_incorrect'),
|
||||
], 401);
|
||||
}
|
||||
|
||||
// If 2FA is enabled, verify the code
|
||||
if ($user->isTwoFactorEnabled() && $request->code) {
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
$secret = $user->getTwoFactorSecret();
|
||||
|
||||
if (!$google2fa->verifyKey($secret, $request->code)) {
|
||||
return response()->json([
|
||||
'message' => __('auth.2fa_invalid'),
|
||||
], 401);
|
||||
}
|
||||
}
|
||||
|
||||
// Disable 2FA
|
||||
$user->two_factor_secret = null;
|
||||
$user->two_factor_recovery_codes = null;
|
||||
$user->two_factor_enabled = false;
|
||||
$user->save();
|
||||
|
||||
return response()->json([
|
||||
'message' => __('auth.2fa_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function regenerateRecoveryCodes(Request $request)
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if (!$user->isTwoFactorEnabled()) {
|
||||
return response()->json([
|
||||
'message' => __('auth.2fa_not_enabled'),
|
||||
], 400);
|
||||
}
|
||||
|
||||
$recoveryCodes = $user->generateRecoveryCodes();
|
||||
$user->two_factor_recovery_codes = $recoveryCodes;
|
||||
$user->save();
|
||||
|
||||
return response()->json([
|
||||
'message' => __('auth.recovery_codes_regenerated'),
|
||||
'recovery_codes' => $recoveryCodes,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class TwoFactorController extends Controller
|
||||
{
|
||||
public function show()
|
||||
{
|
||||
$user = auth()->user();
|
||||
return view('auth.2fa-settings', compact('user'));
|
||||
}
|
||||
|
||||
public function enable(Request $request)
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if ($user->isTwoFactorEnabled()) {
|
||||
return redirect()->route('2fa.settings')->with('error', __('auth.2fa_already_enabled'));
|
||||
}
|
||||
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
$secret = $google2fa->generateSecretKey();
|
||||
|
||||
$qrCodeUrl = $google2fa->getQRCodeUrl(
|
||||
config('app.name'),
|
||||
$user->email,
|
||||
$secret
|
||||
);
|
||||
|
||||
// Generate QR code image
|
||||
$qrCode = \BaconQrCode\Renderer\ImageRenderer::class;
|
||||
$writer = new \BaconQrCode\Writer(new \BaconQrCode\Renderer\ImageRenderer(
|
||||
new \BaconQrCode\Renderer\RendererStyle\RendererStyle(400),
|
||||
new \BaconQrCode\Renderer\Image\SvgImageBackEnd()
|
||||
));
|
||||
$qrCodeSvg = $writer->writeString($qrCodeUrl);
|
||||
|
||||
session(['2fa_secret' => $secret]);
|
||||
|
||||
return view('auth.2fa-enable', [
|
||||
'secret' => $secret,
|
||||
'qrCodeSvg' => $qrCodeSvg,
|
||||
]);
|
||||
}
|
||||
|
||||
public function confirm(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'code' => ['required', 'string', 'size:6'],
|
||||
]);
|
||||
|
||||
$user = auth()->user();
|
||||
$secret = session('2fa_secret');
|
||||
|
||||
if (!$secret) {
|
||||
return redirect()->route('2fa.settings')->with('error', __('auth.2fa_session_expired'));
|
||||
}
|
||||
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
|
||||
if (!$google2fa->verifyKey($secret, $request->code)) {
|
||||
return back()->withErrors(['code' => __('auth.2fa_invalid')]);
|
||||
}
|
||||
|
||||
// Enable 2FA
|
||||
$recoveryCodes = $user->generateRecoveryCodes();
|
||||
$user->setTwoFactorSecret($secret);
|
||||
$user->two_factor_recovery_codes = $recoveryCodes;
|
||||
$user->two_factor_enabled = true;
|
||||
$user->save();
|
||||
|
||||
session()->forget('2fa_secret');
|
||||
|
||||
return view('auth.2fa-recovery-codes', [
|
||||
'recoveryCodes' => $recoveryCodes,
|
||||
]);
|
||||
}
|
||||
|
||||
public function disable(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'password' => ['required', 'string'],
|
||||
'code' => ['nullable', 'string'],
|
||||
]);
|
||||
|
||||
$user = auth()->user();
|
||||
|
||||
if (!Hash::check($request->password, $user->password)) {
|
||||
return back()->withErrors(['password' => __('auth.password_incorrect')]);
|
||||
}
|
||||
|
||||
// If 2FA is enabled, verify the code
|
||||
if ($user->isTwoFactorEnabled() && $request->code) {
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
$secret = $user->getTwoFactorSecret();
|
||||
|
||||
if (!$google2fa->verifyKey($secret, $request->code)) {
|
||||
return back()->withErrors(['code' => __('auth.2fa_invalid')]);
|
||||
}
|
||||
}
|
||||
|
||||
$user->two_factor_secret = null;
|
||||
$user->two_factor_recovery_codes = null;
|
||||
$user->two_factor_enabled = false;
|
||||
$user->save();
|
||||
|
||||
return redirect()->route('2fa.settings')->with('success', __('auth.2fa_disabled'));
|
||||
}
|
||||
|
||||
public function regenerateRecoveryCodes()
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (!$user->isTwoFactorEnabled()) {
|
||||
return redirect()->route('2fa.settings')->with('error', __('auth.2fa_not_enabled'));
|
||||
}
|
||||
|
||||
$recoveryCodes = $user->generateRecoveryCodes();
|
||||
$user->two_factor_recovery_codes = $recoveryCodes;
|
||||
$user->save();
|
||||
|
||||
return view('auth.2fa-recovery-codes', [
|
||||
'recoveryCodes' => $recoveryCodes,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class WebAuthController extends Controller
|
||||
{
|
||||
public function showLogin()
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
public function login(Request $request)
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required'],
|
||||
]);
|
||||
|
||||
$user = User::where('email', $request->email)->first();
|
||||
|
||||
if (!$user || !Hash::check($request->password, $user->password)) {
|
||||
return back()->withErrors([
|
||||
'email' => __('auth.failed'),
|
||||
])->onlyInput('email');
|
||||
}
|
||||
|
||||
// Check if 2FA is enabled
|
||||
if ($user->isTwoFactorEnabled()) {
|
||||
session(['2fa_user_id' => $user->id]);
|
||||
return redirect()->route('2fa.challenge');
|
||||
}
|
||||
|
||||
Auth::login($user, $request->boolean('remember'));
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->intended(route('dashboard'));
|
||||
}
|
||||
|
||||
public function show2FAChallenge()
|
||||
{
|
||||
if (!session()->has('2fa_user_id')) {
|
||||
return redirect()->route('login');
|
||||
}
|
||||
return view('auth.2fa-challenge');
|
||||
}
|
||||
|
||||
public function verify2FA(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'code' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
$userId = session('2fa_user_id');
|
||||
if (!$userId) {
|
||||
return redirect()->route('login');
|
||||
}
|
||||
|
||||
$user = User::find($userId);
|
||||
if (!$user) {
|
||||
return redirect()->route('login');
|
||||
}
|
||||
|
||||
$google2fa = app('pragmarx.google2fa');
|
||||
$secret = $user->getTwoFactorSecret();
|
||||
|
||||
$valid = $google2fa->verifyKey($secret, $request->code);
|
||||
|
||||
// Check recovery codes if TOTP is invalid
|
||||
if (!$valid) {
|
||||
$recoveryCodes = $user->two_factor_recovery_codes ?? [];
|
||||
if (in_array($request->code, $recoveryCodes)) {
|
||||
$user->two_factor_recovery_codes = array_diff($recoveryCodes, [$request->code]);
|
||||
$user->save();
|
||||
$valid = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$valid) {
|
||||
return back()->withErrors([
|
||||
'code' => __('auth.2fa_invalid'),
|
||||
]);
|
||||
}
|
||||
|
||||
session()->forget('2fa_user_id');
|
||||
Auth::login($user);
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->intended(route('dashboard'));
|
||||
}
|
||||
|
||||
public function showRegister()
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
public function register(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
|
||||
'password' => ['required', 'confirmed', Password::defaults()],
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'password' => Hash::make($request->password),
|
||||
]);
|
||||
|
||||
Auth::login($user);
|
||||
|
||||
return redirect()->route('dashboard');
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
Auth::logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect()->route('login');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, ValidatesRequests;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Patient;
|
||||
use App\Models\Appointment;
|
||||
use App\Models\Invoice;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$today = Carbon::today();
|
||||
|
||||
$stats = [
|
||||
'total_patients' => Patient::count(),
|
||||
'today_appointments' => Appointment::whereDate('appointment_date', $today)->count(),
|
||||
'pending_invoices' => Invoice::where('status', 'sent')->orWhere('status', 'partial')->count(),
|
||||
'month_revenue' => Invoice::whereMonth('invoice_date', $today->month)
|
||||
->whereYear('invoice_date', $today->year)
|
||||
->sum('paid_amount'),
|
||||
];
|
||||
|
||||
$recent_appointments = Appointment::with('patient', 'user')
|
||||
->whereDate('appointment_date', '>=', $today)
|
||||
->orderBy('appointment_date')
|
||||
->limit(5)
|
||||
->get();
|
||||
|
||||
return view('dashboard', compact('stats', 'recent_appointments'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
|
||||
class Kernel extends HttpKernel
|
||||
{
|
||||
/**
|
||||
* The application's global HTTP middleware stack.
|
||||
*
|
||||
* These middleware are run during every request to your application.
|
||||
*
|
||||
* @var array<int, class-string|string>
|
||||
*/
|
||||
protected $middleware = [
|
||||
// \App\Http\Middleware\TrustHosts::class,
|
||||
\App\Http\Middleware\TrustProxies::class,
|
||||
\Illuminate\Http\Middleware\HandleCors::class,
|
||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||
\App\Http\Middleware\TrimStrings::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware groups.
|
||||
*
|
||||
* @var array<string, array<int, class-string|string>>
|
||||
*/
|
||||
protected $middlewareGroups = [
|
||||
'web' => [
|
||||
\App\Http\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
|
||||
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's middleware aliases.
|
||||
*
|
||||
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
|
||||
*
|
||||
* @var array<string, class-string|string>
|
||||
*/
|
||||
protected $middlewareAliases = [
|
||||
'auth' => \App\Http\Middleware\Authenticate::class,
|
||||
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
|
||||
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
|
||||
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
||||
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
||||
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
||||
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
||||
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
|
||||
'signed' => \App\Http\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class Authenticate extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the path the user should be redirected to when they are not authenticated.
|
||||
*/
|
||||
protected function redirectTo(Request $request): ?string
|
||||
{
|
||||
return $request->expectsJson() ? null : route('login');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
|
||||
|
||||
class EncryptCookies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the cookies that should not be encrypted.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
|
||||
|
||||
class PreventRequestsDuringMaintenance extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RedirectIfAuthenticated
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string ...$guards): Response
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
foreach ($guards as $guard) {
|
||||
if (Auth::guard($guard)->check()) {
|
||||
return redirect(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
|
||||
|
||||
class TrimStrings extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the attributes that should not be trimmed.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustHosts as Middleware;
|
||||
|
||||
class TrustHosts extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the host patterns that should be trusted.
|
||||
*
|
||||
* @return array<int, string|null>
|
||||
*/
|
||||
public function hosts(): array
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustProxies as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TrustProxies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The trusted proxies for this application.
|
||||
*
|
||||
* @var array<int, string>|string|null
|
||||
*/
|
||||
protected $proxies;
|
||||
|
||||
/**
|
||||
* The headers that should be used to detect proxies.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $headers =
|
||||
Request::HEADER_X_FORWARDED_FOR |
|
||||
Request::HEADER_X_FORWARDED_HOST |
|
||||
Request::HEADER_X_FORWARDED_PORT |
|
||||
Request::HEADER_X_FORWARDED_PROTO |
|
||||
Request::HEADER_X_FORWARDED_AWS_ELB;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
|
||||
|
||||
class ValidateSignature extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the query string parameters that should be ignored.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
// 'fbclid',
|
||||
// 'utm_campaign',
|
||||
// 'utm_content',
|
||||
// 'utm_medium',
|
||||
// 'utm_source',
|
||||
// 'utm_term',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
|
||||
|
||||
class VerifyCsrfToken extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be excluded from CSRF verification.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreAppointmentRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'patient_id' => ['required', 'exists:patients,id'],
|
||||
'therapist_id' => ['required', 'exists:users,id'],
|
||||
'appointment_date' => ['required', 'date'],
|
||||
'duration_minutes' => ['required', 'integer', 'min:15'],
|
||||
'type' => ['nullable', 'in:session,assessment,follow-up'],
|
||||
'room' => ['nullable', 'string', 'max:50'],
|
||||
'notes' => ['nullable', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StorePatientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'first_name' => ['required', 'string', 'max:255'],
|
||||
'last_name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['nullable', 'email', 'max:255', 'unique:patients'],
|
||||
'phone' => ['nullable', 'string', 'max:50'],
|
||||
'whatsapp' => ['nullable', 'string', 'max:50'],
|
||||
'national_id' => ['nullable', 'string', 'max:50'],
|
||||
'date_of_birth' => ['nullable', 'date'],
|
||||
'gender' => ['nullable', 'in:male,female,other'],
|
||||
'address' => ['nullable', 'string'],
|
||||
'referral_source' => ['nullable', 'string', 'max:255'],
|
||||
'emergency_contact_name' => ['nullable', 'string', 'max:255'],
|
||||
'emergency_contact_phone' => ['nullable', 'string', 'max:50'],
|
||||
'medical_history' => ['nullable', 'string'],
|
||||
'allergies' => ['nullable', 'string'],
|
||||
'notes' => ['nullable', 'string'],
|
||||
'status' => ['nullable', 'in:active,inactive'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateAppointmentRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'patient_id' => ['required', 'exists:patients,id'],
|
||||
'therapist_id' => ['required', 'exists:users,id'],
|
||||
'appointment_date' => ['required', 'date'],
|
||||
'duration_minutes' => ['required', 'integer', 'min:15'],
|
||||
'type' => ['nullable', 'in:session,assessment,follow-up'],
|
||||
'room' => ['nullable', 'string', 'max:50'],
|
||||
'status' => ['required', 'in:scheduled,confirmed,in_progress,completed,cancelled,no_show'],
|
||||
'notes' => ['nullable', 'string'],
|
||||
'cancellation_reason' => ['nullable', 'string', 'required_if:status,cancelled'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdatePatientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
$patientId = $this->route('patient');
|
||||
|
||||
return [
|
||||
'first_name' => ['required', 'string', 'max:255'],
|
||||
'last_name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['nullable', 'email', 'max:255', 'unique:patients,email,' . $patientId],
|
||||
'phone' => ['nullable', 'string', 'max:50'],
|
||||
'whatsapp' => ['nullable', 'string', 'max:50'],
|
||||
'national_id' => ['nullable', 'string', 'max:50'],
|
||||
'date_of_birth' => ['nullable', 'date'],
|
||||
'gender' => ['nullable', 'in:male,female,other'],
|
||||
'address' => ['nullable', 'string'],
|
||||
'referral_source' => ['nullable', 'string', 'max:255'],
|
||||
'emergency_contact_name' => ['nullable', 'string', 'max:255'],
|
||||
'emergency_contact_phone' => ['nullable', 'string', 'max:50'],
|
||||
'medical_history' => ['nullable', 'string'],
|
||||
'allergies' => ['nullable', 'string'],
|
||||
'notes' => ['nullable', 'string'],
|
||||
'status' => ['nullable', 'in:active,inactive'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class AppointmentResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'patient' => [
|
||||
'id' => $this->patient->id,
|
||||
'name' => $this->patient->fullName(),
|
||||
'phone' => $this->patient->phone,
|
||||
],
|
||||
'therapist' => [
|
||||
'id' => $this->user->id,
|
||||
'name' => $this->user->name,
|
||||
],
|
||||
'appointment_date' => $this->appointment_date->format('Y-m-d'),
|
||||
'appointment_time' => $this->appointment_date->format('H:i'),
|
||||
'duration_minutes' => $this->duration_minutes,
|
||||
'end_time' => $this->appointment_date->copy()->addMinutes($this->duration_minutes)->format('H:i'),
|
||||
'status' => $this->status,
|
||||
'notes' => $this->notes,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class CurrencyResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'name' => $this->name,
|
||||
'symbol' => $this->symbol,
|
||||
'decimal_places' => $this->decimal_places,
|
||||
'exchange_rate_to_base' => $this->exchange_rate_to_base,
|
||||
'is_base' => $this->is_base,
|
||||
'is_active' => $this->is_active,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class InvoiceResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'invoice_number' => $this->invoice_number,
|
||||
'patient' => [
|
||||
'id' => $this->patient->id,
|
||||
'name' => $this->patient->fullName(),
|
||||
],
|
||||
'invoice_date' => $this->invoice_date->format('Y-m-d'),
|
||||
'due_date' => $this->due_date->format('Y-m-d'),
|
||||
'subtotal' => $this->subtotal,
|
||||
'tax_amount' => $this->tax_amount,
|
||||
'discount_amount' => $this->discount_amount,
|
||||
'total_amount' => $this->total_amount,
|
||||
'paid_amount' => $this->paid_amount,
|
||||
'balance' => $this->balance,
|
||||
'status' => $this->status,
|
||||
'currency' => new CurrencyResource($this->currency),
|
||||
'notes' => $this->notes,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class LedgerEntryResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'entry_date' => $this->entry_date->format('Y-m-d'),
|
||||
'account' => [
|
||||
'id' => $this->chartOfAccount->id,
|
||||
'code' => $this->chartOfAccount->code,
|
||||
'name' => $this->chartOfAccount->name,
|
||||
'type' => $this->chartOfAccount->type,
|
||||
],
|
||||
'currency' => new CurrencyResource($this->currency),
|
||||
'amount' => $this->amount,
|
||||
'description' => $this->description,
|
||||
'source_type' => $this->source_type,
|
||||
'source_id' => $this->source_id,
|
||||
'created_by' => [
|
||||
'id' => $this->creator->id,
|
||||
'name' => $this->creator->name,
|
||||
],
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PackageResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'number_of_sessions' => $this->number_of_sessions,
|
||||
'price' => $this->price,
|
||||
'currency' => new CurrencyResource($this->currency),
|
||||
'validity_days' => $this->validity_days,
|
||||
'description' => $this->description,
|
||||
'is_active' => $this->is_active,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PatientPackageResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'patient_id' => $this->patient_id,
|
||||
'package' => new PackageResource($this->package),
|
||||
'total_sessions' => $this->total_sessions,
|
||||
'remaining_sessions' => $this->remaining_sessions,
|
||||
'used_sessions' => $this->total_sessions - $this->remaining_sessions,
|
||||
'start_date' => $this->start_date->format('Y-m-d'),
|
||||
'end_date' => $this->end_date->format('Y-m-d'),
|
||||
'status' => $this->status,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PatientProfileResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'patient_code' => $this->patient_code,
|
||||
'full_name' => $this->fullName(),
|
||||
'email' => $this->email,
|
||||
'phone' => $this->phone,
|
||||
'whatsapp' => $this->whatsapp,
|
||||
'status' => $this->status,
|
||||
'upcoming_appointments' => AppointmentResource::collection(
|
||||
$this->appointments()->where('appointment_date', '>=', now())->orderBy('appointment_date')->limit(5)->get()
|
||||
),
|
||||
'past_appointments' => AppointmentResource::collection(
|
||||
$this->appointments()->where('appointment_date', '<', now())->orderByDesc('appointment_date')->limit(5)->get()
|
||||
),
|
||||
'invoices' => InvoiceResource::collection($this->invoices()->orderByDesc('invoice_date')->limit(10)->get()),
|
||||
'payments' => PaymentResource::collection(
|
||||
Payment::whereIn('invoice_id', $this->invoices->pluck('id'))->orderByDesc('payment_date')->limit(10)->get()
|
||||
),
|
||||
'balance' => $this->invoices->sum('balance'),
|
||||
'active_packages' => PatientPackageResource::collection(
|
||||
$this->packages()->where('status', 'active')->get()
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PatientResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'patient_code' => $this->patient_code,
|
||||
'first_name' => $this->first_name,
|
||||
'last_name' => $this->last_name,
|
||||
'full_name' => $this->fullName(),
|
||||
'email' => $this->email,
|
||||
'phone' => $this->phone,
|
||||
'whatsapp' => $this->whatsapp,
|
||||
'national_id' => $this->national_id,
|
||||
'date_of_birth' => $this->date_of_birth?->format('Y-m-d'),
|
||||
'gender' => $this->gender,
|
||||
'address' => $this->address,
|
||||
'referral_source' => $this->referral_source,
|
||||
'status' => $this->status,
|
||||
'emergency_contact' => [
|
||||
'name' => $this->emergency_contact_name,
|
||||
'phone' => $this->emergency_contact_phone,
|
||||
],
|
||||
'medical_history' => $this->medical_history,
|
||||
'allergies' => $this->allergies,
|
||||
'notes' => $this->notes,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
'updated_at' => $this->updated_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PaymentResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'payment_number' => $this->payment_number,
|
||||
'invoice' => [
|
||||
'id' => $this->invoice->id,
|
||||
'number' => $this->invoice->invoice_number,
|
||||
],
|
||||
'patient' => [
|
||||
'id' => $this->invoice->patient->id,
|
||||
'name' => $this->invoice->patient->fullName(),
|
||||
],
|
||||
'payment_date' => $this->payment_date->format('Y-m-d'),
|
||||
'amount' => $this->amount,
|
||||
'payment_method' => $this->payment_method,
|
||||
'reference_number' => $this->reference_number,
|
||||
'notes' => $this->notes,
|
||||
'received_by' => [
|
||||
'id' => $this->receivedBy->id,
|
||||
'name' => $this->receivedBy->name,
|
||||
],
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ReminderResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'appointment_id' => $this->appointment_id,
|
||||
'patient' => [
|
||||
'id' => $this->appointment->patient->id,
|
||||
'name' => $this->appointment->patient->fullName(),
|
||||
],
|
||||
'channel' => $this->channel,
|
||||
'content' => $this->content,
|
||||
'send_at' => $this->send_at?->format('Y-m-d H:i:s'),
|
||||
'sent_at' => $this->sent_at?->format('Y-m-d H:i:s'),
|
||||
'status' => $this->status,
|
||||
'error_message' => $this->error_message,
|
||||
'response' => $this->response,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class TherapistResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'email' => $this->email,
|
||||
'role' => $this->role,
|
||||
'specialization' => $this->specialization,
|
||||
'hourly_rate' => $this->hourly_rate,
|
||||
'session_rate' => $this->session_rate,
|
||||
'target_sessions_per_day' => $this->target_sessions_per_day,
|
||||
'target_sessions_per_month' => $this->target_sessions_per_month,
|
||||
'working_schedule' => $this->working_schedule,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class WageResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'therapist' => [
|
||||
'id' => $this->user->id,
|
||||
'name' => $this->user->name,
|
||||
],
|
||||
'period_start' => $this->period_start->format('Y-m-d'),
|
||||
'period_end' => $this->period_end->format('Y-m-d'),
|
||||
'sessions_count' => $this->sessions_count,
|
||||
'hours_worked' => $this->hours_worked,
|
||||
'base_amount' => $this->base_amount,
|
||||
'bonus' => $this->bonus,
|
||||
'deductions' => $this->deductions,
|
||||
'total_amount' => $this->total_amount,
|
||||
'currency' => new CurrencyResource($this->currency),
|
||||
'status' => $this->status,
|
||||
'notes' => $this->notes,
|
||||
'created_at' => $this->created_at?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Appointment extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'patient_id',
|
||||
'user_id',
|
||||
'appointment_date',
|
||||
'duration_minutes',
|
||||
'status',
|
||||
'notes',
|
||||
'cancellation_reason',
|
||||
'cancelled_by',
|
||||
'cancelled_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'appointment_date' => 'datetime',
|
||||
'cancelled_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function patient(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Patient::class);
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function cancelledBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'cancelled_by');
|
||||
}
|
||||
|
||||
public function treatments()
|
||||
{
|
||||
return $this->hasMany(Treatment::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ChartOfAccount extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'name',
|
||||
'type',
|
||||
'category',
|
||||
'description',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
class Currency extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'name',
|
||||
'symbol',
|
||||
'decimal_places',
|
||||
'exchange_rate_to_base',
|
||||
'is_base',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'decimal_places' => 'integer',
|
||||
'exchange_rate_to_base' => 'decimal:6',
|
||||
'is_base' => 'boolean',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Invoice extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'invoice_number',
|
||||
'patient_id',
|
||||
'treatment_id',
|
||||
'invoice_date',
|
||||
'due_date',
|
||||
'subtotal',
|
||||
'tax_amount',
|
||||
'discount_amount',
|
||||
'total_amount',
|
||||
'paid_amount',
|
||||
'status',
|
||||
'currency_id',
|
||||
'notes',
|
||||
'created_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'invoice_date' => 'date',
|
||||
'due_date' => 'date',
|
||||
'subtotal' => 'decimal:2',
|
||||
'tax_amount' => 'decimal:2',
|
||||
'discount_amount' => 'decimal:2',
|
||||
'total_amount' => 'decimal:2',
|
||||
'paid_amount' => 'decimal:2',
|
||||
];
|
||||
|
||||
public function patient(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Patient::class);
|
||||
}
|
||||
|
||||
public function treatment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Treatment::class);
|
||||
}
|
||||
|
||||
public function currency(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Currency::class);
|
||||
}
|
||||
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
|
||||
public function payments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Payment::class);
|
||||
}
|
||||
|
||||
public function getBalanceAttribute(): float
|
||||
{
|
||||
return $this->total_amount - $this->paid_amount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class LedgerEntry extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'entry_date',
|
||||
'chart_of_account_id',
|
||||
'currency_id',
|
||||
'amount',
|
||||
'description',
|
||||
'source_type',
|
||||
'source_id',
|
||||
'created_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'entry_date' => 'date',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
|
||||
public function chartOfAccount(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ChartOfAccount::class);
|
||||
}
|
||||
|
||||
public function currency(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Currency::class);
|
||||
}
|
||||
|
||||
public function creator(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
|
||||
public function scopeIncome($query)
|
||||
{
|
||||
return $query->whereHas('chartOfAccount', function ($q) {
|
||||
$q->where('type', 'income');
|
||||
});
|
||||
}
|
||||
|
||||
public function scopeExpense($query)
|
||||
{
|
||||
return $query->whereHas('chartOfAccount', function ($q) {
|
||||
$q->where('type', 'expense');
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Package extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'number_of_sessions',
|
||||
'price',
|
||||
'currency_id',
|
||||
'validity_days',
|
||||
'description',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'number_of_sessions' => 'integer',
|
||||
'price' => 'decimal:2',
|
||||
'validity_days' => 'integer',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
|
||||
public function currency(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Currency::class);
|
||||
}
|
||||
|
||||
public function patientPackages(): HasMany
|
||||
{
|
||||
return $this->hasMany(PatientPackage::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Patient extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'patient_code',
|
||||
'first_name',
|
||||
'last_name',
|
||||
'email',
|
||||
'phone',
|
||||
'date_of_birth',
|
||||
'gender',
|
||||
'address',
|
||||
'emergency_contact_name',
|
||||
'emergency_contact_phone',
|
||||
'medical_history',
|
||||
'allergies',
|
||||
'notes',
|
||||
'created_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'date_of_birth' => 'date',
|
||||
];
|
||||
|
||||
public function appointments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Appointment::class);
|
||||
}
|
||||
|
||||
public function treatments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Treatment::class);
|
||||
}
|
||||
|
||||
public function invoices(): HasMany
|
||||
{
|
||||
return $this->hasMany(Invoice::class);
|
||||
}
|
||||
|
||||
public function fullName(): string
|
||||
{
|
||||
return "{$this->first_name} {$this->last_name}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class PatientPackage extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'patient_id',
|
||||
'package_id',
|
||||
'total_sessions',
|
||||
'remaining_sessions',
|
||||
'start_date',
|
||||
'end_date',
|
||||
'status',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'total_sessions' => 'integer',
|
||||
'remaining_sessions' => 'integer',
|
||||
'start_date' => 'date',
|
||||
'end_date' => 'date',
|
||||
];
|
||||
|
||||
public function patient(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Patient::class);
|
||||
}
|
||||
|
||||
public function package(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Package::class);
|
||||
}
|
||||
|
||||
public function consumeSession(): bool
|
||||
{
|
||||
if ($this->remaining_sessions > 0 && $this->status === 'active') {
|
||||
$this->remaining_sessions--;
|
||||
if ($this->remaining_sessions === 0) {
|
||||
$this->status = 'completed';
|
||||
}
|
||||
$this->save();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Payment extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'payment_number',
|
||||
'invoice_id',
|
||||
'payment_date',
|
||||
'amount',
|
||||
'payment_method',
|
||||
'reference_number',
|
||||
'notes',
|
||||
'received_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'payment_date' => 'date',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
|
||||
public function invoice(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Invoice::class);
|
||||
}
|
||||
|
||||
public function receivedBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'received_by');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Reminder extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'appointment_id',
|
||||
'template_id',
|
||||
'channel',
|
||||
'content',
|
||||
'send_at',
|
||||
'sent_at',
|
||||
'status',
|
||||
'error_message',
|
||||
'response',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'send_at' => 'datetime',
|
||||
'sent_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function appointment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Appointment::class);
|
||||
}
|
||||
|
||||
public function template(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ReminderTemplate::class, 'template_id');
|
||||
}
|
||||
|
||||
public function markAsSent(string $response = null): void
|
||||
{
|
||||
$this->status = 'sent';
|
||||
$this->sent_at = now();
|
||||
$this->response = $response;
|
||||
$this->save();
|
||||
}
|
||||
|
||||
public function markAsFailed(string $errorMessage): void
|
||||
{
|
||||
$this->status = 'failed';
|
||||
$this->error_message = $errorMessage;
|
||||
$this->save();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class ReminderTemplate extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'content',
|
||||
'channel',
|
||||
'hours_before',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'hours_before' => 'integer',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
|
||||
public function reminders(): HasMany
|
||||
{
|
||||
return $this->hasMany(Reminder::class, 'template_id');
|
||||
}
|
||||
|
||||
public function parseContent(array $placeholders): string
|
||||
{
|
||||
$content = $this->content;
|
||||
foreach ($placeholders as $key => $value) {
|
||||
$content = str_replace('{' . $key . '}', $value, $content);
|
||||
}
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Treatment extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'patient_id',
|
||||
'appointment_id',
|
||||
'user_id',
|
||||
'treatment_code',
|
||||
'name',
|
||||
'description',
|
||||
'sessions_count',
|
||||
'sessions_completed',
|
||||
'start_date',
|
||||
'end_date',
|
||||
'status',
|
||||
'total_cost',
|
||||
'currency_id',
|
||||
'notes',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'start_date' => 'date',
|
||||
'end_date' => 'date',
|
||||
'sessions_count' => 'integer',
|
||||
'sessions_completed' => 'integer',
|
||||
'total_cost' => 'decimal:2',
|
||||
];
|
||||
|
||||
public function patient(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Patient::class);
|
||||
}
|
||||
|
||||
public function appointment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Appointment::class);
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function currency(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Currency::class);
|
||||
}
|
||||
|
||||
public function invoices(): HasMany
|
||||
{
|
||||
return $this->hasMany(Invoice::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
|
||||
class User extends Authenticatable implements MustVerifyEmail
|
||||
{
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'role',
|
||||
'specialization',
|
||||
'hourly_rate',
|
||||
'session_rate',
|
||||
'target_sessions_per_day',
|
||||
'target_sessions_per_month',
|
||||
'working_schedule',
|
||||
'two_factor_secret',
|
||||
'two_factor_recovery_codes',
|
||||
'two_factor_enabled',
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'remember_token',
|
||||
'two_factor_secret',
|
||||
'two_factor_recovery_codes',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
'two_factor_enabled' => 'boolean',
|
||||
'two_factor_recovery_codes' => 'array',
|
||||
];
|
||||
|
||||
public function isTwoFactorEnabled(): bool
|
||||
{
|
||||
return $this->two_factor_enabled === true;
|
||||
}
|
||||
|
||||
public function getTwoFactorSecret(): ?string
|
||||
{
|
||||
return $this->two_factor_secret ? decrypt($this->two_factor_secret) : null;
|
||||
}
|
||||
|
||||
public function setTwoFactorSecret(string $secret): void
|
||||
{
|
||||
$this->two_factor_secret = encrypt($secret);
|
||||
}
|
||||
|
||||
public function generateRecoveryCodes(): array
|
||||
{
|
||||
$codes = [];
|
||||
for ($i = 0; $i < 8; $i++) {
|
||||
$codes[] = bin2hex(random_bytes(4));
|
||||
}
|
||||
return $codes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Wage extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'period_start',
|
||||
'period_end',
|
||||
'sessions_count',
|
||||
'hours_worked',
|
||||
'base_amount',
|
||||
'bonus',
|
||||
'deductions',
|
||||
'total_amount',
|
||||
'currency_id',
|
||||
'status',
|
||||
'notes',
|
||||
'created_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'period_start' => 'date',
|
||||
'period_end' => 'date',
|
||||
'sessions_count' => 'integer',
|
||||
'hours_worked' => 'integer',
|
||||
'base_amount' => 'decimal:2',
|
||||
'bonus' => 'decimal:2',
|
||||
'deductions' => 'decimal:2',
|
||||
'total_amount' => 'decimal:2',
|
||||
];
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function currency(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Currency::class);
|
||||
}
|
||||
|
||||
public function creator(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Appointment;
|
||||
|
||||
class AppointmentPolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function view(User $user, Appointment $appointment): bool
|
||||
{
|
||||
if (in_array($user->role, ['admin', 'manager', 'receptionist'])) {
|
||||
return true;
|
||||
}
|
||||
// Therapists can see their own appointments
|
||||
return $appointment->user_id === $user->id;
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager', 'receptionist']);
|
||||
}
|
||||
|
||||
public function update(User $user, Appointment $appointment): bool
|
||||
{
|
||||
if (in_array($user->role, ['admin', 'manager', 'receptionist'])) {
|
||||
return true;
|
||||
}
|
||||
// Therapists can update their own appointments
|
||||
return $appointment->user_id === $user->id;
|
||||
}
|
||||
|
||||
public function delete(User $user, Appointment $appointment): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
class InvoicePolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager', 'receptionist']);
|
||||
}
|
||||
|
||||
public function view(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager', 'receptionist']);
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager', 'receptionist']);
|
||||
}
|
||||
|
||||
public function update(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
|
||||
public function delete(User $user): bool
|
||||
{
|
||||
return $user->role === 'admin';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
class LedgerPolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
|
||||
public function view(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
|
||||
public function viewReports(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Patient;
|
||||
|
||||
class PatientPolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager', 'receptionist', 'therapist']);
|
||||
}
|
||||
|
||||
public function view(User $user, Patient $patient): bool
|
||||
{
|
||||
if (in_array($user->role, ['admin', 'manager', 'receptionist'])) {
|
||||
return true;
|
||||
}
|
||||
// Therapists can only see their own patients
|
||||
if ($user->role === 'therapist') {
|
||||
return $patient->appointments()->where('user_id', $user->id)->exists();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager', 'receptionist']);
|
||||
}
|
||||
|
||||
public function update(User $user, Patient $patient): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager', 'receptionist']);
|
||||
}
|
||||
|
||||
public function delete(User $user, Patient $patient): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
class WagePolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
|
||||
public function view(User $user, $wage): bool
|
||||
{
|
||||
if (in_array($user->role, ['admin', 'manager'])) {
|
||||
return true;
|
||||
}
|
||||
// Therapists can only see their own wages
|
||||
return $wage->user_id === $user->id;
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
|
||||
public function approve(User $user): bool
|
||||
{
|
||||
return in_array($user->role, ['admin', 'manager']);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
||||
use App\Models\Patient;
|
||||
use App\Models\Appointment;
|
||||
use App\Policies\PatientPolicy;
|
||||
use App\Policies\AppointmentPolicy;
|
||||
use App\Policies\InvoicePolicy;
|
||||
use App\Policies\LedgerPolicy;
|
||||
use App\Policies\WagePolicy;
|
||||
|
||||
class AuthServiceProvider extends ServiceProvider
|
||||
{
|
||||
protected $policies = [
|
||||
Patient::class => PatientPolicy::class,
|
||||
Appointment::class => AppointmentPolicy::class,
|
||||
];
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
// Gates for invoices
|
||||
Gate::define('view-invoices', [InvoicePolicy::class, 'viewAny']);
|
||||
Gate::define('create-invoices', [InvoicePolicy::class, 'create']);
|
||||
|
||||
// Gates for ledger
|
||||
Gate::define('view-ledger', [LedgerPolicy::class, 'viewAny']);
|
||||
Gate::define('create-ledger', [LedgerPolicy::class, 'create']);
|
||||
Gate::define('view-reports', [LedgerPolicy::class, 'viewReports']);
|
||||
|
||||
// Gates for wages
|
||||
Gate::define('view-wages', [WagePolicy::class, 'viewAny']);
|
||||
Gate::define('approve-wages', [WagePolicy::class, 'approve']);
|
||||
|
||||
// Role-based gates
|
||||
Gate::define('is-admin', fn($user) => $user->role === 'admin');
|
||||
Gate::define('is-manager', fn($user) => in_array($user->role, ['admin', 'manager']));
|
||||
Gate::define('is-therapist', fn($user) => $user->role === 'therapist');
|
||||
Gate::define('is-receptionist', fn($user) => $user->role === 'receptionist');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Broadcast;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class BroadcastServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
Broadcast::routes();
|
||||
|
||||
require base_path('routes/channels.php');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
|
||||
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
|
||||
class EventServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The event to listener mappings for the application.
|
||||
*
|
||||
* @var array<class-string, array<int, class-string>>
|
||||
*/
|
||||
protected $listen = [
|
||||
Registered::class => [
|
||||
SendEmailVerificationNotification::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any events for your application.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if events and listeners should be automatically discovered.
|
||||
*/
|
||||
public function shouldDiscoverEvents(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
class RouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The path to your application's "home" route.
|
||||
*
|
||||
* Typically, users are redirected here after authentication.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const HOME = '/home';
|
||||
|
||||
/**
|
||||
* Define your route model bindings, pattern filters, and other route configuration.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
RateLimiter::for('api', function (Request $request) {
|
||||
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
|
||||
});
|
||||
|
||||
$this->routes(function () {
|
||||
Route::middleware('api')
|
||||
->prefix('api')
|
||||
->group(base_path('routes/api.php'));
|
||||
|
||||
Route::middleware('web')
|
||||
->group(base_path('routes/web.php'));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Appointment;
|
||||
use App\Models\Patient;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class AppointmentService
|
||||
{
|
||||
/**
|
||||
* Check for conflicting appointments for a therapist
|
||||
*/
|
||||
public function hasConflict(int $therapistId, Carbon $startTime, int $duration, ?int $excludeId = null): bool
|
||||
{
|
||||
$endTime = $startTime->copy()->addMinutes($duration);
|
||||
|
||||
$query = Appointment::where('user_id', $therapistId)
|
||||
->whereIn('status', ['scheduled', 'confirmed', 'in_progress'])
|
||||
->where(function ($q) use ($startTime, $endTime) {
|
||||
// Check if any appointment overlaps with the requested time
|
||||
$q->whereBetween('appointment_date', [$startTime, $endTime->copy()->subSecond()])
|
||||
->orWhereRaw("datetime(appointment_date, '+' || duration_minutes || ' minutes') BETWEEN ? AND ?", [$startTime, $endTime]);
|
||||
});
|
||||
|
||||
if ($excludeId) {
|
||||
$query->where('id', '!=', $excludeId);
|
||||
}
|
||||
|
||||
return $query->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for patient double-booking
|
||||
*/
|
||||
public function hasPatientConflict(int $patientId, Carbon $startTime, int $duration, ?int $excludeId = null): bool
|
||||
{
|
||||
$endTime = $startTime->copy()->addMinutes($duration);
|
||||
|
||||
$query = Appointment::where('patient_id', $patientId)
|
||||
->whereIn('status', ['scheduled', 'confirmed', 'in_progress'])
|
||||
->whereBetween('appointment_date', [$startTime, $endTime->copy()->subSecond()]);
|
||||
|
||||
if ($excludeId) {
|
||||
$query->where('id', '!=', $excludeId);
|
||||
}
|
||||
|
||||
return $query->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available time slots for a therapist on a given date
|
||||
*/
|
||||
public function getAvailableSlots(int $therapistId, string $date, int $duration = 60): array
|
||||
{
|
||||
$workingHours = ['09:00', '17:00']; // 9 AM to 5 PM
|
||||
$slotInterval = 30; // minutes
|
||||
|
||||
$slots = [];
|
||||
$start = Carbon::parse("$date {$workingHours[0]}");
|
||||
$end = Carbon::parse("$date {$workingHours[1]}");
|
||||
|
||||
while ($start->lt($end)) {
|
||||
$slotEnd = $start->copy()->addMinutes($duration);
|
||||
|
||||
if ($slotEnd->lte($end) && !$this->hasConflict($therapistId, $start, $duration)) {
|
||||
$slots[] = $start->format('H:i');
|
||||
}
|
||||
|
||||
$start->addMinutes($slotInterval);
|
||||
}
|
||||
|
||||
return $slots;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get calendar feed for a date range
|
||||
*/
|
||||
public function getCalendarFeed(string $startDate, string $endDate, ?int $therapistId = null): array
|
||||
{
|
||||
$query = Appointment::with(['patient', 'user'])
|
||||
->whereBetween('appointment_date', [$startDate, $endDate]);
|
||||
|
||||
if ($therapistId) {
|
||||
$query->where('user_id', $therapistId);
|
||||
}
|
||||
|
||||
return $query->orderBy('appointment_date')->get()->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume a package session for an appointment
|
||||
*/
|
||||
public function consumePackageSession(Appointment $appointment, int $patientPackageId): bool
|
||||
{
|
||||
$patientPackage = \App\Models\PatientPackage::find($patientPackageId);
|
||||
|
||||
if (!$patientPackage || $patientPackage->patient_id !== $appointment->patient_id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $patientPackage->consumeSession();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\LedgerEntry;
|
||||
use App\Models\ChartOfAccount;
|
||||
use App\Models\Payment;
|
||||
use App\Models\Wage;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class LedgerService
|
||||
{
|
||||
/**
|
||||
* Create a ledger entry from a payment (income)
|
||||
*/
|
||||
public function recordPayment(Payment $payment): LedgerEntry
|
||||
{
|
||||
$incomeAccount = ChartOfAccount::where('type', 'income')
|
||||
->where('category', 'revenue')
|
||||
->first();
|
||||
|
||||
return LedgerEntry::create([
|
||||
'entry_date' => $payment->payment_date,
|
||||
'chart_of_account_id' => $incomeAccount?->id,
|
||||
'currency_id' => $payment->invoice->currency_id,
|
||||
'amount' => $payment->amount,
|
||||
'description' => "Payment received - {$payment->payment_number}",
|
||||
'source_type' => 'payment',
|
||||
'source_id' => $payment->id,
|
||||
'created_by' => $payment->received_by,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ledger entry for a wage (expense)
|
||||
*/
|
||||
public function recordWage(Wage $wage): LedgerEntry
|
||||
{
|
||||
$expenseAccount = ChartOfAccount::where('type', 'expense')
|
||||
->where('category', 'operating_expense')
|
||||
->first();
|
||||
|
||||
return LedgerEntry::create([
|
||||
'entry_date' => $wage->period_end,
|
||||
'chart_of_account_id' => $expenseAccount?->id,
|
||||
'currency_id' => $wage->currency_id,
|
||||
'amount' => -$wage->total_amount, // negative for expense
|
||||
'description' => "Wage payment - {$wage->user->name} ({$wage->period_start} to {$wage->period_end})",
|
||||
'source_type' => 'wage',
|
||||
'source_id' => $wage->id,
|
||||
'created_by' => $wage->created_by,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get income summary for a period
|
||||
*/
|
||||
public function getIncomeSummary(string $startDate, string $endDate): array
|
||||
{
|
||||
$entries = LedgerEntry::income()
|
||||
->whereBetween('entry_date', [$startDate, $endDate])
|
||||
->with('chartOfAccount')
|
||||
->get();
|
||||
|
||||
$byAccount = $entries->groupBy('chart_of_account_id')
|
||||
->map(fn($group) => [
|
||||
'account_name' => $group->first()->chartOfAccount->name,
|
||||
'total' => $group->sum('amount'),
|
||||
])
|
||||
->values();
|
||||
|
||||
return [
|
||||
'total_income' => $entries->sum('amount'),
|
||||
'by_account' => $byAccount,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get expense summary for a period
|
||||
*/
|
||||
public function getExpenseSummary(string $startDate, string $endDate): array
|
||||
{
|
||||
$entries = LedgerEntry::expense()
|
||||
->whereBetween('entry_date', [$startDate, $endDate])
|
||||
->with('chartOfAccount')
|
||||
->get();
|
||||
|
||||
$byAccount = $entries->groupBy('chart_of_account_id')
|
||||
->map(fn($group) => [
|
||||
'account_name' => $group->first()->chartOfAccount->name,
|
||||
'total' => abs($group->sum('amount')),
|
||||
])
|
||||
->values();
|
||||
|
||||
return [
|
||||
'total_expenses' => abs($entries->sum('amount')),
|
||||
'by_account' => $byAccount,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get net profit for a period
|
||||
*/
|
||||
public function getNetProfit(string $startDate, string $endDate): float
|
||||
{
|
||||
$income = $this->getIncomeSummary($startDate, $endDate)['total_income'];
|
||||
$expenses = $this->getExpenseSummary($startDate, $endDate)['total_expenses'];
|
||||
|
||||
return $income - $expenses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get full P&L report
|
||||
*/
|
||||
public function getProfitLossReport(string $startDate, string $endDate): array
|
||||
{
|
||||
$income = $this->getIncomeSummary($startDate, $endDate);
|
||||
$expenses = $this->getExpenseSummary($startDate, $endDate);
|
||||
|
||||
return [
|
||||
'period' => [
|
||||
'start' => $startDate,
|
||||
'end' => $endDate,
|
||||
],
|
||||
'income' => $income,
|
||||
'expenses' => $expenses,
|
||||
'net_profit' => $income['total_income'] - $expenses['total_expenses'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Reminder;
|
||||
use App\Models\ReminderTemplate;
|
||||
use App\Models\Appointment;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class ReminderService
|
||||
{
|
||||
/**
|
||||
* Generate reminders for an appointment
|
||||
*/
|
||||
public function generateReminders(Appointment $appointment): void
|
||||
{
|
||||
$templates = ReminderTemplate::where('is_active', true)->get();
|
||||
|
||||
foreach ($templates as $template) {
|
||||
$sendAt = $appointment->appointment_date->copy()->subHours($template->hours_before);
|
||||
|
||||
// Don't create if send time is in the past
|
||||
if ($sendAt->isPast()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$placeholders = [
|
||||
'patient_name' => $appointment->patient->fullName(),
|
||||
'date' => $appointment->appointment_date->format('Y-m-d'),
|
||||
'time' => $appointment->appointment_date->format('H:i'),
|
||||
'therapist_name' => $appointment->user->name,
|
||||
];
|
||||
|
||||
Reminder::create([
|
||||
'appointment_id' => $appointment->id,
|
||||
'template_id' => $template->id,
|
||||
'channel' => $template->channel,
|
||||
'content' => $template->parseContent($placeholders),
|
||||
'send_at' => $sendAt,
|
||||
'status' => 'queued',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get due reminders
|
||||
*/
|
||||
public function getDueReminders(int $limit = 50): array
|
||||
{
|
||||
return Reminder::with('appointment.patient')
|
||||
->where('status', 'queued')
|
||||
->where('send_at', '<=', now())
|
||||
->limit($limit)
|
||||
->get()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process and send reminders
|
||||
*/
|
||||
public function processReminders(): array
|
||||
{
|
||||
$reminders = Reminder::with('appointment.patient')
|
||||
->where('status', 'queued')
|
||||
->where('send_at', '<=', now())
|
||||
->get();
|
||||
|
||||
$results = [
|
||||
'sent' => 0,
|
||||
'failed' => 0,
|
||||
];
|
||||
|
||||
foreach ($reminders as $reminder) {
|
||||
try {
|
||||
$this->sendReminder($reminder);
|
||||
$reminder->markAsSent();
|
||||
$results['sent']++;
|
||||
} catch (\Exception $e) {
|
||||
$reminder->markAsFailed($e->getMessage());
|
||||
$results['failed']++;
|
||||
}
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a single reminder (stub - implement with actual SMS/WhatsApp provider)
|
||||
*/
|
||||
public function sendReminder(Reminder $reminder): void
|
||||
{
|
||||
// Stub implementation - integrate with SMS/WhatsApp provider
|
||||
$channel = $reminder->channel;
|
||||
$content = $reminder->content;
|
||||
|
||||
switch ($channel) {
|
||||
case 'sms':
|
||||
// TODO: Integrate with SMS provider
|
||||
break;
|
||||
case 'whatsapp':
|
||||
// TODO: Integrate with WhatsApp Business API
|
||||
break;
|
||||
case 'email':
|
||||
// TODO: Send email
|
||||
break;
|
||||
case 'internal':
|
||||
// Internal notification - logged only
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get reminder configuration
|
||||
*/
|
||||
public function getConfiguration(): array
|
||||
{
|
||||
return ReminderTemplate::where('is_active', true)
|
||||
->get()
|
||||
->map(fn($t) => [
|
||||
'id' => $t->id,
|
||||
'name' => $t->name,
|
||||
'channel' => $t->channel,
|
||||
'hours_before' => $t->hours_before,
|
||||
])
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update reminder configuration
|
||||
*/
|
||||
public function updateConfiguration(int $templateId, array $data): ReminderTemplate
|
||||
{
|
||||
$template = ReminderTemplate::findOrFail($templateId);
|
||||
$template->update($data);
|
||||
return $template;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Wage;
|
||||
use App\Models\User;
|
||||
use App\Models\Appointment;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class WageService
|
||||
{
|
||||
/**
|
||||
* Calculate wage for a therapist in a given period
|
||||
*/
|
||||
public function calculateWage(int $therapistId, string $periodStart, string $periodEnd): array
|
||||
{
|
||||
$therapist = User::find($therapistId);
|
||||
|
||||
$completedAppointments = Appointment::where('user_id', $therapistId)
|
||||
->where('status', 'completed')
|
||||
->whereBetween('appointment_date', [$periodStart, $periodEnd . ' 23:59:59'])
|
||||
->get();
|
||||
|
||||
$sessionsCount = $completedAppointments->count();
|
||||
$hoursWorked = $completedAppointments->sum('duration_minutes') / 60;
|
||||
|
||||
$baseAmount = 0;
|
||||
|
||||
if ($therapist->session_rate) {
|
||||
$baseAmount = $sessionsCount * $therapist->session_rate;
|
||||
} elseif ($therapist->hourly_rate) {
|
||||
$baseAmount = $hoursWorked * $therapist->hourly_rate;
|
||||
}
|
||||
|
||||
return [
|
||||
'therapist_id' => $therapistId,
|
||||
'period_start' => $periodStart,
|
||||
'period_end' => $periodEnd,
|
||||
'sessions_count' => $sessionsCount,
|
||||
'hours_worked' => round($hoursWorked, 2),
|
||||
'base_amount' => round($baseAmount, 2),
|
||||
'bonus' => 0,
|
||||
'deductions' => 0,
|
||||
'total_amount' => round($baseAmount, 2),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create wage record
|
||||
*/
|
||||
public function createWage(array $data, int $createdBy): Wage
|
||||
{
|
||||
$wage = Wage::create(array_merge($data, [
|
||||
'created_by' => $createdBy,
|
||||
]));
|
||||
|
||||
// Auto-create ledger entry
|
||||
$ledgerService = new LedgerService();
|
||||
$ledgerService->recordWage($wage);
|
||||
|
||||
return $wage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get therapist performance metrics
|
||||
*/
|
||||
public function getPerformanceMetrics(int $therapistId, string $periodStart, string $periodEnd): array
|
||||
{
|
||||
$wage = $this->calculateWage($therapistId, $periodStart, $periodEnd);
|
||||
$therapist = User::find($therapistId);
|
||||
|
||||
$targetSessions = $therapist->target_sessions_per_month ?? 0;
|
||||
$sessionsAchieved = $targetSessions > 0 ? ($wage['sessions_count'] / $targetSessions) * 100 : 0;
|
||||
|
||||
return [
|
||||
'sessions_count' => $wage['sessions_count'],
|
||||
'hours_worked' => $wage['hours_worked'],
|
||||
'target_sessions' => $targetSessions,
|
||||
'sessions_achieved_percentage' => round($sessionsAchieved, 2),
|
||||
'base_amount' => $wage['base_amount'],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user