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,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()