Initial commit - Physiotherapy Clinic Management System

This commit is contained in:
Deploy committed 2026-03-10 00:38:51 +03:00
commit dbb326f2cc
300 files changed
+144285

No files matched your search

@@ -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]);
}
}
+139
View File
@@ -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');
}
}
+12
View File
@@ -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'));
}
}
+68
View File
@@ -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,
];
}
+17
View File
@@ -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');
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -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);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -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'],
];
}
}
+35
View File
@@ -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'),
];
}
}
+23
View File
@@ -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,
];
}
}
+33
View File
@@ -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'),
];
}
}
+24
View File
@@ -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()
),
];
}
}
+38
View File
@@ -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'),
];
}
}
+35
View File
@@ -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'),
];
}
}
+29
View File
@@ -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'),
];
}
}
+26
View File
@@ -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'),
];
}
}
+32
View File
@@ -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'),
];
}
}