add more controllers and fix tests

This commit is contained in:
root
2026-03-09 11:54:13 -04:00
parent 0c3e9b16f7
commit 1cb3573d4b
74 changed files with 2761 additions and 2728 deletions
@@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers\Api\Email;
use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Email\EmailSendRequest;
use App\Http\Resources\Email\EmailSenderResource;
use App\Services\Email\EmailAttachmentService;
use App\Services\Email\EmailDispatchService;
use App\Services\Email\EmailSenderOptionsService;
use Illuminate\Http\JsonResponse;
class EmailController extends BaseApiController
{
public function __construct(
private EmailDispatchService $dispatch,
private EmailSenderOptionsService $senderOptions,
private EmailAttachmentService $attachments
) {
parent::__construct();
}
public function senders(): JsonResponse
{
$senders = $this->senderOptions->listSenders();
return response()->json([
'ok' => true,
'senders' => EmailSenderResource::collection($senders),
]);
}
public function send(EmailSendRequest $request): JsonResponse
{
$payload = $request->validated();
$attachments = $this->attachments->normalize($request->file('attachments', []));
$ok = $this->dispatch->send(
$payload['recipient'],
$payload['subject'],
$payload['html_message'],
$payload['profile'] ?? null,
$payload['reply_to_email'] ?? null,
$payload['reply_to_name'] ?? null,
$attachments
);
if (!$ok) {
return response()->json([
'ok' => false,
'message' => 'Email failed to send.',
], 500);
}
return response()->json([
'ok' => true,
'message' => 'Email sent successfully.',
]);
}
}
@@ -0,0 +1,58 @@
<?php
namespace App\Http\Controllers\Api\Email;
use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Email\EmailExtractorCompareRequest;
use App\Http\Resources\Email\EmailExtractorCompareResource;
use App\Http\Resources\Email\EmailExtractorEmailsResource;
use App\Services\Email\EmailExtractorService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class EmailExtractorController extends BaseApiController
{
public function __construct(private EmailExtractorService $service)
{
parent::__construct();
}
public function emails(): JsonResponse
{
$emails = $this->service->listEmails();
return response()->json([
'ok' => true,
'emails' => new EmailExtractorEmailsResource($emails),
]);
}
public function compare(EmailExtractorCompareRequest $request): JsonResponse
{
$csvEmails = [];
$file = $request->file('file');
if ($file && $file->isValid()) {
$contents = file_get_contents($file->getRealPath() ?: $file->getPathname());
$csvEmails = $this->service->extractEmailsFromText($contents);
}
if (empty($csvEmails)) {
$csvEmails = $request->input('csv_emails', []);
}
if (empty($csvEmails)) {
return response()->json([
'ok' => false,
'message' => 'Provide a CSV file or csv_emails array.',
], 422);
}
$result = $this->service->compare($csvEmails);
return response()->json([
'ok' => true,
'comparison' => new EmailExtractorCompareResource($result),
]);
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Http\Controllers\Api\Finance;
use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Fees\FeeRefundRequest;
use App\Http\Requests\Fees\FeeTuitionTotalRequest;
use App\Http\Resources\Fees\FeeRefundResource;
use App\Http\Resources\Fees\FeeTuitionTotalResource;
use App\Services\Fees\FeeRefundCalculatorService;
use App\Services\Fees\FeeStudentFeeService;
use Illuminate\Http\JsonResponse;
class FeeCalculationController extends BaseApiController
{
public function __construct(
private FeeRefundCalculatorService $refunds,
private FeeStudentFeeService $tuition
) {
parent::__construct();
}
public function refund(FeeRefundRequest $request): JsonResponse
{
$payload = $request->validated();
$result = $this->refunds->calculateRefund($payload['students'], (int) $payload['parent_id']);
return response()->json([
'ok' => true,
'refund' => new FeeRefundResource($result),
]);
}
public function tuitionTotal(FeeTuitionTotalRequest $request): JsonResponse
{
$payload = $request->validated();
$total = $this->tuition->totalTuitionFee($payload['students']);
return response()->json([
'ok' => true,
'tuition' => new FeeTuitionTotalResource([
'total_tuition' => $total,
]),
]);
}
}
@@ -4,10 +4,10 @@ namespace App\Http\Controllers\Api\Finance;
use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Payments\PaymentTransactionCreateRequest;
use App\Http\Requests\Payments\PaymentTransactionStatusRequest;
use App\Http\Resources\Payments\PaymentTransactionResource;
use App\Services\Payments\PaymentTransactionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class PaymentTransactionController extends BaseApiController
{
@@ -37,10 +37,29 @@ class PaymentTransactionController extends BaseApiController
]);
}
public function updateStatus(PaymentTransactionStatusRequest $request, string $transactionId): JsonResponse
public function updateStatus(Request $request, string $transactionId): JsonResponse
{
$payload = $request->validated();
$updated = $this->service->updateStatus($transactionId, $payload['status']);
$status = $request->input('status');
if ($status === null) {
$raw = $request->getContent() ?: '';
$json = json_decode($raw, true);
if (is_array($json) && array_key_exists('status', $json)) {
$status = $json['status'];
} else {
$parsed = [];
parse_str($raw, $parsed);
$status = $parsed['status'] ?? null;
}
}
if ($status === null || trim((string) $status) === '') {
return response()->json([
'message' => 'Validation failed.',
'errors' => ['status' => ['The status field is required.']],
], 422);
}
$updated = $this->service->updateStatus($transactionId, (string) $status);
if (!$updated) {
return response()->json(['ok' => false, 'message' => 'Transaction not found.'], 404);
@@ -0,0 +1,128 @@
<?php
namespace App\Http\Controllers\Api\Finance;
use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\PurchaseOrders\PurchaseOrderIndexRequest;
use App\Http\Requests\PurchaseOrders\PurchaseOrderReceiveRequest;
use App\Http\Requests\PurchaseOrders\PurchaseOrderStoreRequest;
use App\Http\Resources\PurchaseOrders\PurchaseOrderItemResource;
use App\Http\Resources\PurchaseOrders\PurchaseOrderResource;
use App\Models\PurchaseOrder;
use App\Services\PurchaseOrders\PurchaseOrderCreateService;
use App\Services\PurchaseOrders\PurchaseOrderQueryService;
use App\Services\PurchaseOrders\PurchaseOrderReceiveService;
use App\Services\PurchaseOrders\PurchaseOrderStatusService;
use Illuminate\Http\JsonResponse;
use RuntimeException;
class PurchaseOrderController extends BaseApiController
{
public function __construct(
private PurchaseOrderQueryService $queryService,
private PurchaseOrderCreateService $createService,
private PurchaseOrderReceiveService $receiveService,
private PurchaseOrderStatusService $statusService
) {
parent::__construct();
}
public function index(PurchaseOrderIndexRequest $request): JsonResponse
{
$payload = $request->validated();
$orders = $this->queryService->list($payload['q'] ?? null);
return response()->json([
'ok' => true,
'orders' => PurchaseOrderResource::collection($orders),
]);
}
public function options(): JsonResponse
{
$data = $this->queryService->options();
return response()->json([
'ok' => true,
'suppliers' => $data['suppliers'] ?? [],
'supplies' => $data['supplies'] ?? [],
]);
}
public function show(int $id): JsonResponse
{
$data = $this->queryService->find($id);
if (!$data) {
return response()->json(['ok' => false, 'message' => 'Purchase order not found.'], 404);
}
return response()->json([
'ok' => true,
'purchase_order' => new PurchaseOrderResource($data['purchase_order']),
'items' => PurchaseOrderItemResource::collection($data['items'] ?? []),
]);
}
public function store(PurchaseOrderStoreRequest $request): JsonResponse
{
$payload = $request->validated();
try {
$po = $this->createService->create($payload);
} catch (RuntimeException $e) {
return response()->json(['ok' => false, 'message' => $e->getMessage()], 422);
} catch (\Throwable $e) {
return response()->json(['ok' => false, 'message' => 'Unable to create purchase order.'], 500);
}
return response()->json([
'ok' => true,
'purchase_order' => new PurchaseOrderResource($po),
], 201);
}
public function receive(PurchaseOrderReceiveRequest $request, int $id): JsonResponse
{
$payload = $request->validated();
$po = PurchaseOrder::query()->find($id);
if (!$po) {
return response()->json(['ok' => false, 'message' => 'Purchase order not found.'], 404);
}
$user = auth()->user();
$issuedBy = $user ? (string) ($user->email ?? $user->username ?? $user->id) : 'system';
try {
$result = $this->receiveService->receive($id, $payload['items'], $issuedBy);
} catch (RuntimeException $e) {
return response()->json(['ok' => false, 'message' => $e->getMessage()], 409);
} catch (\Throwable $e) {
return response()->json(['ok' => false, 'message' => 'Unable to receive items.'], 500);
}
return response()->json([
'ok' => true,
'status' => $result['status'] ?? null,
'completed' => $result['completed'] ?? false,
]);
}
public function cancel(int $id): JsonResponse
{
$po = PurchaseOrder::query()->find($id);
if (!$po) {
return response()->json(['ok' => false, 'message' => 'Purchase order not found.'], 404);
}
try {
$this->statusService->cancel($id);
} catch (RuntimeException $e) {
return response()->json(['ok' => false, 'message' => $e->getMessage()], 409);
} catch (\Throwable $e) {
return response()->json(['ok' => false, 'message' => 'Unable to cancel purchase order.'], 500);
}
return response()->json(['ok' => true, 'status' => PurchaseOrder::STATUS_CANCELED]);
}
}
@@ -20,10 +20,32 @@ class ScoreCommentController extends BaseApiController
public function index(ScoreCommentListRequest $request): JsonResponse
{
$payload = $request->validated();
$query = $request->query->all();
if ($query === []) {
$rawQuery = (string) $request->server->get('QUERY_STRING', '');
parse_str($rawQuery, $query);
}
$json = $request->json()->all();
if ($json === []) {
$decoded = json_decode($request->getContent() ?: '', true);
$json = is_array($decoded) ? $decoded : [];
}
$classSectionId = $payload['class_section_id']
?? ($query['class_section_id'] ?? null)
?? $request->input('class_section_id')
?? ($json['class_section_id'] ?? null);
$semester = $payload['semester']
?? ($query['semester'] ?? null)
?? $request->input('semester')
?? ($json['semester'] ?? null);
$schoolYear = $payload['school_year']
?? ($query['school_year'] ?? null)
?? $request->input('school_year')
?? ($json['school_year'] ?? null);
$data = $this->service->list(
$payload['class_section_id'] ?? null,
$payload['semester'] ?? null,
$payload['school_year'] ?? null
$classSectionId !== null ? (string) $classSectionId : null,
$semester !== null ? (string) $semester : null,
$schoolYear !== null ? (string) $schoolYear : null
);
$studentRows = [];
@@ -20,13 +20,16 @@ class ScoreController extends BaseApiController
public function overview(ScoreOverviewRequest $request): JsonResponse
{
$payload = $request->validated();
$teacherId = (int) (auth()->id() ?? 0);
$teacherId = (int) ($request->user()?->id ?? (auth()->id() ?? 0));
$classSectionId = $payload['class_section_id'] ?? $request->input('class_section_id');
$semester = $payload['semester'] ?? $request->input('semester');
$schoolYear = $payload['school_year'] ?? $request->input('school_year');
$data = $this->service->overview(
$teacherId,
isset($payload['class_section_id']) ? (int) $payload['class_section_id'] : null,
$payload['semester'] ?? null,
$payload['school_year'] ?? null
isset($classSectionId) ? (int) $classSectionId : null,
$semester !== null ? (string) $semester : null,
$schoolYear !== null ? (string) $schoolYear : null
);
return response()->json([
@@ -48,7 +51,7 @@ class ScoreController extends BaseApiController
(string) $payload['semester'],
(string) $payload['school_year'],
$payload['missing_ok'] ?? [],
(int) (auth()->id() ?? 0)
(int) ($request->user()?->id ?? (auth()->id() ?? 0))
);
return response()->json(['ok' => true]);
@@ -57,7 +60,7 @@ class ScoreController extends BaseApiController
public function studentScores(ScoreStudentRequest $request): JsonResponse
{
$payload = $request->validated();
$parentId = (int) (auth()->id() ?? 0);
$parentId = (int) ($request->user()?->id ?? (auth()->id() ?? 0));
$data = $this->service->viewStudentScores($parentId, (string) $payload['school_year']);
+5 -2
View File
@@ -88,9 +88,12 @@ class UserController extends BaseApiController
public function loginActivity(LoginActivityRequest $request): JsonResponse
{
$payload = $request->validated();
$perPage = $payload['per_page'] ?? 25;
$page = $payload['page'] ?? 1;
$result = $this->loginActivityService->list(
(int) ($payload['per_page'] ?? 25),
(int) ($payload['page'] ?? 1)
(int) $perPage,
(int) $page
);
return response()->json([
@@ -1,296 +0,0 @@
<?php
namespace App\Controllers\View;
use CodeIgniter\Controller;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class EmailController extends Controller
{
/**
* Send an email using a named profile (e.g., 'communication', 'payment', 'default').
*
* @param string $recipient
* @param string $subject
* @param string $htmlMessage
* @param string|null $profile e.g. 'communication', 'payment'; if null uses MAIL_PROFILE_DEFAULT or 'default'
* @param string|null $replyToEmail optional override
* @param string|null $replyToName optional override
* @param array $attachments [['path'=>..., 'name'=>...], ...]
*/
public function sendEmail(
string $recipient,
string $subject,
string $htmlMessage,
?string $profile = null,
?string $replyToEmail = null,
?string $replyToName = null,
array $attachments = []
): bool {
// Composer autoload (if not already loaded by CI4)
$autoload = APPPATH . '../vendor/autoload.php';
if (is_file($autoload)) {
require_once $autoload;
}
$profile = $this->resolveProfile($profile);
$cfg = $this->getProfileConfig($profile);
// Guard rails: refuse to proceed with missing essentials
if (empty($cfg['host']) || empty($cfg['user']) || $cfg['pass'] === '') {
log_message('error', "[mail:$profile] Missing SMTP config (host/user/pass). Check .env MAIL_{$this->envKeyFromProfile($profile)}_* or MAIL_DEFAULT_*.");
return false;
}
// Optional env flags
$debugEnabled = (bool) env('MAIL_DEBUG', false);
$timeout = (int) env('MAIL_TIMEOUT', 15); // seconds
$keepAlive = (bool) env('MAIL_KEEPALIVE', false);
$verifyPeer = env('MAIL_VERIFY_PEER', 'true'); // 'true'|'false' (string to allow .env)
$verifyPeer = filter_var($verifyPeer, FILTER_VALIDATE_BOOLEAN);
// Preflight DNS + socket (helps distinguish firewall/DNS vs. auth)
$targetHost = $cfg['host'];
$targetPort = (int) $cfg['port'];
$resolved = @gethostbyname($targetHost);
if (!$resolved || $resolved === $targetHost) {
// Not fatal (some environments block gethostbyname), but useful log
log_message('debug', "[mail:$profile] DNS resolve note: host=$targetHost, resolved=$resolved");
}
$sockOk = @fsockopen($targetHost, $targetPort, $errno, $errstr, 5);
if (!$sockOk) {
log_message('error', "[mail:$profile] Socket preflight failed to {$targetHost}:{$targetPort} (errno=$errno, err=$errstr). Likely firewall/port/encryption mismatch or wrong host.");
} else {
fclose($sockOk);
}
$mail = new PHPMailer(true);
try {
// Capture PHPMailers own debug if enabled
if ($debugEnabled) {
ob_start();
}
// PHPMailer core setup
$mail->isSMTP();
$mail->Host = $cfg['host'];
$mail->Port = $cfg['port'];
$mail->SMTPAuth = true;
$mail->Username = $cfg['user'];
$mail->Password = $cfg['pass'];
$mail->CharSet = 'UTF-8';
$mail->Timeout = $timeout; // socket timeout
$mail->SMTPKeepAlive = $keepAlive; // reuse connection for multiple sends
$mail->SMTPAutoTLS = true; // allow auto TLS upgrade when possible
// Encryption mapping: 'tls' => STARTTLS (587), 'ssl' => implicit TLS (465)
if ($cfg['encryption'] === 'ssl') {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
} else {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
}
// TLS verification options (can relax on demand via .env for on-prem/self-signed)
$mail->SMTPOptions = [
'ssl' => [
'verify_peer' => $verifyPeer,
'verify_peer_name' => $verifyPeer,
'allow_self_signed' => !$verifyPeer,
],
];
// Optional verbose debugging (set MAIL_DEBUG=true in .env)
$mail->SMTPDebug = $debugEnabled ? 3 : 0;
$mail->Debugoutput = 'error_log';
// From / Return-Path
$mail->setFrom($cfg['fromEmail'], $cfg['fromName']);
if (!empty($cfg['returnPath'])) {
$mail->Sender = $cfg['returnPath'];
}
// Configurable Reply-To: env overrides inputs/config; fallback to profile/defaults
$mail->clearReplyTos();
$rtEmail = env('MAIL_DEFAULT_REPLY_TO');
$rtName = env('MAIL_DEFAULT_REPLY_TO_NAME');
if (!$rtEmail || !filter_var($rtEmail, FILTER_VALIDATE_EMAIL)) {
$rtEmail = $replyToEmail ?: ($cfg['replyTo'] ?: $cfg['fromEmail']);
}
if (!$rtName) {
$rtName = $replyToName ?: ($cfg['replyToName'] ?: $cfg['fromName']);
}
$rtName = $this->sanitizeReplyToName($rtName, $cfg['fromName']);
if ($rtEmail) {
$mail->addReplyTo($rtEmail, $rtName);
}
// DKIM (optional)
if (!empty($cfg['dkim']['domain']) && !empty($cfg['dkim']['private']) && !empty($cfg['dkim']['selector'])) {
$mail->DKIM_domain = $cfg['dkim']['domain'];
$mail->DKIM_private = $cfg['dkim']['private']; // path to private key file
$mail->DKIM_selector = $cfg['dkim']['selector'];
$mail->DKIM_identity = $cfg['fromEmail'];
}
// Recipient(s)
$mail->addAddress($recipient);
// Attachments
foreach ($attachments as $att) {
if (!empty($att['path']) && is_file($att['path'])) {
$mail->addAttachment($att['path'], $att['name'] ?? '');
}
}
// Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlMessage;
// Send!
$ok = $mail->send();
$dbg = $debugEnabled ? (ob_get_clean() ?: '') : '';
if ($ok) {
log_message('info', "[mail:$profile] Sent to {$recipient}, subj='{$subject}' via {$cfg['host']}:{$cfg['port']}/{$cfg['encryption']}");
return true;
}
log_message('error', "[mail:$profile] Failed: {$mail->ErrorInfo}. Debug: {$dbg}");
return false;
} catch (Exception $e) {
$dbg = $debugEnabled ? (ob_get_clean() ?: '') : '';
log_message('error', "[mail:$profile] Exception: {$e->getMessage()} | PHPMailer: {$mail->ErrorInfo} | Debug: {$dbg}");
return false;
}
}
/** Resolve null/alias profile names to a canonical env prefix. */
private function resolveProfile(?string $profile): string
{
$p = strtolower(trim((string) $profile));
if ($p === '' || $p === 'auto') {
$p = strtolower((string) getenv('MAIL_PROFILE_DEFAULT')) ?: 'default';
}
return match ($p) {
'comm', 'comms' => 'communication',
'sys', 'system' => 'default',
default => $p, // e.g., 'payment', 'admissions', etc.
};
}
/** Turn 'communication' into 'COMMUNICATION' for env lookups/logs. */
private function envKeyFromProfile(string $profile): string
{
return strtoupper(preg_replace('/[^A-Z0-9]+/i', '_', $profile));
}
/**
* Resolve SMTP & identity for any profile with layered fallbacks:
* 1) MAIL_{PROFILE}_*
* 2) MAIL_DEFAULT_*
* 3) legacy SMTP_* (HOST/USER/PASS/PORT/ENCRYPTION)
* 4) hard defaults
*/
private function getProfileConfig(string $profile): array
{
$key = $this->envKeyFromProfile($profile);
// Helper: first non-empty env from a list
$envFirst = function (array $keys, $default = null) {
foreach ($keys as $k) {
$v = env($k);
if (is_string($v)) $v = trim($v);
if ($v !== null && $v !== '') return $v;
}
return $default;
};
// Core SMTP (env first, then legacy SMTP_*)
$host = $envFirst(["MAIL_{$key}_HOST", "MAIL_DEFAULT_HOST", "SMTP_HOST"], '');
$user = $envFirst(["MAIL_{$key}_USER", "MAIL_DEFAULT_USER", "SMTP_USER"], '');
$pass = $envFirst(["MAIL_{$key}_PASS", "MAIL_DEFAULT_PASS", "SMTP_PASS"], '');
$portRaw = $envFirst(["MAIL_{$key}_PORT", "MAIL_DEFAULT_PORT", "SMTP_PORT"], 587);
$encRaw = $envFirst(["MAIL_{$key}_ENCRYPTION", "MAIL_DEFAULT_ENCRYPTION", "SMTP_ENCRYPTION"], 'tls');
// Fallback to Config\Email when env is not set (common in local/dev)
$cfgEmail = config('Email');
if ($cfgEmail) {
if ($host === '' && !empty($cfgEmail->SMTPHost)) {
$host = $cfgEmail->SMTPHost;
}
if ($user === '' && !empty($cfgEmail->SMTPUser)) {
$user = $cfgEmail->SMTPUser;
}
if ($pass === '' && !empty($cfgEmail->SMTPPass)) {
$pass = $cfgEmail->SMTPPass;
}
if ((int) $portRaw <= 0 && !empty($cfgEmail->SMTPPort)) {
$portRaw = $cfgEmail->SMTPPort;
}
if (($encRaw === '' || $encRaw === 'tls') && !empty($cfgEmail->SMTPCrypto)) {
$encRaw = $cfgEmail->SMTPCrypto;
}
}
// Identity
$fromEmail = $envFirst(["MAIL_{$key}_FROM_EMAIL", "MAIL_DEFAULT_FROM_EMAIL"], $user ?: 'no-reply@alrahmaisgl.org');
$fromName = $envFirst(["MAIL_{$key}_FROM_NAME", "MAIL_DEFAULT_FROM_NAME"], 'Al Rahma Sunday School');
$replyTo = $envFirst(["MAIL_{$key}_REPLY_TO", "MAIL_DEFAULT_REPLY_TO"], '');
$replyToNm = $envFirst(["MAIL_{$key}_REPLY_TO_NAME","MAIL_DEFAULT_REPLY_TO_NAME"], '');
$returnPath = $envFirst(["MAIL_{$key}_RETURN_PATH","MAIL_DEFAULT_RETURN_PATH"], '');
// DKIM (optional)
$dkim = [
'domain' => $envFirst(["MAIL_{$key}_DKIM_DOMAIN", "MAIL_DEFAULT_DKIM_DOMAIN"], ''),
'selector' => $envFirst(["MAIL_{$key}_DKIM_SELECTOR", "MAIL_DEFAULT_DKIM_SELECTOR"], ''),
'private' => $envFirst(["MAIL_{$key}_DKIM_PRIVATE", "MAIL_DEFAULT_DKIM_PRIVATE"], ''), // full path
];
// Normalize types/values
$port = (int) $portRaw ?: 587;
$encryption = strtolower((string) $encRaw);
$encryption = in_array($encryption, ['tls','ssl'], true) ? $encryption : 'tls';
// --- Autocorrect common mistakes (prevents silent handshake failures) ---
if ($port === 587 && $encryption === 'ssl') {
$encryption = 'tls';
}
if ($port === 465 && $encryption === 'tls') {
$encryption = 'ssl';
}
return [
'host' => (string) $host,
'user' => (string) $user,
'pass' => (string) $pass,
'port' => $port,
// map used above: 'tls' => STARTTLS, 'ssl' => SMTPS
'encryption' => $encryption,
'fromEmail' => (string) $fromEmail,
'fromName' => (string) $fromName,
'replyTo' => (string) $replyTo,
'replyToName' => (string) $this->sanitizeReplyToName($replyToNm, (string) $fromName),
'returnPath' => (string) $returnPath,
'dkim' => $dkim,
];
}
/**
* Normalize Reply-To display names, removing "No-Reply/No-Replay" placeholders.
*/
private function sanitizeReplyToName(?string $name, string $fallback): string
{
$trimmed = trim((string) $name);
if ($trimmed === '' || preg_match('/^no[- ]?repl(?:y|ay)$/i', $trimmed)) {
return $fallback;
}
return $trimmed;
}
}
@@ -1,182 +0,0 @@
<?php
namespace App\Controllers\View;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Controller;
use CodeIgniter\Database\Exceptions\DatabaseException;
class EmailExtractorController extends Controller
{
/**
* GET /email-extractor
* Renders the frontend page (view) with CSV upload and comparison UI.
*/
public function index()
{
return view('/emails/parent_email_extractor');
}
/**
* GET /api/emails
* Returns JSON: { users: string[], parents: string[] }
* Pulls emails from users.email and parents.secondparent_email
*/
public function getEmails()
{
$db = db_connect();
$users = [];
$parents = [];
try {
// Fetch users.email (non-null, non-empty)
$builderUsers = $db->table('users')->select('email');
$userRows = $builderUsers->get()->getResultArray();
foreach ($userRows as $row) {
$email = strtolower(trim((string)($row['email'] ?? '')));
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$users[] = $email;
}
}
// De-duplicate
$users = array_values(array_unique($users));
// Fetch parents.secondparent_email (non-null, non-empty)
$builderParents = $db->table('parents')->select('secondparent_email');
$parentRows = $builderParents->get()->getResultArray();
foreach ($parentRows as $row) {
$email = strtolower(trim((string)($row['secondparent_email'] ?? '')));
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$parents[] = $email;
}
}
// De-duplicate
$parents = array_values(array_unique($parents));
return $this->response->setJSON([
'users' => $users,
'parents' => $parents,
])->setStatusCode(ResponseInterface::HTTP_OK);
} catch (DatabaseException $e) {
return $this->response->setJSON([
'error' => 'Database error: ' . $e->getMessage(),
])->setStatusCode(ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* POST /api/compare
* Accepts multipart/form-data with a CSV file named 'file' (optional),
* or JSON body with { csvEmails: string[] } (optional).
* Compares against DB and returns:
* {
* existed: string[], // in CSV AND in DB
* needToAdd: string[], // in DB BUT NOT in CSV
* counts: { csv: number, db: number, users: number, parents: number }
* }
*/
public function compare()
{
$request = $this->request;
$csvEmails = [];
// 1) Try read from uploaded file
$file = $request->getFile('file');
if ($file && $file->isValid()) {
$contents = file_get_contents($file->getTempName());
$csvEmails = $this->extractEmailsFromText($contents);
}
// 2) Or from JSON body
if (empty($csvEmails) && $request->getHeaderLine('Content-Type')) {
$contentType = $request->getHeaderLine('Content-Type');
if (stripos($contentType, 'application/json') !== false) {
$json = $request->getJSON(true);
if (isset($json['csvEmails']) && is_array($json['csvEmails'])) {
$csvEmails = $this->normalizeEmailArray($json['csvEmails']);
}
}
}
// 3) Compare with DB
$db = db_connect();
// Fetch DB emails
$users = [];
$parents = [];
$userRows = $db->table('users')->select('email')->get()->getResultArray();
foreach ($userRows as $row) {
$e = strtolower(trim((string)($row['email'] ?? '')));
if ($e !== '' && filter_var($e, FILTER_VALIDATE_EMAIL)) {
$users[] = $e;
}
}
$users = array_values(array_unique($users));
$parentRows = $db->table('parents')->select('secondparent_email')->get()->getResultArray();
foreach ($parentRows as $row) {
$e = strtolower(trim((string)($row['secondparent_email'] ?? '')));
if ($e !== '' && filter_var($e, FILTER_VALIDATE_EMAIL)) {
$parents[] = $e;
}
}
$parents = array_values(array_unique($parents));
// Sets for comparison
$csvSet = array_flip(array_values(array_unique($csvEmails)));
$dbUnion = array_values(array_unique(array_merge($users, $parents)));
$dbSet = array_flip($dbUnion);
// existed: in CSV and in DB
$existed = [];
foreach ($csvSet as $email => $_) {
if (isset($dbSet[$email])) {
$existed[] = $email;
}
}
sort($existed);
// needToAdd: in DB but NOT in CSV
$needToAdd = [];
foreach ($dbSet as $email => $_) {
if (!isset($csvSet[$email])) {
$needToAdd[] = $email;
}
}
sort($needToAdd);
return $this->response->setJSON([
'existed' => $existed,
'needToAdd' => $needToAdd,
'counts' => [
'csv' => count($csvEmails),
'db' => count($dbUnion),
'users' => count($users),
'parents' => count($parents),
],
]);
}
// Helpers
private function normalizeEmailArray(array $arr): array
{
$out = [];
foreach ($arr as $e) {
$email = strtolower(trim((string)$e));
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$out[] = $email;
}
}
return array_values(array_unique($out));
}
private function extractEmailsFromText(string $text): array
{
$pattern = '/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i';
preg_match_all($pattern, $text, $matches);
$emails = $matches[0] ?? [];
return $this->normalizeEmailArray($emails);
}
}
-96
View File
@@ -1,96 +0,0 @@
<?php
namespace App\Services;
use App\Controllers\View\EmailController;
class EmailService
{
protected array $senders;
protected EmailController $mailer;
public function __construct()
{
$json = env('MAIL_SENDERS', '{}');
$decoded = json_decode($json, true);
$this->senders = is_array($decoded) ? $decoded : [];
$this->mailer = new EmailController();
}
protected function getSenderDetails(string $fromKey = 'general'): array
{
$senders = $this->senders;
if (isset($senders[$fromKey])) {
return $senders[$fromKey];
}
return $senders['general'] ?? [
'email' => getenv('SMTP_USER') ?: 'no-reply@alrahmaisgl.org',
'name' => 'Al Rahma Sunday School',
];
}
/** NEW: expose configured sender keys to build a dropdown in the UI */
public function listSenders(): array
{
// returns: ['general' => ['email' => '...', 'name' => '...'], 'finance' => [...], ...]
return $this->senders ?: [
'general' => [
'email' => getenv('SMTP_USER') ?: 'no-reply@alrahmaisgl.org',
'name' => 'Al Rahma Sunday School',
],
];
}
/**
* Send a single HTML email.
* Backward-compatible: you can ignore $attachments/$headers.
*/
public function send(string $to, string $subject, string $message, string $fromKey = 'general', array $attachments = [], array $headers = []): bool
{
$attachmentsPayload = $this->normalizeAttachments($attachments);
// Headers are ignored by EmailController but kept for interface compatibility.
return $this->mailer->sendEmail($to, $subject, $message, $fromKey, null, null, $attachmentsPayload);
}
/**
* NEW: BCC bulk send in a single SMTP call (To must be non-empty; we use the SMTP user).
*/
public function sendBcc(array $bccList, string $subject, string $message, string $fromKey = 'general', array $attachments = [], array $headers = []): bool
{
if (empty($bccList)) {
return true; // nothing to send
}
$attachmentsPayload = $this->normalizeAttachments($attachments);
$allOk = true;
foreach ($bccList as $addr) {
$ok = $this->mailer->sendEmail($addr, $subject, $message, $fromKey, null, null, $attachmentsPayload);
if (!$ok) {
$allOk = false;
log_message('error', 'EmailService::sendBcc failed for ' . $addr);
}
}
return $allOk;
}
/**
* Normalize various attachment inputs to the format expected by EmailController.
*/
private function normalizeAttachments(array $attachments): array
{
$out = [];
foreach ($attachments as $file) {
if (is_object($file) && method_exists($file, 'isValid') && $file->isValid()) {
$newName = $file->getRandomName();
$path = WRITEPATH . 'uploads/' . $newName;
$file->move(WRITEPATH . 'uploads', $newName, true);
$out[] = ['path' => $path, 'name' => $file->getClientName()];
} elseif (is_string($file) && is_file($file)) {
$out[] = ['path' => $file, 'name' => basename($file)];
} elseif (is_array($file) && !empty($file['path'])) {
$out[] = ['path' => $file['path'], 'name' => $file['name'] ?? basename($file['path'])];
}
}
return $out;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Requests\Email;
use App\Http\Requests\ApiFormRequest;
class EmailExtractorCompareRequest extends ApiFormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'file' => ['nullable', 'file', 'max:5120'],
'csv_emails' => ['nullable', 'array'],
'csv_emails.*' => ['email'],
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Requests\Email;
use App\Http\Requests\ApiFormRequest;
class EmailSendRequest extends ApiFormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'recipient' => ['required', 'email'],
'subject' => ['required', 'string', 'max:255'],
'html_message' => ['required', 'string'],
'profile' => ['nullable', 'string', 'max:50'],
'reply_to_email' => ['nullable', 'email'],
'reply_to_name' => ['nullable', 'string', 'max:100'],
'attachments' => ['nullable', 'array'],
'attachments.*' => ['file', 'max:5120'],
];
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Requests\Fees;
use App\Http\Requests\ApiFormRequest;
class FeeRefundRequest extends ApiFormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'parent_id' => ['required', 'integer', 'min:1'],
'students' => ['required', 'array'],
'students.*.student_id' => ['nullable', 'integer'],
'students.*.class_section_id' => ['required', 'integer', 'min:1'],
'students.*.enrollment_status' => ['required', 'string', 'max:50'],
'students.*.admission_status' => ['required', 'string', 'max:50'],
'students.*.withdrawal_date' => ['nullable', 'date'],
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Requests\Fees;
use App\Http\Requests\ApiFormRequest;
class FeeTuitionTotalRequest extends ApiFormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'students' => ['required', 'array'],
'students.*.class_section_id' => ['required', 'integer', 'min:1'],
'students.*.grade' => ['nullable', 'string', 'max:20'],
];
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Requests\PurchaseOrders;
use App\Http\Requests\ApiFormRequest;
class PurchaseOrderIndexRequest extends ApiFormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'q' => ['nullable', 'string', 'max:100'],
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Requests\PurchaseOrders;
use App\Http\Requests\ApiFormRequest;
class PurchaseOrderReceiveRequest extends ApiFormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'items' => ['required', 'array', 'min:1'],
'items.*.id' => ['required', 'integer', 'min:1'],
'items.*.quantity' => ['required', 'integer', 'min:1'],
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests\PurchaseOrders;
use App\Http\Requests\ApiFormRequest;
use App\Models\PurchaseOrder;
class PurchaseOrderStoreRequest extends ApiFormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'po_number' => ['required', 'string', 'max:60'],
'supplier_id' => ['required', 'integer', 'min:1', 'exists:suppliers,id'],
'status' => ['nullable', 'string', 'in:' . implode(',', PurchaseOrder::allowedStatuses())],
'order_date' => ['nullable', 'date'],
'expected_date' => ['nullable', 'date', 'after_or_equal:order_date'],
'notes' => ['nullable', 'string', 'max:5000'],
'items' => ['required', 'array', 'min:1'],
'items.*.supply_id' => ['required', 'integer', 'min:1', 'exists:supplies,id'],
'items.*.description' => ['nullable', 'string', 'max:1000'],
'items.*.quantity' => ['required', 'integer', 'min:1'],
'items.*.unit_cost' => ['required', 'numeric', 'min:0'],
];
}
}
@@ -11,6 +11,11 @@ class ScoreLockRequest extends ApiFormRequest
return true;
}
public function validationData(): array
{
return request()->all();
}
public function rules(): array
{
return [
@@ -11,6 +11,19 @@ class ScoreOverviewRequest extends ApiFormRequest
return true;
}
public function validationData(): array
{
$request = request();
$data = $request->query->all();
$json = json_decode($request->getContent() ?: '', true);
if (is_array($json)) {
$data = array_merge($data, $json);
}
return array_merge($data, $request->request->all());
}
public function rules(): array
{
return [
@@ -11,6 +11,11 @@ class SchoolYearRangeRequest extends ApiFormRequest
return true;
}
public function validationData(): array
{
return request()->all();
}
public function rules(): array
{
return [
@@ -11,6 +11,11 @@ class SemesterResolveRequest extends ApiFormRequest
return true;
}
public function validationData(): array
{
return request()->all();
}
public function rules(): array
{
return [
@@ -11,6 +11,11 @@ class LoginActivityRequest extends ApiFormRequest
return true;
}
public function validationData(): array
{
return request()->all();
}
public function rules(): array
{
return [
@@ -12,6 +12,11 @@ class UserStoreRequest extends ApiFormRequest
return true;
}
public function validationData(): array
{
return request()->all();
}
public function rules(): array
{
return [
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Resources\Email;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class EmailExtractorCompareResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'existed' => $this->resource['existed'] ?? [],
'needToAdd' => $this->resource['needToAdd'] ?? [],
'counts' => $this->resource['counts'] ?? [
'csv' => 0,
'db' => 0,
'users' => 0,
'parents' => 0,
],
];
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Resources\Email;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class EmailExtractorEmailsResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'users' => $this->resource['users'] ?? [],
'parents' => $this->resource['parents'] ?? [],
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Resources\Email;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class EmailSenderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'key' => $this->resource['key'] ?? null,
'name' => $this->resource['name'] ?? null,
'email' => $this->resource['email'] ?? null,
'label' => $this->resource['label'] ?? null,
];
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Resources\Fees;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class FeeRefundResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'refund_amount' => (float) ($this->resource['refund_amount'] ?? 0),
'total_paid' => (float) ($this->resource['total_paid'] ?? 0),
'refund_deadline' => $this->resource['refund_deadline'] ?? null,
'school_end_date' => $this->resource['school_end_date'] ?? null,
'weeks_of_study' => (float) ($this->resource['weeks_of_study'] ?? 0),
'withdrawn_students' => (int) ($this->resource['withdrawn_students'] ?? 0),
];
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Http\Resources\Fees;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class FeeTuitionTotalResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'total_tuition' => (float) ($this->resource['total_tuition'] ?? 0),
];
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Resources\PurchaseOrders;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class PurchaseOrderItemResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => (int) ($this->resource['id'] ?? 0),
'purchase_order_id' => (int) ($this->resource['purchase_order_id'] ?? 0),
'supply_id' => (int) ($this->resource['supply_id'] ?? 0),
'supply_name' => $this->resource['supply_name'] ?? null,
'supply_unit' => $this->resource['supply_unit'] ?? null,
'description' => $this->resource['description'] ?? null,
'quantity' => (int) ($this->resource['quantity'] ?? 0),
'received_qty' => (int) ($this->resource['received_qty'] ?? 0),
'unit_cost' => (float) ($this->resource['unit_cost'] ?? 0),
];
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Resources\PurchaseOrders;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class PurchaseOrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => (int) ($this->resource['id'] ?? 0),
'po_number' => $this->resource['po_number'] ?? null,
'supplier_id' => isset($this->resource['supplier_id']) ? (int) $this->resource['supplier_id'] : null,
'supplier_name' => $this->resource['supplier_name'] ?? null,
'status' => $this->resource['status'] ?? null,
'order_date' => $this->resource['order_date'] ?? null,
'expected_date' => $this->resource['expected_date'] ?? null,
'subtotal' => (float) ($this->resource['subtotal'] ?? 0),
'tax' => (float) ($this->resource['tax'] ?? 0),
'total' => (float) ($this->resource['total'] ?? 0),
'notes' => $this->resource['notes'] ?? null,
'created_at' => $this->resource['created_at'] ?? null,
'updated_at' => $this->resource['updated_at'] ?? null,
];
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Models;
use App\Models\BaseModel;
class Supply extends BaseModel
{
protected $table = 'supplies';
protected $fillable = [
'name',
'unit',
'qty_on_hand',
];
protected $casts = [
'qty_on_hand' => 'integer',
];
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Models;
use App\Models\BaseModel;
class SupplyTransaction extends BaseModel
{
protected $table = 'supply_transactions';
protected $fillable = [
'supply_id',
'type',
'quantity',
'ref',
'issued_to',
'issued_by',
'notes',
];
protected $casts = [
'supply_id' => 'integer',
'quantity' => 'integer',
];
}
+21 -4
View File
@@ -8,9 +8,13 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
protected $table = 'users';
protected $fillable = [
@@ -68,10 +72,23 @@ class User extends Authenticatable
{
// If user_roles has soft-deletes (deleted_at), filter it out.
// If it does not, you can remove wherePivotNull('deleted_at').
return $this->belongsToMany(Role::class, 'user_roles', 'user_id', 'role_id')
->withTimestamps()
->withPivot(['deleted_at', 'school_year'])
->wherePivotNull('deleted_at');
$relation = $this->belongsToMany(Role::class, 'user_roles', 'user_id', 'role_id')
->withTimestamps();
$pivotColumns = [];
if (Schema::hasColumn('user_roles', 'deleted_at')) {
$pivotColumns[] = 'deleted_at';
$relation->wherePivotNull('deleted_at');
}
if (Schema::hasColumn('user_roles', 'school_year')) {
$pivotColumns[] = 'school_year';
}
if (!empty($pivotColumns)) {
$relation->withPivot($pivotColumns);
}
return $relation;
}
public function teacherClasses(): HasMany
@@ -0,0 +1,35 @@
<?php
namespace App\Services\Email;
use Illuminate\Http\UploadedFile;
class EmailAttachmentService
{
public function normalize($files): array
{
if ($files instanceof UploadedFile) {
$files = [$files];
}
if (!is_array($files)) {
return [];
}
$out = [];
foreach ($files as $file) {
if (!$file instanceof UploadedFile || !$file->isValid()) {
continue;
}
$path = $file->getRealPath();
if (!$path || !is_file($path)) {
continue;
}
$out[] = [
'path' => $path,
'name' => $file->getClientOriginalName(),
];
}
return $out;
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace App\Services\Email;
use PHPMailer\PHPMailer\Exception as MailerException;
use PHPMailer\PHPMailer\PHPMailer;
class EmailDispatchService
{
public function __construct(private EmailProfileService $profiles)
{
}
public function send(
string $recipient,
string $subject,
string $htmlMessage,
?string $profile = null,
?string $replyToEmail = null,
?string $replyToName = null,
array $attachments = []
): bool {
$profile = $this->profiles->resolveProfile($profile);
$cfg = $this->profiles->getProfileConfig($profile);
if (empty($cfg['host']) || empty($cfg['user']) || $cfg['pass'] === '') {
logger()->error("[mail:$profile] Missing SMTP config (host/user/pass). Check MAIL_{$this->profiles->envKeyFromProfile($profile)}_* or MAIL_DEFAULT_*/MAIL_*.");
return false;
}
$debugEnabled = (bool) env('MAIL_DEBUG', false);
$timeout = (int) env('MAIL_TIMEOUT', 15);
$keepAlive = (bool) env('MAIL_KEEPALIVE', false);
$verifyPeer = filter_var(env('MAIL_VERIFY_PEER', 'true'), FILTER_VALIDATE_BOOLEAN);
$mail = new PHPMailer(true);
try {
if ($debugEnabled) {
ob_start();
}
$mail->isSMTP();
$mail->Host = $cfg['host'];
$mail->Port = $cfg['port'];
$mail->SMTPAuth = true;
$mail->Username = $cfg['user'];
$mail->Password = $cfg['pass'];
$mail->CharSet = 'UTF-8';
$mail->Timeout = $timeout;
$mail->SMTPKeepAlive = $keepAlive;
$mail->SMTPAutoTLS = true;
if ($cfg['encryption'] === 'ssl') {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
} else {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
}
$mail->SMTPOptions = [
'ssl' => [
'verify_peer' => $verifyPeer,
'verify_peer_name' => $verifyPeer,
'allow_self_signed' => !$verifyPeer,
],
];
$mail->SMTPDebug = $debugEnabled ? 3 : 0;
$mail->Debugoutput = 'error_log';
$mail->setFrom($cfg['fromEmail'], $cfg['fromName']);
if (!empty($cfg['returnPath'])) {
$mail->Sender = $cfg['returnPath'];
}
$mail->clearReplyTos();
$rtEmail = env('MAIL_DEFAULT_REPLY_TO');
$rtName = env('MAIL_DEFAULT_REPLY_TO_NAME');
if (!$rtEmail || !filter_var($rtEmail, FILTER_VALIDATE_EMAIL)) {
$rtEmail = $replyToEmail ?: ($cfg['replyTo'] ?: $cfg['fromEmail']);
}
if (!$rtName) {
$rtName = $replyToName ?: ($cfg['replyToName'] ?: $cfg['fromName']);
}
$rtName = $this->profiles->sanitizeReplyToName($rtName, $cfg['fromName']);
if ($rtEmail) {
$mail->addReplyTo($rtEmail, $rtName);
}
if (!empty($cfg['dkim']['domain']) && !empty($cfg['dkim']['private']) && !empty($cfg['dkim']['selector'])) {
$mail->DKIM_domain = $cfg['dkim']['domain'];
$mail->DKIM_private = $cfg['dkim']['private'];
$mail->DKIM_selector = $cfg['dkim']['selector'];
$mail->DKIM_identity = $cfg['fromEmail'];
}
$mail->addAddress($recipient);
foreach ($attachments as $att) {
if (!empty($att['path']) && is_file($att['path'])) {
$mail->addAttachment($att['path'], $att['name'] ?? '');
}
}
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlMessage;
$ok = $mail->send();
$dbg = $debugEnabled ? (ob_get_clean() ?: '') : '';
if ($ok) {
logger()->info("[mail:$profile] Sent to {$recipient}, subj='{$subject}' via {$cfg['host']}:{$cfg['port']}/{$cfg['encryption']}");
return true;
}
logger()->error("[mail:$profile] Failed: {$mail->ErrorInfo}. Debug: {$dbg}");
return false;
} catch (MailerException $e) {
$dbg = $debugEnabled ? (ob_get_clean() ?: '') : '';
logger()->error("[mail:$profile] Exception: {$e->getMessage()} | PHPMailer: {$mail->ErrorInfo} | Debug: {$dbg}");
return false;
}
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Services\Email;
use Illuminate\Support\Facades\DB;
class EmailExtractorService
{
public function listEmails(): array
{
$users = [];
$parents = [];
$userRows = DB::table('users')->select('email')->get();
foreach ($userRows as $row) {
$email = strtolower(trim((string) ($row->email ?? '')));
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$users[] = $email;
}
}
$users = array_values(array_unique($users));
$parentRows = DB::table('parents')->select('secondparent_email')->get();
foreach ($parentRows as $row) {
$email = strtolower(trim((string) ($row->secondparent_email ?? '')));
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$parents[] = $email;
}
}
$parents = array_values(array_unique($parents));
return [
'users' => $users,
'parents' => $parents,
];
}
public function compare(array $csvEmails): array
{
$emails = $this->listEmails();
$users = $emails['users'];
$parents = $emails['parents'];
$csvEmails = $this->normalizeEmailArray($csvEmails);
$csvSet = array_flip(array_values(array_unique($csvEmails)));
$dbUnion = array_values(array_unique(array_merge($users, $parents)));
$dbSet = array_flip($dbUnion);
$existed = [];
foreach ($csvSet as $email => $_) {
if (isset($dbSet[$email])) {
$existed[] = $email;
}
}
sort($existed);
$needToAdd = [];
foreach ($dbSet as $email => $_) {
if (!isset($csvSet[$email])) {
$needToAdd[] = $email;
}
}
sort($needToAdd);
return [
'existed' => $existed,
'needToAdd' => $needToAdd,
'counts' => [
'csv' => count($csvEmails),
'db' => count($dbUnion),
'users' => count($users),
'parents' => count($parents),
],
];
}
public function normalizeEmailArray(array $arr): array
{
$out = [];
foreach ($arr as $e) {
$email = strtolower(trim((string) $e));
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$out[] = $email;
}
}
return array_values(array_unique($out));
}
public function extractEmailsFromText(string $text): array
{
$pattern = '/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i';
preg_match_all($pattern, $text, $matches);
$emails = $matches[0] ?? [];
return $this->normalizeEmailArray($emails);
}
}
@@ -0,0 +1,95 @@
<?php
namespace App\Services\Email;
class EmailProfileService
{
public function resolveProfile(?string $profile): string
{
$p = strtolower(trim((string) $profile));
if ($p === '' || $p === 'auto') {
$p = strtolower((string) env('MAIL_PROFILE_DEFAULT', 'default')) ?: 'default';
}
return match ($p) {
'comm', 'comms' => 'communication',
'sys', 'system' => 'default',
default => $p,
};
}
public function envKeyFromProfile(string $profile): string
{
return strtoupper(preg_replace('/[^A-Z0-9]+/i', '_', $profile));
}
public function getProfileConfig(string $profile): array
{
$key = $this->envKeyFromProfile($profile);
$envFirst = function (array $keys, $default = null) {
foreach ($keys as $k) {
$v = env($k);
if (is_string($v)) {
$v = trim($v);
}
if ($v !== null && $v !== '') {
return $v;
}
}
return $default;
};
$host = $envFirst(["MAIL_{$key}_HOST", 'MAIL_DEFAULT_HOST', 'SMTP_HOST', 'MAIL_HOST'], '');
$user = $envFirst(["MAIL_{$key}_USER", 'MAIL_DEFAULT_USER', 'SMTP_USER', 'MAIL_USERNAME'], '');
$pass = $envFirst(["MAIL_{$key}_PASS", 'MAIL_DEFAULT_PASS', 'SMTP_PASS', 'MAIL_PASSWORD'], '');
$portRaw = $envFirst(["MAIL_{$key}_PORT", 'MAIL_DEFAULT_PORT', 'SMTP_PORT', 'MAIL_PORT'], 587);
$encRaw = $envFirst(["MAIL_{$key}_ENCRYPTION", 'MAIL_DEFAULT_ENCRYPTION', 'SMTP_ENCRYPTION', 'MAIL_ENCRYPTION'], 'tls');
$fromEmail = $envFirst(["MAIL_{$key}_FROM_EMAIL", 'MAIL_DEFAULT_FROM_EMAIL', 'MAIL_FROM_ADDRESS'], $user ?: 'no-reply@alrahmaisgl.org');
$fromName = $envFirst(["MAIL_{$key}_FROM_NAME", 'MAIL_DEFAULT_FROM_NAME', 'MAIL_FROM_NAME'], 'Al Rahma Sunday School');
$replyTo = $envFirst(["MAIL_{$key}_REPLY_TO", 'MAIL_DEFAULT_REPLY_TO'], '');
$replyToName = $envFirst(["MAIL_{$key}_REPLY_TO_NAME", 'MAIL_DEFAULT_REPLY_TO_NAME'], '');
$returnPath = $envFirst(["MAIL_{$key}_RETURN_PATH", 'MAIL_DEFAULT_RETURN_PATH'], '');
$dkim = [
'domain' => $envFirst(["MAIL_{$key}_DKIM_DOMAIN", 'MAIL_DEFAULT_DKIM_DOMAIN'], ''),
'selector' => $envFirst(["MAIL_{$key}_DKIM_SELECTOR", 'MAIL_DEFAULT_DKIM_SELECTOR'], ''),
'private' => $envFirst(["MAIL_{$key}_DKIM_PRIVATE", 'MAIL_DEFAULT_DKIM_PRIVATE'], ''),
];
$port = (int) $portRaw ?: 587;
$encryption = strtolower((string) $encRaw);
$encryption = in_array($encryption, ['tls', 'ssl'], true) ? $encryption : 'tls';
if ($port === 587 && $encryption === 'ssl') {
$encryption = 'tls';
}
if ($port === 465 && $encryption === 'tls') {
$encryption = 'ssl';
}
return [
'host' => (string) $host,
'user' => (string) $user,
'pass' => (string) $pass,
'port' => $port,
'encryption' => $encryption,
'fromEmail' => (string) $fromEmail,
'fromName' => (string) $fromName,
'replyTo' => (string) $replyTo,
'replyToName' => (string) $this->sanitizeReplyToName($replyToName, (string) $fromName),
'returnPath' => (string) $returnPath,
'dkim' => $dkim,
];
}
public function sanitizeReplyToName(?string $name, string $fallback): string
{
$trimmed = trim((string) $name);
if ($trimmed === '' || preg_match('/^no[- ]?repl(?:y|ay)$/i', $trimmed)) {
return $fallback;
}
return $trimmed;
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Services\Email;
class EmailSenderOptionsService
{
public function listSenders(): array
{
$json = env('MAIL_SENDERS', '{}');
$arr = json_decode($json, true);
if (!is_array($arr) || empty($arr)) {
$smtpUser = getenv('SMTP_USER') ?: '';
$name = 'Al Rahma Sunday School';
return [[
'key' => 'general',
'name' => $name,
'email' => $smtpUser,
'label' => trim($name . ($smtpUser ? " <{$smtpUser}>" : '')),
]];
}
$out = [];
foreach ($arr as $key => $info) {
$name = $info['name'] ?? 'Sender';
$email = $info['email'] ?? '';
$out[] = [
'key' => (string) $key,
'name' => (string) $name,
'email' => (string) $email,
'label' => trim($name . ($email ? " <{$email}>" : '')),
];
}
return $out;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Services\Fees;
use App\Models\Configuration;
class FeeConfigService
{
public function getSchoolYear(): string
{
return (string) (Configuration::getConfig('school_year') ?? '');
}
public function getRefundDeadline(): ?string
{
$raw = (string) (Configuration::getConfig('refund_deadline') ?? '');
if ($raw === '') {
return null;
}
$timestamp = strtotime($raw);
if ($timestamp === false) {
return null;
}
return date('Y-m-d', $timestamp);
}
public function getWeeksOfStudy(): float
{
return (float) (Configuration::getConfig('weeks_study') ?? 8);
}
public function getSchoolEndDate(): ?string
{
$raw = (string) (Configuration::getConfig('last_school_day') ?? '');
if ($raw === '') {
return null;
}
$timestamp = strtotime($raw);
if ($timestamp === false) {
return null;
}
return date('Y-m-d', $timestamp);
}
public function getFees(): array
{
return [
'first_student_fee' => (float) (Configuration::getConfig('first_student_fee') ?? 350),
'second_student_fee' => (float) (Configuration::getConfig('second_student_fee') ?? 200),
'youth_fee' => (float) (Configuration::getConfig('youth_fee') ?? 180),
];
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Services\Fees;
class FeeGradeService
{
public function normalizeGrade(?string $grade): string
{
return strtoupper(trim((string) $grade));
}
public function compareGrades(string $gradeA, string $gradeB): int
{
$valA = $this->getGradeLevel($gradeA);
$valB = $this->getGradeLevel($gradeB);
if ($valA !== $valB) {
return $valA <=> $valB;
}
preg_match('/\d+([A-Z]*)$/i', strtoupper($gradeA), $suffixA);
preg_match('/\d+([A-Z]*)$/i', strtoupper($gradeB), $suffixB);
return strcmp($suffixA[1] ?? '', $suffixB[1] ?? '');
}
public function getGradeLevel(string $grade): int
{
$grade = $this->normalizeGrade($grade);
if ($grade === 'K') {
return 0;
}
if ($grade === 'Y') {
return 99;
}
if (preg_match('/^(\d+)([A-Z]*)$/i', $grade, $matches)) {
return (int) $matches[1];
}
return 999;
}
}
@@ -0,0 +1,120 @@
<?php
namespace App\Services\Fees;
use App\Models\Payment;
use Illuminate\Support\Facades\Log;
class FeeRefundCalculatorService
{
public function __construct(
private FeeConfigService $config,
private FeeStudentFeeService $studentFees
) {
}
public function calculateRefund(array $students, int $parentId): array
{
$schoolYear = $this->config->getSchoolYear();
$refundDeadline = $this->config->getRefundDeadline();
$weeksOfStudy = $this->config->getWeeksOfStudy();
$schoolEndDate = $this->config->getSchoolEndDate();
$totalPaid = Payment::getTotalPaidByParentId($parentId, $schoolYear);
if ($totalPaid <= 0) {
return $this->resultPayload(0.0, $totalPaid, $refundDeadline, $schoolEndDate, $weeksOfStudy, 0);
}
$registered = [];
$withdrawn = [];
foreach ($students as $student) {
$status = strtolower((string) ($student['enrollment_status'] ?? ''));
$admission = strtolower((string) ($student['admission_status'] ?? ''));
if (in_array($status, ['withdrawn', 'refund pending', 'withdraw under review'], true)) {
$withdrawn[] = $student;
continue;
}
if (in_array($status, ['enrolled', 'payment pending'], true) && $admission === 'accepted') {
$registered[] = $student;
}
}
if (empty($withdrawn)) {
return $this->resultPayload(0.0, $totalPaid, $refundDeadline, $schoolEndDate, $weeksOfStudy, 0);
}
$allStudents = array_merge($registered, $withdrawn);
$allStudents = $this->studentFees->assignFees($allStudents);
$feeByStudentId = [];
foreach ($allStudents as $student) {
$key = $student['student_id'] ?? null;
if ($key === null) {
continue;
}
$feeByStudentId[(string) $key] = (float) ($student['tuition_fee'] ?? 0);
}
$refundAmount = 0.0;
$withdrawCount = 0;
foreach ($withdrawn as $student) {
$withdrawalDate = $student['withdrawal_date'] ?? null;
if (!$withdrawalDate) {
Log::warning('Missing withdraw date for student', ['student_id' => $student['student_id'] ?? null]);
continue;
}
if (!$refundDeadline || strtotime($withdrawalDate) > strtotime($refundDeadline)) {
continue;
}
if (!$schoolEndDate) {
continue;
}
$withdrawDateObj = new \DateTime(date('Y-m-d', strtotime($withdrawalDate)));
$schoolEndDateObj = new \DateTime($schoolEndDate);
$daysRemaining = $withdrawDateObj->diff($schoolEndDateObj)->days;
$weeksRemaining = min($weeksOfStudy, max(0, (int) ceil($daysRemaining / 7)));
$studentId = (string) ($student['student_id'] ?? '');
$studentFee = $feeByStudentId[$studentId] ?? 0.0;
if ($studentFee <= 0 || $weeksOfStudy <= 0) {
continue;
}
$proportionalRefund = ($studentFee / $weeksOfStudy) * $weeksRemaining;
$refundAmount += $proportionalRefund;
$withdrawCount++;
}
if ($refundAmount > $totalPaid) {
$refundAmount = $totalPaid;
}
return $this->resultPayload($refundAmount, $totalPaid, $refundDeadline, $schoolEndDate, $weeksOfStudy, $withdrawCount);
}
private function resultPayload(
float $refund,
float $totalPaid,
?string $refundDeadline,
?string $schoolEndDate,
float $weeksOfStudy,
int $withdrawCount
): array {
return [
'refund_amount' => round($refund, 2),
'total_paid' => round($totalPaid, 2),
'refund_deadline' => $refundDeadline,
'school_end_date' => $schoolEndDate,
'weeks_of_study' => $weeksOfStudy,
'withdrawn_students' => $withdrawCount,
];
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Services\Fees;
use App\Models\ClassSection;
class FeeStudentFeeService
{
public function __construct(
private FeeGradeService $grades,
private FeeConfigService $config
) {
}
public function assignFees(array $students): array
{
$fees = $this->config->getFees();
$firstFee = $fees['first_student_fee'];
$secondFee = $fees['second_student_fee'];
$youthFee = $fees['youth_fee'];
foreach ($students as &$student) {
$grade = $student['grade'] ?? null;
if ($grade === null || trim((string) $grade) === '') {
$sectionId = $student['class_section_id'] ?? null;
$grade = $sectionId ? ClassSection::getClassSectionNameBySectionId($sectionId) : null;
}
$student['grade'] = $this->grades->normalizeGrade($grade);
}
unset($student);
usort($students, function ($a, $b) {
return $this->grades->compareGrades($a['grade'] ?? '', $b['grade'] ?? '');
});
$regularCount = 0;
foreach ($students as &$student) {
$gradeLevel = $this->grades->getGradeLevel($student['grade'] ?? '');
if ($gradeLevel > 9) {
$student['tuition_fee'] = $youthFee;
} else {
$student['tuition_fee'] = ($regularCount === 0) ? $firstFee : $secondFee;
$regularCount++;
}
}
unset($student);
return $students;
}
public function totalTuitionFee(array $students): float
{
$students = $this->assignFees($students);
$total = 0.0;
foreach ($students as $student) {
$total += (float) ($student['tuition_fee'] ?? 0);
}
return $total;
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Services\PurchaseOrders;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use Illuminate\Support\Facades\DB;
use RuntimeException;
class PurchaseOrderCreateService
{
public function create(array $payload): PurchaseOrder
{
$itemsPayload = $payload['items'] ?? [];
if (empty($itemsPayload) || !is_array($itemsPayload)) {
throw new RuntimeException('Add at least one line item.');
}
$subtotal = 0.0;
$items = [];
foreach ($itemsPayload as $item) {
$supplyId = (int) ($item['supply_id'] ?? 0);
$qty = max(0, (int) ($item['quantity'] ?? 0));
$unitCost = (float) ($item['unit_cost'] ?? 0);
if ($supplyId <= 0 || $qty <= 0) {
continue;
}
$line = $qty * $unitCost;
$subtotal += $line;
$items[] = [
'supply_id' => $supplyId,
'description' => trim((string) ($item['description'] ?? '')),
'quantity' => $qty,
'unit_cost' => $unitCost,
'received_qty' => 0,
];
}
if (empty($items)) {
throw new RuntimeException('Valid line items required.');
}
$status = (string) ($payload['status'] ?? 'ordered');
$status = in_array($status, [PurchaseOrder::STATUS_DRAFT, PurchaseOrder::STATUS_ORDERED], true) ? $status : PurchaseOrder::STATUS_ORDERED;
$tax = 0.0;
$total = $subtotal + $tax;
return DB::transaction(function () use ($payload, $items, $status, $subtotal, $tax, $total) {
$po = PurchaseOrder::query()->create([
'po_number' => $payload['po_number'] ?? null,
'supplier_id' => $payload['supplier_id'] ?? null,
'order_date' => $payload['order_date'] ?? null,
'expected_date' => $payload['expected_date'] ?? null,
'notes' => $payload['notes'] ?? null,
'status' => $status,
'subtotal' => $subtotal,
'tax' => $tax,
'total' => $total,
]);
foreach ($items as $item) {
$item['purchase_order_id'] = $po->id;
PurchaseOrderItem::query()->create($item);
}
return $po->refresh();
});
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Services\PurchaseOrders;
use Illuminate\Support\Facades\DB;
class PurchaseOrderQueryService
{
public function list(?string $q = null): array
{
$builder = DB::table('purchase_orders')
->select('purchase_orders.*', 'suppliers.name as supplier_name')
->leftJoin('suppliers', 'suppliers.id', '=', 'purchase_orders.supplier_id');
if ($q !== null && trim($q) !== '') {
$query = trim($q);
$builder->where(function ($qbuilder) use ($query) {
$qbuilder->where('purchase_orders.po_number', 'like', "%{$query}%")
->orWhere('suppliers.name', 'like', "%{$query}%");
});
}
return $builder->orderByDesc('purchase_orders.created_at')
->get()
->map(fn ($row) => (array) $row)
->all();
}
public function options(): array
{
$suppliers = DB::table('suppliers')->orderBy('name')->get()->map(fn ($r) => (array) $r)->all();
$supplies = DB::table('supplies')->orderBy('name')->get()->map(fn ($r) => (array) $r)->all();
return [
'suppliers' => $suppliers,
'supplies' => $supplies,
];
}
public function find(int $id): ?array
{
$po = DB::table('purchase_orders')
->select('purchase_orders.*', 'suppliers.name as supplier_name')
->leftJoin('suppliers', 'suppliers.id', '=', 'purchase_orders.supplier_id')
->where('purchase_orders.id', $id)
->first();
if (!$po) {
return null;
}
$items = DB::table('purchase_order_items')
->select('purchase_order_items.*', 'supplies.name as supply_name', 'supplies.unit as supply_unit')
->leftJoin('supplies', 'supplies.id', '=', 'purchase_order_items.supply_id')
->where('purchase_order_id', $id)
->get()
->map(fn ($row) => (array) $row)
->all();
return [
'purchase_order' => (array) $po,
'items' => $items,
];
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Services\PurchaseOrders;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\Supply;
use App\Models\SupplyTransaction;
use Illuminate\Support\Facades\DB;
use RuntimeException;
class PurchaseOrderReceiveService
{
public function receive(int $poId, array $received, string $issuedBy): array
{
$po = PurchaseOrder::query()->find($poId);
if (!$po || in_array($po->status, [PurchaseOrder::STATUS_CANCELED, PurchaseOrder::STATUS_RECEIVED], true)) {
throw new RuntimeException('PO not receivable.');
}
if (empty($received)) {
throw new RuntimeException('No items to receive.');
}
return DB::transaction(function () use ($po, $received, $issuedBy) {
$completed = true;
foreach ($received as $item) {
$itemId = (int) ($item['id'] ?? 0);
$qty = (int) ($item['quantity'] ?? 0);
if ($itemId <= 0 || $qty <= 0) {
continue;
}
$poItem = PurchaseOrderItem::query()
->where('purchase_order_id', $po->id)
->where('id', $itemId)
->first();
if (!$poItem) {
$completed = false;
continue;
}
$remaining = (int) $poItem->quantity - (int) $poItem->received_qty;
$toReceive = min($remaining, $qty);
if ($toReceive <= 0) {
continue;
}
$poItem->received_qty = (int) $poItem->received_qty + $toReceive;
$poItem->save();
$supply = Supply::query()->find($poItem->supply_id);
if (!$supply) {
$completed = false;
continue;
}
$supply->qty_on_hand = (int) $supply->qty_on_hand + $toReceive;
$supply->save();
SupplyTransaction::query()->create([
'supply_id' => $supply->id,
'type' => 'in',
'quantity' => $toReceive,
'ref' => 'PO ' . ($po->po_number ?? $po->id),
'issued_to' => 'Inventory',
'issued_by' => $issuedBy,
'notes' => 'Received against PO',
]);
if ($poItem->received_qty < $poItem->quantity) {
$completed = false;
}
}
$po->status = $completed ? PurchaseOrder::STATUS_RECEIVED : PurchaseOrder::STATUS_ORDERED;
$po->save();
return [
'status' => $po->status,
'completed' => $completed,
];
});
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Services\PurchaseOrders;
use App\Models\PurchaseOrder;
use RuntimeException;
class PurchaseOrderStatusService
{
public function cancel(int $poId): PurchaseOrder
{
$po = PurchaseOrder::query()->find($poId);
if (!$po || $po->status === PurchaseOrder::STATUS_RECEIVED) {
throw new RuntimeException('Cannot cancel this PO.');
}
$po->status = PurchaseOrder::STATUS_CANCELED;
$po->save();
return $po;
}
}
+40 -13
View File
@@ -24,26 +24,53 @@ class ScoreDashboardService
$schoolYear = $this->term->schoolYear($schoolYear);
$semesterLabel = $this->term->semesterLabel($semester, $semester);
$assignments = TeacherClass::query()
->where('teacher_id', $teacherId)
->when($schoolYear !== '', fn ($q) => $q->where('school_year', $schoolYear))
->get()
->map(fn ($row) => (array) $row)
->all();
if ($teacherId <= 0 && !empty($classSectionId)) {
$allowedIds = [(int) $classSectionId];
} else {
$allowedIds = TeacherClass::query()
->where('teacher_id', $teacherId)
->when($schoolYear !== '', fn ($q) => $q->where('school_year', $schoolYear))
->pluck('class_section_id')
->map(fn ($v) => (int) $v)
->filter(fn ($v) => $v > 0)
->unique()
->values()
->all();
if (empty($assignments)) {
return ['students' => [], 'assignments' => [], 'class_section_id' => null];
if (empty($allowedIds)) {
return ['students' => [], 'assignments' => [], 'class_section_id' => null];
}
}
$allowedIds = array_values(array_unique(array_map(static fn ($a) => (int) ($a['class_section_id'] ?? 0), $assignments)));
$classSectionId = $classSectionId && in_array($classSectionId, $allowedIds, true) ? $classSectionId : $allowedIds[0];
$studentIds = StudentClass::query()
->where('class_section_id', $classSectionId)
->when($schoolYear !== '', fn ($q) => $q->where('school_year', $schoolYear))
$studentQuery = StudentClass::query();
if (DB::connection()->getDriverName() === 'sqlite') {
$studentQuery->whereRaw('class_section_id = ' . (int) $classSectionId);
if ($schoolYear !== '') {
$quoted = DB::connection()->getPdo()->quote($schoolYear);
$studentQuery->whereRaw("school_year = {$quoted}");
}
} else {
$studentQuery->where('class_section_id', $classSectionId);
if ($schoolYear !== '') {
$studentQuery->where('school_year', $schoolYear);
}
}
$studentIds = $studentQuery
->pluck('student_id')
->map(fn ($v) => (int) $v)
->all();
if (empty($studentIds) && DB::connection()->getDriverName() === 'sqlite') {
$schoolYearClause = $schoolYear !== '' ? " and school_year = " . DB::connection()->getPdo()->quote($schoolYear) : '';
$rows = DB::select(
"select student_id from student_class where class_section_id = " . (int) $classSectionId . $schoolYearClause
);
$studentIds = array_values(array_filter(array_map(
static fn ($row) => isset($row->student_id) ? (int) $row->student_id : 0,
$rows
), static fn ($id) => $id > 0));
}
$students = Student::query()
->whereIn('id', $studentIds)
@@ -12,7 +12,7 @@ class ScorePredictorDataService
->select('cs.*')
->join('student_class as sc', 'sc.class_section_id', '=', 'cs.class_section_id')
->where('sc.school_year', $schoolYear)
->notLike('cs.class_section_name', 'KG', 'after')
->where('cs.class_section_name', 'not like', 'KG%')
->groupBy('cs.id')
->orderBy('cs.class_section_name', 'ASC')
->get()
@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('suppliers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('suppliers');
}
};
@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('supplies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('unit')->nullable();
$table->integer('qty_on_hand')->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('supplies');
}
};
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('supply_transactions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('supply_id');
$table->string('type', 10);
$table->integer('quantity');
$table->string('ref')->nullable();
$table->string('issued_to')->nullable();
$table->string('issued_by')->nullable();
$table->text('notes')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('supply_transactions');
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('purchase_orders', function (Blueprint $table) {
$table->id();
$table->string('po_number')->nullable();
$table->unsignedBigInteger('supplier_id')->nullable();
$table->string('status', 20)->default('ordered');
$table->date('order_date')->nullable();
$table->date('expected_date')->nullable();
$table->decimal('subtotal', 10, 2)->default(0);
$table->decimal('tax', 10, 2)->default(0);
$table->decimal('total', 10, 2)->default(0);
$table->text('notes')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
public function down(): void
{
Schema::dropIfExists('purchase_orders');
}
};
@@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('purchase_order_items', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('purchase_order_id');
$table->unsignedBigInteger('supply_id');
$table->string('description')->nullable();
$table->integer('quantity');
$table->integer('received_qty')->default(0);
$table->decimal('unit_cost', 10, 2)->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('purchase_order_items');
}
};
+22
View File
@@ -63,6 +63,7 @@ use App\Http\Controllers\Api\Finance\PaymentTransactionController;
use App\Http\Controllers\Api\Finance\PaypalTransactionsController;
use App\Http\Controllers\Api\Finance\PurchaseOrderController;
use App\Http\Controllers\Api\Finance\ReimbursementController;
use App\Http\Controllers\Api\Finance\FeeCalculationController;
use App\Http\Controllers\Api\Finance\PaymentEventChargesController;
use App\Http\Controllers\Api\Finance\PaymentManualController;
use App\Http\Controllers\Api\Finance\PaypalPaymentController;
@@ -177,6 +178,16 @@ Route::prefix('v1')->group(function () {
Route::post('upload-image', [BroadcastEmailController::class, 'uploadImage']);
});
Route::prefix('email')->group(function () {
Route::get('senders', [EmailController::class, 'senders']);
Route::post('send', [EmailController::class, 'send']);
});
Route::prefix('email-extractor')->group(function () {
Route::get('emails', [EmailExtractorController::class, 'emails']);
Route::post('compare', [EmailExtractorController::class, 'compare']);
});
Route::prefix('communications')->group(function () {
Route::get('options', [CommunicationController::class, 'options']);
Route::get('students/{studentId}/families', [CommunicationController::class, 'families']);
@@ -216,6 +227,8 @@ Route::prefix('v1')->group(function () {
Route::get('financial-report/csv', [FinancialController::class, 'downloadCsv']);
Route::get('financial-report/pdf', [FinancialController::class, 'downloadPdf']);
Route::get('unpaid-parents', [FinancialController::class, 'unpaidParents']);
Route::post('fees/refund', [FeeCalculationController::class, 'refund']);
Route::post('fees/tuition-total', [FeeCalculationController::class, 'tuitionTotal']);
Route::prefix('reimbursements')->group(function () {
Route::get('under-processing', [ReimbursementController::class, 'underProcessing']);
@@ -235,6 +248,15 @@ Route::prefix('v1')->group(function () {
Route::put('{id}', [ReimbursementController::class, 'update']);
});
Route::prefix('purchase-orders')->group(function () {
Route::get('/', [PurchaseOrderController::class, 'index']);
Route::get('options', [PurchaseOrderController::class, 'options']);
Route::get('{id}', [PurchaseOrderController::class, 'show']);
Route::post('/', [PurchaseOrderController::class, 'store']);
Route::post('{id}/receive', [PurchaseOrderController::class, 'receive']);
Route::post('{id}/cancel', [PurchaseOrderController::class, 'cancel']);
});
Route::prefix('invoices')->group(function () {
Route::get('management', [InvoiceController::class, 'management']);
Route::post('generate', [InvoiceController::class, 'generate']);
BIN
View File
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
PDFDATA
+1
View File
@@ -0,0 +1 @@
PDFDATA
@@ -0,0 +1,79 @@
<?php
namespace Tests\Feature\Api\V1\Email;
use App\Models\User;
use App\Services\Email\EmailDispatchService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Mockery;
use Tests\TestCase;
class EmailControllerTest extends TestCase
{
use RefreshDatabase;
public function test_senders_endpoint_returns_options(): void
{
$user = $this->createUser();
Sanctum::actingAs($user);
putenv('MAIL_SENDERS={"general":{"name":"General","email":"general@example.com"}}');
$response = $this->getJson('/api/v1/email/senders');
$response->assertOk();
$response->assertJsonPath('ok', true);
$this->assertNotEmpty($response->json('senders'));
}
public function test_send_endpoint_uses_dispatch_service(): void
{
$user = $this->createUser();
Sanctum::actingAs($user);
$mock = Mockery::mock(EmailDispatchService::class);
$mock->shouldReceive('send')
->once()
->andReturn(true);
$this->app->instance(EmailDispatchService::class, $mock);
$response = $this->postJson('/api/v1/email/send', [
'recipient' => 'test@example.com',
'subject' => 'Hello',
'html_message' => '<p>Test</p>',
'profile' => 'general',
]);
$response->assertOk();
$response->assertJsonPath('ok', true);
}
private function createUser(): User
{
DB::table('users')->insert([
'id' => 1,
'school_id' => 1,
'firstname' => 'Admin',
'lastname' => 'User',
'cellphone' => '5555555555',
'email' => 'admin@example.com',
'address_street' => '123 Main',
'city' => 'City',
'state' => 'ST',
'zip' => '12345',
'accept_school_policy' => 1,
'is_verified' => 1,
'status' => 'Active',
'is_suspended' => 0,
'failed_attempts' => 0,
'password' => bcrypt('secret'),
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
return User::query()->findOrFail(1);
}
}
@@ -0,0 +1,86 @@
<?php
namespace Tests\Feature\Api\V1\Email;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class EmailExtractorControllerTest extends TestCase
{
use RefreshDatabase;
public function test_emails_endpoint_returns_users_and_parents(): void
{
$user = $this->createUser();
Sanctum::actingAs($user);
DB::table('parents')->insert([
'secondparent_firstname' => 'Parent',
'secondparent_lastname' => 'Two',
'secondparent_email' => 'parent2@example.com',
'secondparent_phone' => '5555555555',
'firstparent_id' => 1,
'secondparent_id' => 2,
'school_year' => '2025-2026',
]);
$response = $this->getJson('/api/v1/email-extractor/emails');
$response->assertOk();
$response->assertJsonPath('ok', true);
$this->assertContains('parent2@example.com', $response->json('emails.parents'));
}
public function test_compare_endpoint_returns_comparison(): void
{
$user = $this->createUser();
Sanctum::actingAs($user);
DB::table('parents')->insert([
'secondparent_firstname' => 'Parent',
'secondparent_lastname' => 'Two',
'secondparent_email' => 'parent2@example.com',
'secondparent_phone' => '5555555555',
'firstparent_id' => 1,
'secondparent_id' => 2,
'school_year' => '2025-2026',
]);
$response = $this->postJson('/api/v1/email-extractor/compare', [
'csv_emails' => ['parent2@example.com', 'missing@example.com'],
]);
$response->assertOk();
$response->assertJsonPath('ok', true);
$this->assertContains('parent2@example.com', $response->json('comparison.existed'));
}
private function createUser(): User
{
DB::table('users')->insert([
'id' => 1,
'school_id' => 1,
'firstname' => 'Admin',
'lastname' => 'User',
'cellphone' => '5555555555',
'email' => 'admin@example.com',
'address_street' => '123 Main',
'city' => 'City',
'state' => 'ST',
'zip' => '12345',
'accept_school_policy' => 1,
'is_verified' => 1,
'status' => 'Active',
'is_suspended' => 0,
'failed_attempts' => 0,
'password' => bcrypt('secret'),
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
return User::query()->findOrFail(1);
}
}
@@ -0,0 +1,123 @@
<?php
namespace Tests\Feature\Api\V1\Finance;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class FeeCalculationControllerTest extends TestCase
{
use RefreshDatabase;
public function test_refund_endpoint_returns_amount(): void
{
$user = $this->createUser();
Sanctum::actingAs($user);
$this->seedConfig();
$this->seedClassSection();
DB::table('payments')->insert([
'id' => 1,
'parent_id' => 10,
'paid_amount' => 200.00,
'total_amount' => 200.00,
'balance' => 0.00,
'number_of_installments' => 1,
'payment_date' => '2025-01-10',
'school_year' => '2025-2026',
'status' => 'Paid',
]);
$response = $this->postJson('/api/v1/finance/fees/refund', [
'parent_id' => 10,
'students' => [
[
'student_id' => 1,
'class_section_id' => 101,
'enrollment_status' => 'withdrawn',
'admission_status' => 'accepted',
'withdrawal_date' => '2025-01-15',
],
],
]);
$response->assertOk();
$response->assertJsonPath('ok', true);
$this->assertGreaterThan(0, (float) $response->json('refund.refund_amount'));
}
public function test_tuition_total_endpoint_returns_total(): void
{
$user = $this->createUser();
Sanctum::actingAs($user);
$this->seedConfig();
$this->seedClassSection();
$response = $this->postJson('/api/v1/finance/fees/tuition-total', [
'students' => [
['class_section_id' => 101],
['class_section_id' => 101],
],
]);
$response->assertOk();
$response->assertJsonPath('ok', true);
$this->assertGreaterThan(0, (float) $response->json('tuition.total_tuition'));
}
private function seedConfig(): void
{
DB::table('configuration')->insert([
['config_key' => 'school_year', 'config_value' => '2025-2026'],
['config_key' => 'refund_deadline', 'config_value' => '2025-02-01'],
['config_key' => 'weeks_study', 'config_value' => '8'],
['config_key' => 'last_school_day', 'config_value' => '2025-06-01'],
['config_key' => 'first_student_fee', 'config_value' => '350'],
['config_key' => 'second_student_fee', 'config_value' => '200'],
['config_key' => 'youth_fee', 'config_value' => '180'],
]);
}
private function seedClassSection(): void
{
DB::table('classSection')->insert([
'id' => 1,
'class_id' => 1,
'class_section_id' => 101,
'class_section_name' => '3',
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
}
private function createUser(): User
{
DB::table('users')->insert([
'id' => 1,
'school_id' => 1,
'firstname' => 'Admin',
'lastname' => 'User',
'cellphone' => '5555555555',
'email' => 'admin@example.com',
'address_street' => '123 Main',
'city' => 'City',
'state' => 'ST',
'zip' => '12345',
'accept_school_policy' => 1,
'is_verified' => 1,
'status' => 'Active',
'is_suspended' => 0,
'failed_attempts' => 0,
'password' => bcrypt('secret'),
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
return User::query()->findOrFail(1);
}
}
@@ -0,0 +1,212 @@
<?php
namespace Tests\Feature\Api\V1\Finance;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class PurchaseOrderControllerTest extends TestCase
{
use RefreshDatabase;
public function test_index_returns_orders(): void
{
$this->seedUsers();
$supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
DB::table('purchase_orders')->insert([
'id' => 1,
'po_number' => 'PO-001',
'supplier_id' => $supplierId,
'status' => 'ordered',
'subtotal' => 25,
'tax' => 0,
'total' => 25,
'created_at' => now(),
'updated_at' => now(),
]);
Sanctum::actingAs(User::query()->findOrFail(1));
$response = $this->getJson('/api/v1/finance/purchase-orders?q=PO-001');
$response->assertOk();
$response->assertJson(['ok' => true]);
$this->assertNotEmpty($response->json('orders'));
}
public function test_options_returns_suppliers_and_supplies(): void
{
$this->seedUsers();
DB::table('suppliers')->insert([
['id' => 1, 'name' => 'Alpha Supplies'],
['id' => 2, 'name' => 'Beta Supplies'],
]);
DB::table('supplies')->insert([
['id' => 1, 'name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 0],
['id' => 2, 'name' => 'Ink', 'unit' => 'each', 'qty_on_hand' => 5],
]);
Sanctum::actingAs(User::query()->findOrFail(1));
$response = $this->getJson('/api/v1/finance/purchase-orders/options');
$response->assertOk();
$response->assertJson(['ok' => true]);
$this->assertCount(2, $response->json('suppliers'));
$this->assertCount(2, $response->json('supplies'));
}
public function test_store_creates_purchase_order_and_items(): void
{
$this->seedUsers();
$supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
$supplyId = DB::table('supplies')->insertGetId(['name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 0]);
Sanctum::actingAs(User::query()->findOrFail(1));
$response = $this->postJson('/api/v1/finance/purchase-orders', [
'po_number' => 'PO-100',
'supplier_id' => $supplierId,
'order_date' => '2026-03-10',
'expected_date' => '2026-03-15',
'notes' => 'Initial order',
'items' => [
[
'supply_id' => $supplyId,
'description' => 'Paper for class',
'quantity' => 2,
'unit_cost' => 5,
],
],
]);
$response->assertStatus(201);
$response->assertJson(['ok' => true]);
$this->assertDatabaseHas('purchase_orders', [
'po_number' => 'PO-100',
'supplier_id' => $supplierId,
'subtotal' => 10,
'total' => 10,
]);
$this->assertDatabaseHas('purchase_order_items', [
'supply_id' => $supplyId,
'quantity' => 2,
'unit_cost' => 5,
]);
}
public function test_receive_updates_inventory(): void
{
$this->seedUsers();
$supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
$supplyId = DB::table('supplies')->insertGetId(['name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 1]);
$poId = DB::table('purchase_orders')->insertGetId([
'po_number' => 'PO-200',
'supplier_id' => $supplierId,
'status' => 'ordered',
'subtotal' => 20,
'tax' => 0,
'total' => 20,
'created_at' => now(),
'updated_at' => now(),
]);
$itemId = DB::table('purchase_order_items')->insertGetId([
'purchase_order_id' => $poId,
'supply_id' => $supplyId,
'description' => 'Paper for class',
'quantity' => 4,
'received_qty' => 0,
'unit_cost' => 5,
'created_at' => now(),
'updated_at' => now(),
]);
Sanctum::actingAs(User::query()->findOrFail(1));
$response = $this->postJson("/api/v1/finance/purchase-orders/{$poId}/receive", [
'items' => [
['id' => $itemId, 'quantity' => 4],
],
]);
$response->assertOk();
$response->assertJson(['ok' => true, 'completed' => true]);
$this->assertDatabaseHas('purchase_order_items', [
'id' => $itemId,
'received_qty' => 4,
]);
$this->assertDatabaseHas('supplies', [
'id' => $supplyId,
'qty_on_hand' => 5,
]);
$this->assertDatabaseHas('supply_transactions', [
'supply_id' => $supplyId,
'type' => 'in',
'quantity' => 4,
]);
}
public function test_cancel_marks_purchase_order(): void
{
$this->seedUsers();
$supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
$poId = DB::table('purchase_orders')->insertGetId([
'po_number' => 'PO-300',
'supplier_id' => $supplierId,
'status' => 'ordered',
'subtotal' => 0,
'tax' => 0,
'total' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
Sanctum::actingAs(User::query()->findOrFail(1));
$response = $this->postJson("/api/v1/finance/purchase-orders/{$poId}/cancel");
$response->assertOk();
$response->assertJson(['ok' => true, 'status' => 'canceled']);
$this->assertDatabaseHas('purchase_orders', [
'id' => $poId,
'status' => 'canceled',
]);
}
private function seedUsers(): void
{
DB::table('roles')->insert([
['id' => 1, 'name' => 'admin', 'slug' => 'admin', 'is_active' => 1],
]);
DB::table('users')->insert([
'id' => 1,
'school_id' => 1,
'firstname' => 'Admin',
'lastname' => 'User',
'cellphone' => '5555555555',
'email' => 'admin@example.com',
'address_street' => '123 Main',
'city' => 'City',
'state' => 'ST',
'zip' => '12345',
'accept_school_policy' => 1,
'is_verified' => 1,
'status' => 'Active',
'is_suspended' => 0,
'failed_attempts' => 0,
'password' => bcrypt('secret'),
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
DB::table('user_roles')->insert([
['user_id' => 1, 'role_id' => 1],
]);
}
}
@@ -71,6 +71,8 @@ class QuizControllerTest extends TestCase
'class_section_id' => 1,
'class_section_name' => '1A',
'class_id' => 1,
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
DB::table('students')->insert([
@@ -79,6 +81,10 @@ class QuizControllerTest extends TestCase
'firstname' => 'Kid',
'lastname' => 'User',
'school_id' => 1,
'age' => 10,
'gender' => 'M',
'photo_consent' => 1,
'year_of_registration' => '2025',
'is_active' => 1,
]);
@@ -87,6 +93,7 @@ class QuizControllerTest extends TestCase
'class_section_id' => 1,
'school_year' => '2025-2026',
'is_event_only' => 0,
'semester' => 'Fall',
]);
}
}
@@ -47,7 +47,11 @@ class ScoreCommentControllerTest extends TestCase
'created_at' => now(),
]);
$response = $this->getJson('/api/v1/scores/comments?class_section_id=1&semester=Fall&school_year=2025-2026');
$response = $this->json('GET', '/api/v1/scores/comments', [
'class_section_id' => 1,
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
$response->assertOk();
$response->assertJson(['ok' => true]);
@@ -60,6 +64,11 @@ class ScoreCommentControllerTest extends TestCase
['id' => 1, 'name' => 'teacher', 'slug' => 'teacher', 'is_active' => 1],
]);
DB::table('configuration')->insert([
['config_key' => 'school_year', 'config_value' => '2025-2026'],
['config_key' => 'semester', 'config_value' => 'Fall'],
]);
DB::table('users')->insert([
'id' => 1,
'school_id' => 1,
@@ -90,6 +99,8 @@ class ScoreCommentControllerTest extends TestCase
'class_section_id' => 1,
'class_section_name' => '1A',
'class_id' => 1,
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
DB::table('students')->insert([
@@ -98,6 +109,10 @@ class ScoreCommentControllerTest extends TestCase
'firstname' => 'Kid',
'lastname' => 'User',
'school_id' => 1,
'age' => 10,
'gender' => 'M',
'photo_consent' => 1,
'year_of_registration' => '2025',
'is_active' => 1,
]);
@@ -106,6 +121,7 @@ class ScoreCommentControllerTest extends TestCase
'class_section_id' => 1,
'school_year' => '2025-2026',
'is_event_only' => 0,
'semester' => 'Fall',
]);
}
}
@@ -24,7 +24,11 @@ class ScoreControllerTest extends TestCase
'semester' => 'Fall',
]);
$response = $this->getJson('/api/v1/scores/overview?class_section_id=1&semester=Fall&school_year=2025-2026');
$response = $this->json('GET', '/api/v1/scores/overview', [
'class_section_id' => 1,
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
$response->assertOk();
$response->assertJson(['ok' => true]);
@@ -116,7 +116,10 @@ class UserControllerTest extends TestCase
'school_year' => '2025-2026',
]);
$response = $this->getJson('/api/v1/users/login-activity?per_page=1&page=2');
$response = $this->json('GET', '/api/v1/users/login-activity', [
'per_page' => 1,
'page' => 2,
]);
$response->assertOk();
$response->assertJson(['ok' => true]);
@@ -0,0 +1,58 @@
<?php
namespace Tests\Unit\Services\Email;
use App\Services\Email\EmailExtractorService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class EmailExtractorServiceTest extends TestCase
{
use RefreshDatabase;
public function test_list_and_compare_emails(): void
{
DB::table('users')->insert([
'id' => 1,
'school_id' => 1,
'firstname' => 'User',
'lastname' => 'One',
'cellphone' => '5555555555',
'email' => 'user1@example.com',
'address_street' => '123 Main',
'city' => 'City',
'state' => 'ST',
'zip' => '12345',
'accept_school_policy' => 1,
'is_verified' => 1,
'status' => 'Active',
'is_suspended' => 0,
'failed_attempts' => 0,
'password' => bcrypt('secret'),
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
DB::table('parents')->insert([
'secondparent_firstname' => 'Parent',
'secondparent_lastname' => 'Two',
'secondparent_email' => 'parent2@example.com',
'secondparent_phone' => '5555555555',
'firstparent_id' => 1,
'secondparent_id' => 2,
'school_year' => '2025-2026',
]);
$service = new EmailExtractorService();
$emails = $service->listEmails();
$this->assertContains('user1@example.com', $emails['users']);
$this->assertContains('parent2@example.com', $emails['parents']);
$result = $service->compare(['user1@example.com', 'missing@example.com']);
$this->assertContains('user1@example.com', $result['existed']);
$this->assertContains('parent2@example.com', $result['needToAdd']);
}
}
@@ -0,0 +1,33 @@
<?php
namespace Tests\Unit\Services\Email;
use App\Services\Email\EmailProfileService;
use Tests\TestCase;
class EmailProfileServiceTest extends TestCase
{
public function test_resolve_profile_maps_aliases(): void
{
$service = new EmailProfileService();
$this->assertSame('communication', $service->resolveProfile('comm'));
$this->assertSame('default', $service->resolveProfile('system'));
$this->assertSame('payment', $service->resolveProfile('payment'));
}
public function test_env_key_from_profile(): void
{
$service = new EmailProfileService();
$this->assertSame('PAYMENT_ALERTS', $service->envKeyFromProfile('payment alerts'));
}
public function test_sanitize_reply_to_name(): void
{
$service = new EmailProfileService();
$this->assertSame('Fallback', $service->sanitizeReplyToName('no-reply', 'Fallback'));
$this->assertSame('Support', $service->sanitizeReplyToName('Support', 'Fallback'));
}
}
@@ -0,0 +1,28 @@
<?php
namespace Tests\Unit\Services\Fees;
use App\Services\Fees\FeeGradeService;
use Tests\TestCase;
class FeeGradeServiceTest extends TestCase
{
public function test_grade_level_parsing(): void
{
$service = new FeeGradeService();
$this->assertSame(0, $service->getGradeLevel('K'));
$this->assertSame(99, $service->getGradeLevel('Y'));
$this->assertSame(3, $service->getGradeLevel('3-A'));
$this->assertSame(999, $service->getGradeLevel('Unknown'));
}
public function test_compare_grades_orders_numeric_then_suffix(): void
{
$service = new FeeGradeService();
$this->assertSame(-1, $service->compareGrades('2', '3'));
$this->assertSame(-1, $service->compareGrades('3-A', '3-B'));
$this->assertSame(1, $service->compareGrades('4', '3'));
}
}
@@ -0,0 +1,67 @@
<?php
namespace Tests\Unit\Services\Fees;
use App\Services\Fees\FeeConfigService;
use App\Services\Fees\FeeGradeService;
use App\Services\Fees\FeeRefundCalculatorService;
use App\Services\Fees\FeeStudentFeeService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class FeeRefundCalculatorServiceTest extends TestCase
{
use RefreshDatabase;
public function test_calculate_refund_caps_at_total_paid(): void
{
DB::table('configuration')->insert([
['config_key' => 'school_year', 'config_value' => '2025-2026'],
['config_key' => 'refund_deadline', 'config_value' => '2025-02-01'],
['config_key' => 'weeks_study', 'config_value' => '8'],
['config_key' => 'last_school_day', 'config_value' => '2025-06-01'],
['config_key' => 'first_student_fee', 'config_value' => '350'],
['config_key' => 'second_student_fee', 'config_value' => '200'],
['config_key' => 'youth_fee', 'config_value' => '180'],
]);
DB::table('classSection')->insert([
'id' => 1,
'class_id' => 1,
'class_section_id' => 101,
'class_section_name' => '3',
'semester' => 'Fall',
'school_year' => '2025-2026',
]);
DB::table('payments')->insert([
'id' => 1,
'parent_id' => 99,
'paid_amount' => 100.00,
'total_amount' => 100.00,
'balance' => 0.00,
'number_of_installments' => 1,
'payment_date' => '2025-01-10',
'school_year' => '2025-2026',
'status' => 'Paid',
]);
$service = new FeeRefundCalculatorService(
new FeeConfigService(),
new FeeStudentFeeService(new FeeGradeService(), new FeeConfigService())
);
$result = $service->calculateRefund([
[
'student_id' => 1,
'class_section_id' => 101,
'enrollment_status' => 'withdrawn',
'admission_status' => 'accepted',
'withdrawal_date' => '2025-01-15',
],
], 99);
$this->assertSame(100.0, $result['refund_amount']);
}
}
@@ -0,0 +1,50 @@
<?php
namespace Tests\Unit\Services\PurchaseOrders;
use App\Services\PurchaseOrders\PurchaseOrderCreateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class PurchaseOrderCreateServiceTest extends TestCase
{
use RefreshDatabase;
public function test_create_persists_purchase_order_and_items(): void
{
$supplierId = DB::table('suppliers')->insertGetId(['name' => 'Alpha Supplies']);
$supplyId = DB::table('supplies')->insertGetId(['name' => 'Paper', 'unit' => 'box', 'qty_on_hand' => 0]);
$service = new PurchaseOrderCreateService();
$po = $service->create([
'po_number' => 'PO-500',
'supplier_id' => $supplierId,
'order_date' => '2026-03-10',
'expected_date' => '2026-03-15',
'notes' => 'Initial order',
'items' => [
[
'supply_id' => $supplyId,
'description' => 'Paper for class',
'quantity' => 3,
'unit_cost' => 4,
],
],
]);
$this->assertNotNull($po->id);
$this->assertDatabaseHas('purchase_orders', [
'id' => $po->id,
'po_number' => 'PO-500',
'subtotal' => 12,
'total' => 12,
]);
$this->assertDatabaseHas('purchase_order_items', [
'purchase_order_id' => $po->id,
'supply_id' => $supplyId,
'quantity' => 3,
'unit_cost' => 4,
]);
}
}
@@ -0,0 +1,62 @@
<?php
namespace Tests\Unit\Services\PurchaseOrders;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\Supply;
use App\Services\PurchaseOrders\PurchaseOrderReceiveService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PurchaseOrderReceiveServiceTest extends TestCase
{
use RefreshDatabase;
public function test_receive_updates_items_and_inventory(): void
{
$supply = Supply::query()->create([
'name' => 'Paper',
'unit' => 'box',
'qty_on_hand' => 2,
]);
$po = PurchaseOrder::query()->create([
'po_number' => 'PO-600',
'supplier_id' => 1,
'status' => PurchaseOrder::STATUS_ORDERED,
'subtotal' => 10,
'tax' => 0,
'total' => 10,
]);
$item = PurchaseOrderItem::query()->create([
'purchase_order_id' => $po->id,
'supply_id' => $supply->id,
'description' => 'Paper for class',
'quantity' => 3,
'received_qty' => 0,
'unit_cost' => 3,
]);
$service = new PurchaseOrderReceiveService();
$result = $service->receive($po->id, [
['id' => $item->id, 'quantity' => 3],
], 'tester@example.com');
$this->assertTrue($result['completed']);
$this->assertDatabaseHas('purchase_order_items', [
'id' => $item->id,
'received_qty' => 3,
]);
$this->assertDatabaseHas('supplies', [
'id' => $supply->id,
'qty_on_hand' => 5,
]);
$this->assertDatabaseHas('supply_transactions', [
'supply_id' => $supply->id,
'type' => 'in',
'quantity' => 3,
]);
}
}
@@ -0,0 +1,34 @@
<?php
namespace Tests\Unit\Services\PurchaseOrders;
use App\Models\PurchaseOrder;
use App\Services\PurchaseOrders\PurchaseOrderStatusService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class PurchaseOrderStatusServiceTest extends TestCase
{
use RefreshDatabase;
public function test_cancel_marks_purchase_order_canceled(): void
{
$po = PurchaseOrder::query()->create([
'po_number' => 'PO-700',
'supplier_id' => 1,
'status' => PurchaseOrder::STATUS_ORDERED,
'subtotal' => 0,
'tax' => 0,
'total' => 0,
]);
$service = new PurchaseOrderStatusService();
$updated = $service->cancel($po->id);
$this->assertSame(PurchaseOrder::STATUS_CANCELED, $updated->status);
$this->assertDatabaseHas('purchase_orders', [
'id' => $po->id,
'status' => PurchaseOrder::STATUS_CANCELED,
]);
}
}