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,
];
}
}